4

This seems valid code to me but it doesn't unwrap 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 generic setter for NSUserDefaults. The reason why i use a generic is so i can pass it easily in my reactive code as followed (next expects a function of T->():

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

UPDATE:

it seems that this seems to work, it unwraps 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()
}
Andy Jacobs
  • 15,187
  • 13
  • 60
  • 91

1 Answers1

2

You are using a generic function and then accessing the parameter like a typed parameter.

Surely your function should be...

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

updateUserDefaults(("loop", true))

When using generics it doesn't mean it will automatically know the type schema of the data you pass in.

It means it doesn't know the schema of the data you pass in but also that it doesn't and shouldn't care.

Also, the parameter data is not optional so there isn't a need to unwrap it.

You can't "unwrap" a generic parameter into a known type. It doesn't work that way.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • The problem is that this method will be called form a method that accepts (T)->() i will update my question for that. But when i try to unwrap my data property i check if its a tuple so my question remains.. – Andy Jacobs Jul 07 '15 at 12:47