swift - 可以通过结构扩展 Swift 字典吗?

标签 swift generics struct swift-extensions

我已经尝试了 extension of Dictionary where <String, AnyObject> 中的解决方案但它不会为我编译。

我只是想将字典扩展限制为 struct 类型。有什么办法可以做到这一点吗?

import Cocoa

struct Foo: Hashable {
    let bar: String

    static let predefinedFoo = Foo(bar: "something")

    var hashValue: Int { return bar.hashValue }

    public static func ==(lhs: Foo, rhs: Foo) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}


struct Baz {
    let isSpecial: Bool
}


extension Dictionary where Key: Foo, Value: Baz { // Note that the == syntax does not compile, either
    var hasSpecialPredefined: Bool {
        return self[.predefinedFoo]?.isSpecial ?? false
    }
}

let test: [Foo: Baz] = [.predefinedFoo: Baz(isSpecial: true)]

test.hasSpecialPredefined

使用上面的代码,我得到了两个编译错误:

error: type 'Key' constrained to non-protocol type 'Foo'
error: type 'Value' constrained to non-protocol type 'Baz'
error: '[Foo : Baz]' is not convertible to '<<error type>>'
    test.hasSpecialPredefined
    ^~~~

是否可以通过结构来限制扩展?如果不能,为什么不呢?这似乎非常合理。


Note that Foo and Bar, here, are not under my control. They represent structs that are defined in an external module, and the dictionary I want to extend also comes from this module. Answers should assume Foo will always be a struct, and that struct will always be the key type for the dictionary.

最佳答案

试试我的版本

1。代码(带结构)

import Foundation

struct Foo: Hashable {
    let bar: String

    static let predefinedFoo = Foo(bar: "something")

    var hashValue: Int { return bar.hashValue }

    static func ==(lhs: Foo, rhs: Foo) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

struct Baz {
    let isSpecial: Bool
    init(isSpecial: Bool) {
        self.isSpecial = isSpecial
    }
}

extension Dictionary where Key: Any, Value: Any {
    var hasSpecialPredefined: Bool {
        for key in keys {
            if let _key = key as? Foo, _key == .predefinedFoo, let value = self[key] as? Baz {
                return value.isSpecial
            }
        }
        return false
    }
}

let foo1 = Foo(bar: "ddddd")
var test: [Foo: Baz] = [foo1: Baz(isSpecial: true)]
print("\(test), hasSpecialPredefined: \(test.hasSpecialPredefined)")
test[.predefinedFoo] =  Baz(isSpecial: true)
print("\(test), hasSpecialPredefined: \(test.hasSpecialPredefined)")

结果

enter image description here

2。代码(带类)

import Foundation

class Foo: Hashable {
    let bar: String

    init(bar:String) {
        self.bar = bar
    }

    static let predefinedFoo = Foo(bar: "something")

    var hashValue: Int { return bar.hashValue }

    public static func ==(lhs: Foo, rhs: Foo) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

class Baz: AnyObject {
    let isSpecial: Bool
    init(isSpecial: Bool) {
        self.isSpecial = isSpecial
    }
}

extension Dictionary where Key: Foo, Value: Baz {
    var hasSpecialPredefined: Bool {
        for key in keys {
            if key == .predefinedFoo {
                return self[key]?.isSpecial ?? false
            }
        }
        return false
    }
}

let foo1 = Foo(bar: "ddddd")
var test: [Foo: Baz] = [foo1: Baz(isSpecial: true)]
print ("hasSpecialPredefined: \(test.hasSpecialPredefined)")
test[.predefinedFoo] =  Baz(isSpecial: true)
print ("hasSpecialPredefined: \(test.hasSpecialPredefined)")

关于swift - 可以通过结构扩展 Swift 字典吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40766657/

相关文章:

swift - 当我尝试放大时 map 不断反弹

json - Swift - 参数类型不符合预期类型

objective-c - Swift 3 中的 withMemoryRebound 不适用于 Objective-C 结构指针

ios - Swift - 如何防止在强制退出时关闭套接字?

ios - 在 Swift 中的自定义单元格之间切换

使用动态协议(protocol)类型的 Swift 动态类型初始化

java - 方法返回类型来实现多个接口(interface) - 再次

c# - 通用委托(delegate)的使用

c# - 我可以在重载的结构运算符中使用常量参数吗?

c - 如何将 strtok 返回的指针中的数据存储到结构中而不丢失?