【问题标题】:Return Generic Type in a function with Swift (Cannot convert return expression of type...)使用 Swift 在函数中返回通用类型(无法转换类型的返回表达式......)
【发布时间】:2017-05-28 17:14:18
【问题描述】:

我对 swift 中的泛型有疑问。让我们公开我的代码。

可解析协议:

protocol Parsable {
    associatedtype T
    var value: String {get set}
    init(value: String)
    func parseString() -> T
}

通用类:

class ParsableGeneric<T: Parsable> {
    var value: String
    init(v: String) {
        value = v
    }

    func parse() -> T{
        return T(value: self.value)
    }
}

Int 类型的实现:

class ParsableIntNew: ParsableGeneric<IntParse> {}

struct IntParse: Parsable {
    func parseString() -> Int {
        return Int(value)!
    }
    var value: String
    typealias T = Int
}

然后我有一个这样的函数,我想返回一个 ParsableGeneric 类型:

func test<T: Parsable>() -> ParsableGeneric<T> {
        let intclass = ParsableIntNew(v: "54")
        let number: Int = intclass.parse().parseString()
        return intclass
    }

但我在return intclass 中有一个错误(无法将“ParsableIntNew”类型的返回表达式转换为“ParsableGeneric”类型的返回表达式

为什么会这样。我正在返回正确的值。

谢谢,我希望我能找到一个好的解决方案。

【问题讨论】:

    标签: swift generics


    【解决方案1】:

    您的test() 函数基本上承诺“我将为任何T 返回一个ParsableGeneric&lt;T&gt; 对象,即Parsable”。但是,该实现只返回一个ParsableIntNew,即它仅在TIntParse 时才有效。

    想象一下,当您还有一个 BoolParse: Parsable 时会发生什么,编译器得出结论,当您调用 test() 时,TBoolParse。即使本例中的函数返回类型是ParsableGeneric&lt;BoolParse&gt;,该函数仍将返回ParsableGeneric&lt;IntParse&gt;

    【讨论】:

    • 嘿,谢谢您的贡献。在这种情况下你打算怎么做?使用一些枚举来包装值?我不想做的是返回 Any,因为不是类型安全的。
    • 不客气。你的test 函数应该做什么?
    • 我在这个函数之外有一个映射,这个映射调用了一个返回 ParsableGeneric 的函数。然后我可以调用 test().parse().parseString() 并获取将数组转换为这个通用值的值。如果我在测试函数中返回 Any 然后在测试函数中直接返回 test().parse().parseString() ,它就可以工作
    • 对不起,我不明白。什么样的地图?什么是“数组”?你想达到什么目的?
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    相关资源
    最近更新 更多