Edited at

[Swift]配列をループで条件を探すいろんな書き方

More than 3 years have passed since last update.


基本的な書き方

let saveValue: Int = 1

Private fund checkSaveValue (array: [Int]) -> Bool {
for value in array {
if value == saveValue {
return true
}
}
return false
}


.filterを使う

let saveValue: Int = 1

private func checkSaveValue(array: [Int]) -> Bool {
array.filter { value in
value == saveValue
}.first != nil
}


.Containsを使う

let saveValue: Int = 1

private func checkSaveValue(array: [Int]) -> Bool {
return array.contains { $0 == self.saveValue }
}


.enumerate()を使う

let array = [1, 2, 3, 4]

let pairList = array.enumerate().map { (tuple: (count: Int, int: Int)) -> String in
return count == int
}


いろいろ合わせた例

これ↓を

var checkedIndexPath: [NSIndexPath] = []

private func checkeIndex(indexPath: NSIndexPath) -> Int? {
var returnIndex: Int? = nil
checkedIndexPath.enumerate().forEach { (index, data) in
if data == indexPath {
returnIndex = index
}
}
return returnIndex
}

いろいろ合わせてこう書ける↓

var checkedIndexPath: [NSIndexPath] = []

private func checkedCellIndex(indexPath: NSIndexPath) -> Int? {
return checkedIndexPath
.enumerate()
.filter { $0.1 == indexPath }
.flatMap { return $0.0 }
.first
}