Skip to content

Instantly share code, notes, and snippets.

@niwatako
Created September 14, 2016 12:55
Show Gist options
  • Save niwatako/e286002b344d4698334ad6fc53977d46 to your computer and use it in GitHub Desktop.
Save niwatako/e286002b344d4698334ad6fc53977d46 to your computer and use it in GitHub Desktop.
この型パラメーターの T かっこ良くないですか? #CodePiece #iphonekyoto
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