Created
September 14, 2016 12:55
-
-
Save niwatako/e286002b344d4698334ad6fc53977d46 to your computer and use it in GitHub Desktop.
この型パラメーターの T かっこ良くないですか? #CodePiece #iphonekyoto
This file contains hidden or 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
func get<T: JSONPrimitive>(_ key: String) throws -> T { // この T は型推論で左辺の型になる | |
guard let value = dictionary[key] else { | |
throw JSONDecodeError.missingRequiredKey(key) | |
} | |
// Int に let number: Int = get("key") とすればここは Int にキャストを試み、失敗したらエラーになる。 | |
guard let typed = value as? T else { | |
throw JSONDecodeError.unexpectedType( | |
key: key, | |
expected: T.self, | |
actual: type(of: value)) | |
} | |
return typed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment