LoginSignup
9
9

More than 5 years have passed since last update.

Swift1.2 で追加されたSet<T> を使ってみた。

Last updated at Posted at 2015-04-24

はじめに

Swift1.2からNSSetの代替としてSetが追加されたので使ってみた。

NSSetとの違い

  • 型がある
var oldSet = NSSet(array: ["oldValue1", "oldValue2"])
var oldValue1: String
oldValue1 = oldSet.anyObject() as! String //キャストが必要

var newSet = Set<String>(arrayLiteral: "newValue1", "newValue2")
var newValue1: String
newValue1 = newSet.first!                 // キャスト不要
  • Mutableの扱い
var oldMutableSet = NSMutableSet(array: ["oldValue1", "oldValue2"]) // NSMutableSet として宣言する必要がある
oldMutableSet.addObject("oldValue3")

var oldImmutableSet = NSSet(array: ["oldValue1", "oldValue2"]) // NSSetで宣言するとImmutableになる
oldImmutablSet.addObject("oldValue3")                          // コンパイルエラー

var newMutableSet = Set<String>(arrayLiteral: "newValue1", "newValue2") // varで宣言すれば自動でMutableになる
newMutableSet.insert("newValue3")

let newImmutableSet = Set<String>(arrayLiteral: "newValue2", "newValue2") // letで宣言すると自動でImmutableになる
newImmutableSet.insert("newValue3")                                       // コンパイルエラー

既存のプロジェクトに導入する際の注意点

これまでNSSetを引数に取っていたメソッドの引数がNSSetからSetに変更されている。

/* SKScene のtouchesBeganの例 */

// Xcode6.2まで
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)

// Xcode6.3から
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)

そのまま移行しようとするとビルドエラーになる。

9
9
0

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
9
9