Last active
October 10, 2017 02:13
-
-
Save letsspeak/e5eab040d1b30c6533c801a46edb1e30 to your computer and use it in GitHub Desktop.
Swift optional is empty or nil
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
// | |
// check if array is empty or nil | |
// | |
class Example { | |
func check(_ array: [String]?) { | |
if (array ?? []).isEmpty == true { | |
print("array is empty or nil") | |
} else { | |
print("array is not empty or nil") | |
} | |
} | |
func example { | |
check(nil) // => array is empty or nil | |
check([]) // => array is empty or nil | |
check(["abc"]) // => array is not empty or nil | |
} | |
} |
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
// | |
// check if class is nil, or class member is nil or empty | |
// | |
class Person { | |
let name: String? | |
init(name: String?) { | |
self.name = name | |
} | |
} | |
class Example2 { | |
func check(_ person: Person?) { | |
if (person?.name?.isEmpty ?? true) { | |
print("invalid") | |
} else { | |
print("valid") | |
} | |
} | |
func example2 { | |
check(nil) // => invalid | |
check(Person(name: nil)) // => invalid | |
check(Person(name: "")) // => invalid | |
check(Person(name: "mei")) // valid | |
} | |
} |
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
// | |
// check if class is nil, or class member is nil | |
// | |
class Person { | |
let name: String? | |
init(name: String?) { | |
self.name = name | |
} | |
} | |
class Example3 { | |
func check(_ person: Person?) { | |
if person?.name == nil { | |
print("invalid") | |
} else { | |
print("valid") | |
} | |
} | |
func example3 { | |
check(nil) // => invalid | |
check(Person(name: nil)) // => invalid | |
check(Person(name: "")) // => valid | |
check(Person(name: "mei")) // valid | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
javascriptの var hoge = fuga || '' に近い挙動