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 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..