LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Day 11: "When you should use extensions in Swift"

Forums > 100 Days of SwiftUI

This page really confuses me. It's so abstract to me, I barely know what protocols are yet, same goes for extensions, and I do not see the correlation between them, or what conformance grouping and purpose grouping really are. Basicaly, I'm overwhelemd. Help, anyone? Thanks.

3      

Someone is sitting by the beach thinking of purpose vs conformance.

I barely know what protocols are yet, same goes for extensions, and I do not see the correlation between them, or what conformance grouping and purpose grouping really are. Basicaly, I'm overwhelemd.

This is an example of purpose grouping.

Keep this in mind: You are coding an extension to String for a specific purpose.

Say it again. You are coding an extension to String for a specific purpose.

String out of the box functions

First, what does the String type offer? Paste this code into Playgrounds. Playgrounds is a GREAT way to test concepts and play with options.

See -> Swift String Documentation

import UIKit
// Start with a simple string. What can you do with this string??
var hwsLearner = "vacation"  // Create a string

// Type hwsLearner <dot>
// XCode will show you all the built-in methods
// that you can chain to your variable.
// In swift these are sometimes called modifiers.
// But behind the scenes, they are prebuilt functions.
print(String(hwsLearner.reversed()) )   // very Swifty way to reverse a string
print(hwsLearner.uppercased()       )   // another modification
print(hwsLearner.contains("cat")    )   // function returns a bool
print(hwsLearner.isEmpty            )   // function returns a bool
print("\(hwsLearner.count) letters" )   // what do you think this does?
print(String(hwsLearner.shuffled()) )

I need a Translate function!

But what if you want to translate your string into Pig Latin.
vacation -> acation-vay

Swift does not provide a built-in method to do this.
Lucky you! Your task is to write your own stand alone function.

//
enum KnownLanguages {
    case PigLatin, Klingon, ScoobyDoo, Unknown
}
//
// TODO: - Exhaust all the valid PigLatin use cases.
func translate(_ someText: String, into language: KnownLanguages) -> String {
    if language == .PigLatin {
        var someText    = someText               // Trick code. Change parameter into local variable.
        let firstLetter = someText.removeFirst() // Remove first letter
        someText       += "\(firstLetter)ay"     // Slap first letter and "ay" to end of word.
        return String(someText).capitalized      // Zip it and Ship it.
    } else { return "unknown language"}
}

// Then you can use this function thusly:
 let translatedHWSLearner = translate( hwsLearner, into: .PigLatin)  // returns Acationvay

🤮 Not very Swifty

This works! 🥳🥂 But, this function is not very swifty. 🤮

Instead this is the business case for extending the functionality of String. It's not a built-in function, but don't let that stop you! EXTEND the built-in capabilities of String! Do it!

// Continue in Playgrounds.....
//
// Say it again. You are coding an extension to String for a specific purpose.
// PURPOSE GROUPING ------------------------------
extension String {
    // This function works on a string, so use SELF
    func translate(into language: KnownLanguages) -> String {
        if language == .PigLatin {
            var someText    = self                   // self is the actual string you're modifying
            let firstLetter = someText.removeFirst() // Remove first letter
            someText       += "\(firstLetter)ay"     // Slap first letter and "ay" to end of word.
            return String(someText).capitalized      // Zip it and Ship it.
        }
        return ""
    }
}

// Voila!  String now has a new function.
print (hwsLearner.translate(into: .PigLatin))  // This is more Swifty!

Keep coding!

Because it's an extension, it will be easy for you to cut / paste into other projects where you might need igpay atinLay.

5      

I totally understand where you're coming from. When delving into complex topics like protocols, extensions, conformance grouping, and purpose grouping, it's natural to feel overwhelmed.

Protocols are essentially sets of rules that devices or systems follow to communicate effectively. Extensions often enhance or expand upon these rules. Conformance grouping and purpose grouping are ways to categorize and organize these rules and extensions.

Take it step by step, and don't hesitate to ask specific questions. We're here to help you navigate this complexity. You're not alone in your confusion, and with time and guidance, it will start making more sense. Keep asking questions, and you'll get there

3      

Part Deux

I barely know what protocols are yet, same goes for extensions,
and I do not see the correlation between them, or what conformance grouping is ...[snip]....

What is Conformance?

Swift boffins use the term conformance to indicate that a struct implements a protocol. Clear as mud?

Think of it in other terms. In his CS193p course Paul Hegerty describes protocols as a behaviour. Instead of saying conformance (which may be abstract) try substituting Behaves Like

Sorting Fruit

An example might be you have a Fruit structure that captures the name, color, and caloric density of fruit. Create an array of these Fruit objects.

struct Fruit {
    var name:           String  // Watermelon
    var icon:           String  // 🍉
    var color:          String  // Tricolor
    var caloricDensity: Int
}

// In playgrounds create an array.
var fruitBowl: [Fruit]  // <- An array of fruit objects.

Now sort them!

The compiler will complain that you cannot sort the array of Fruit objects. Why? Because your basic Fruit structure does not behave the way that comparable objects behave!

Protocols to the Rescue

This is where protocols come in handy. On their own, how do you compare one fruit (apple) to another (kiwi) ? How would you sort them? By calories? By color? Alphabetically?

Conform to Behave Like a Comparible object

Apple has provided a protocol named Comparible. If you make your Fruit structure conform to behave like something that can be compared, Swift will give you a free sorted() method to use on your array of fruits.

Below is a link to an example, using a Fruit structure, I wrote a while back. Please notice how the sorting code is in an extension to the Fruit structure! This is an example of Conformance Grouping. The code to conform to Comparible is in its own extension. This keeps Fruit definitions and Fruit specific functions separate from Comparible functions.

It's not required, but is a very common way Swift programmers organize their code.

See -> Conformance Grouping

3      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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.