Recent work • Rewrite Hatena Blog for iOS with Swift • Hatena Summer Internship 2015 “iOS App Course” • Sample code: hatena/swift-Sample-GitHubSearch • Textbook: Available soon • Secret projects‥
Which is better? enum JSONDecodeError: ErrorType { case MissingRequiredKey(String) case UnexpectedType(key: String, expected: Any.Type, actual: Any.Type) } enum JSONDecodeError: ErrorType { case MissingRequiredKey case UnexpectedType }
Which is better? enum JSONDecodeError: ErrorType { case MissingRequiredKey(String) case UnexpectedType(key: String, expected: Any.Type, actual: Any.Type) }
Do more better enum JSONDecodeError: ErrorType, CustomDebugStringConvertible { case MissingRequiredKey(String) case UnexpectedType(key: String, expected: Any.Type, actual: Any.Type) var debugDescription: String { switch self { case .MissingRequiredKey(let key): return "Required key '\(key)' missing" case let .UnexpectedType(key: key, expected: expected, actual: actual): return "Unexpected type '\(actual)' was supplied for '\(key): \(expected)'" } } }
Do more better struct JSONObject { let raw: [NSString : AnyObject] /** Get typed value for the key - parameters: - key: JSON key - returns: Typed value */ func getValue(key: String) throws -> T { guard let value = raw[key] else { throw JSONDecodeError.MissingRequiredKey(key) } ...
Do more better struct JSONObject { let raw: [NSString : AnyObject] /** Get typed value for the key - parameters: - key: JSON key - returns: Typed value - throws: JSONDecodeError */ func getValue(key: String) throws -> T { guard let value = raw[key] else { throw JSONDecodeError.MissingRequiredKey(key) } ...
as NSError enum MyError: ErrorType { case SuperError } let error = MyError.SuperError as NSError print(error.localizedDescription) // The operation couldn’t be completed. (Module.MyError error 0.)
Error handling in practice • Functions can return Optional type or throw error • ErrorType should provide informations in detail • Documentation comment with possible error kind • Treating ErrorType as NSError have some problems