Two ways to define a string variable in swift

I'm just wondering if these two forms of variable definition are different. Or should be used in some special scenario.

var string1: String  {
    return "ok"
}

var string2: String = "ok"
+4
source share
2 answers

The first approach is called the so-called computed property :

Classes, structures, and enumerations can define computed properties that do not actually hold value. Instead, they provide a getter and an additional installer to retrieve and set other properties and values ​​indirectly.

The form you use provides only getter for string1, which makes it read-only.


:

, . ( var), ( let).

- ( var).


, . (, , ).

+3

get string1, . :

var string1: String {
    get {
        return "ok1"
    }
}

string2 ok,

+2

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


All Articles