swift - Swift 中泛型变量的解决方法

标签 swift variables generics tuples type-alias

所以我有一个类型别名元组

public typealias MyTuple<T> = (key: T, value: String)

在我的 ViewController 中,我想声明一个具有通用数据类型的 MyTuple 数组,因为我还不知道键的类型。然而,来自this在 Swift 中不可能有泛型变量。还有其他解决方法如下,但我都不喜欢它们中的任何一个。谁有更好的想法?

class ViewController: UIViewController {
    var array1 = [MyTuple<T>]() // compile error of course

    var array2 = [MyTuple<Any>]() // no point as I'd use `Any` for MyTuple

    func getArray<T>(array: Array<MyTuple<T>>) -> Array<MyTuple<T>> {
        return array // not a good approach
    }
}

最佳答案

我认为解决这个问题的通常方法是将类型决策“推”到依赖链的上游,到 View Controller :

class ViewController<T>: UIViewController {
    var array: [MyTuple<T>]
}

这是有道理的,因为您可能会将 Controller 视为“foo Controller ”,其中“foo”是 T 的具体值。 (“宠物 Controller ”、“产品 Controller ”等)但是,在知 Prop 体类型之前,您当然无法创建数组的实例。

关于swift - Swift 中泛型变量的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469650/

相关文章:

c# - 使用泛型装箱和拆箱

swift - 用于 nil 过滤的通用 Swift 字典扩展

ios - Xcode 11.4 不生成自定义意图类

swift - Alamofire 不下载 PDF

Java - 比较两个字符串并将值分配给第三个变量?

django - 检测 Django 模板中未设置的变量

java - 好的模式? <X extends Exception> ... method() 抛出 X

ios - 如何模拟 NSUbiquitousKeyValueStore 进行单元测试?

list - TCL:检查变量是否为列表

Java 泛型 : What is the compiler's issue here? ("no unique maximal instance")