我想创建一个接受结构类型的函数,并且在该函数内,我想返回创建的结构的实例。
例如:
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/