Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Closures in Swift First Class Functions Higher Order Functions

Randell Pur
Randell Pur
4,934 Points

What is the difference between these 2?

both of them do the same thing in Xcode so I am a little confused about the difference, or if there is one.

the first one let result = removeVowels(from:"Hello World!")

the second one "Hello, World!".transform(removeVowels)

functions.swift
// Enter your code below
extension String {
    func transform(_ argument : (String) -> String) -> String{
        return argument(self)
    }
}

func removeVowels(from string: String) -> String {
    var newString = ""
    for character in string.characters {
        if ["a","e","i","o","u"].contains(character) {
            continue
        }

        newString.append(character)
    }

    return newString
}

let result = removeVowels(from:"Hello World!")
Randell Pur
Randell Pur
4,934 Points

on the second one, I know I have to add the let result for the code to work, I am mainly looking for the difference between the 2 code snippets and why they do the same thing but are written differently

1 Answer

So your goal is to use the extension to call the function removeVowels. I think this is more about teaching you to use extensions. Both examples you give are actually using removeVowels() to do the job. Transform is calling the function on itself and could be reused with any function that takes a String and returns a String. For example:

func removeWhiteSpace(from string: String) -> String {
    let newString = string.lowercased()
    return newString
}

let result2 = "Hello, World!".transform(removeWhiteSpace)