问题
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?
回答1:
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
}
}
回答2:
Even though you checked for nil you still haven’t converted the Int? into an Int to use as an index. To do that you need to unwrap the Optional:
var entries = [String]()
func addEntry(text: String, position: Int?) {
// guard against a nil position by attempting to
// unwrap it with optional binding
guard
// test for nil and unwrap using optional binding
let unwrappedPosition = position,
// make sure the position isn't
// past the end of the array
unwrappedPosition < entries.count else {
// can't unwrap it or
// it's out of bounds,
// append it
entries.append(text)
return
}
// successfully unwrapped, set item at index
entries[unwrappedPosition] = text
}
来源:https://stackoverflow.com/questions/40290202/swift-optional-parameter-not-unwrapped