将Struct传递给函数并在函数内创建该struct的实例

时间:2017-10-31 08:46:52

标签: swift function generics struct

我想创建一个接受结构类型的函数,并且在该函数内部,我想返回创建的Struct的实例。

例如:

struct Person {
  var name: String
  func greet() {
    print("Hi person \(self.name)")
  }
}

struct Animal {
  var name: String
  func greet() {
    print("Hi animal \(self.name)")
  }
}

// T is the stuct type, so I can pass either Person or Animal.
// name is the name string.
func greet<T>(_ a: T, name: String) {
  let thingToGreet: a = a(name: name)
  thingToGreet.greet()
}

// Pass the struct type and a string.
greet(Person, name: "Johny")

这甚至可能吗? 在应用程序中,我想创建一个接受URL的函数,结构类型然后在完成时我想返回基于数据任务请求创建的结构。

1 个答案:

答案 0 :(得分:3)

您需要使用协议向编译器解释A)这些类型具有.name,B)它们具有.greet()函数,并且最后,C)它们可以被初始化只有name。在greet()全局函数中,您可以参考协议。最后的皱纹是您传入的类型,并且您明确地调用init(name:) ...

protocol HasName {
    var name: String { get set }
    func greet()
    init(name: String)
}

struct Person: HasName {
    var name: String
    func greet() {
        print("Hi person \(self.name)")
    }
}

struct Animal: HasName {
    var name: String
    func greet() {
        print("Hi animal \(self.name)")
    }
}

// ** We demand T follows the protocol, 
// ** & declare A is a type that follows the protocol, not an instance
func greet<T: HasName>(_ A: T.Type, name: String) { 
    let thingToGreet = A.init(name: name) // ** A(name: ) doesn't work
    thingToGreet.greet()
}

// Pass the struct type and a string.
greet(Person.self, name: "Johny") // ** .self returns the type