I want to insert an optional in an array as follows
let arr: AnyObject[] = [1, 2, nil, 4, 5]
The following expression throws a compile error saying
Cannot convert the expression's type 'AnyObject[]' to type 'AnyObject'
How can I made this work? I need optional or nil value in the array even though I know I shouldn't.
We declare an array in Swift by using a list of values surrounded by square brackets. Line 1 shows how to explicitly declare an array of integers. Line 2 accomplishes the same thing as we initialize the array with value [1, 2] and Swift infers from that that it's an array of integers.
But arrays in Swift are dynamic: you can grow them. And it is a lot less clear whether Swift is efficient in this case.
If you're just going to be inserting either Int
s or nil
s, use
Swift < 2.0
var arr: Int?[] = [1, 2, nil, 4, 5]
Swift >= 2.0
var arr: [Int?] = [1, 2, nil, 4, 5]
Swift 3x
var arr: Array<Int?> = [1, 2, nil, 4, 5]
This can be done for any type (not just Int
; that is if you want an array
to hold a specific type but allow it to be empty in some indices, like say a carton of eggs.)
Just like this:
let arr: AnyObject?[] = [1, 2, nil, 4, 5]
it makes the Array of type AnyObject?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With