Posts

Showing posts with the label Initializer

Treehouse Intermediate Course Part 3 (Initialization)

Well here we go - next part of Pasan's course! Not going to waste time with a preamble but am honestly going to aim for 40 minutes max. It's 11:40 am (Dubai time) now so will finish at 12:20 - or as close to if I'm in the middle of something.  Object Initialization So what is init? Preparing the instance of a class/struct/enum by giving values to stored properties. Parameters are used - following the same rules as function parameters. Default or optional values can be used to store properties. All stored properties must have initial values. Structs have member-wise initializers. Failable and Throwing Initializers What about where init is not possible? It could depend on external data. *All coding typed out by Pasan already - I'm just copying and pasting it.  enum Day: Int {     case sunday = 1     case monday     case tuesday     case wednesday     case thursday     case friday ...

Classes and Structs - interim Practice!

So I was all ready to move onto the next course but really feel the need to crack the whole initialiser (which is one of the most difficult words to type by the way!) thing first. It makes more sense to have a little more practice with this! So for the first time since going back to Treehouse, I'm veering away from it - albeit briefly... First stop - the Apple Developer Guidance Structures  and  classes  are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions. Straight from the text! All of that makes sense. Pasan also referred to them as 'Objects'. Ah hang on, that's an instance of a construct. Again, from the text, here is what both Structures and Classes can do: Define properties to store values Define methods to provide functionality Define subscripts t...

Object-Oriented Swift - Classes

Yep, two in a day - I couldn't resist! A great sign that I want to work through more coding! I'm picking back up with where I got to - from structures to classes... Introduction to Classes The syntax for these is similar in terms of the UpperCamelCase etc. A variable is used as a property rather than a constant because this value is likely to change. One of the differences with structs and classes are that we almost must write the init methods in the latter. Initializer methods are always just init, no need for prepositional phrases etc. class Enemy {          var life: Int = 2     let position: Point          init (x: Int , y: Int ) {         self . position = Point (x: x, y: y)              }          func decreaseLife(by factor: Int ) {                  life -= f...