Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // OPTIONALS
- // Make an optional value = nil
- var someNilValue: Int? = nil
- // UNWRAPPING OPTIONALS
- var name: String? = nil
- if let unwrapped = name {
- print("\(unwrapped.count) letters")
- } else {
- print("no letters")
- }
- // UNWRAPPING WITH GUARD LET
- // In this example, function has an optional parameter.
- // If the parameter is nil, the function will exit
- func receiveMessage(_ message: String?) {
- guard let text = message else {
- print("There's no text in the message.")
- return
- }
- print("Your message is: \(text)")
- }
- receiveMessage(nil) // "There's no text in the message"
- receiveMessage("Hi!") // "You message is: Hi!"
- // Another example:
- func stringCounter(_ word: String?) -> Int? {
- guard let word = word else {
- return nil
- }
- return word.count
- }
- let myWord: String? = nil
- if let myWordCount = stringCounter(myWord) {
- print(myWordCount)
- } else {
- print("You didn't send a word.") // You didn't send a word
- }
- // FORCE UNWRAPPING
- let str = "5"
- let num = Int(str)!
- // IMPLICITELY UNWRAPPED OPTIONALS
- // Variable starts off as nil but we know it will eventually have a value when we need it.
- // Therefore, no need to use "if let" or "guard."
- let age: Int! = nil
- // NIL COALESCING
- // Swift unwraps the optional and return a value if there is one, otherwise
- // a default value is provided
- func username(for id: Int) -> String? {
- if id == 1 {
- return "Taylor Swift"
- } else {
- return nil
- }
- }
- let user = username(for: 15) ?? "Anonymous"
- print(user) // "Anonymous"
- // OPTIONAL CHAINING
- // In this example, Swift checks whether there is a value for names.first
- // If there isn't, it won't proceed with uppercased method.
- let names = ["John", "Paul", "George", "Ringo"]
- let beatle = names.first?.uppercased() // "JOHN"
- // OPTIONAL TRY
- // Code we've seen in a previous lesson (Do, Try, Catch)
- enum PasswordError: Error {
- case obvious
- }
- func checkPassword(_ password: String) throws -> Bool {
- if password == "password" {
- throw PasswordError.obvious
- }
- return true
- }
- // Using try? -- changes throwing functions into fuction that return an optional
- if let result = try? checkPassword("password") {
- print("Result was \(result)")
- } else {
- print("d'oh!")
- }
- // try! -- when you know for sure that function will not fail.
- // If it does throw and error, your code will crash
- try! checkPassword("sekrit")
- print("no error thrown!")
- // FAILABLE INITIALIZERS
- // Use init? rather than init()
- // If the condition is met, the struct will return an optional
- // that you can unwrap in the manner you want.
- struct Person {
- var id: String
- init?(id: String) {
- if id.count == 9 {
- self.id = id
- } else {
- return nil
- }
- }
- }
- // TYPECASTING
- // In this example, both Fish and Dog inherit from Aninal()
- class Animal { }
- class Fish: Animal { }
- class Dog: Animal {
- func makeNoise() {
- print("Woof!")
- }
- }
- // Create array of pets:
- let pets = [Fish(), Dog(), Fish(), Dog()]
- // Using a for loop, we check to see which pet is of the Dog class
- // "as?" will return an optional, either 1) nil if the typecast failed
- // or 2) the converted type
- for pet in pets {
- if let dog = pet as? Dog {
- dog.makeNoise()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment