I want to write the code for moving the screen
@IBAction funcgoSecond(_sender:Any){
let secondVC = self.storyboard ?.instantiateViewController (withIdentifier: "second")
present(secondVC!, animated:true, completion:nil)
}
I wrote the code to connect to the button, but I don't understand if secondVC
in presents(secondVC!~...
has !
.I understand that it will be solved if I make it optional, but could you tell me the specific reason for this error as it seems to occur frequently in the future?Thank you for your cooperation.
This line of your code:
let secondVC=self.storyboard?instantiateViewController (withIdentifier: "second")
The return type of the instantiateViewController(withIdentifier:)
method you are using is defined as non-optional UIViewController
, which is called in optional chaining (?
).
In the optional chain, if Therefore, the By the way, you may know that In this code, the (I moved a part of the comment to the body, though it was too much.) If you've asked questions before you've done enough research, please ask them to do more research in advance in the future. However, it is difficult to select keywords other than optional content, so it may not have been a hit as much as you want. Here are some tips for finding information online. We look forward to creating a great app using search engines, QA sites, textbooks and whatever is available.self.storyboard
on the left side of ?
was nil
, the expression as a whole must return nil
, so the optional value of self.storyboard?instantiateViewController(withIdentifier:"second"> is
secondVC
data type declared as the initial value is also UIViewController?
, which requires action such as forced unwrapping (!
) to be used in places where optional is not allowed.(secondVC
data type is determined by type inference by looking at Quick Help on the right sidebar of Xcode.)!
of forced unwrap should not be used unless you are 100% confident that it will never be nil
, but if you need to force unwrap in the end, applying it as soon as possible will make it easier to locate the original nil
when the app crashes.@IBAction funcgoSecond(_sender:Any){
let secondVC = self.storyboard!.instantiateViewController (withIdentifier: "second")
present(secondVC, animated:true, completion:nil)
}
secondVC
data type is non-optional UIViewController
, so you do not need !
to call the present(_:animated:completion:)
method.
(Unfortunately, Swift terminology doesn't have a regular translation, so the English word Optional might be better, but there are still a lot of articles in Japanese.)
(However, please note that it has nothing to do with whether it's right or best.)
(There is only an English version, but it's a simple expression that you can understand if you understand a word.)
© 2024 OneMinuteCode. All rights reserved.