根据Swift Standard Library Reference,使用下标运算符的Swift字典查找返回包含在Optional
中的可能值。我可以通过模式匹配来验证这一点:
let d = [ "a": 1, "b": 2]
switch d["a"] {
case .Some(let x): print(x)
case .None: print("Nothing")
}
但是,当我尝试在查找值上使用Optional
类型的map
方法时:
d["a"].map { print($0 * 2) }
我收到错误:
24:1: error: '(String, Int)' does not have a member named 'map'
d["a"].map { print($1 * 2) }
^ ~~~
这里发生了什么?
答案 0 :(得分:5)
你的问题在于:
d["a"].map { print($1 * 2) }
^~~~ you mean $0
面对这种情况,Swift会根据其他类型的下标给你最好的猜测(它接受字典索引并给你一个键/值对,因此会提供第二个参数)。