Reputation: 5108
We can declare nil
variables like below in swift 3.0
var aString : String?
then we can assign values after like this
aString = "hello"
then if we concatenate
, we have to cast
it like below
var newone: String = aString! + " stackoverflow"
But We can do the same thing like below and when we
concatenate
, we do not need toUnwrap
. why is that
.
var bStirng : String
bStirng = "hello"
var newBString : String = bStirng + " StackOveflow"
is the only advantage of using optional is that we can check whether the variable is nil or not
Upvotes: 1
Views: 322
Reputation: 5108
?
and !
with a variables means both are optional
.!
this sign means implicitly unwrapped optional.?
sign with a variable, we have to unwrap when we use it.optional
cannot be nil. Ex :
var valueOne : Int = 4 // this cannot be nil
?
menas its type is optional
var valueTwo :Int? = 8 //type of this variable is Optional Int and
this can be nil. and also when we use this we have to unwrap it and should check whethe this is nil or not like below
valueOne + valueTwo!
if let newVal = valueTwo{ valueOne + newVal //check the value is nil or not }
!
. implicitly unwrapped optional.
var valueThree : Int! = 12 // type of this variable is implicitly unwrapped optional Int we do not need to unwrap when we do any operation with it like below. this also can be nil
valueOne + valueThree
Upvotes: 1
Reputation: 611
To satisfy the compiler, we either assign values such as:
aString = "hello"
or in the case where we do not know the value ahead of time or if whether there will even be a value, we tell the compiler that the variable is of type optional.
var aString : String?
This satisfies the compiler and allows the value to be either nil or non-nil without erroring in either case within the code.
For instance, suppose you have a class to represent a user's friends and their stockImageID's and whether they have a profile picture (among the many kinds of properties you may want):
class friend {
var stockImageID: Int!
var profilePicture: UIImage?
}
You may search the Address Book for pictures of his friends (contacts) and for contacts with pictures:
myFriend.profilePicture = profilePictureFromAddressBook
However, many friends will not have photos. For those friends, you will use their stock image ID (each friend has one, note the ! which tells the compiler that every friend will have one) which is associated with a library of stock images you use to randomly assign users profile pictures.
Having the ability to make profilePicture optional is really useful here because at other areas in your code, you won't know which friends have a profilePicture and which ones don't. As an optional, you will be able to safely and elegantly handle not knowing this ahead of time by doing something like:
if let profilePicture = myFriend.profilePicture {
print("display profile picture...")
}
else {
let profilePicture = stockImageDictionary["myFriend.stockImageID"]
print("display profile picture...")
}
Hope this helps some. The use of optionals becomes more apparent with more time spent with the language. They really are quite nice imho.
Upvotes: 2
Reputation: 275055
Using optionals has a lot of advantages, and yes the main advantage, in my opinion, is that it forces you to check for a nil
value every single time.
However, you are using optionals in the wrong way (judging from the code you showed). You don't just say "Ah the weather's good today, let me make this variable an optional!" I think this is why you think there is only one advantage of using them.
Sometimes, it only makes sense to make a variable optional because the variable's nature is like that. Let's say you're writing a minesweeper game. Your model class that represents a tile on the minesweeper board might have properties like hasMine: Bool
, xPos: Int
and yPos: Int
. It also has a property that stores the number that will show up when the user clicks on the tile, numberOfMinesNearby: Int?
. Note that it is declared as an optional integer. Why? Because if that tile has a mine, no number will show up when the user clicks on it! It just explodes! Basically, the idea of storing the number of mines around that tile is inapplicable, so it has the value of nil
.
Another time when you would use optionals is when you are too lazy to create an initializer for your class, or you want to do initialization in some other method, like viewDidLoad
.
class MyModel {
var property: String?
var anotherProperty: Int?
}
class MyViewController: UIViewController {
var property: String?
var anotherProperty: Int?
override func viewDidLoad() {
property = "hello"
anotherProperty = 10
}
}
If you are sure that property
and anotherProperty
will be assigned every time you create a new MyModel
object, you can make them an implicitly unwrapped optional:
class MyModel {
var property: String!
var anotherProperty: Int!
}
class MyViewController: UIViewController {
var property: String!
var anotherProperty: Int!
override func viewDidLoad() {
property = "hello"
anotherProperty = 10
}
}
This causes the optional to be implicitly forced unwrapped whenever you use it.
I just explained two more advantages of optionals - making your code make sense and saving your time of writing initializers. You will definitely discover some more when you write more code.
Upvotes: 3
Reputation: 1363
Yes, that''s it. More information about: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330
Upvotes: 0