我有这些我想变异的结构:
public struct CheckoutViewModel {
var sections: [Section]
var total: String
public struct Section {
var title: String
var description: String
var kind: Kind
var expandState: ExpandState
enum Kind {
case products([ProductOrderViewModel])
case shippingMode(SelectableArray<ShippingMode>)
case shippingTarget(SelectableArray<ShippingKind>)
case billingAddress(SelectableArray<Address>)
case payment(SelectableArray<PaymentProvider>)
case promoCode(String?)
case legalAdvice(userAccepted: Bool)
}
}
}
struct SelectableArray<T> {
var selectedIndex: Int?
let options: [T]
init(options: [T]) {
self.options = options
self.selectedIndex = nil
}
mutating func select(atIndex: Int) throws -> T {
guard atIndex < options.count else {
throw SelectableArrayError.outOfBoundsIndex
}
selectedIndex = atIndex
return options[atIndex]
}
var selectedElement: T? {
guard let selectedIndex = selectedIndex else { return nil }
return options[selectedIndex]
}
}
我想在 SelectableArray 中使用这个变异 func select() 方法,我从一个变异函数链中调用它(因为 Sections 嵌套在一个结构中)
extension CheckoutViewModel {
mutating func select(atIndexPath indexPath: IndexPath) {
sections[indexPath.section].select(atIndex: indexPath.row)
}
}
extension CheckoutViewModel.Section {
mutating func select(atIndex idx: Int) {
switch kind {
case .shippingMode(var modes):
do { _ = try modes.select(atIndex: idx) } catch { return }
default:
return nil
}
dump(self) // Here self hasn't changed
}
}
问题是 CheckoutViewModel 结构永远不会发生变异。我猜这个 switch 不是一个变异函数,所以var modes
在那个 switch 里面是不可变的,然后下面的函数是否会发生任何变异都没有关系。我设法做的解决方法是:
mutating func select(atIndex idx: Int) {
switch kind {
case .shippingMode(var modes):
do {
_ = try modes.select(atIndex: idx)
self.kind = .shippingMode(modes)
} catch { return }
default:
return
}
}
你对这个问题有什么其他的解决方案吗?有什么mutating switch
我可以使用的功能吗?