LoginSignup
0
0

More than 1 year has passed since last update.

【Swift】associatetype

Posted at

用途

protocolの中で使用される定義で、どんな型でもあてはまるよう汎用性を持たせるために使用する。

実行環境

No 項目 内容
1 OS Mac
2 Swift 5.7.2
3 Xcode 14.2

実行例

protocol Collection {
    associatedtype Item
    var count: Int { get }
    subscript(index: Int) -> Item { get }
    mutating func append(_ item: Item)
}

struct UppercaseStringsCollection: Collection {
    
    var container: [String] = []
    
    var count: Int { container.count }
    
    mutating func append(_ item: String) {
        guard !container.contains(item) else { return }
        container.append(item.uppercased())
    }
    
    subscript(index: Int) -> String {
        return container[index]
        
    }
}
var upper = UppercaseStringsCollection() // append がmutatingのため、upperインスタンスを変更してしまうためvarで宣言
upper.append("string")
print(upper.container) // ["STRING"]
print(upper[0]) // "STRING"

上の実行例のように、subscriptを使用すると、インスタンス[]の形で添字をつければ、subscript内の戻り値が返される。

参考

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