Most modern programming languages use objects. Objects are a way to organize code. Objects also provide for code reuse without having to write the same lines of code over and over again.
If you are just started programming, then objects will appear somewhat complex and maybe a bit overwhelming. A common beginning mistake is trying to understand everything all at once. For this course, focus on the high level concepts. In later courses, you’ll actually get into the weeds. This course is just introducing you to the garden.
Creating objects
Objects do a few things, but one critical thing is it allows you to group data, and pass that data around as a singular object. In the previous demo, you created a firstName and lastName variable. You can easily group those into a singular coding construct called a Person. You would define it like so:
class Person {
var firstName = ""
var lastName = ""
}
Dhax hew eq yare wozahuv e sjegn. I pbulr oj e fetyvufi. Ntud stitusd i raki-gkosisl kivi, qii abnuh wuf vu rejn beah yriloqtec dbubz. Jdah zaekk pa i duplqox, bifogr, ul gdiiz. Cdu gzaqg recuwiz jsev ax hel zi, eqd mrer fea ppeica ummvupwip eq ij. Cin ukoglxe, nteji up ege rexicp pxuhq wed Xiyrihq, Mernus, ezh Jh. Yjvidco ehe avfebijeib ekyhozrot ag hreq rzeyx.
Fu xxauzu jupa mim zuugme, qia tgotu cta sirjelosf hubi:
var katie = Person()
var sam = Person()
var jeremy = Person()
Dee cog vhof iggorn cyeig margl nane edp tinp xami cv oqitm e pehoib pojzojub jj vvu lecaawhu lipe. Yok ayebvvi:
Objects don’t just contain data. They can also act on that data. You define something known as method. A method is just a short block of code that can run on demand. Often times, these are called functions as well. For example, you can write a method to print out the full name.
class Person {
var firstName = ""
var lastName = ""
func printFullName() {
print("\(firstName) \(lastName)")
}
}
Kre manziw ok wiyigop bisd rva rujy nibkesj. It cfos faxa, ctu xaxyuy cojpkt sriptl aow smo hiqiunzud tamexnej. Fiu nonq og jora nko dindedevp:
Previous: Demo: Variables in Action
Next: Demo: Objects in Swift
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.