Encore PTL
Encore PTL

Reputation: 8214

How to include optional in array in 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.

Upvotes: 12

Views: 14855

Answers (5)

STO
STO

Reputation: 634

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.)

Upvotes: 21

Bruce1q
Bruce1q

Reputation: 522

let ar: AnyObject[] = [1,2,nil,3] is illegal because nil is not convertible to AnyObject.

let a: AnyObject?[] = [1,3,nil,2] or let a: Int?[] = [1,3,nil,2] works.

If you need an Objective-C bridgeable Array use

let a: AnyObject[] = [1, 2, NSNull(), 4, 5]

Upvotes: 3

iluvcapra
iluvcapra

Reputation: 9464

It's a cheat, but if you're using the nil as a sentinel it might be advisable to just use Tuples, one element being a Bool to rep the validity of the second.

var arr = [(true, 1), (true, 2) , (false, 0) , (true, 4),(true,5)]

Upvotes: 1

GoZoner
GoZoner

Reputation: 70175

You can't use AnyObject:

 18> let ar : AnyObject?[] = [1, 2, nil, 4, 5]
<REPL>:18:25: error: cannot convert the expression's type 'AnyObject?[]' to type 'AnyObject?'
let ar : AnyObject?[] = [1, 2, nil, 4, 5]
                        ^~~~~~~~~~~~~~~~~

But you can use Any:

 18> let ar : Any?[] = [1, 2, nil, 4, 5]
ar: Any?[] = size=5 {
  [0] = Some {
    Some = <read memory from 0x7f8d4b841dc0 failed (0 of 8 bytes read)>
  }
  [1] = Some {
    Some = <read memory from 0x7f8d50da03c0 failed (0 of 8 bytes read)>
  }
  [2] = Some {
    Some = nil
  }
  [3] = Some {
    Some = <read memory from 0x7f8d4be77160 failed (0 of 8 bytes read)>
  }
  [4] = Some {
    Some = <read memory from 0x7f8d4be88480 failed (0 of 8 bytes read)>
  }
}

The Apple documentation makes this clear:

“Swift provides two special type aliases for working with non-specific types:
o AnyObject can represent an instance of any class type.
o Any can represent an instance of any type at all, apart from function types.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

It appears that Int and probably other primitive types are not subtypes of a class type and thus AnyObject won't work.

Upvotes: 5

Connor
Connor

Reputation: 64664

Just like this:

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

it makes the Array of type AnyObject?

Upvotes: 7

Related Questions