gpt4 book ai didi

swift - 可散列结构不存储其值类型 Array 的变量

转载 作者:行者123 更新时间:2023-11-30 12:28:32 25 4
gpt4 key购买 nike

我原以为计数是 3,但结果是 0。我已经连续编码了 9 个小时,所以也许我已经盯着这个看太久了。

我对 Swift 的理解可能有一个漏洞。任何帮助表示赞赏。

struct Service {

enum Category: String {

case hospital, pharmacy, surgery

var title: String {
switch self {
case .hospital:
return "Hospitals"
case .pharmacy:
return "Pharmacies"
case .surgery:
return "Surgeries"
}
}

}

let title: String
let category: Category
var fetched: [Annotation] = []

}

extension Service {

init(category: Category) {
self.title = category.title
self.category = category
}

}

extension Service: Equatable {

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

}

extension Service: Hashable {

var hashValue: Int {
return category.hashValue
}

}

class Annotation: NSObject {

let name: String

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

}

class Services {

var currentService: Service {
didSet {
if currentService != oldValue {
if let previousService = previousServices[currentService.category.rawValue] {
currentService = previousService
} else {
previousServices[currentService.category.rawValue] = currentService
}
}
}
}

private var previousServices: [String : Service] = [:]

init() {
currentService = Service(category: .hospital)
}

}

let services = Services()
services.currentService.fetched = [Annotation(name: "1"),Annotation(name: "2"),Annotation(name: "3")]
services.currentService = Service(category: .surgery)
services.currentService.fetched = [Annotation(name: "4"),Annotation(name: "5")]
services.currentService = Service(category: .hospital)
print(services.currentService.fetched.count)

最佳答案

didSet 中 else-case 的行应该是:

previousServices[oldValue.category.rawValue] = oldValue

否则您将存储新值。

关于swift - 可散列结构不存储其值类型 Array<classobjects> 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43872933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com