Last active
March 29, 2024 22:29
-
-
Save benvium/d6bf91f50f00628af652 to your computer and use it in GitHub Desktop.
searching arrays in apple swift. Search for matching strings and strings containing other strings.
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
class Person { | |
var name = "" | |
var age = 0 | |
init(name: String, age:Int) { | |
self.name = name | |
self.age = age | |
} | |
} | |
var people = [ Person(name: "bob", age: 23), Person(name: "alice", age: 56), Person(name: "david", age: 88)] | |
// search people for those called bob | |
let bobs = filter(people) { $0.name == "bob" } | |
println("found \(bobs.count) bobs"); | |
for person in bobs { | |
println(person.name); | |
} | |
// I can't find an equivalent to the _.find command in underscore (i.e. stop after first match..) | |
// Could probably write one I suppose. | |
let iInName = filter(people) { $0.name.rangeOfString("i") != nil } | |
println("found \(iInName.count) names with i in"); | |
for person in iInName { | |
println(person.name); | |
} | |
// Now try people over 30 | |
let notYoung = filter(people) { $0.age > 30 } | |
println("found \(notYoung.count) people over 30") | |
// map nicer than for in..! | |
notYoung.map() { println("a" + $0.name) } |
if I want to search for the name and the age?? how the filter should be.
just add expressions as you want to the { }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if I want to search for the name and the age?? how the filter should be.