Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
John Sanchez
3,325 PointsOptionals question swift
Why is this not an error
var x: String x = "Hello World" Shouldn't an error be thrown since the type of x is String and before x is assigned to "Hello World" it is equal to nil (not a string)?
I thought that you had to do something like this: var x: String? x = "Hello World"
Thanks.
1 Answer
miguelcastro2
Courses Plus Student 6,573 PointsWhen you declare x:
var x: String
The variable x is uninitialized, but it is not equal to nil since the variable has not been declared as an optional by using the ? directive. When you set x equal to "Hello World", it then initializes a String to that variable. However, you could not use a statement like this:
if x == nil {
println("X is not set")
}
Unless you set the variable as an optional:
var x: String?
In your code you are basically saying that the variable x can only ever have the value of a String