Swift 4 Notes

Notes

You must always declare a lazy property as a variable, using the var keyword, because its initial value might not be retrieved until after the completion of instance initialization. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

A computed property with a getter but no setter is known as a read-only computed property. It always returns a value, and can be accessed through dot syntax. However, that value cannot be altered(Specified here are get and set properties.).

If you assign a value to a property within its own didSet observer, the new assigned value will replace the one that was just set.

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.

"self" keyword refers to the current instance.We can use the self property to distinguish between the parameter name and the property name.

Mutating methods can assign an entirely new instance to the implicit self property.
struct Mult {
   var x = 1, y = 1
   mutating func multiply(mX: Int, mY: Int) {
     x *= mX
     y *= mY
   }
}
var p = Mult()
p.multiply(mX: 2, mY: 4)
print(p)

OUTPUT:
Mult(x: 2, y: 4)


You can prevent a method, property, or subscript override by marking it as final (such as final var, final func, final class func, and final subscript). You can mark an entire class as final by placing the final modifier before the class keyword in its class definition (final class).

When you assign a default value to a stored property, or set its initial value within an initializer, the value of that property is set directly, without calling any property observers.
struct KALI {
  var tempInC: String=""
  init(fromKali kali: String) {
    print("Initializing from KALI :~$ \(kali)")
  }
  init(fromSuse suse: String) {
    print("Initializing from SUSE :/# \(suse)")
  }
}
let kCommand = KALI(fromKali: "echo '1+1' | bc")
let sCommand = KALI(fromSuse: "ls -l")

OUTPUT: Initializing from KALI :~$ echo '1+1' | bc Initializing from SUSE :/# ls -l


It's not necessary to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.
with required:
class SClass { required init() { print("superclass") } } class SSubclass: SClass { required init() { print("subclass") } } let s = SSubclass()
no required : class SClass { init() { print("superclass") } } class SSubclass: SClass { override init() { print("subclass") } } let s = SSubclass()

Comments

Popular posts from this blog

Tech Duos For Web Development

CIFAR-10 Dataset Classification Using Convolutional Neural Networks (CNNs) With PyTorch

Long-short-term-memory (LSTM) Word Prediction With PyTorch