简体   繁体   中英

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 (ie 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM