将值分配给Swift中的可选字典 [英] Assign value to optional dictionary in Swift

查看:148
本文介绍了将值分配给Swift中的可选字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var foo:Dictionary< String,String>?????????????? 

if(foo == nil){
foo = [bar:baz]
}
else {
//关注行'字典< String,String> ;?'的错误
//没有名为'subscript'的成员'
foo [qux] =quux
}

我已经玩了很多,试图弄清楚我可能会失踪,但似乎没有这个代码按预期的方式工作,使字典不是可选的。我缺少什么?



最接近的是以下内容,但当然可笑。

  var foo:Dictionary< String,String>? 

if(foo == nil){
foo = [bar:baz]
}
如果var foofoo = foo {
foofoo [qux] =quux
foo = foofoo
}


解决方案

灯泡的时刻是当您意识到可选字典不是字典时。一个可选的东西不是那个东西!这是一个可选的!这就是这一切。可选本身就是一种类型。一个可选只是一个枚举,包装可能的情况和一些价值。包装的值是一个完全不同的对象,存储在里面。



所以一个可选的任何东西都不像这样的东西。这不是那个东西!这只是一个可选的。获取东西的唯一方法是打开它。



隐含解开的可选项也是如此;不同之处在于隐式解开的Optional可以自动生成(公开)包装的值。但实际上它仍然包裹着。而正如陈水扁所观察到的那样,它是不可磨灭的;可选的只是为你提供 - 它不是给你一个玩的地方。


I'm finding some surprising behavior with optional dictionaries in Swift.

var foo:Dictionary<String, String>?

if (foo == nil) {
    foo = ["bar": "baz"]
}
else {
    // Following line errors with "'Dictionary<String, String>?' does
    // not have a member named 'subscript'"
    foo["qux"] = "quux"
}

I've played with this a lot, trying to figure out what I might be missing, but nothing seems to make this code work as expected short of making the dictionary not optional. What am I missing?

The closest I can get is the following, but of course it's ridiculous.

var foo:Dictionary<String, String>?

if (foo == nil) {
    foo = ["bar": "baz"]
}
else if var foofoo = foo {
    foofoo["qux"] = "quux"
    foo = foofoo
}

解决方案

The lightbulb moment is when you realize that an Optional dictionary is not a Dictionary. An Optional anything is not that thing! It is an Optional!! And that's all it is. Optional is itself a type. An Optional is just an enum, wrapping the possible cases nil and some value. The wrapped value is a completely different object, stored inside.

So an Optional anything does not act like the type of that thing. It is not that thing! It is just an Optional. The only way to get at the thing is to unwrap it.

The same is true of an implicitly unwrapped Optional; the difference is just that the implicitly unwrapped Optional is willing to produce (expose) the wrapped value "automatically". But it is still, in fact, wrapped. And, as Bryan Chen has observed, it is wrapped immutably; the Optional is just holding it for you - it is not giving you a place to play with it.

这篇关于将值分配给Swift中的可选字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆