All about Properties in swift

Image for post
Image for post
just an illustration from somewhere :p
@property (nonatomic, retain) NSString *myString;

Stored Property vs Computed property

struct FixedLengthRange {var firstValue: Intlet length: Int}var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)// the range represents integer values 0, 1, and 2rangeOfThreeItems.firstValue = 6// the range now represents integer values 6, 7, and 8

Stored Properties of Constant Structure Instances

let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)// this range represents integer values 0, 1, 2, and 3rangeOfFourItems.firstValue = 6// this will report an error, even though firstValue is a variable property

Lazy Stored Properties

Computed Properties

var a:String{return “a”}print(a) // prints a
var a:String{get {
return “a”
}
}
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
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?

Property Observers:

let b:Int {return 4 //error. error: ‘let’ declarations cannot be computed properties}

Type Properties :

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.

If you enjoyed reading this post and found it useful, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

iOS and tvOS developer, dreamer, photographer 🤨