1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift 配列から条件にあった要素のインデックス値を取得する

Posted at

String配列の一部を置換する例

var students = ["マリオ", "ピーチ", "ワルイージ", "ヨッシー"]
if let i = students.firstIndex(of: "ワルイージ") {
    students[i] = "ルイージ"
}
print(students)
// Prints "["マリオ", "ピーチ", "ルイージ", "ヨッシー"]"

UIBarButtonItem配列でtag==3な要素のインデックスを取得する

let buttonA : UIBarButtonItem {
  let button = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(onPlayPauseButton(_:)))
  button.tag = 1
  return button
}

let buttonB : UIBarButtonItem {
  let button = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action: #selector(onPlayPauseButton(_:)))
  button.tag = 3
  return button
}

// buttonB のインデックス位置を取得したい
let buttons = [ buttonA, buttonB ]
if let i = buttons.firstIndex(where: {$0.tag == 3}) else{
  print(i)
  // 1
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?