40
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

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

背景

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

変換方法

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
40
Help us understand the problem. What are the problem?