iOS
Swift

NSArrayやNSDictionaryを、SwiftのArrayやDictionaryと相互に変換する

More than 3 years have passed since last update.


背景

ちょっと調べないと分からなかったので。


変換方法

実はほぼそのままキャストできてしまう模様。


Array

// Array -> NSArray

var nsarr: NSArray = NSArray(array: ["A", "B", "C"])
println(nsarr)

// NSArray -> Array
var arr: [String] = nsarr as [String]
println(arr)

(

A,
B,
C
)
[A, B, C]


Dictionary

// Dictionary -> NSDictionary

var nsdic: NSDictionary = NSDictionary(dictionary: ["key1": "value1", "key2": "value2"])
println(nsdic)

// NSDictionary -> Dictionary
var dic: Dictionary = nsdic as Dictionary
println(dic)

{

key1 = value1;
key2 = value2;
}
[key2: value2, key1: value1]


おまけ: Array of Dictionary

var sample: [Dictionary<String, AnyObject>] = [

["key1": "value1", "key2": "value2"],
["key3": "value3", "key4": "value4"]]

// Array of Dictionary -> NSArray of NSDictionary
var nsdicarr: NSArray = NSArray(array: sample)
println(nsdicarr)

// NSArray of NSDictionary -> Array of Dictionary
var dicarr: [Dictionary<String, AnyObject>] = nsdicarr as [Dictionary<String, AnyObject>]
println(dicarr)


output

(

{
key1 = value1;
key2 = value2;
},
{
key3 = value3;
key4 = value4;
}
)
[[key2: value2, key1: value1], [key4: value4, key3: value3]]


参考

Mac Developers blog — Convert NSMutableArray to Swift Array...

http://dev.eltima.com/post/96538497489/convert-nsmutablearray-to-swift-array