Swift 4 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 }

5th Mar 2018, 5:12 AM
Ugiloy Boymirzaeva
Ugiloy Boymirzaeva - avatar
4 Answers
+ 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.
5th Mar 2018, 5:56 AM
Sylar
+ 2
thank you so much. I understood what you mean, it was useful )))
5th Mar 2018, 11:39 AM
Ugiloy Boymirzaeva
Ugiloy Boymirzaeva - avatar
+ 1
chunmadim nima demoqchiligizzi
27th May 2018, 5:00 PM
Ugiloy Boymirzaeva
Ugiloy Boymirzaeva - avatar
0
O'rganib qolganimni o'ylamaydi O'g'iloy)))
27th May 2018, 11:44 AM
Ravshanbek Subihonov
Ravshanbek Subihonov - avatar