NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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()

   

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.

1      

@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

    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")

banana.description  // Check your objects.
apple.description   // This 🍏 granny smith is Green.
peach.description   // This πŸ‘ peach is Pinkish.
lemon.description   // This πŸ‹ lemon is Yellow. 

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

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

Now try some common array functions on your fruit bowl.

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!

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 conform, 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 {
    // 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. 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. This doesn't require a function. Identifiable only requires your struct to have a property named id that you guarantee is unique.

// 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.

1      

@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.

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Reply to this topic…

You need to create an account or log in to reply.

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.