Aleksi Sjöberg
Aleksi Sjöberg

Reputation: 1474

Optional casting of an AnyObject into Array gives an error

I was trying to do optional casting on a type of AnyObject into an array of ints, and in case it would be nil, an empty array would be stored using coalescing operator. Code:

import UIKit

let arrayAsAnyObject: AnyObject = [3, 4]

let arrayAsInts: [Int] = arrayAsAnyObject as? [Int] ?? [] // causes issue

This gives me the following issue:

Array types are now written with the brackets around the element type

If I click "Fix-it" button, it replaces the last line with

let arrayAsInts: [Int] = arrayAsAnyObject as? [[Int] ??[]

which obviously doesn't solve this. Any ideas why this happens and how to fix it? I am using Xcode 6.3 beta with Swift 1.2.

Upvotes: 0

Views: 163

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40955

This is a precedence issue between ?? and as? that is resolved in 6.3 beta 2. ?? got a precedence bump in that release, so you can now also do things like optInt == otherOptInt ?? 0 and have the default bind to the right-hand side.

If I try with the 1.2 beta 2 version of Swift, this works as-is, so I'd suggest upgrading (since this is between old and new beta versions, not between beta and release) rather than going with a parentheses fix, which would also resolve it.

Upvotes: 1

Related Questions