如何在Swift中编写类似于协议组合的类型?
例如,我有一个likes
数据,这是一个字典,其值为Int
或String
,但不是其他。
likes: {
"1": {
"id": "l1"
"ts": 1551796878504
"userId": "u1"
}
}
目前,我使用一个变量类型,
var likes: [String: [String: Any]]
但是,我希望它是类型的
var likes: [String: [String: AlphaNum]]
我可以使用像typealias AlphaNum = String & Int
或类似的东西,而不使用类或结构?
您可以创建自己的协议,让String
和Int
符合它:
protocol ValueProtocol {}
extension String:ValueProtocol{}
extension Int:ValueProtocol{}
var likes:[String : [String:ValueProtocol]] = ["1": [
"id": "l1",
"ts": 1551796878504,
"userId": "u1"
]
]
但是要使用ValueProtocols,您还必须根据需要添加getValue
等函数。
我知道这个问题已经得到了解答,但在我看来,你似乎正在尝试使用JSON,因此我强烈建议在swift中使用Decodable
protocol
可解码:可以从外部表示docs解码自身的类型
这将轻松处理所有传入的JSON,例如:
struct decodableIncomming: Decodable {
let name: String
let ID: Int
let externalURL: URL
}
let json = """
{
"name": "Robert Jhonson",
"ID": 1234256,
"externalURL": "http://someurl.com/helloworld"
}
""".data(using: .utf8)! // data in JSON which might be requested from a url
let decodedStruct = try JSONDecoder().decode(Swifter.self, from: json) // Decode data
print(decodedStruct) //Decoded structure ready to use
不,你不能,因为你可以看到typealias AlphaNum = String & Int
它的&
运算符而不是| \\ or
你不能使用[String: [String: AlphaNum]]
因为内部Dictionary
值基本上是String & Int
,一个值不能是两种类型或者其中之一,看看这个question,因为答案是关于创建一个虚拟协议,并使用它但是Int
和String
之间没有共享属性,但是一个,Description
,因此即使使用虚拟protocol
你也必须在某些时候施放,除非你只是使用Description
指的answer,
protocol IntOrString {
var description: String { get }
}
extension Int : IntOrString {}
extension String : IntOrString {}
像这样使用它,var likes: [String: [String: IntOrString]]
。
进入IntOrString
值后,您可以使用.description
属性。