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

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!