func getIndex(valueToFind: T) -> Int? {...}
mutating func replaceObjectWithObject(obj1: T, obj2: T) {
if let index =
This answer is for a duplicate question stated her: Create swift array extension for typed arrays
There is a way to solve extensions to Array that are only applicable to a specific type of array. But you have to use an Array with elements of type Any, which sort of circumvents Swift's type system. But the code still works even if there are elements of other types in the array. See example below.
class Job {
var name: String
var id: Int
var completed: Bool
init(name: String, id: Int, completed: Bool) {
self.name = name
self.id = id
self.completed = completed
}
}
var jobs: [Any] = [
Job(name: "Carpenter", id: 32, completed: true),
Job(name: "Engineer", id: 123, completed: false),
Job(name: "Pilot", id: 332, completed: true)]
extension Array {
// These methods are intended for arrays that contain instances of Job
func withId(id: Int) -> Job? {
for j in self {
if (j as? Job)?.id == id {
return j as? Job
}
}
return nil
}
func thatAreCompleted() -> [Job] {
let completedJobs = self.filter { ($0 as? Job) != nil && ($0 as? Job)!.completed}
return completedJobs.map { $0 as! Job }
}
}
jobs.withId(332)
println(jobs.withId(332)?.name)
//prints "Optional("Pilot")"
let completedJobs = jobs.thatAreCompleted().map {$0.name}
println(completedJobs)
//prints "[Carpenter, Pilot]"