【问题标题】:Not Able to access values with .Type swift无法使用 .Type swift 访问值
【发布时间】:2019-10-11 22:16:48
【问题描述】:

为什么我无法在下面的代码中分配和读取 Type B 的值? B.self 应该作为类型而不是实例传递,所以它应该访问 class B 中的静态变量对吗?

class A{

}

class B:A{
   static var a = 5
}

class c{
     static func a(){
        b(type: B.self)

    }
    static func b(type:B.Type){
        print(type.a)
    }

    func takeObject<T>(type:T.Type){


        print(type(of:String.self)) // String.Type
        print(type) // B
        print(type.a) // Value of type 'T' has no member 'a'
        var a :type // Use of undeclared type 'type'

    }

}
let objects : c = c()
objects.takeObject(object: B.self)

请纠正我,我是这个话题的新手,看起来很有趣。

【问题讨论】:

  • 很难说出你在问什么。首先,atakeObjects() 函数中做了什么?您要分配什么类型?为什么要打印String.Type 的值?你为什么要这样做?我唯一可以帮助您的是takeObjects() 函数的第 3 行。做print((type as! B).a)。这会将泛型类型转换为特定类型B。此外,将函数参数type 重命名为其他名称,以避免与函数type(of:) 发生冲突。抱歉,我只能用当前问题的措辞来做这些了。
  • @AlexH 对不起代码措辞,我想将自定义类型作为函数参数传递,然后使用它们。
  • 你想用它们做什么? @Tushar Sharma
  • 您会制作有限数量的可以跟踪的对象吗?
  • @AlexH 是 4 或 5。

标签: swift generics swift4


【解决方案1】:

我认为您只想添加B 类型的对象,因此您可以指定B 类型的通用T,如下所示,

class A {}

class B: A {
    static var a = 5
}

class c {
    static func a() {
        b(type: B.self)

    }
    static func b(type: B.Type){
        print(type.a)
    }

    func takeObject<T: B>(type: T.Type){
        print(type)
        print(type.a)
        var a : T
    }
}

let objects : c = c()
objects.takeObject(type: B.self)

【讨论】:

  • 如果不想具体描述 B 怎么办?
  • 当您在type.a 内部访问a 时,所有这些对象都应该是B 类的子对象,因为a 是在该类内部声明的。
猜你喜欢
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 2021-08-28
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多