Last active
March 20, 2019 10:11
-
-
Save bouchtaoui-dev/98dd1d9d33fd54744da5ac447b1a9d60 to your computer and use it in GitHub Desktop.
Optionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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