Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign to property: <Enum:case> is not settable

Tags:

enums

swift

for example we have simple enum

public enum CXActionSheetToolBarButtonItem {
    case cancel
    case done
    case now

    private static var titles: [CXActionSheetToolBarButtonItem: String] = [
        .cancel: "Cancel",
        .done: "Done",
        .now: "Now",
    ]

    public var title: String  {
        get { return CXActionSheetToolBarButtonItem.titles[self] ?? String(describing: self) }
        // what am I want to do
        set(value) { CXActionSheetToolBarButtonItem.titles[self] = value }
    }

    // what am I forced to do
    public static func setTitle(_ title: String, for item: CXActionSheetToolBarButtonItem) {
        CXActionSheetToolBarButtonItem.titles[item] = title
    }
}

why I don't can set new title like this

CXActionSheetToolBarButtonItem.cancel.title = "asd"

compiler responded error - Cannot assign to property: 'cancel' is not settable, but I can set title with function

CXActionSheetToolBarButtonItem.setTitle("asd", for: .cancel)

what should I change for worked my var as settable? .cancel.title = "asd"

like image 415
EvGeniy Ilyin Avatar asked Dec 14 '22 17:12

EvGeniy Ilyin


1 Answers

Using an enum for this seems inappropriate, but I'll address the porblem at face value. You need to mark your setter as nonmutating, so that it can be called on non-var instances of your enum:

public enum CXActionSheetToolBarButtonItem {

    // ...

    public var title: String  {
        get { return CXActionSheetToolBarButtonItem.titles[self] ?? String(describing: self) }
        nonmutating set(value) { CXActionSheetToolBarButtonItem.titles[self] = value }
    }
}

CXActionSheetToolBarButtonItem.cancel.title = "foo" // Works... but why would you want this?!
like image 146
Alexander Avatar answered Jan 06 '23 21:01

Alexander