gpt4 book ai didi

Swift 2.0 - 返回由函数实现确定的类型的通用工厂函数

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

这可能吗?

场景是,我想要一个函数接受一个与该函数的通用约束无关的参数,并根据该参数返回一个未知类型的结果。这些类型彼此之间没有任何关系。一个可能是一个字符串,一个可能是一个整数,一个可能是一个字符串数组等等。

我已经在协议(protocol)中使用类型别名对此进行了试验,每个符合它的对象都会设置自己的类型,并在其工作中使用类型别名。

我已经将其作为协议(protocol)进行了试验:

protocol BaseFunctionality {
typealias ReturnType
var property: ReturnType { get set }
func getData() -> ReturnType
}

然后我有几个一致的类:

class StringClass: BaseFunctionality {
typealias ReturnType = String
var property: ReturnType = "HELLO WORLD"
func getData() -> ReturnType {
return property
}
}

class IntClass: BaseFunctionality {
typealias ReturnType = Int
var property: ReturnType = 12345
func getData() -> ReturnType {
return property
}
}

所以,我想到的是:

func getIt<T: BaseFunctionality>(int: Int) -> T.ReturnType {
if (int == 0) {
let stringClass = StringClass()
return stringClass.getData() as! T.ReturnType // for some reason I have to as! this
} else {
let intClass = IntClass()
return intClass.getData() as! T.ReturnType // same as above comment
}
}

并这样调用它:

let testing = getIt(1)

但是,我收到一条错误消息,

"Cannot invoke 'getIt' with argument list of type '(int)'".

我知道编译器在弄清楚我到底想要什么作为返回类型时遇到问题,因此,我考虑提供一个闭包,将 T: BaseFunctionality 映射到它所拥有的属性。

func getIt<T:BaseFunctionality, U where U == T.ReturnType>(int:Int, unwrapType: T -> U ) -> U {
if (int == 0) {
let source = StringClass()
return unwrapType(source as! T) // for some reason, source is not a valid T
}
else {
let source = IntClass()
return unwrapType(source as! T) // see above comment
}
}

签名中对 U 的约束可能有问题,但我已经尝试了多种......

例如,我这样调用它。

let data = getIt(1, mapToType: {(unwrapType) -> String in
return unwrapType.property as String
})

然而,这会导致 Playground 上发生疯狂的事情......(崩溃)

有没有人知道如何实现这个在编译时返回类型未知的神奇函数?

这里是 swiftstub:http://swiftstub.com/800198020/?v=beta

谢谢!

最佳答案

正如Qbyte所说或

enum TextOrNum {
case Text(s: String)
case Num(x: Int)
}

func getIt(i: Int) -> TextOrNum {
if i == 0 {
return .Text("Hello")
} else {
return .Num(42)
}
}

// usage
switch getIt(0) {
case let .Num(x):
// use x return value as Int
case let .Text(s):
// use s return value as String
}

枚举的优点是编译器会检查所有情况。

关于Swift 2.0 - 返回由函数实现确定的类型的通用工厂函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32062800/

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