我可以在 Swift 中组合类型吗?

Can I compose types in Swift?

如何在 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 或类似的东西,而不使用 class 或结构吗?

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

protocol ValueProtocol {}

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


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

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

不,你不能,正如你所看到的 typealias AlphaNum = String & Int 它是 & 运算符而不是 | \ or 并且你不能使用 [String: [String: AlphaNum]] 因为内部 Dictionary 值基本上是 String & Int ,一个值不能是两种类型之一,看看这个 , as the answers is about creating a dummy protocol, and use that however there are no shared properties between Int and String but one, Description, therefore even with dummy protocol you would have to cast at some point, unless you are only using Description referring to the ,

 protocol IntOrString {
    var description: String { get }
}

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

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

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

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

Decodable: A type that can decode itself from an external representation 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