0

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

例如,我有一个likes数据,它是一个字典,其值具有Intor String,但没有其他值。

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

当前,我使用带类型的变量,

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

但是,我希望它是类型

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

我可以typealias AlphaNum = String & Int在不使用类或结构的情况下使用类似或类似的东西吗?

4

3 回答 3

3

我知道这个问题已经得到解答,但在我看来,您正在尝试使用 JSON,因此我强烈建议您Decodable快速使用该协议

可解码:一种可以从外部表示文档中自行解码的类型

这将轻松处理所有传入的 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
于 2019-03-25T10:15:38.610 回答
2

不,你不能,因为你可以看到typealias AlphaNum = String & Int&不是运算符| \\ or,你不能使用[String: [String: AlphaNum]],因为内部Dictionary值基本上是String & Int,一个值不能是两种类型中的任何一种,看看这个问题,因为答案是关于创建一个虚拟协议,并使用它Int,但是String只有一个,之间没有共享属性Description,因此即使使用 dummyprotocol你也必须在某个时候强制转换,除非你只使用Description引用答案

 protocol IntOrString {
    var description: String { get }
}

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

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

进入IntOrStringvalue 后,您可以使用.descriptionproperty 。

于 2019-03-25T10:01:55.960 回答
2

您可以创建自己的协议并让StringInt遵守它:

protocol ValueProtocol {}

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


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

但是要使用 ValueProtocols,您还必须getValue根据需要添加类似的功能。

于 2019-03-25T09:55:32.407 回答