gpt4 book ai didi

swift - 试图 swift 概括

转载 作者:搜寻专家 更新时间:2023-11-01 06:19:24 28 4
gpt4 key购买 nike

我正在尝试在 Swift、Xcode 7.3(所以是 Swift 2.2)中创建一个通用类,但我似乎无法让它通过编译器:

protocol Struct1Protocol {
}

struct Struct1 {
var name1: String
}

protocol Struct2Protocol {
}

struct Struct2: Struct2Protocol {
var name2: String
}

class StructDependent<T> {
func setupFrom<T:Struct1Protocol>(value: T) {
print("we want to setup StructDependent with struct 1")
}

func setupFrom<T:Struct2Protocol>(value: T) {
print("we want to setup StructDependent with struct 2")
}
}

class A<T> {
func test(value: T) {
let structInstance = StructDependent<T>()
// this gives a compiler error:
// Cannot invoke 'setupFrom' with an argument list of type '(T)'
structInstance.setupFrom(value)
}
}

想法是拥有一个可以从不同结构设置的 StructDependent。如果类已使用兼容结构实例化,则类 A 应该能够调用 setupFrom。像这样:

let a = A<Struct1>()
let v = Struct1(name1: "")
a.test(v)

我该怎么做?我在这里有点受阻,所以欢迎所有想法。

最佳答案

我觉得你想多了。我会以更简单的方式看待这个案例,完全不用泛型来做;相反,我们只是使用协议(protocol)作为两个结构的一种父类(super class)型(就像如果结构是类,我们将使用父类(super class)一样):

protocol StructProtocol {
var name : String {get set}
func setup()
}

struct Struct1 : StructProtocol{
var name: String
func setup() {}
}

struct Struct2 : StructProtocol {
var name: String
func setup() {}
}

class StructDependent {
func setup(s:StructProtocol) {
s.setup() // or not, I don't care...
// or you could just switch on the type, e.g.:
switch s {
case is Struct1: // ...
case is Struct2: // ...
default: break
}
}
}

class A {
func test(value: StructProtocol) {
let structInstance = StructDependent()
structInstance.setup(value)
}
}

如果 StructDependent 本身 确实需要根据调用 setup 的方式做不同的事情,它可以切换到实际类型。但第一种方式会更好,我们只调用 Struct1 和 Struct2 都知道如何做的东西,每个都以自己的方式。

关于swift - 试图 swift 概括,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37010947/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com