使用performSegue时出现奇怪的转换行为

时间:2019-04-25 11:25:20

标签: ios swift xcode segue

我有以下代码:

protocol Greeter {
    func printHi()
}

struct Person: Greeter {
    func printHi() {
        print("hi")
    }
}

class ViewController: UIViewController {
    var person: Person?

    @IBAction func tap(_ sender: Any) {
        person = Person()
        perform(with: person!)
    }

    func perform(with greeter: Greeter) {
        performSegue(withIdentifier: "test", sender: greeter)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let greeter = sender as? Greeter
        let person = sender as? Person
        let greeter2 = sender as? Person as? Greeter

        print("Greeter: \(greeter)")
        print("Person: \(person)")
        print("Greeter2: \(greeter2)")
    }
}

它给出了以下输出:

Greeter: nil
Person: Optional(testSegue.Person())
Greeter2: Optional(testSegue.Person())

有人可以解释发生了什么事吗?

其他信息:

  • 如果在调用nil之前进行相同的打印,我不会得到任何performSegue
  • "test"设置是从此ViewController到另一个的“显示”设置
  • 我已使用此代码创建了一个示例项目,这表明该代码与不干净的状态或类似内容无关

WORKAROUND

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let greeter = sender as? AnyObject as? Greeter

    print("Greeter: \(greeter)")
}

0 个答案:

没有答案