如果我在Swift中有一个数组,并尝试访问超出范围的索引,则会出现一个不足为奇的运行时错误:
var str = ["Apple", "Banana", "Coconut"]
str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
Run Code Online (Sandbox Code Playgroud)
但是,我会想到Swift带来的所有可选链接和安全性,这样做会很简单:
let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
print(nonexistent)
...do other things with nonexistent...
}
Run Code Online (Sandbox Code Playgroud)
代替:
let theIndex = 3
if (theIndex < str.count) { // Bounds check
let nonexistent = str[theIndex] // Lookup
print(nonexistent)
...do other things with nonexistent...
}
Run Code Online (Sandbox Code Playgroud)
但事实并非如此 - 我必须使用ol' if语句来检查并确保索引小于str.count.
我尝试添加自己的subscript()实现,但我不知道如何将调用传递给原始实现,或者不使用下标符号来访问项目(基于索引):
extension Array {
subscript(var index: Int) …Run Code Online (Sandbox Code Playgroud) 我无法在下面的代码中找出"Indices.Iterator.Element == Index"的目的/含义
extension Collection where Indices.Iterator.Element == Index {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
Run Code Online (Sandbox Code Playgroud) 我正在学习 Swift 中的泛型。对我来说,这个话题很难理解。在我正在读的书中,关于泛型有两个挑战:
第一个挑战:它要求编写一个函数findAll(_:_:),该函数接受符合 Equatable 协议的任何类型 T 的数组和单个元素(也是 T 类型)。findAll(_:_:)应该返回一个整数数组,对应于数组中找到该元素的每个位置。例如,findAll([5,3,7,3,9], 3]应该返回[1,3].
第二个挑战:修改findAll(_:_:)为接受 Collection 而不是数组,并给出提示“您需要将返回类型从 [Int] 更改为 Collection 协议关联类型的数组”
这就是我为第一个挑战所做的
func findAll<T:Equatable> (_ first: [T], _ second: T) -> [Int] {
var array = [Int]()
for i in 0..<first.count {
if first[i] == second {
array.append(i)
}
}
return array
}
Run Code Online (Sandbox Code Playgroud)
对于第二个挑战,我正在考虑的是一个可以传递集合(可以是数组、字典或集合)的通用函数。但是对于Set类型,由于它没有定义的顺序,如何找到Set中项目的位置?
谢谢。
我知道这是一个非常新手的问题,但它已经把我扔了好几天,我似乎无法找到一个我真正理解的解决方案.
我正在尝试创建一个嵌套数组来存储纬度和经度,但是Xcode/playground会抛出一个EXC_BAD_INSTRUCTION错误.
我想声明,初始化和打印数组的内容.我究竟做错了什么?
var arrayLocations:[[Float]] = []
arrayLocations[0] = [27.1750199, 78.0399665]
print("\(arrayLocations[0][0]) and \(arrayLocations[0][1])")
Run Code Online (Sandbox Code Playgroud)