Generics call with Type T in Swift

后端 未结 7 977
逝去的感伤
逝去的感伤 2021-02-12 17:14

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:09

    You need to make initializer required, then add let realType = T.self line and replace T() with realType().

    class Person {
        required init() { }
    
        func getWorkingHours() -> Float {
            return 40.0
        }
    }
    
    class Boss : Person {
        override func getWorkingHours() -> Float {
            println(100.0)
            return 100.0
        }
    }
    
    class Worker : Person {
        override func getWorkingHours() -> Float {
            println(42.0)
            return 42.0
        }
    }
    
    func getWorkingHours() -> T {
        let realType = T.self
        var person = realType()
        person.getWorkingHours()
    
        return person
    }
    

提交回复
热议问题