Skip to content

Instantly share code, notes, and snippets.

@TakahashiIkki
Last active June 11, 2018 04:58
Show Gist options
  • Save TakahashiIkki/4b4a02d76c7917728f5b387d21d7d0ac to your computer and use it in GitHub Desktop.
Save TakahashiIkki/4b4a02d76c7917728f5b387d21d7d0ac to your computer and use it in GitHub Desktop.
swift_begin_day13
// Optional<Wrapped>型のエラー処理イメージ
struct Customer {
let id: Int
let name: String
let email: String
}
func findCustomer(byId id: Int) -> Customer? {
let customers = [
Customer(id: 1,
name: "Customer1",
email: "[email protected]"),
Customer(id: 2,
name: "Customer2",
email: "[email protected]"),
]
for customer in customers {
if customer.id == id {
return customer
}
}
return nil;
}
let id = 1;
if let customer = findCustomer(byId: id) {
print("Found: Name = \(customer.name)")
} else {
print("Error Not Found")
}
// Result<T, Error>型 のエラー処理イメージ
// Result<T, Error>型を実装
enum Result<T, Error> {
case success(T) // .successの場合は T型 の連想値を持つ。
case failure(Error) // .failureの場合は Error型 の連想値を持つ。
}
// 今回用に自前でデータベースのレコードについてのエラーをまとめて定義しておく。
enum DatabaseRecordError {
case entryNotFound
case duplicatedEntry
case invalidEntry(reason: String)
}
struct Customer {
let id: Int
let name: String
let email: String
}
func findCustomer(byId id: Int) -> Result<Customer, DatabaseRecordError> {
let customers = [
Customer(id: 1,
name: "Customer1",
email: "[email protected]"),
Customer(id: 2,
name: "Customer2",
email: "[email protected]"),
]
for customer in customers {
if customer.id == id {
return .success(customer)
}
}
// 失敗した事とエラーの詳細 .entryNotFound(登録無し)を記述する。
return .failure(.entryNotFound);
}
let id = 10;
result = findCustomer(byId: id)
switch result {
case let .success(name):
print("データ取得出来ました \(name)")
case let .failure(error):
switch error {
case .entryNotFound:
print("データが見つかりませんでした。")
case .duplicatedEntry:
print("既に登録されているデータです。")
case .invalidEntry(let reason):
print("予期せぬエラーが発生しました。\(reason)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment