UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: My checkpoint 8. Please be brutal ;D

Forums > SwiftUI

At first swift seemed pretty easy. But, the last couple of days have me begging for mercy.

I just barely... barely understand what I'm doing here. But, after a lot of messing around with it and checking past lessons I think I got it working as requested.

Do you guys ever feel like you don't know what you don't know? I don't even know what to ask at this point. Ha

I learned the shorcuts for highlighting and commenting code in xcode today if achieving nothing else.

//Describe a building with a protocol
protocol Building {
    var type: String { get }
    var rooms: Int { get set }
    var price: Int { get }
    var agent: String { get }
}

//Add an extension to Building protocol to access function from structs
extension Building {
    func salesSummary() {
        print("\(rooms) room \(type) sold for $\(price) by \(agent)")
    }
}

//Create two structs to conform to Building protocol
struct House: Building {
    let type: String
    var rooms: Int
    let price: Int
    let agent: String

}

struct Office: Building {
    let type: String
    var rooms: Int
    let price: Int
    let agent: String

}

//Create copy of House
var house = House(type: "House", rooms: 3, price: 500_000, agent: "Harvey")

//Update rooms
house.rooms = 4

house.salesSummary()

//Create copy of Office
var office = Office(type: "Office", rooms: 22, price: 10_000_000, agent: "Suzanne")

//Update rooms
office.rooms = 24

office.salesSummary()

2      

This looks fine to me. It's kind of hard to understand the purpose of protocols when you first learn about them, and just create one for no reason other than that you were told to.

But, later on, you will learn how to make your own structs/classes conform to protocols that exist in Swift natively, and then I think the purpose of them becomes a bit more clear.

As long as you got the idea well enough to do what you have done for now, I think you'll be in good shape for the future.

3      

@Ostrich has a great observation:

It's kind of hard to understand the purpose of protocols when you first learn about them,
and just create one for no reason other than that you were told to.

So true!

Here's an example from my Playgrounds to help me process Protocols.

This is a simple fruit structure:

struct Fruit {
    var name:   String  // Watermelon
    var icon:   String  // πŸ‰
    var color:  String  // Tricolor 
}

// Conformance Grouping. Fruit behaves like a CustomStringConvertible
extension Fruit: CustomStringConvertible {
var description: String {
        "This \(icon) " + name.lowercased() + " is " + color + "."
    }
}

Simple enough. Now create a simple fruit bowl.

let banana     = Fruit(name: "Banana",       icon: "🍌", color: "Yellow"  )
let apple      = Fruit(name: "Granny Smith", icon: "🍏", color: "Green"   )
let peach      = Fruit(name: "Peach",        icon: "πŸ‘", color: "Pinkish" )
let lemon      = Fruit(name: "Lemon",        icon: "πŸ‹", color: "Yellow"  )
let watermelon = Fruit(name: "Watermelon",   icon: "πŸ‰", color: "Tricolor")

// Check your objects
banana.description  // This 🍌 banana is Yellow.
apple.description   // This 🍏 granny smith is Green.
// Because Fruit behaves like a CustomStringConvertible
// It knows how to describe itself.  No need to add .description
peach   // This πŸ‘ peach is Pinkish.
lemon   // This πŸ‹ lemon is Yellow. 

var fruitBowl = [peach, apple, peach, watermelon, lemon, banana, banana] // some random order

Run this in Playgrounds and you'll see you have an array of Fruit objects. So far, so good.

Now try some common array functions on your fruit bowl.

// Common array functions
fruitBowl.randomElement()!.description  // Fruit struct works great in an array.
fruitBowl.first!.icon                   // Fruit struct works with array.

// This line tosses an error!
// Referencing instance method 'sorted()' on 'Sequence' requires that 'Fruit' conform to 'Comparable'
fruitBowl.sorted()

How do you sort fruit?

It's easy to sort Strings. Simple to sort Integers. But Swift has no idea how to sort Fruit. By color? By icon? By caloric density? You may be tempted to write your own Bubble sort routine to compare two Fruit objects and generate a new sorted array. This is a LOT of work. Plus, in future applications, you'll have to write your own sort routines to sort Books, Recipes, BucketList items, etc.

This is the strength of Protocols. Swift boffins devised a protocol named Comparable. In short, the Comparable protocol is a collection of rules that allows Swift to compare two of the same objects. By making your Fruit structure conform to the Comparable protocol, you'll gain all the benefits that Swift provides for sorting objects! Free!

In other words, make your Fruit object Behave Like something that can be compared.

Let's conform!

So add this to your Fruit playground:

// Keep your original structure.       
// But tell Swift that your struct now conforms to the Comparable protocol.
// To Behave Like something that can be compared, Swift requires you to add one function.         
// This function takes any two Fruit objects (left hand side and right hand side)        
// and you tell Swift which one is higher in the sorted order. Swift handles the rest.
extension Fruit: Comparable { // <-- Also Conformance Grouping
    // This function is required to conform to the Comparable protocol.
    static func < (lhs: Fruit, rhs: Fruit) -> Bool {
        lhs.name < rhs.name // <- This is how you compare two fruits. Must return a boolean
    }
}

Now, when you run the line below, Swift knows how to sort your Fruits. All you had to do was add a Protocol to your existing Fruit object. In otherwords, a Fruit structure behaves like something can can be compared.

// Because Fruit objects conform to comparable,     
// you can, well, compare them and sort them. Easy!
fruitBowl.sorted().forEach { fruit in
    print( fruit.description )
}

Sorted Results

When I run the line in Playgrounds I see:

This 🍌 banana is Yellow.
This 🍌 banana is Yellow.
This 🍏 granny smith is Green.
This πŸ‹ lemon is Yellow.
This πŸ‘ peach is Pinkish.
This πŸ‘ peach is Pinkish.
This πŸ‰ watermelon is Tricolor.

More Behaviours

If you want to show your fruits in a List view, Swift may want to know how to identify one piece of fruit from another. To do this, you'll have to make your Fruit conform to the Identifiable protocol. Your Fruit object needs to behave like something that can be identified, or distinguished from another, similar object.

This doesn't require a function. Identifiable only requires your struct to have a property named id that you guarantee is unique.

Keep Coding!

3      

@Obelix Thank you! This is like a who 'nother lesson on it. I bookmarked this to mess with it in playground later. The fruit salad idea already makes more sense than the buildings.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.