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