swift - 将结构传递给函数并在函数内创建该结构的实例

标签 swift function generics 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、结构类型的函数,然后在完成后我想返回根据数据任务请求创建的结构。

最佳答案

您需要使用协议(protocol)向编译器解释 A) 这些类型具有 .name,B) 它们具有 .greet() 函数,并且,最后,C) 它们可以仅使用 name 进行初始化。然后,在您的 greet() 全局函数中,您可以引用该协议(protocol)。最后的问题是您传入类型,并显式调用 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

关于swift - 将结构传递给函数并在函数内创建该结构的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47031167/

相关文章:

function - 经典 asp JScript 中的重载函数

ios - Swift 泛型数组

swift - ChannelInboundHandler (Swift-NIO) 中的 writeDataUnsupported

swift - 从 iOS 10 开始安全传递 NSManagedObject 线程?

postgresql - Postgres 触发器适用于 INSERT,不适用于 DELETE

function - 如何在 lisp 中使用 do?

vb.net - 在 vb.Net 中实现继承的泛型接口(interface)

java - 从 T 到 T 的 map

ios - UITableView 中的可变高度单元格仅在单元格不在 View 中时才有效

swift - Swift 的 TableView 中最多有一个复选标记