perform segue and send tuple as sender

2019-09-11 00:47发布

I've been trying to set a tuple to the sender object when doing a perform segue like:

performSegue(withIdentifier: "", sender: ("hello", "hello2"))

But inside override func prepare(for segue: UIStoryboardSegue, sender: Any?) I'm getting cast exception when trying to cast sender as (String, String)

It seems that only the first element of the tuple is in sender.

I'd expect since sender is of type Any? I could use a tuple as variable?

Has anyone else experienced this?

2条回答
Anthone
2楼-- · 2019-09-11 01:21

Even if the argument sender is not supposed to be used to pass any data or it may not be a good practice, I find it useful and clean. I don't think it would confuse people of a working team if its short and simple. I think Apple's API some way gets it the way Obj-C treats it.

I've tried some ways to pass it and find a way I'd use:

In array:

    let tuple = ("string1", "string2")
    performSegue(withIdentifier: "theSegue", sender: [tuple])

So you get:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let data = sender as? [Any] {
        if let first = data.first {
            print(first)
        }
    }
}

Or as a dictionary:

    let tuple = ("string1", "string2")
    performSegue(withIdentifier: "theSegue", sender: ["userInfo":tuple])

So you get:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let data = sender as? [String:Any] {
        if let userInfo = data["userInfo"] {
            print(userInfo)
        }
    }
}
查看更多
干净又极端
3楼-- · 2019-09-11 01:43

Per the documentation, the sender is supposed to be the object that is initiating the segue; this is not a place for you to stuff data to pass to the destination viewcontroller. Instead you should put it in a property in your view controller and then use it to set the destination view controller's properties in prepareForSegue.

Anyways, to answer your question, here is how you cast back from Any? to a tuple of (String, String)

let b = ("g", "f")
let a: Any? = b
if let c = a as? (String, String) {
    print (c)
}
查看更多
登录 后发表回答