Expand the tuple in quick

It seems to me that this is the correct code, but it does not expand the tuple

func updateUserDefaults<T>(data:T) {
    if let data = data as? (String, Any) {
        println(data.1)
    }
}

updateUserDefaults(("loop", true))

My goal is to make this a universal installer for NSUserDefaults. The reason I use generic so that I can easily pass it in my reactive code as it should (the following expects a T → () function:

loop.producer |> map { ("loop", $0) } |> start(next: updateUserDefaults)

UPDATE:

This seems to work, it is unpacked, and can be provided as T → ()

func updateUserDefaults<T>(data:(String, T)) {
    if let value = data.1 as? Bool {
        userDefaults.setBool(value, forKey: data.0)
    } else if let value: AnyObject = data.1 as? AnyObject {
        userDefaults.setObject(value, forKey: data.0)
    }
    userDefaults.synchronize()
}
+4
source share
1 answer

You use a generic function and then access the parameter as a typed parameter.

Of course, your function should be ...

func updateUserDefaults(data: (String, Any)) {
    println(data.1)
}

updateUserDefaults(("loop", true))

When using generics, this does not mean that it will automatically recognize the scheme of the types of data that you transmit.

, , , .

, data , .

"" . .

+2

All Articles