I was trying to learn about swift basics and I encountered this problem:
Assume we have a dic:
var presidentialPetsDict = ["Barack Obama":"Bo", "Bill Clinton": "Socks", "George Bush": "Miss Beazley", "Ronald Reagan": "Lucky"]
And to Remove the entry for "George Bush" and replace it with an entry for "George W. Bush":
What I did:
var oldvalue = presidentialPetsDict.removeValueForKey("George Bush")
if let value = oldvalue
{
presidentialPetsDict["George W. Bush"] = value
}else
{
print("no matching found")
}
Because I believe removeValueForKey method will return an optional value in case key "George Bush" will not return a value but nil so we need to safely unwrap it by using if let. However, the solution code looks like this:
var oldValue = presidentialPetsDict.removeValueForKey("Georgee Bush")
presidentialPetsDict["George W. Bush"] = oldValue
The part I don't understand is that if we want to assign nil to a var we usually do this:
var value:String?
value = nil
But the solution code above works even though the method returns nil, could somebody explain why it worked because I think in solution we didn't declare oldValue as optional at all.
答案 0 :(得分:2)
由于您的数组定义为[String:String]
,您想知道为什么编译器允许您为值指定可选的String
(String?
}。
编译器如何冒险将nil
置于应该是非可选字符串的内容中?
这段代码怎么编译?
var oldValue: String? = presidentialPetsDict.removeValueForKey("Georgee Bush")
presidentialPetsDict["George W. Bush"] = oldValue
下标具有以下逻辑,即使Dictionary
的值为String
,您也可以使用下标来指定nil
。
在这种情况下,密钥将从阵列中删除。
看这里
var numbers: [String:Int] = ["one": 1, "two": 2, "three": 3]
numbers["two"] = nil // it looks like I'm putting nil into a Int right?
numbers // ["one": 1, "three": 3]
答案 1 :(得分:1)
var oldValue = presidentialPetsDict.removeValueForKey("George Bush")
由于返回类型的类型推断,oldValue获取可选字符串。
请参阅removeValueForKey的函数定义 public mutating func removeValueForKey(key:Key) - >值?