I am new to Swift and trying to figure out the Optional concept. I have a small piece of code in Playground which is giving me "Variable binding in a condition requires an initializer" error. Can someone please explain why and how do I fix it?
I only want to print "Yes" or "No" depending on if "score1" has a value or not. Here is the code:
import Cocoa
class Person {
var score1: Int? = 9
func sum() {
if let score1 {
print("yes")
} else {
print("No")
}
}//end sum
}// end person
var objperson = person()
objperson.sum()
The if let statement takes an optional variable. If it is nil, the else block or nothing is executed. If it has a value, the value is assigned to a different variable as a non-optional type.
So, the following code would output the value of score1 or "No" if there is none:
if let score1Unwrapped = score1
{
print(score1Unwrapped)
}
else
{
print("No")
}
A shorter version of the same would be:
print(score1 ?? "No")
In your case, where you don't actually use the value stored in the optional variable, you can also check if the value is nil:
if score1 != nil {
...
}
Writing
if let score1 {
doesn't make sense. If you want to see if score has a value, use
if score1 != nil {
or
if let score = score1 {
The last case binds a new non-optional constant score
to score1
. This lets you use score
inside the if statement.
The code in your question is similar to something I saw in the swift book and documentation and they are correct.
Your playground is just using an old version of swift which currently doesn't support this syntax. Using a beta version of XCode should fix
https://www.reddit.com/r/swift/comments/vy7jhx/unwrapping_optionals/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With