jjatie
jjatie

Reputation: 5332

How to cast Array<String> to NSArray full of NSString

In working with CloudKit, all types need to be Objective-C foundation classes. Since most types used in CloudKit are bridged from Swift to Obj-C there isn't any issue (i.e. record[key] = 1 as NSNumber), but I'm having trouble converting an Array<String> to the appropriate CloudKit type (a string list in the CK dashboard). I figured

record[key] = ([myString] as [NSString]) as NSArray

would work, but no such luck. How can I convert this?

Upvotes: 2

Views: 2809

Answers (3)

Simon
Simon

Reputation: 1076

the real issue here is that the subscript is broken, you can use setObject(forKey:) to use native Swift types!

edit:
I was wrong, setObject(forKey:) does not work, however I managed to get passed this issue temporarily by using setValue(forKey:) instead. I also extended CKRecord with a subscript to be used until Apple fixes the issue.

extension CKRecord {
    @nonobjc
    subscript(key: String) -> Any? {
        set {
            setValue(newValue, forKey: key)
        }
        get {
            return value(forKey: key)
        }
    }
}

Upvotes: 0

Grimxn
Grimxn

Reputation: 22507

Just bridging will work, together with NSArray's array constructor:

let a = ["a", "bc", "def"]
let nsa = NSArray(array: a)
nsa[0] is NSString // *** true ***

Upvotes: 3

iSaalis
iSaalis

Reputation: 622

var str = "Hello, playground"

var arrayString:[String] = [str]

var arrayNSString = NSMutableArray()

for p in 0..<arrayString.count
{
   arrayNSString.add(arrayString[p] as NSString)
}

Hope this helps.

Upvotes: 0

Related Questions