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

Extract first character of Swift String object instance using the characters property

How do you extract the fist character from a string instance in Swift?

See my code in attachment, probably don't have the right syntax to extract proper index...?

functions.swift
extension String {
      func modify(fun: String -> String) -> String {
          return fun(self)
          }

      func firstLetter(str: String -> String) {
          return str.characters.startIndex
          }
      }

2 Answers

I actually figured one solution out. Please feel free to share if you have something better.

Here is my code:

let str: String = "Hello"

str.characters.startIndex
str.characters[str.characters.startIndex]
Abhishek Salokhe
Abhishek Salokhe
10,612 Points

Bit late, but you may use like below:

let message = "Hello World"
print(message.first)

Done. .first will return the first character of the string. Make sure you check on empty string/nil result.