简体   繁体   中英

How can ı add value to nil object in swift

I have issue about this code you see. Why its give me nil value and how can ı figure it out to right plz hep me

struct NilControl{
    var name:String?
}

var k: NilControl?

print(k)
// nil -> Okey ı guess just like that
k?.name = "name"

print(k?.name)
// nil -> ı expect to see name but its still give me nil

See inline comments for an explanation of what's going on:

struct NilControl{
    var name:String?
}

var k: NilControl? //you've defined k as NilControl? and not assigned it a value yet

print(k) //this will be nil, since k has not been set

k = NilControl() //this sets k to have a value (ie not nil), but its `name` is still nil at this point
k?.name = "name"

print(k?.name) //will print Optional("name")

If you want to do some nil checking on it before printing the name , it might look something like this:

k = NilControl(name: "name") //this sets k to have a value & assigns a name

if let k = k, let name = k.name {
    print(name)
}

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