Skip to content

Instantly share code, notes, and snippets.

@letsspeak
Last active October 10, 2017 02:13
Show Gist options
  • Save letsspeak/e5eab040d1b30c6533c801a46edb1e30 to your computer and use it in GitHub Desktop.
Save letsspeak/e5eab040d1b30c6533c801a46edb1e30 to your computer and use it in GitHub Desktop.
Swift optional is empty or nil
//
// 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
}
}
//
// 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
}
}
//
// 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
}
}
@letsspeak
Copy link
Author

javascriptの var hoge = fuga || '' に近い挙動

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment