简体   繁体   中英

Generic Type in Swift as Return Value

I would like to implement some code so that I can call something like:

NSUserDefaults("key1", "value1")
let s = NSUserDefaults("key1") // "value1" expected
NSUserDefaults("key2", 2.01)
let s = NSUserDefaults("key2") // 2.01 expected

I have some code in concept as below, but obviously it's not going to work. So my question is, instead of writing a series of functions like class func bool(key: String, _ v: Bool? = nil) -> Bool? is there any way to take the advantage of generic please?

extension NSUserDefaults {
    class func object<T: AnyObject>(key: String, _ v: T? = nil) -> T? {
        if let obj: T = v {
            NSUserDefaults.standardUserDefaults().setObject(obj, forKey: key)
            NSUserDefaults.standardUserDefaults().synchronize()
        } else {
            return NSUserDefaults.standardUserDefaults().objectForKey(key) as T?
        }
        return v
    }
}

Your syntax is going to wind up being very poor. This line can't work as written:

let s = NSUserDefaults("key1") // "value1" expected

Swift has to pick a type for s at compile time, not run time. So the only type it can assign here is Any (not even AnyObject is expansive enough if you want to return Double since Double is not AnyObject ).

That means you have to explicitly call out let s : Any = ... (because Swift wisely won't let you create Any implicitly), and then you're going to wind up with an Any that you have to type-check somehow. When you're done, you're going to come full circle to objectForKey() .

Even if you could get this syntax working, you shouldn't try to overload a single function syntax to do opposite things. That's very confusing. If you were going to build an extension like this, you should probably make it a subscript. That way you'd say defaults["key1"] and defaults["key2"] = 2.01 . That's something may be able to build (though there will still be type annotation headaches required to deal with AnyObject? ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM