只需在swift 2.1中抛出异常消息

时间:2016-02-05 03:00:49

标签: ios swift

我只是在寻找一些东西。如果出现某种错误。你怎么说Exception(" Missing Information")

class func Lookup() throws -> String{
    let defaults = NSUserDefaults.standardUserDefaults()
    if let url = defaults.objectForKey("url"){

        return url as! String
    }
    if let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist"), dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
        if let url = dictionary["url"] {
            defaults.setValue(api, forKey: "url")
            defaults.synchronize()
            return url as! String
        }
    }
    return Exception("missing data") //something like this
}

1 个答案:

答案 0 :(得分:3)

enum LookupError: ErrorType {
    case MissingData
    case UnknownError
    etc..
}

class func lookup() throws -> String{
    ...blahblah
    guard url != nil else {
        throw LookupError.MissingData
    }    
}

然后您可以将其称为

do {
    try func()
} catch LookupError.MissingData {
    // do something
} catch LookupError.UnknownError {
    // do something else
}