Tumgik
#willset in swift
yogeshpatelios · 5 years
Video
youtube
Swift 5 & Xcode 11 : Property Observer WillSet and DidSet with UITableVi...
0 notes
jacob-cs · 7 years
Link
original source : https://medium.com/@abhimuralidharan/all-about-properties-in-swift-d618481b1cc1
First , let me talk about a property . Suppose if we need to change or access an iVar in your class using an object of your class, then there should be getter and setter methods assigned to the iVar. A property is used mainly when other objects need to change or access the ivars in your object, without manually defining getters and setters, or using @property (in objective - c).
In objective-c, @property declares a property in your class header. Here is an example:
@property (nonatomic, retain) NSString *myString;
@synthesize creates your setter and getter for your property (accessor methods). Without synthesize you have to write your own setter and getter implemention, like getMyString or setMyString (capitalize the first character of your property).
So, the above property declaration is equivalent to:
- (NSString*)myString {} - (void)setMyString:(NSString*)newValue {}
Properties can be further classified into Stored properties and Computed properties.
Stored Property vs Computed property
Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value.
►Computed properties are provided by classes, structures, and enumerations.
(참고 eumeration 에 대하여 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-ID145)
►Stored properties are provided only by classes and structures.
In its simplest form, a stored property is a constant or variable that is stored as part of an instance of a particular class or structure. Stored properties can be either variable stored properties (introduced by the varkeyword) or constant stored properties (introduced by the let keyword).
The example below defines a structure called FixedLengthRange, which describes a range of integers whose range length cannot be changed once it is created:
struct FixedLengthRange { var firstValue: Int let length: Int } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) // the range represents integer values 0, 1, and 2 rangeOfThreeItems.firstValue = 6 // the range now represents integer values 6, 7, and 8
Instances of FixedLengthRange have a variable stored property called firstValue and a constant stored property called length. In the example above, length is initialized when the new range is created and cannot be changed thereafter, because it is a constant property.
Stored Properties of Constant Structure Instances
If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties:
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) // this range represents integer values 0, 1, 2, and 3 rangeOfFourItems.firstValue = 6 // this will report an error, even though firstValue is a variable property
Because rangeOfFourItems is declared as a constant (with the let keyword), it is not possible to change its firstValue property, even though firstValueis a variable property.
NOTE: This behavior is due to structures being value types. When an instance of a value type is marked as a constant, so are all of its properties.
The same is not true for classes, which are reference types. If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.
Lazy Stored Properties
A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.
Please refer my article on lazy var : lazy var in ios swift
Computed Properties
In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
If you define get { } inside the property declaration, it makes that property to a computed property. And it cannot have initial value as when you access the property, it will always call get{} function declared in property.
► We can skip the associated get and set keyword and their curly brackets if we do not have to set a value to the variable. Computed property with a getter but no setter is known as a read-only computed property. Check the below example:
var a:String{ return “a” } print(a) // prints a
The above declaration is same as:
var a:String{ get { return “a” } }
►We can use an optional setter to the computed variable which accepts a newValue as parameter.
class Alphabets { var _a:String? var a:String { get { return _a ?? “not set” } set(newVal) { //you can use any name for the passed parameter.Default is newValue _a = newVal } } } /*----------------------------------------------------*/ let alphabet1 = Alphabets() alphabet1.a = “a” print(alphabet1.a) // prints a
(참고 ?? 에 대하여 https://stackoverflow.com/a/30837121 coalescing operator)
If a computed property’s setter does not define a name for the new value to be set, a default name of newValue is used. Here’s an alternative version of the Alphabets class, which takes advantage of this shorthand notation:
class Alphabets { var _a:String? var a:String { get { return _a ?? “not set” } set { // no values passed.. _a = newValue // default value name is newValue } } } /* — — — — — — — — — — — — — — — — — */ let alphabet1 = Alphabets() alphabet1.a = “a” print(alphabet1.a) // prints a
Well, what happens if you try to set a computed property in its own setter?
You cannot do that. It will call the same setter method again and again and it will create an endless loop. The app may crash due to a memory overrun.
By definition, a computed property is one whose value you cannot set because, well, it’s computed. It has no independent existence. The purpose of the setter in a computed property is not to set the value of the property but to set the values of other properties, from which the computed property is computed.
Property Observers:
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value. You can add property observers to any stored properties you define, except for lazy stored properties. We can add property observers to ‘inherited’ property by method ‘overriding’.
You have the option to define either or both of these observers on a property:
willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.
If you implement a willSet observer, it’s passed the new property value as a constant parameter. You can specify a name for this parameter as part of your willSet implementation. If you don’t write the parameter name and parentheses within your implementation, the parameter is made available with a default parameter name of newValue.
Similarly, if you implement a didSet observer, it’s passed a constant parameter containing the old property value. You can name the parameter or use the default parameter name of oldValue.
Here is an example given by apple to explain the flow:
class StepCounter {    var totalSteps: Int = 0 {        willSet(newTotalSteps) {            print("About to set totalSteps to \(newTotalSteps)")        }        didSet {            if totalSteps > oldValue  {                print("Added \(totalSteps - oldValue) steps")            }        }    } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 // About to set totalSteps to 200 // Added 200 steps stepCounter.totalSteps = 360 // About to set totalSteps to 360 // Added 160 steps stepCounter.totalSteps = 896 // About to set totalSteps to 896 // Added 536 steps
The willSet and didSet observers for totalSteps are called whenever the property is assigned a new value. This is true even if the new value is the same as the current value.
Note:Computed property should be a variable.
let b:Int { return 4 //error. error: ‘let’ declarations cannot be computed properties }
Type Properties :
Instance properties are properties that belong to an instance of a particular type. Every time you create a new instance of that type, it has its own set of property values, separate from any other instance.
You can also define properties that belong to the type itself, not to any one instance of that type. There will only ever be one copy of these properties, no matter how many instances of that type you create. These kinds of properties are called type properties.
In Swift, type properties are written as part of the type’s definition, within the type’s outer curly braces, and each type property is explicitly scoped to the type it supports.
You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation.
static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.
The example below shows the syntax for type properties:
class Player {    static var totalNumberOfPlayers = 0    var name:String    init(name:String) {        Player.totalNumberOfPlayers += 1        self.name = name    }    static func printTotalNumberOfPlayers() {        print("Function log --> Total no of players: \(Player.totalNumberOfPlayers)")    }     class func printGameName() {       print("Road runner")    } } let a  = Player(name: "abhi") let b  = Player(name: "joe") print("Total no of players: \(Player.totalNumberOfPlayers)")// prints Total no of players: 2 Player.printTotalNumberOfPlayers() // print Function log --> Total no of players: 2 class Enemy: Player {     override class func printGameName() {        super.printGameName()    print("Super mario")    } //    override static func printTotalNumberOfPlayers() { //error: cannot override static method //        print("Function log --> Total no of players: \(Player.totalNumberOfPlayers)") //    } } Enemy.printGameName() prints Road runner and Super mario as super method is also called
In the above example, we tried to override a static func in the subclass Enemybut got an error like : error: cannot override static method .
If you enjoyed reading this post and found it useful, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!
Thanks!!
0 notes
Text
HackingWithSwift Day 15
Properties - Which are the variables and constants Properties observer - didset , willset Computed Properties - variable with only get, no need assign value , get value on the fly Static Properties - make the properties belongs to the type instead of the instance Access Control - Public: this means everyone can read and write the property. - Internal: this means only your Swift code can read and write the property. If you ship your code as a framework for others to use, they won’t be able to read the property. - File Private: this means that only Swift code in the same file as the type can read and write the property. - Private: this is the most restrictive option, and means the property is available only inside methods that belong to the type, or its extensions.
// Declaring "A" class that has the two types of "private" and "fileprivate": class A {    private var aPrivate: String?    fileprivate var aFileprivate: String?
   func accessMySelf() {        // this works fine        self.aPrivate = ""        self.aFileprivate = ""    } }
// Declaring "B" for checking the abiltiy of accessing "A" class: class B {    func accessA() {        // create an instance of "A" class        let aObject = A()
       // Error! this is NOT accessable...        aObject.aPrivate = "I CANNOT set a value for it!"
       // this works fine        aObject.aFileprivate = "I CAN set a value for it!"    } }
https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html Have to read more…….
============= TypeCasting
Typecasting “as?” allow you to check the data type is the one you want or not, else it will return nil and won’t execute the code inside the if statement
============= Closure …..might as well just read back the previous note for review.
0 notes
for-the-user · 6 years
Text
swift property observers
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
var something: String! = "hellooooo" { didSet { myGroovyMethod() } willSet { myOtherGroovyMethod() } } something = "goodbye"
In the above code snippet, the order of operations are like this:
something is equal to "hellooooo" willSet was called myOtherGroovyMethod() was called something is equal to "goodbye" didSet was called myGroovyMethod() was called
1 note · View note
56perc · 7 years
Text
프로퍼티 상속 파고들기 - Swift
프로퍼티 상속 파고들기 – Swift
프로퍼티에 대한 이야기를 몇 번 하긴하였는데, 실제로 프로퍼티 상속은 실제로 상당히 오묘하게 헷갈릴 수 있는 여지가 많아서 다시 한 번 정리하는 차원에서 예제와 함께 포스팅한다. 이 글에서는 클래스의 프로퍼티가 서브클래싱할 때 어떤식으로 처리되는지를 살펴볼 것이다. 먼저 저장 프로퍼티와 계산 프로퍼티에 대해서 살펴보자. 다음 예제 코드는 정수형 프로퍼티 4개를 가지고 있는 클래스 Foo를 구현한 예이다.
class Foo {   var a: Int = 5   var b: Int = 30 {     willSet { print("[Foo] property b will be changed.") }     didSet { print("[Foo] property b has been changed.") }   }…
View On WordPress
0 notes
jacob-cs · 7 years
Text
Swift Properties
Properties
Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures.
Stored and computed properties are usually associated with instances of a particular type. However, properties can also be associated with the type itself. Such properties are known as type properties.
In addition, you can define property observers to monitor changes in a property’s value, which you can respond to with custom actions. Property observers can be added to stored properties you define yourself, and also to properties that a subclass inherits from its superclass.
Stored Properties
Stored properties can be either variable stored properties (introduced by the varkeyword) or constant stored properties (introduced by the let keyword).
You can provide a default value for a stored property as part of its definition, as described in Default Property Values. You can also set and modify the initial value for a stored property during initialization. This is true even for constant stored properties, as described in Assigning Constant Properties During Initialization.
struct FixedLengthRange {    var firstValue: Int    let length: Int } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) // the range represents integer values 0, 1, and 2 rangeOfThreeItems.firstValue = 6 // the range now represents integer values 6, 7, and 8
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) // this range represents integer values 0, 1, 2, and 3 rangeOfFourItems.firstValue = 6 // this will report an error, even though firstValue is a variable property
This behavior is due to structures being value types. When an instance of a value type is marked as a constant, so are all of its properties.
The same is not true for classes, which are reference types. If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.
Stored Properties of Constant Structure Instances
If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties:
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) // this range represents integer values 0, 1, 2, and 3 rangeOfFourItems.firstValue = 6 // this will report an error, even though firstValue is a variable property
This behavior is due to structures being value types. When an instance of a value type is marked as a constant, so are all of its properties.
The same is not true for classes, which are reference types. If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.
Lazy Stored Properties
A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.
NOTE
You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.
class DataImporter {    /*     DataImporter is a class to import data from an external file.     The class is assumed to take a nontrivial amount of time to initialize.     */    var filename = "data.txt"    // the DataImporter class would provide data importing functionality here } class DataManager {    lazy var importer = DataImporter()    var data = [String]()    // the DataManager class would provide data management functionality here } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") // the DataImporter instance for the importer property has not yet been created
Because it is marked with the lazy modifier, the DataImporter instance for the importer property is only created when the importer property is first accessed, such as when its filename property is queried:
print(manager.importer.filename) // the DataImporter instance for the importer property has now been created // Prints "data.txt"
NOTE
If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.
Computed Properties
getter and an optional setter to retrieve and set other properties and values indirectly.
struct Point {    var x = 0.0, y = 0.0 } struct Size {    var width = 0.0, height = 0.0 } struct Rect {    var origin = Point()    var size = Size()    var center: Point {        get {            let centerX = origin.x + (size.width / 2)            let centerY = origin.y + (size.height / 2)            return Point(x: centerX, y: centerY)        }        set(newCenter) {            origin.x = newCenter.x - (size.width / 2)            origin.y = newCenter.y - (size.height / 2)        }    } } var square = Rect(origin: Point(x: 0.0, y: 0.0),                  size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 15.0) print("square.origin is now at (\(square.origin.x), \(square.origin.y))") // Prints "square.origin is now at (10.0, 10.0)"
Shorthand Setter Declaration
If a computed property’s setter does not define a name for the new value to be set, a default name of newValueis used. 
struct AlternativeRect {    var origin = Point()    var size = Size()    var center: Point {        get {            let centerX = origin.x + (size.width / 2)            let centerY = origin.y + (size.height / 2)            return Point(x: centerX, y: centerY)        }
       // set(사용될변수이름) 
      //  이런 형태이나 아래와 같이 축약형으로사용 가능 newValue는 swift가          //  제공하는 기본 변수이름        set {            origin.x = newValue.x - (size.width / 2)            origin.y = newValue.y - (size.height / 2)        }    } }
Read-Only Computed Properties
A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.
NOTE
You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.
struct Cuboid {    var width = 0.0, height = 0.0, depth = 0.0    var volume: Double {        return width * height * depth    } } let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0) print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") // Prints "the volume of fourByFiveByTwo is 40.0"
Property Observers
Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
You can add property observers to any stored properties you define, except for lazy stored properties. You can also add property observers to any inherited property (whether stored or computed) by overriding the property within a subclass. You don’t need to define property observers for nonoverridden computed properties, because you can observe and respond to changes to their value in the computed property’s setter. Property overriding is described in Overriding.
You have the option to define either or both of these observers on a property:
willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.
If you implement a willSet observer, it’s passed the new property value as a constant parameter. You can specify a name for this parameter as part of your willSet implementation. If you don’t write the parameter name and parentheses within your implementation, the parameter is made available with a default parameter name of newValue.
Similarly, if you implement a didSet observer, it’s passed a constant parameter containing the old property value. You can name the parameter or use the default parameter name of oldValue. If you assign a value to a property within its own didSet observer, the new value that you assign replaces the one that was just set.
NOTE
The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They are not called while a class is setting its own properties, before the superclass initializer has been called.
class StepCounter {    var totalSteps: Int = 0 {        willSet(newTotalSteps) {            print("About to set totalSteps to \(newTotalSteps)")        }        didSet {            if totalSteps > oldValue  {                print("Added \(totalSteps - oldValue) steps")            }        }    } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 // About to set totalSteps to 200 // Added 200 steps stepCounter.totalSteps = 360 // About to set totalSteps to 360 // Added 160 steps stepCounter.totalSteps = 896 // About to set totalSteps to 896 // Added 536 steps
NOTE
If you pass a property that has observers to a function as an in-out parameter, the willSet and didSet observers are always called. This is because of the copy-in copy-out memory model for in-out parameters: The value is always written back to the property at the end of the function. For a detailed discussion of the behavior of in-out parameters, see In-Out Parameters.
Global and Local Variables
The capabilities described above for computing and observing properties are also available to global variables and local variables. Global variables are variables that are defined outside of any function, method, closure, or type context. Local variables are variables that are defined within a function, method, or closure context.
The global and local variables you have encountered in previous chapters have all been stored variables. Stored variables, like stored properties, provide storage for a value of a certain type and allow that value to be set and retrieved.
However, you can also define computed variables and define observers for stored variables, in either a global or local scope. Computed variables calculate their value, rather than storing it, and they are written in the same way as computed properties.
NOTE
Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.
Local constants and variables are never computed lazily.
Type Properties
Instance properties are properties that belong to an instance of a particular type. 
You can also define properties that belong to the type itself, not to any one instance of that type. There will only ever be one copy of these properties.
Type properties are useful for defining values that are universal to all instances of a particular type, such as a constant property that all instances can use (like a static constant in C), or a variable property that stores a value that is global to all instances of that type (like a static variable in C).
Stored type properties can be variables or constants. Computed type properties are always declared as variable properties, in the same way as computed instance properties.
NOTE
Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.
Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.
Type Property Syntax
type properties are written as part of the type’s definition, within the type’s outer curly braces, and each type property is explicitly scoped to the type it supports.
You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation. The example below shows the syntax for stored and computed type properties:
struct SomeStructure {    static var storedTypeProperty = "Some value."    static var computedTypeProperty: Int {        return 1    } } enum SomeEnumeration {    static var storedTypeProperty = "Some value."    static var computedTypeProperty: Int {        return 6    } } class SomeClass {    static var storedTypeProperty = "Some value."    static var computedTypeProperty: Int {        return 27    }    class var overrideableComputedTypeProperty: Int {        return 107    } }
NOTE
The computed type property examples above are for read-only computed type properties, but you can also define read-write computed type properties with the same syntax as for computed instance properties.
Querying and Setting Type Properties
(type property는 클래스에 존재하는 상수,변수이며 이는 클래스이름을 통해 공유된다.)
Type properties are queried and set with dot syntax, just like instance properties. However, type properties are queried and set on the type, not on an instance of that type. For example:
print(SomeStructure.storedTypeProperty) // Prints "Some value." SomeStructure.storedTypeProperty = "Another value." print(SomeStructure.storedTypeProperty) // Prints "Another value." print(SomeEnumeration.computedTypeProperty) // Prints "6" print(SomeClass.computedTypeProperty) // Prints "27"
struct AudioChannel {    static let thresholdLevel = 10    static var maxInputLevelForAllChannels = 0    var currentLevel: Int = 0 {        didSet {            if currentLevel > AudioChannel.thresholdLevel {                // cap the new audio level to the threshold level                currentLevel = AudioChannel.thresholdLevel            }            if currentLevel > AudioChannel.maxInputLevelForAllChannels {                // store this as the new overall maximum input level                AudioChannel.maxInputLevelForAllChannels = currentLevel            }        }    } }
var leftChannel = AudioChannel() var rightChannel = AudioChannel()
leftChannel.currentLevel = 7 print(leftChannel.currentLevel) // Prints "7" print(AudioChannel.maxInputLevelForAllChannels) // Prints "7"
rightChannel.currentLevel = 11 print(rightChannel.currentLevel) // Prints "10" print(AudioChannel.maxInputLevelForAllChannels) // Prints "10"
// 위에와는 달리 할당되 새로운 값이 type property에 존재하는 것을 알수 있다.
0 notes
Text
HackingWithSwift Day 8
Introducing Struct (Part 1)
struct Sport {    var name: String }
“var name” inside the struct is consider as properties, known as stored properties
var tennis = Sport(name: "Tennis") print(tennis.name)
tennis.name = "Lawn tennis"
Pretty standard for now
Struct vs Tuple
func authenticate(_ user: User) { ... } func showProfile(for user: User) { ... } func signOut(_ user: User) { ... }
Vs
func authenticate(_ user: (name: String, age: Int, city: String)) { ... } func showProfile(for user: (name: String, age: Int, city: String)) { ... } func signOut(_ user: (name: String, age: Int, city: String)) { ... }
I will choose Struct, because I’m lazy and better for code re-usability haha ==================
Computed properties - can be a properties that you don’t need it to be store to a variable, value of the properties can be different if there’s condition set to it
struct Sport {    var name: String    var isOlympicSport: Bool
   var olympicStatus: String {        if isOlympicSport {            return "\(name) is an Olympic sport"        } else {            return "\(name) is not an Olympic sport"        }    } }
var olympicStatus: String is a computed properties , no set value but only return
If it’s a dependancy value , go for computed , if it’s a value that need to be read very often or stored, then go for stored ===================
Property Observer
struct Progress {    var task: String    var amount: Int {        didSet {            print("\(task) is now \(amount)% complete")        }    } }
didset is the keyword - means after I set value to the variable “amount” , I want to do something. There’s “willset” as well - means before the value got set, I want to do something
================
Methods
struct City {    var population: Int
   func collectTaxes() -> Int {        return population * 1000    } }
Quite similar to computed properties I have to say.
Mutated Methods
struct Person {    var name: String
   mutating func makeAnonymous() {        name = "Anonymous"    } }
Need the mutating keyword if one gonna change the value of a properties inside the struct even if you created the properties as “var” and if it’s declare as “let” you can’t change it.
Reason is, you can create a Person struct as let, or struct as a var at the actual code, mutating is the safeguard =================
Properties and Method of Strings
“Almost all of Swift’s core types are implemented as structs, including strings, integers, arrays, dictionaries, and even Booleans. This isn’t an accident: structs are simple, fast, and efficient in Swift, which means we can create and destroy them as much as we need without worrying too much about performance.”
Basically it’s just not a variable or class type.
Another interesting topic https://www.hackingwithswift.com/articles/181/why-using-isempty-is-faster-than-checking-count-0
====================
Properties and Method of Arrays
let tens = [30, 20, 10] tens.sorted() == [10, 20, 30]
This code will return true, you can’t add or remove data after the constant declaration, but you can sort the existing data even if it’s a constant
0 notes