1

As far as I understand, an Array in Swift will be automatically casted to NSArray if necessary.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html says on that account

„When you bridge from an NSArray object to a Swift array, the resulting array is of type AnyObject[]. An object is AnyObject compatible if it is an instance of an Objective-C or Swift class, or if the object can be bridged to one. You can bridge any NSArray object to a Swift array because all Objective-C objects are AnyObject compatible. Because all NSArray objects can be bridged to Swift arrays, the Swift compiler replaces the NSArray class with AnyObject[] when it imports Objective-C APIs.“

Auszug aus: Apple Inc. „Using Swift with Cocoa and Objective-C.“ iBooks. https://itunes.apple.com/de/book/using-swift-cocoa-objective/id888894773?mt=11

In my Playground the following fails with

[Position] is not convertible to 'NSArray'

import Foundation

enum Position : String {
    case TopLeft = "Top Left", TopCenter = "Top Center", TopRight = "Top Right", BottomLeft = "Bottom Left", BottomCenter = "Bottom Center", BottomRight = "Bottom Right"
    // pattern to iterate enums by http://www.swift-studies.com/blog/2014/6/10/enumerating-enums-in-swift
    static let allValues : [Position] = [TopLeft, TopCenter, TopRight, BottomLeft, BottomCenter, BottomRight]
}

let a : NSArray = Position.allValues

As fas as I understand Position.allValues is a valid Array, though static. Do I miss something or can anybody help? Thanks.

2 Answers 2

4

The problem is that allValues is an array of Position. But Position is an enum, and a Swift enum can't cross the bridge to Objective-C.

So, yes, [Int] or [String] will magically cross the bridge to become an NSArray, but not [Position] - exactly what the error message told you.

Sign up to request clarification or add additional context in comments.

Comments

2

As a complement to @matt's answer, since I notice you're using raw values in your enum, you can convert the array of enum cases to an array of strings, by just taking the raw value for each case, and using the map method:

let a : NSArray = Position.allValues.map { $0.rawValue }

3 Comments

Actually this gives me the error Position does not have a member named rawValue in my Playground (after another crash form SourceKit...)
Are you using Xcode 6.0.x? If yes, then you have to replace rawValue with toRaw(). If it's not that, can you tell me what's the error?
Yes, that was it. Very cool! Thanks! Haven't upgraded to 6.1 yet since I am currently on a mobile connection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.