// *** before: ***
// the error came back through an NSError pointer, the result was optional,
// and nothing forced the caller to look at either of them
var error: NSError?
let text = String(contentsOfFile: "/etc/hosts",
encoding: NSUTF8StringEncoding,
error: &error)
if text == nil {
print("failed: \(error!)")
}
// *** in version 2.0: ***
// a call that may fail is marked with try, and the compiler refuses to
// forget it: either the error is caught, or the function itself throws
do {
let text = try String(contentsOfFile: "/etc/hosts",
encoding: NSUTF8StringEncoding)
print(text)
} catch {
print("failed: \(error)") // error is bound by itself, without a declaration
}
func loadAll() throws -> String {
return try String(contentsOfFile: "/etc/hosts",
encoding: NSUTF8StringEncoding)
}