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

Make sure you're only extending the array where Element conforms to PrefixContaining

ain't what I'm doing?

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

extension Array: < Element: PrefixContaining > {
associatedtype Element

var test = [Element]


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

return test.hasprefix


 }
 }

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,861 Points

Hi John,

For your Array extension, watch the video again, especially at 3:06 where Pasan extends Array to make the type's Elements conform to his protocol. You want to use the same syntax he uses.

Then for the implementation of filter, remember that hasPrefix() is a method on types conforming to PrefixContaining. As we see in the example code, String conforms to PrefixContaining but Array doesn't. Therefore it makes no sense to try to call hasPrefix() on test, which you declared as an array. Also, because you've not used parentheses, you wouldn't be calling hasPrefix even if it were valid on an array.

When you implement the filter method, you should think about what Apple has already provided as a filter method and whether you can use the inputs you've been provided in the challenge to apple's own filter method to return an array of type [Element].

Hope those hints point you in the right direction.

Cheers

Alex

not really but thks anyway

protocol PrefixContaining {

associatedtype Element var test = [Element] {get} func hasPrefix(_ prefix: String) -> Bool func filter(byPrefix prefix: String) -> [Element] }

extension Array where Element: PrefixContaining {

func hasPrefix(_ prefix: String) -> Bool { func filter(byPrefix prefix: String) -> [Element] {

} return }