Object-Oriented Swift - Complex Data Structures

I am now onto the next course! This is the last full course I need to recap/redo before continuing with the one I got to before. All of the skills I have built up over the past week or so have really made me feel positive about Swift. The next lot of videos are about 'structures' - bundling together a number of variables and values. It is going to be a step up....

Introduction to Structs

The first example Pasan gives is vaguely familiar - it's about using coordinates for shooting towers for a game. The number of values needed means that we would need to create a struct. Creating a separate value for each of the x and y axes are useless. Creating a tuple would be better as the x and y values are linked together. 

let coordinate1: (x: Int, y: Int) = (0,0)

This is fine but is going to be quite limited. Instead we are going to create a custom struct. As struct can define variables or constants, which are called stored properties. No value needs to be assigned to either the x or y values. 

struct Point {
    let x: Int
    let y: Int
    
}

let p1 = Point(x: 0, y: 0)

A couple of key things here. The struct syntax has a capital for the value - UpperCamelCase rather than lowerCamelCase. The Point struct is its own type - it is a custom type. Interesting stuff thus far!

Instance of Objects

So in the above example, I have created a blueprint. This blueprint for coordinates can now be applied to different instances of it. Pasan describes an example - ice tray. The mould is the same, but I could put in other liquids - not just water. But the underlying properties can be customised! So the p1 I created above - the last line of the code - is an instance. The struct definition is used to create an instance. So the struct is the blueprint. The struct is an object in the sense that it contains stored properties. 

A point about scope - the properties of the struct do not exist outside of the struct. They are local rather than global. As we have not given initial values to the variables/constants (the properties in the struct), we have to specify the type. Similar to a function with parameters and arguments. 


Methods

Now before this video starts, I believe that this is to do with functions within structures. I think it's called a method as it is local to that structure and thus cannot be used outside of it. I'm sure there's more to it than that!

The advantage with an object is that the values can all be linked together. There's another point about the use of comments - something I have not been doing as I've been documenting everything on this block instead! The example he goes through is quite complex so I'll post the whole code below when it's ready...

struct Point {
    let x: Int
    let y: Int
    
    func points(inRange range: Int = 1) -> [Point] {
    
    ///returns surrounding points in range of
    ///the current one
        
        var results = [Point]()
        
        let lowerBoundOfXRange = x - range
        
        let upperBoundOfXRange = x + range
        
        let upperBoundOfYRange = y - range
        
        let lowerBoundOfYRange = y + range
        
        for xCoordinate in lowerBoundOfXRange...upperBoundOfXRange {
            
            for yCoordinate in lowerBoundOfYRange...upperBoundOfYRange {
                
                let coordinatePoint = Point(x: xCoordinate, y: yCoordinate)
                
                results.append(coordinatePoint)
            }
        }
        
        return results
    }
    
}

So there was a lot going on here! The two for loops were used to iterate over all of the x and y points greater than and less than 1. From that, the x and y coordinates were created into an array, which are then returned within the method of points. In the next part we'll see how this is actually used...

Instance Methods

A method is a function associated with any particular type. E.g. the 'append' used is a method as it's associated with a particular type - in the array. The dot notation is used. The rest of this was a little confusing but I think I made sense of it. You have to create an instance of a method i.e. a constant that uses the points function basically. 

All challenges done! Make perfect sense - the use of methods now is a lot clearer to me :)

Initialisers and Self

The init method can contain parameters. I've never got used to the whole 'self' thing. It's when distinguishing between parameter labels and property names. Pasan says only to use it within init methods but nowhere else, unless necessary. 

Summary

  • A struct - one of the objects used in Swift to create custom data type
  • Uses stored properties/values
  • It can use functions - these are methods
  • Stored properties and functions can only be used after creating an instance 
  • We can write out a special init method - assign values to all the stored properties during creation (still not too sure about this yet...)
  • Referring to an instance of the structure - use the keyword self. 

The code challenge was puzzling at first but I got it!

struct RGBColor {
    let red: Double
    let green: Double
    let blue: Double
    let alpha: Double
    
    let description: String
    
    // Add your code below

  init (red: Double, green: Double, blue: Double, alpha: Double) {
    
    self.red = red
    self.green = green
    self.blue = blue
    self.alpha = alpha
    
        description = "red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)"
    
}


In this, I basically used the init method, which used all of the same constants, then applied self to them, then had the string created which would access each value. Still not COMPLETELY sure the point of this but it's a good introduction!

Again, these tutorials and courses are really helping me. Next time it will be 'Classes', which I know are similar to structs but there's more you can do, including 'inheritance'. Until then!


Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)