How to add nil value to a NSArray in swift?

CLOX

NSArray.init(array: [Any])

NSArray has an initial function whose parameter is [Any]. But not [Any?], so, how to add a nil value to this array?

rmaddy

NSArray/NSMutableArray don't allow you to store nil values in the array. This is why none of the Swift APIs allow optional values.

If you really need to something for nil, use NSNull() though I'm not 100% sure how that will work with Core Data.

And Swift actually does this for you. If you pass a Swift array of optionals, any nil values get converted to NSNull. Example:

var array = [Int?]()
array.append(4)
array.append(nil)
let nsa = array as NSArray
print(nsa) // (4, "<null>")
print(type(of: nsa[1])) // NSNull

Note that using let nsa = NSArray(array: array) instead of let nsa = array as NSArray worked without warning under Swift 4.0 but gives a warning as of Swift 4.1.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related