Skip to content

Instantly share code, notes, and snippets.

@stansidel
Created June 19, 2019 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stansidel/089cc6ee1105d2440ca8d3d2600e2dee to your computer and use it in GitHub Desktop.
Save stansidel/089cc6ee1105d2440ca8d3d2600e2dee to your computer and use it in GitHub Desktop.
Мутабельность классов и структур
class MyClass {
var name: String
init(name: String) {
self.name = name
}
}
var mc1 = MyClass(name: "Name 1")
var mc2 = mc1
// Мы изменяем поле объекта, не копируя сам объект, так как это класс
mc2.name = "Name 2"
// Переменная mc1 ссылается всё на тот же объект, поэтому значение в нём изменились
print(mc1.name) // Name 2
print(mc2.name) // Name 2
// Можно проверить, указывают ли две переменные на один и тот же объект
// https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html#ID90
mc1 === mc2
struct MyStruct {
var name: String
}
var ms1 = MyStruct(name: "Name 1")
var ms2 = ms1
// При изменении поля структуры происходит копирование исходной структуры с новым полем
ms2.name = "Name 2"
// Хотя кажется, что мы изменили всё тот же объект (ms2 вроде мутабельная переменная),
// ms1 и ms2 уже указывают на два разных объекта.
// В ms1 остался прежняя структура, со прежним значением поля name
print(ms1.name) // Name 1
print(ms2.name) // Name 2
// Строка ниже не скомпилируется, так как мы не можем сравнить не-reference-type объекты
// ms1 === ms2
/*
Из документации:
Because classes are reference types, it’s possible for multiple constants and
variables to refer to the same single instance of a class behind the scenes.
(The same isn’t true for structures and enumerations, because they are always
copied when they are assigned to a constant or variable, or passed to a function.)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment