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 Closures in Swift 2 First Class Functions Higher Order Functions

Javier Porras
Javier Porras
11,382 Points

Stuck on task 2 of 3; extending String, and function code.

I'm having trouble getting passed the challenge, I believe the issue is with me accessing the array of characters.

functions.swift
// Enter your code below
extension String{
    func modify(a: String -> String) -> String {
        return  a(self)
    }
}

func fistLetter(userString: String) -> String{
   let tempVar = userString.characters
   return tempVar[0]
}
Javier Porras
Javier Porras
11,382 Points

var string = "Hello, playground" let firstCharacter = string.characters.first // returns "H" let lastCharacter = string.characters.last // returns "d"

1 Answer

Mohamed Moukhtar
PLUS
Mohamed Moukhtar
Courses Plus Student 6,151 Points

The characters property returns a character view object not an array of characters, therefore you can’t access the first character using index as in arrays, yet to access the first character you have to access the β€œfirst” property and then use string interpolation to return the required value as String

extension String{ func modify(a: String -> String) -> String { return a(self) } }

func firstLetter(userString: String) -> String{ if let firstCharacter = userString.characters.first { return "(firstCharacter)" } else { return "" } }

"Test String".modify(firstLetter)

// as an alternative if you want to use index you can use the Map method to transform every element in string characters into String as following

func firstLetter1(userString: String) -> String{ let array = userString.characters.map { character in return String(character) } return array[0] }

"Another String".modify(firstLetter1)