如何最好地检查数组中特定索引处的对象是否存在(在范围内)?
如果可以这么简单就好了,但不幸的是这是不可能的:
let testArray = ["A", "B", "C", "D"]
if let result = testArray[6] {
println("Result: \(result)")
}
else {
println("Result does not exist. Out of bounds.")
}
我需要检查总数吗?
谢谢!
你也可以扩展Array,这样你就能使用if-let进行检查:
extension Array {
func at(index: Int) -> Element? {
if index < 0 || index > self.count - 1 {
return nil
}
return self[index]
}
}
let arr = [1, 2, 3]
if let value = arr.at(index: 2) {
print(value)
}
~=
运算符与indices
函数结合使用,这是创建容器完整索引范围的快捷方式:let a = [1,2,3]
let idx = 3 // one past the end
if indices(a) ~= idx {
println("within")
}
else {
println("without")
}
需要注意的是,此方法适用于任何具有可比较索引的容器,而不仅仅是像数组一样具有整数索引的容器。习惯将索引视为数字通常是一个好习惯,因为它可以帮助您更加普遍地考虑对不具备这些索引的容器(如字符串或字典)上的算法:
let s = "abc"
let idx = s.endIndex
idx < count(s) // this won't compile
idx < s.startIndex // but this will
// and so will this
if indices(s) ~= idx {
println("within")
}
else {
println("without")
}
如果您的算法越通用,那么它们就越容易被拆分成通用代码并增加重用性。
lhs
赋值为lhs ~ rhs
的结果 - 就像其他<op>=
运算符一样。 - GoZonerRange
应该有一个包含运算符,但不幸的是,它无法利用比较器,因为范围的索引是无限制的。 - Airspeed Velocity在Swift中有一种新的(好用的)方法:
array.indices.contains(index)
@alkku已经有了,但为了简单起见并使用所有语言中最不常用的句法形式?:
:
extension Array {
func atIndex(index: Int) -> T? {
return (0 <= index && index < self.count
? self[index]
: nil)
}
}
检查使用的对象索引是否大于等于零且小于数组的总数,就像这样:
//Here index is object you want for
if(index >= 0 && index < [yourArray count])
{
//inside of array
}
else
{
//out of bound
}
<=
需要改成 >=
。 - keithbhunterif index < testArray.count { ... }
:) - Martin R在Swift中检查索引是否在数组界限内,您可以使用以下方法:
if index < testArray.count {
//index is inside bounds
} else {
//index is outside bounds
}