【问题标题】:Pass a Struct to a function and create an instance of that struct inside the function将结构传递给函数并在函数内创建该结构的实例
【发布时间】:2017-10-31 08:46:51
【问题描述】:

我想创建一个接受 Struct Type 的函数,并且在该函数内部,我想返回创建的 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、结构类型的函数,然后在完成时我想返回基于数据任务请求创建的结构。

【问题讨论】:

  • 我很困惑...a 是什么,他的T 是什么?

标签: swift function generics struct


【解决方案1】:

您需要使用协议向编译器解释 A)这些类型有一个 .name,B)它们有一个 .greet() 函数,最后,C)它们可以用 @987654323 初始化@。在您的 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

【讨论】:

  • 谢谢。协议是关键,现在我对泛型、协议和结构有了更多的了解。
猜你喜欢
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
相关资源
最近更新 更多