Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Stuck on Closures Part 3 of challenge

Hoping someone can point me in the right direction:

// Enter your code below
extension String {
    func transform(_ function: (String) -> String) -> String {
        return function(self)
    }
}

func removeVowels(from word: String) -> String {
    let vowels = ["a", "e", "i", "o", "u"]
    var newString = ""
    for char in word.characters {
        let lowercaseChar = String(char).lowercased()
        if vowels.contains(lowercaseChar) == nil {
            newString += lowercaseChar
        }

    }
    return newString
}

let helloString = "Hello World!"
helloString.transform(removeVowels(from: helloString)

2 Answers

Jeff McDivitt
Jeff McDivitt
23,970 Points

This is how I did it, but there are probably better ways

extension String{

    func transform(_ argument : (String) -> String) -> String {
        return  argument(self)
    }
}

func removeVowels(from value: String) -> String {
    var output = ""

    for char in value.characters {
        if !(char == "a" || char == "A" || char == "e" || char == "e"
            || char == "i" || char == "I" || char == "o" || char == "O"
            || char == "u" || char == "U") {
            output.append(char)
        }
    }
    return output
}

"Hello, World!".transform(removeVowels)

Thanks, It was the last line I wasn't sure about how to implement. I was trying to figure out a way to use enums but ended up with this as my final code:

extension String {
    func transform(_ function: (String)-> String) -> String {
        return function(self)   
    }
}

func removeVowels(from word: String) -> String {

    let vowels = ["a", "e", "i", "o", "u"]
    var newString = ""

    for char in word.characters{
        if vowels.contains(String(char).lowercased()) == nil {
            newString += String(char)  
        }
    }
    return newString
}

"Hello, World!".transform(removeVowels)
Jeff McDivitt
Jeff McDivitt
23,970 Points

Allen Soberano I like the way you handled it, it is much cleaner

Thanks Jeff! Would like to figure out using enums.