42
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-03-04

背景

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

変換方法

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

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

42
40
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?