Swift modifiable in properties

protocol Deck {
var cards: [String] {get set} // {get mutable set}
}

struct MyDeck: Deck {   
 var cards: [String] =  (1...7).map {_ in return String(rand())}
}

Do I just need to specify {get mutable set} in the protocol? It is not possible to find any documents on why not using the mutable keyword in the setter declaration if my setter mutates my structure

+2
source share
1 answer

First of all, note that the discussion keyword is , not . mutatingmutable


The default state setismutating

  • To quickly answer your question: mutating- this is the default state for setters, and therefore you do not need to explicitly use the keyword mutatingto indicate this.

More details

The following default behavior is performed for getter and seters:

  • get nonmutating default
  • set mutating default

, , ... { get set } , ( ), , nonmutating get mutating set struct,

protocol Deck {
    var cards: [String] {get set}
}

// implicitly, OK
struct MyDeckA: Deck {
    var mutateMe: Int = 0
    var cards: [String] {
        get { return ["foo"] }
        set { mutateMe += 1 }
    }
}

// explicitly, OK
struct MyDeckB: Deck {
    var mutateMe: Int = 0
    var cards: [String] {
        nonmutating get { return ["foo"] }
        mutating set { mutateMe += 1 }
    }
}

/* error, MyDeckC does not conform to Deck 
  (mutating getter, wheres a nonmutating one is blueprinted!) */
struct MyDeckC: Deck {
    var mutateMe: Int = 0
    var cards: [String] {
        mutating get { return ["foo"] }
        mutating set { mutateMe += 1 }
    }
}

, , ( , , ).

protocol Deck {
    var cards: [String] {mutating get nonmutating set}
}

/* when conforming to this non-default get/set setup blueprinted in 
   protocol Deck, we need to explicitly specify our non-default 
   (w.r.t. mutating) getter and setter */
struct MyDeckD: Deck {
    var mutateMe: Int = 0
    var cards: [String] {
        mutating get { mutateMe += 1; return ["foo"] }
        nonmutating set { print("I can't mutate self ...") }
    }
}

, , ( ) (... {get set}), , , mutating set, nonmutating

protocol Deck {
    var cards: [String] {get set}
}

struct MyDeckE: Deck {
    var mutateMe: Int = 0
    var cards: [String] {
        get { return ["foo"] }
        nonmutating set { print("I can't mutate self ...") }
            /* setter cannot mutate self */
    }
}

, , , , , , , , self. , , get mutating getter: - nonmutating one.

protocol Deck {
    var cards: [String] {mutating get set}
}

struct MyDeckF: Deck {
    var mutateMe: Int = 0
    var cards: [String] {
        nonmutating get { print("I can't mutate self ..."); return ["foo"] }
            /* getter cannot mutate self */
        set { mutateMe += 1 }
    }
}
+2

Source: https://habr.com/ru/post/1691624/


All Articles