I'm rewriting this calculator app with swift2.
There is an error in this part.
How do I rewrite it with swift2?
I understand that you are going to check if there are any contents in the variable.Please.
The linked video has Jun 8, 2014, so it's from the beta version even before Swift 1.0.As long as you're learning Swift from now on, you'll still have a lot of difficulties, so you'd better look for another tutorial as soon as possible.If you don't mind English, you'll find some tutorials updated with the latest Swift using the calculator app.
However, the code that says, "I get an error in this part.":
should have also received an error in the beta version at that time (if you had declared num1, num2 as
Int as you wrote).In the early beta, if it's an optional type, it could have been written that way, so in the original video num1, num2 might have been
Optional<Int> instead of Int type.
If you try to get the correct code in , you need to fix it first.
With this way of writing, if the lastNumber or answerField.text values cannot be interpreted as integers, the app crashes.(Think that
! in Swift (other than the prepositional expression for negation) means "crash and let me know if you're wrong.")
The initializer of type
Int is failable (sorry, I don't know the exact translation) and is the type that returns nil if an integer is given an uninterpreted string.And as a syntax for defining variables that determine whether or not nil is nil, Swift has an if-let syntax (called optional binding) (from the beta era), so you should use it.
Rewrite the entire
enterTapped method and it looks like this:
The text property of the UILabel can be nil (and I don't want to crash the app just because it was nil), so I changed it to include the default value using the
If you try to rewrite the old code to Swift2, it tends to be less recommended (but easier to rewrite).Unless you want to practice that kind of rewriting itself (which is also from the old beta version...), you should switch to a new tutorial quickly.
Additional (forgotten writing)
The showError was nested in enterTapped, but it doesn't make much sense, so it's supposed to be a normal method.
Forgot to write one more
If it's Swift2, you should use the guard, and the code is likely to be pointed out.Try to see how you can write it yourself.
© 2023 OneMinuteCode. All rights reserved.