Swift Array.insert generics

前端 未结 5 1671
盖世英雄少女心
盖世英雄少女心 2020-12-07 03:02
func getIndex(valueToFind: T) -> Int? {...}

mutating func replaceObjectWithObject(obj1: T, obj2: T) {
    if let index =          


        
5条回答
  •  粉色の甜心
    2020-12-07 03:28

    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]"
    

提交回复
热议问题