简体   繁体   中英

Cannot assign value of type 'String??' to type 'String?' error

let say I defined a 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? and Dictionary returns optional of its value type when used subscript but what is String?? type in 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? it returns type 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. 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??

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 .

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:

dummy.title = foo[1] ?? nil

or even

dummy.title = foo[1] ?? ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM