Ios 如何在Swift中引用类型本身
这是Objective-C版本Ios 如何在Swift中引用类型本身,ios,Ios,这是Objective-C版本 + (NSDictionary *)modelContainerPropertyGenericClass { return @{ "picIds" : String, "picInfos" : [WBPicture class] }; } 我这样做了,但编译器抛出了错误 static func modelContainerPropertyGenericClass() -> [String: AnyClass]
+ (NSDictionary *)modelContainerPropertyGenericClass {
return @{
"picIds" : String,
"picInfos" : [WBPicture class]
};
}
我这样做了,但编译器抛出了错误
static func modelContainerPropertyGenericClass() -> [String: AnyClass] {
return [
"picIds" : String.self,
"picInfos" : WBPicture.self
]
}
试试这个
static func modelContainerPropertyGenericClass() -> [String : Any.Type] {
return ["picIds": String.self, "picInfos": WBPicture.self]
}
试试这个
static func modelContainerPropertyGenericClass() -> [String : Any.Type] {
return ["picIds": String.self, "picInfos": WBPicture.self]
}
您的问题是,
String
不是Class
的类型,而是它的结构。字符串的定义是
public struct String {
/// An empty `String`.
public init()
}
您需要定义它Any.Type
static func modelContainerPropertyGenericClass() -> [String : Any.Type] {
return ["picIds": String.self, "picInfos": UITableViewCell.self]
}
您的问题是,String
不是Class
的类型,而是它的结构。字符串的定义是
public struct String {
/// An empty `String`.
public init()
}
您需要定义它Any.Type
static func modelContainerPropertyGenericClass() -> [String : Any.Type] {
return ["picIds": String.self, "picInfos": UITableViewCell.self]
}
问题是String
不符合AnyObject
,因为它是结构
,而AnyClass
只是AnyObject.Type的类型别名
将返回类型更改为Any.type
也将接受结构和基本类型,如Int
、Float
和Bool
:
static func modelContainerPropertyGenericClass() -> [String: Any.Type] {
return [
"picIds": String.self,
"picInfos": WBPicture.self
]
}
要保持Objective-C兼容性,请使用Objective-C兼容类替换结构和基本类型:
static func modelContainerPropertyGenericClass() -> [String: AnyClass] {
return [
"picIds": NSString.self,
"picInfos": WBPicture.self,
"int": NSNumber.self,
]
}
问题是String
不符合AnyObject
,因为它是结构
,而AnyClass
只是AnyObject.Type的类型别名
将返回类型更改为Any.type
也将接受结构和基本类型,如Int
、Float
和Bool
:
static func modelContainerPropertyGenericClass() -> [String: Any.Type] {
return [
"picIds": String.self,
"picInfos": WBPicture.self
]
}
要保持Objective-C兼容性,请使用Objective-C兼容类替换结构和基本类型:
static func modelContainerPropertyGenericClass() -> [String: AnyClass] {
return [
"picIds": NSString.self,
"picInfos": WBPicture.self,
"int": NSNumber.self,
]
}
你在数组结构中有一个额外的方括号]
,你在数组结构中有一个额外的方括号]
,这个不编译它不编译:(是的,现在编译;)这个不编译它不编译:(是的,现在编译;)非常感谢!它很有效,但我只能把一个答案标记为正确答案,非常抱歉,非常感谢!它很有效,但我只能将一个答案标记为正确答案,非常抱歉,非常感谢!,它起作用了!顺便说一下,我想把这个函数添加到一个协议中,并将其标记为可选的,但是编译器说的方法不能是objc协议的成员,因为它的结果类型不能用Objective-C表示。有没有一种方法可以将协议中的函数标记为可选的,而不将objc放在协议关键字之前?很遗憾,没有,可选协议需要Objective-C兼容性,否则它们的行为就像需要实现的标准面向对象接口。如果需要,您可以切换回AnyClass
,并使用Objective-C类,如NSString
和NSNumber
。看看我的最新答案。哦,我明白了。谢谢你的帮助!非常感谢!,它起作用了!顺便说一下,我想把这个函数添加到一个协议中,并将其标记为可选的,但是编译器说的方法不能是objc协议的成员,因为它的结果类型不能用Objective-C表示。有没有一种方法可以将协议中的函数标记为可选的,而不将objc放在协议关键字之前?很遗憾,没有,可选协议需要Objective-C兼容性,否则它们的行为就像需要实现的标准面向对象接口。如果需要,您可以切换回AnyClass
,并使用Objective-C类,如NSString
和NSNumber
。看看我的最新答案。哦,我明白了。谢谢你的帮助!