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

Napatchol Thaipanich
PLUS
Napatchol Thaipanich
Courses Plus Student 13,534 Points

how to do it

Next we need to define a function that we can apply as an operation on a String literal. Create a function named firstLetter that takes a string and returns a string. In the body, return the first character of the string passed in.

Hint: To get individual letters in a string, use the characters property, which returns an array of Character type.

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

func firstLetter(sth: String)->String{
  return String(sth.characters.first)
}

1 Answer

Hannah Gaskins
Hannah Gaskins
14,572 Points

hey there Napatchol,

You are really close.

You will need to force unwrap the .first property as that takes an optional value. Here is a look at what I did:

// Enter your code below
extension String {
    func modify(arg: String -> String) -> String {
      return arg(self)
    }
}

func firstLetter(arg: String) -> String {
    return String(arg.characters.first!)
}

hope this helps!