Skip to content

Instantly share code, notes, and snippets.

@el-hoshino
Last active February 18, 2017 00:41
Show Gist options
  • Save el-hoshino/19d30bf6ddf5ed40422e1accc7412da2 to your computer and use it in GitHub Desktop.
Save el-hoshino/19d30bf6ddf5ed40422e1accc7412da2 to your computer and use it in GitHub Desktop.
配列の特定要素を抽出するのに for 文の代わりに if 文を使いましょう ref: http://qiita.com/lovee/items/1ae88d41b573b5d1012c
let list = ["Apple", "Boy", "Serval Cat"]
func search(for target: String) {
for item in list {
if item.lowercased().hasSuffix(target.lowercased()) {
print("We have a \(item)")
return
}
}
print("We don't have a \(target)")
}
search(for: "cat") // We have a Serval Cat
let list = ["Apple", "Boy", "Serval Cat"]
func search(for target: String) {
if let target = list.first(where: {$0.lowercased().hasSuffix(target.lowercased())}) {
print("We have a \(target)")
} else {
print("We don't have a \(target)")
}
}
search(for: "cat") // We have a Serval Cat
let list = ["Apple", "Boy", "Serval Cat"]
func search(for target: String) {
if let target = list.retrieve({$0.lowercased().hasSuffix(target.lowercased())}) {
print("We have a \(target)")
} else {
print("We don't have a \(target)")
}
}
search(for: "cat") // We have a Serval Cat
let list = ["apple", "boy", "cat"]
func search(for target: String) {
if list.retrieve({$0 == target}) != nil {
print("We have a \(target)")
} else {
print("We don't have a \(target)")
}
}
search(for: "dog") // We don't have a dog
let list = ["Apple", "Boy", "Serval Cat"]
func search(for target: String) {
if let target = list.filter({$0.lowercased().hasSuffix(target.lowercased())}).first {
print("We have a \(target)")
} else {
print("We don't have a \(target)")
}
}
search(for: "cat") // We have a Serval Cat
let list = ["Apple", "Boy", "Serval Cat"]
func search(for target: String) {
if let target = list.filter({$0.lowercased().hasSuffix(target.lowercased())}).first {
print("We have a \(target)")
} else {
print("We don't have a \(target)")
}
}
search(for: "cat") // We have a Serval Cat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment