- 直和型欲しいよね
- TypeScriptでいう
let a : string | number
みたいな奴
- TypeScriptでいう
- Swiftにはありません
- でも
enum
で似たような事ができます
enum Foo {
case a(Int)
case b(String)
}
// Fooの値にはInt, Stringどちらも持たせられる
let fooA = Foo.a(123)
let fooB = Foo.b("hello")
// パターンマッチで値を取り出す
let printFoo = { (foo: Foo) in
switch foo {
case .a(let a):
print(a)
case .b(let b):
print(b)
}
}
printFoo(fooA) // 123
printFoo(fooB) // hello
// if letで値を取り出す
if case let .b(b) = fooB {
print(b) // hello
}
使用例
Result
enum Result<T> {
case Result(T)
case Error(Error)
}
エラーが出るまで処理を繰り返す、みたいなコードを書いてみる
enum Result<T> {
case success(T)
case failure(MyError)
}
enum MyError: Error {
case tooSmallError
}
// 10%の確率で失敗する処理
let doit: () -> Result<String> = {
let n = Float.random(in: 0..<1)
if n < 0.1 {
return .failure(.tooSmallError)
}
return .success("SUCCESS!")
}
// 失敗するまで繰り返す
loop: while true {
switch doit() {
case .success(let msg):
print(msg)
case .failure(let err):
print(err)
break loop // 失敗したのでループを抜ける
}
}
Option
Swiftはoptional value (Int?
)があるので要らんけど
enum Option<T> {
case Some(T)
case None
}
let printIfSome = { (opt: Option<T>) in
switch opt {
case .Some(let x):
print(x)
case .None:
print("NONE")
}
}
printIfSome(.Some(123)) // 123
printIfSome(.None) // NONE