Skip to content

Instantly share code, notes, and snippets.

@bouchtaoui-dev
Last active March 20, 2019 10:11
Show Gist options
  • Save bouchtaoui-dev/98dd1d9d33fd54744da5ac447b1a9d60 to your computer and use it in GitHub Desktop.
Save bouchtaoui-dev/98dd1d9d33fd54744da5ac447b1a9d60 to your computer and use it in GitHub Desktop.
Optionals
// variables declaration
var str = "Hello, playground"
var x = Int(10)
// class definition
class ParentClass {
func writeText(_ text: String?) -> Void {
print("\(text ?? "empty text")")
}
}
var p: ParentClass? = ParentClass()
p?.writeText("Hello there!")
// Optionals
var myString:String?
// Check if myString is not nil
if myString != nil {
print(myString!)
} else {
print("myString has nil value")
}
// Assign myString with a value
myString = "I'm a text 😁"
// Check it again
if myString != nil {
print(myString!)
}
// This is the recommended way to check if variable has a value
if let count = myString?.count {
print(count)
}
// But a bit cumbersome to write this again and again
// I want something like this:
// #if myString?.count {
// # ...
// #}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment