Reputation: 5979
I am writing swift code & having a simple problem.
I declared a MSMutableArray
, under certain condition, I set it to nil
:
func doJob() -> NSMutableArray {
var arr = NSMutableArray()
arr = addContentToArray()
if CRITICAL_CONDITION {
//ERROR: Cannot assign a value of type 'nil' to a value of type 'NSMutableArray'
arr = nil
}
return arr
}
But when I set arr
to nil
, I got compiler error:
Cannot assign a value of type 'nil' to a value of type 'NSMutableArray'
Why? How can I set it to nil then?
Upvotes: 0
Views: 1484
Reputation: 130092
You can assign nil
only to optional variables. However, when you are letting the type to be inferred, the compiler doesn't know that you are planning to assign nil
in the future:
var arr: NSMutableArray? = NSMutableArray()
However, the whole thing about assigning nil
to a variable that has previously held an array seems a bit dirty to me. Maybe it would be easier to use a new variable?
You haven't posted your real code so we can't do a real review but:
if CRITICAL_CONDITION {
arr = nil
}
return arr
can be more easily written as
if CRITICAL_CONDITION {
return nil
}
return arr
That will solve the problem, too, because you won't need to reassign the variable. A different approach would be to use a second variable:
var result: NSArray? = array
if CRITICAL_CONDITION {
result = nil
}
return result
or even better
let result = CRITICAL_CONDITION ? nil: array
return result;
The whole point of specifying when a variable cannot be nil
(non-optional) is the fact that optional variables are dangerous and you have to check them for nil
all the time. So, use optionals only for a short time, ideally one condition and then convert them to non-optional. In this case, use the non-optional as long as possible and only when you really need to assign nil
, convert to optional (declare a second, optional variable).
Upvotes: 3