Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

swift3 - Swift optional parameter not unwrapped

I have a function with a optional parameter(position). I test for it to be nil but still Xcode shows me an error: "Value of optional type Int? not unwrapped" and suggests me to use "!" or "?".

var entries = [String]()

func addEntry(text: String, position: Int?) {
    if(position == nil) {
        entries.append(text)
    } else {
        entries[position] = text
    }
}

Im new to Swift and don't understand why this isn't ok. Within this if-clause the compiler should be 100% sure that position is defined, or?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a few ways to code this properly:

func addEntry(text: String, position: Int?) {
    // Safely unwrap the value
    if let position = position {
        entries[position] = text
    } else {
        entries.append(text)
    }
}

or:

func addEntry(text: String, position: Int?) {
    if position == nil {
        entries.append(text)
    } else {
        // Force unwrap since you know it isn't nil
        entries[position!] = text
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...