[Swift] StringInterpolationを使って文字列を生成したり文字列からクラスを生成する

Swiftの文字列補完(String Interpolation)の使い方をまとめます.

自作クラスをstring interpolationに対応させる

1
2
3
4
5
6
7
8
9
10
// 自作のクラスを文字列内で展開させる
extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Animal) {
        appendInterpolation("\(value.kind) name: \(value.name)")
    }
}
 
let dog = Animal(kind: "Dog", name: "Ein")
print("Animal: \(dog)")
// Animal: Dog name: Ein

String.StringInterpolationを拡張する事で対応させる事ができます。

文字列補完に新しい機能を追加する

1
2
3
4
5
6
7
8
9
10
// appendLiteral()を使えば文字を続けて追加可能
extension String.StringInterpolation {
    mutating func appendInterpolation(repeat str: String, _ count: Int) {
        for _ in 0 ..< count {
            appendLiteral(str)
        }
    }
}
 
print("appendLiteral \(repeat: "Ein ", 3)")

自分で追加した補完機能を使って文字列を生成する事ができるようになります。

上級編 String Interpolationを使ってクラスを生成する

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// string interpolationを使えば、文字列からクラスを作成する事も可能
struct SampleComponent: ExpressibleByStringLiteral, ExpressibleByStringInterpolation, CustomStringConvertible {
    struct StringInterpolation: StringInterpolationProtocol {
        var output = ""
 
        init(literalCapacity: Int, interpolationCount: Int) {
            output.reserveCapacity(literalCapacity * 2)
        }
 
        mutating func appendLiteral(_ literal: String) {
            output.append(literal)
        }
 
        mutating func appendInterpolation(hello: String) {
            output.append("Hello = \(hello)")
        }
 
        mutating func appendInterpolation(thanks: String) {
            output.append("thanks = \(thanks)")
        }
    }
 
    let description: String
 
    init(stringLiteral value: String) {
        description = value
    }
 
    init(stringInterpolation: StringInterpolation) {
        description = stringInterpolation.output
    }
}
 
let sample: SampleComponent = "Interpolation sample \(hello: "こんにちは"), \(thanks: "ありがとう")."
print(sample)

String Interpolationを使ってクラスを生成できるようになりました。
AttributedStringを作るサンプルはこの機能をうまく使っていると思います。
(参考URLを参照してください)

どうでもいいけど、String Interpolationってスペルミスしそうです。
extenstionで拡張する時とか、タイポだけで動かなくなるので注意が必要です。

参考URL

0 件のコメント :

コメントを投稿