简体   繁体   中英

Pass a string to a second view controller

I'm trying to pass a string to a second view controller. The string is the title of the new view controller. To pass the string I can use 2 solutions and both solutions work correctly but for me is not so clear the difference. Can someone explain me the differences?

Here the first solution:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "settime") {
            let svc = segue.destinationViewController as! timeSetting;
            //Assign the new title
            svc.toPass = "New Title"

        }
    }

Here the second solution:

   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "settime") {
            let svc = segue.destinationViewController as? timeSetting;
            //Assign the new title
            svc!.toPass = "New Title"

        }
    }

The variable toPass is defined in this way in the second viewController:

 var toPass:String = "Title"

Both of your code is working and it works in the same way.

The only difference is about the optional casting.

Optional in Swift

They are the same.

If there is a difference, it is the time of unwrap the optional value. In the first solution, the type of svc is timeSetting . In the second solution, the type of svc is timeSetting? .

Both solutions will perform the same action. In my opinion, the first solution is preferred because it express your intent more precisely.

By stating let svc = segue.destinationViewController as! timesetting let svc = segue.destinationViewController as! timesetting you state that the destination view controller is certain to be of the type timesetting .

The second form tests to see if the destination view controller is of the type timeSetting . If it is, then the variable svc will have a non-nil value.

If you were to define another segue of the same name that presents a different type of view controller, then both solutions will fail; the first one on the as! clause and the second one when you try to unwrap svc! , which would be nil.

两者都可以使用,但我认为最好的方法是像下面这样拆开可选组件:

if let svc = segue.destinationViewController as? timeSerting { svc.toPass = "xx" }

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