Lorenzo
Lorenzo

Reputation: 3387

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"

Upvotes: 0

Views: 79

Answers (4)

Bobj-C
Bobj-C

Reputation: 5426

Both will work but in my opinion the best way is to unwrap the optional like the following:

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

Upvotes: 1

Drewf
Drewf

Reputation: 414

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 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.

Upvotes: 1

user4385051
user4385051

Reputation:

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

The only difference is about the optional casting.

Optional in Swift

Upvotes: 2

Zhao
Zhao

Reputation: 924

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?.

Upvotes: 1

Related Questions