Изменить значение связанного перечисления - PullRequest
0 голосов
/ 19 марта 2019

У меня есть 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 ]

1 голос
/ 19 марта 2019

Думаю, я наконец понял, как это сделать с 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)

выход

Запись
Название
новая запись
новое название

0 голосов
/ 19 марта 2019

Поскольку ваша переменная info является вычисляемым свойством, вам нужно использовать ключевое слово set, чтобы сделать его доступным для записи. Эта статья объясняет, как это сделать.

...