更改关联枚举的值

时间:2019-03-19 11:04:45

标签: swift struct enums

我有这个associated enum:

public typealias TextFieldInfo = (type: TextFieldType, title: String, entry: String)

public enum TextFieldType {
    case text
    case number
    case capitalLetter
    case date
    case entry
}

public enum TextFieldModelEnum {
    case generic(type: TextFieldType, title: String)
    case entry(type: TextFieldType, title: String, entry: String)

    var info: TextFieldInfo {
        switch self {
        case .generic(let type, let title):
            return (type, title, "")
        case .entry(let type, let title, let entry):
            return (type, title, entry)
        }
    }
}

我正在尝试在以下方法中更改值entry,但第一行却给我一个错误:

  

不能分配给'String'类型的不可变表达式

extension ThirdViewController: TextProtocol {
    func getText(text: String) {
        self.array[self.rowListSelected].info.entry = text
        let indexPaths = [IndexPath(row: self.rowListSelected, section: 0)]
        self.tableView.reloadRows(at: indexPaths, with: .none)
        print(text)
    }
}

2 个答案:

答案 0 :(得分:1)

我想我终于想出了如何使用set作为计算属性的方法

var info: TextFieldInfo { 
    get {
        switch self {
        case .generic(let type, let title):
            return (type, title, "")
        case .entry(let type, let title, let entry):
            return (type, title, entry)
        }
    }
    set {
        switch self {
        case .generic:
            self = TextFieldModelEnum.generic(type: newValue.type, title: newValue.title)
        case .entry:
           self = TextFieldModelEnum.entry(type: newValue.type, title: newValue.title, entry: newValue.entry)
        }
    }
}

示例

var tf = TextFieldModelEnum.entry(type: .text, title: "A Title", entry: "An Entry")
print(tf.info.entry)
print(tf.info.title)
tf.info.entry = "new entry"
print(tf.info.entry)
tf.info.title = "new title"
print(tf.info.title)

输出

  

条目
  标题
  新条目
  新标题

答案 1 :(得分:0)

由于变量// loop through each breakpoint @each $breakpoint in map-keys($grid-breakpoints) { $infix: breakpoint-infix($breakpoint, $grid-breakpoints); .bg#{$infix}-img { .. } } // css for one breakpoint // change style on sm only @include media-breakpoint-between(sm, md){ .bg-sm-img { ... } } 是计算属性,因此需要使用info关键字使其可写。 This article解释了如何做到这一点。