0

I have this 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)
        }
    }
}

I'm trying to change the value entry in the method below, but it gives me an error on the first line:

Cannot assign to immutable expression of type '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)
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
bruno
  • 2,154
  • 5
  • 39
  • 64

2 Answers2

1

I think I finally figured out how to do this with a set for the computed property

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)
        }
    }
}

Example

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)

Output

An Entry
A Title
new entry
new title

bruno
  • 2,154
  • 5
  • 39
  • 64
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

Since your variable info is a computed property, you need to use the set keyword to make it writeable. This article explains how to do that.

Victor Pro
  • 199
  • 4
  • And how do you do that for an enum with associated values? – Joakim Danielson Mar 19 '19 at 11:24
  • @JoakimDanielson This is possible. In this case you need to declare a `mutating` function that changes the value. See https://stackoverflow.com/questions/31488603/can-i-change-the-associated-values-of-a-enum for more information. – Victor Pro Mar 19 '19 at 11:26
  • But in you answer you said the `set` keyword is needed and the link you provided uses a mutating func and not `set`. Please add a description preferable with a code example on how to solve this. – Joakim Danielson Mar 19 '19 at 11:33