Skip to content

Instantly share code, notes, and snippets.

@benvium
Last active March 29, 2024 22:29
Show Gist options
  • Save benvium/d6bf91f50f00628af652 to your computer and use it in GitHub Desktop.
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.
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) }
@benvium
Copy link
Author

benvium commented Aug 30, 2014

I really like the $0 syntax in swift, so short and simple (represents the first parameter to the closure, e.g the person instance to filter with).

@bobgodwinx
Copy link

:) nice one ninja..

@hindalsayyar
Copy link

if I want to search for the name and the age?? how the filter should be.

@abdoh476
Copy link

abdoh476 commented Jan 1, 2019

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