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

Brandon Mahoney
Brandon Mahoney
iOS Development with Swift Techdegree Student 25,115 Points

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)