Structures VS Classes in Swift - iOS - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

1 Nov 2017

Structures VS Classes in Swift - iOS

The difference between structure and class is that structure is a value type where class is a reference type.

We explain each one with a example.

Structures VS Classes in Swift - iOS

Classes:

A class is a blueprint or template for an instance of that class. The term "object" is often used to refer to an instance of a class.

Test following code in playground.

class Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person1 = Person(name: "John", age: 26)
var person2 = person1 // both are having same reference
person2.name = "Nick"

print(person1.name) // Nick
print(person2.name) // Nick

Structures:

Structs are preferable if they are relatively small because copying is way safer than having multiple reference to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multi threaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

Test following code in playground.

struct Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person1 = Person(name: "John", age: 26)
var person2 = person1 // both are having value with different references
person2.name = "Nick"

print(person1.name) // John
print(person2.name) // Nick

No comments:

Post a Comment

Post Top Ad