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 Generics in Swift Generics and Protocols Extending Generic Types

Akos Turi
Akos Turi
7,517 Points

challenge

protocol PrefixContaining { func hasPrefix(_ prefix: String) -> Bool }

extension String: PrefixContaining { func hasPrefix(_ prefix: String) -> Bool { var matching = false

    if prefix.characters.count <= self.characters.count {

    let distance = self.index(self.startIndex, offsetBy: prefix.characters.count)

        if prefix == self.substring(to: distance) {
            matching = true
        }
    }
    return matching
}

}

extension Array where Element: PrefixContaining {

func filter(byPrefix prefix: String) -> [Element] {
    var newArray: [Element] = []

    for item in self {
        if item.hasPrefix(prefix) {
            newArray.append(item)
        }
    }

    return newArray
}

}

let test = ["akos", "ba", "ca", "akosturi", "aki"] let result = test.filter(byPrefix: "akos")

probably this is not the best solution, but it works for me, although i got compiler error in the treehouse compiler. In my Xcode i tried it with many times and it works fine. Thanks for the help in advance.

1 Answer

Jason Tjahja
Jason Tjahja
8,668 Points

Hello, just a reminder String has a instance method which is hasPrefix( ) that takes specific prefix, also return a boolean value of true if the string has the prefix, so... you can make less effort to find out your string has specific prefix rather than code it in hard way..