+ 4
Swift 4
I've got this code from another course: struct markStruct { var mark1: Int var mark2: Int var mark3: Int init(mark1: Int, mark2: Int, mark3: Int) { self.mark1 = mark1 self.mark2 = mark2 self.mark3 = mark3 } } var marks = markStruct(mark1: 98, mark2: 96, mark3:100) print(marks.mark1) print(marks.mark2) print(marks.mark3) here in code, why this block of code is used when it is printing the result without it? init(mark1: Int, mark2: Int, mark3: Int) { self.mark1 = mark1 self.mark2 = mark2 self.mark3 = mark3 }
4 Respuestas
+ 3
'init' is a special method used for initialization of instance when creating from struct or class.
So 1st statement: 'var marks = markStruct(98,96,100)' mean creating an instance(aka object) from markStruct. And you initialize that instance with 'mark1=98, mark2=96, mark3=100'.
'Self' is the reference to that instance itself. So, 'marks' instance contain variable mark1 mark2 & mark3 with their values respectively.
So, when you use print function, marks.mark1/2/3 get their values from 'marks' instance.
That code block is need if you are using instance and want to initialize it with some variable.
PS i don't use swift. I just answer with my poor assumption and understanding. But, i think general usage of programming may be same in swift ,too.
+ 2
thank you so much. I understood what you mean, it was useful )))
+ 1
chunmadim nima demoqchiligizzi
0
O'rganib qolganimni o'ylamaydi O'g'iloy)))