【发布时间】: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