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 trialAnthia Tillbury
3,388 PointsAppending generic value to return array in Extending Generic Types Task
I think I have the logic needed to pass the task, but I shamefully cannot append a generic value (which should be String) to the return array. Or, I could just be wrong.
protocol PrefixContaining {
func hasPrefix(_ prefix: String) -> Bool
}
extension String: PrefixContaining {}
extension Array where Element: PrefixContaining {
func filter(byPrefix prefix: String) -> [Element] {
var output: Element
for (index, element) in self.enumerated() {
if element.hasPrefix(prefix) {
output = element
return [element]
}
}
print("no match")
return []
}
}
let test222 = ["aa", "ba", "ca", "ab"]
let result = test222.filter(byPrefix: "a")
3 Answers
Paolo Scamardella
24,828 PointsNote from Moderator:
Thanks for helping out on the forum! The contents of this post has been removed because it was a solution to the challenge without any explanation. While this might help the student to pass the challenge, it is better to have an explanation so the student know's why the solution works.
Paolo Scamardella, feel free to edit this post, remove this message, and explain the solution to the challenge.
Happy Coding!
Anthia Tillbury
3,388 PointsThank you very much for the detailed feedback. I am still unsure what initialising a variable "Element" actually means?
I used index because it was an Array and I though that looping inside the array would be done this way.
I would have returned the result outside the if block but I just couldn't get that to work.
Paolo Scamardella
24,828 PointsJust look at my example. It worked for me in the code challenge.
Anthia Tillbury
3,388 PointsYes, it works and I understand why, I got the Generic stuff right, so I don't mind reaching out. I need to understand initialisation better, for some reason that passed me by.
Paolo Scamardella
24,828 PointsPaolo Scamardella
24,828 Pointsyou are not initializing output correctly.
you do not need to use index and .enumerated.
you need to append the result(element in your case) into output (inside if block).
you do not return the result inside the if block.
you need to return output after the foreach loop.