我可以在Swift中编写类型吗?

问题描述 投票:0回答:3

如何在Swift中编写类似于协议组合的类型?

例如,我有一个likes数据,这是一个字典,其值为IntString,但不是其他。

likes: {
    "1": {
        "id": "l1"
        "ts": 1551796878504
        "userId": "u1"
    }
}

目前,我使用一个变量类型,

var likes: [String: [String: Any]]

但是,我希望它是类型的

var likes: [String: [String: AlphaNum]]

我可以使用像typealias AlphaNum = String & Int或类似的东西,而不使用类或结构?

swift types composition
3个回答
2
投票

您可以创建自己的协议,让StringInt符合它:

protocol ValueProtocol {}

extension String:ValueProtocol{}
extension Int:ValueProtocol{}


var likes:[String : [String:ValueProtocol]] = ["1": [
                    "id": "l1",
                    "ts": 1551796878504,
                    "userId": "u1"
                ]
            ]

但是要使用ValueProtocols,您还必须根据需要添加getValue等函数。


3
投票

我知道这个问题已经得到了解答,但在我看来,你似乎正在尝试使用JSON,因此我强烈建议在swift中使用Decodableprotocol

可解码:可以从外部表示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

2
投票

不,你不能,因为你可以看到typealias AlphaNum = String & Int它的&运算符而不是| \\ or你不能使用[String: [String: AlphaNum]]因为内部Dictionary值基本上是String & Int,一个值不能是两种类型或者其中之一,看看这个question,因为答案是关于创建一个虚拟协议,并使用它但是IntString之间没有共享属性,但是一个,Description,因此即使使用虚拟protocol你也必须在某些时候施放,除非你只是使用Description指的answer

 protocol IntOrString {
    var description: String { get }
}

extension Int : IntOrString {}
extension String : IntOrString {}

像这样使用它,var likes: [String: [String: IntOrString]]

进入IntOrString值后,您可以使用.description属性。

© www.soinside.com 2019 - 2024. All rights reserved.