Last active
March 25, 2021 09:53
-
-
Save hmhmsh/f1a992a427e479bb8e020866a3ddea40 to your computer and use it in GitHub Desktop.
ExpressibleByStringLiteralの使い所
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 今回は、StringLiteralTypeは、String型でしか使用しないため独自Protocolを定義 | |
protocol CustomExpressibleByStringLiteral: ExpressibleByStringLiteral where StringLiteralType == String { | |
init(stringLiteral value: Self.StringLiteralType) | |
} | |
// UserのIdを表す型 | |
struct UserId { | |
let value: String | |
} | |
// ExpressibleByStringLiteralに準拠 | |
extension UserId: CustomExpressibleByStringLiteral { | |
public init(stringLiteral value: StringLiteralType) { | |
self = UserId(value: value) | |
} | |
} | |
// UserのNameを表す型 | |
struct UserName { | |
let value: String | |
} | |
extension UserName: CustomExpressibleByStringLiteral { | |
public init(stringLiteral value: StringLiteralType) { | |
self = UserName(value: value) | |
} | |
} | |
// どちらもString型だけど、違う型として定義することで、引数などへの入れ間違いを型レベルで禁止できる | |
struct User { | |
let id: UserId | |
let name: UserName | |
} | |
/* | |
* Usage | |
*/ | |
func fetch(userId: UserId) { | |
print("value: \(userId.value)") | |
} | |
// ExpressibleByStringLiteralに準拠しているため、idとnameの初期化が簡単にできる | |
let user = User(id: "abc", name: "tarou") | |
// 引数をUserId型にしているため、idとnameの入れ間違いが発生しない | |
fetch(userId: user.id) | |
//fetch(userId: user.userName) // コンパイルエラー | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment