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

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,887 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 }