Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include optional in array in Swift

Tags:

swift

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.

like image 887
Encore PTL Avatar asked Jun 07 '14 00:06

Encore PTL


People also ask

How do you declare an array in Swift?

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.

Are arrays in Swift dynamic?

But arrays in Swift are dynamic: you can grow them. And it is a lot less clear whether Swift is efficient in this case.


2 Answers

If you're just going to be inserting either Ints or nils, 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.)

like image 53
STO Avatar answered Nov 16 '22 02:11

STO


Just like this:

let arr: AnyObject?[] = [1, 2, nil, 4, 5]

it makes the Array of type AnyObject?

like image 33
Connor Avatar answered Nov 16 '22 04:11

Connor