LoginSignup
2
1

More than 5 years have passed since last update.

Swiftで配列をキャスト(型変換)する

Last updated at Posted at 2016-11-15

Swiftで配列の型をキャストする

タイトルの通りですが、[ProtocolA] → [StructB]みたいな形にキャストして、StructB以外を除いた配列を作るやり方です。
O(N)で処理時間増えます。

サンプルコード

import Foundation

protocol ProtocolA {
    var title: String { get }
}

struct StructA: ProtocolA {
    var title: String
}

struct StructB: ProtocolA {
    var title: String
    var subTitle: String
}

let ob1 = StructA(title: "1")
let ob2 = StructB(title: "2", subTitle: "2")
let ob3 = StructB(title: "3", subTitle: "3")

let arr: [ProtocolA] = [ob1, ob2, ob3]

// [StructB]
let arr2 = arr.flatMap { $0 as? StructB }

arr2.forEach { print($0.subTitle) }

実行結果

2
3
2
1
2

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
2
1