gpt4 book ai didi

swift - 无法使用 .Type swift 访问值

转载 作者:行者123 更新时间:2023-11-28 07:20:26 26 4
gpt4 key购买 nike

为什么我无法在下面的代码中从类型 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)

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

最佳答案

因为我认为您只想添加 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)

关于swift - 无法使用 .Type swift 访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349070/

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