在Swift中,有没有办法检查数组中是否存在索引而没有抛出致命错误?
我希望我能做到这样的事情:
let arr: [String] = ["foo", "bar"]
let str: String? = arr[1]
if let str2 = arr[2] as String? {
// this wouldn't run
println(str2)
} else {
// this would be run
}
Run Code Online (Sandbox Code Playgroud)
但我明白了
致命错误:数组索引超出范围
Man*_*uel 392
Swift的优雅方式:
let isIndexValid = array.indices.contains(index)
Run Code Online (Sandbox Code Playgroud)
Ben*_*ess 56
extension Collection {
subscript(optional i: Index) -> Iterator.Element? {
return self.indices.contains(i) ? self[i] : nil
}
}
Run Code Online (Sandbox Code Playgroud)
使用此选项可以在向索引添加关键字optional时获得可选值,这意味着即使索引超出范围,程序也不会崩溃.在你的例子中:
let arr = ["foo", "bar"]
let str1 = arr[optional: 1] // --> str1 is now Optional("bar")
if let str2 = arr[optional: 2] {
print(str2) // --> this still wouldn't run
} else {
print("No string found at that index") // --> this would be printed
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*nio 31
只需检查索引是否小于数组大小:
if 2 < arr.count {
...
} else {
...
}
Run Code Online (Sandbox Code Playgroud)
man*_*mar 12
最好的办法。
let reqIndex = array.indices.contains(index)
print(reqIndex)
Run Code Online (Sandbox Code Playgroud)
eon*_*ist 11
extension Collection {
subscript(safe index: Index) -> Iterator.Element? {
guard indices.contains(index) else { return nil }
return self[index]
}
}
if let item = ["a","b","c","d"][safe:3] {print(item)}//Output: "c"
//or with guard:
guard let anotherItem = ["a","b","c","d"][safe:3] else {return}
print(anotherItem)//"c"
Run Code Online (Sandbox Code Playgroud)
if let
与数组一起进行样式编码时增强了可读性
你可以用更安全的方式重写这个来检查数组的大小,并使用三元条件:
if let str2 = (arr.count > 2 ? arr[2] : nil) as String?
Run Code Online (Sandbox Code Playgroud)
对我来说,我更喜欢方法。
// MARK: - Extension Collection
extension Collection {
/// Get at index object
///
/// - Parameter index: Index of object
/// - Returns: Element at index or nil
func get(at index: Index) -> Iterator.Element? {
return self.indices.contains(index) ? self[index] : nil
}
}
Run Code Online (Sandbox Code Playgroud)
感谢@Benno Kress
归档时间: |
|
查看次数: |
68272 次 |
最近记录: |