Hashable struct不存储值类型Array <class objects =“”>的变量

时间:2017-05-09 14:44:23

标签: swift syntax

我原本期望得到3分,但是得到了0.我已经连续编了9个小时,所以也许我一直在盯着这个。

我对斯威夫特的理解可能存在漏洞。任何帮助赞赏。

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)

1 个答案:

答案 0 :(得分:0)

else-case的didSet中的行应为:

previousServices[oldValue.category.rawValue] = oldValue

否则您将存储新值。