Can someone explain why this works in Swift 3?
var dict: [AnyHashable: Any]
let b: AnyObject? = nil
let c = b as Any
dict = ["a": "aa", "b": c]
If I test
dict["b"] == nil
It returns false. Is it supposed to be right?
Can someone explain why this works in Swift 3?
var dict: [AnyHashable: Any]
let b: AnyObject? = nil
let c = b as Any
dict = ["a": "aa", "b": c]
If I test
dict["b"] == nil
It returns false. Is it supposed to be right?
ネストされたオプションに遭遇しています。ディクショナリが type を保持している場合、Eディクショナリ アクセス メソッドは type の値 (E?存在する場合は値、または nil) を返します。
あなたの場合、値がオプションである辞書を作成しました。したがって、E上記は のようなものAny?です。E?つまり、ゲッターの戻り値は次のようになります。Any??
あなたの場合、dict["b"]値「nil」を含む非nilオプションを返します
コードをプレイグラウンドに配置して印刷するとdict["b"]、文字列を印刷することでこれを確認できますOptional(nil)
Swift 3.0.1 で最新の Xcode 8.1 (8B62) を使用していると仮定します。
Any単純nilなネストされたオプションほど簡単ではありません。
var dictWithOptional: [String: AnyObject?] = [
"a": "aa" as NSString,
"b": nil,
]
if let b = dictWithOptional["b"] { //<-check if `dict` contains value for "b"
print(b) //->nil (with compiletime warning)
print(b == nil) //->true
}
b == nil戻りますtrue。
Any含むnilvar dict: [AnyHashable: Any]
let b: AnyObject? = nil
let c = b as Any
dict = ["a": "aa", "b": c]
print(Array(dict.keys)) //->[AnyHashable("b"), AnyHashable("a")]
if let b = dict["b"] { //<-check if `dict` contains value for "b"
print(b) //->nil
print(b == nil) //->false (with compiletime warning)
}
b == nilfalseOPで書いた通りになります。
次のようなものnilで、で検出できます。Any
if let b = dict["b"] { //<-check if `dict` contains value for "B"
if b as AnyObject === NSNull() {
print("b is nil") //->b is nil
}
}
(これは Swift 3.0.0 ではなく Swift 3.0.1 で機能します。)