问题
I'm having a dictionary, with values, i'm calling it to populate a field
if let userdata: NSDictionary = self.fbdata {
println(userdata["email"]) // print Optional(email@domain.com)
vc.email.text = userdata["email"] as? String ?? "" // raise a nil error
}
As put in the code, the userdata["email"] exists and has a value, printed by println, anyway at the next line i have a nil optional exception raised (and even the default "" value isn't used)
I don't see what i'm doing wrong here
回答1:
it's an outlet to a textfield but it seems to not unwrap in the prepareForSegue function
That comment reveals your misconception. Things happen in a order, which I discuss here: https://stackoverflow.com/a/29552710/341994
So, by design, prepareForSegue happens before the new view controller has its view - or its outlets. Conversely, the first moment when its outlets are connected is its own viewDidLoad, which is later.
Your real mistake, though, is deeper. One view controller has no business setting or talking to another view controller's outlets and thus manipulating its interface. Instead, set things up so that the destination view controller has an ordinary property which you can set. In viewDidLoad, that view controller than checks that property, retrieves the value, and sets its own interface through its outlet.
So, to sum up: prepareForSegue is your chance to initialize the new view controller. But that's all. The new view controller will then later control its own view — as the name implies! And it will do this starting in its own viewDidLoad and later.
来源:https://stackoverflow.com/questions/29711806/swift-non-nil-optional-value-raising-a-nil-exception