1
votes

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

2 Answers

4
votes

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.

2
votes

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 }