Generics call with Type T in Swift

后端 未结 7 2001
故里飘歌
故里飘歌 2021-02-12 17:20

In my application I want to create an generic method which creates an array of object depening on the given type T.

I created the following function:

fun         


        
7条回答
  •  你的背包
    2021-02-12 18:07

    Working version of the code in the question ( second part )

    • Init is required because a function returns a generic person Type ( newPerson(as person:T) -> T )

    • I've replaced the class methods func getWorkingHours() by var workingHours { get }.. It works equally, in a more 'swifty' way.

    getWorkingHours() returns hours, as the name indicates, not a Person..

    class Person {
        required init() {}
        var workingHours: Float { get { return 40 } }
    }
    
    class Boss : Person {
        override var workingHours: Float { get { return 100 } }
    }
    
    class Worker : Person {
        override var workingHours: Float { get { return 42 } }
    }
    
    func getWorkingHours(_ person: T) -> Float {
        return person.workingHours
    }
    
    func newPerson(as person: T) -> T {
        return T()
    }
    
    // -----------------------------------------------
    
    let worker = Worker()
    let boss = Boss()
    
    print( getWorkingHours(worker) ) // prints 42.0
    print( getWorkingHours(boss) ) // prints 100.0
    
    let person = newPersonOfSameClass(as: worker)
    
    print( getWorkingHours(person) ) // prints 42.0
    

    Hope it helps.. This code is ready for copy/paste in playground.

提交回复
热议问题