[英]Cannot assign value of type 'String??' to type 'String?' error
let say I defined a class假设我定义了一个 class
class Dummy {
var title: String?
}
and I have a dictionary as我有一本字典
let foo: [Int: String?] = [:]
then when I make an assignment as below然后当我进行如下分配时
var dummy = Dummy()
dummy.title = foo[1]
it says它说
Cannot assign value of type 'String??'无法分配“字符串??”类型的值to type 'String?'键入“字符串?”
Insert ' as!插入 ' 作为! String'细绳'
return type of foo
is String?
foo
的返回类型是String?
and Dictionary
returns optional of its value type when used subscript but what is String??
和Dictionary
在使用下标时返回其值类型的可选,但什么是String??
type in swift?输入 swift?
I think it should be legal to make such assignment.我认为进行这样的分配应该是合法的。 Why it complains and how should I make this assignment为什么它会抱怨,我应该如何做这个作业
Since having a value corresponding to the key 1 in the dictionary foo
is optional and the value in the dictionary is of type String?
由于字典foo
中的键 1 对应的值是可选的,并且字典中的值是String?
it returns type String??
它返回类型String??
. . Unwrapping the value once to check if the value exists would fix this issue解开该值一次以检查该值是否存在将解决此问题
if let value = foo[1] {
dummy.title = value
}
By declaring your dictionary as [Int:String?]
you are saying that the key is an Int
and values are optional String
s.通过将您的字典声明为[Int:String?]
您是说键是Int
并且值是可选的String
s。 Now the key may not be present in the dictionary, so foo[1]
optionally returns an optional and you end up with an with an optional optional - String??
现在键可能不存在于字典中,所以foo[1]
可选地返回一个可选的,你最终得到一个可选的可选 - String??
Now while there are sometimes uses for optional optionals, I don't think that is what you want in this case.现在,虽然有时可以使用可选选项,但我认为在这种情况下这不是您想要的。
You can simply make a dictionary of [Int:String]
and then not insert an element if the value is nil
.您可以简单地制作[Int:String]
的字典,然后如果值为nil
则不插入元素。
let foo: [Int: String] = [:]
dummy.title = foo[1]
If you do need to handle the case where "there is a value for this key and it is nil
" then the nil-coalescing operator may help you:如果您确实需要处理“此键有一个值并且它是nil
”的情况,那么 nil-coalescing 运算符可能会帮助您:
dummy.title = foo[1] ?? nil
or even甚至
dummy.title = foo[1] ?? ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.