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

nicholasdevereaux
nicholasdevereaux
16,353 Points

Closures - how to use 'characters' property without force unwrapping?

In this task, we are asked to use the 'characters' property to return the first letter in the string passed through the function. The only way I could get it to work was by using the "!"

I also found a way to make it work by using 'index'. Which function would make more sense here?

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

func firstLetter(b: String) -> String {
    return "\(b[b.startIndex])"
}

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

1 Answer

nicholas, as you say, they ask you to use characters, so here's an alternative. Doesn't seem any better than yours, however:

func firstLetter(b: String) -> String {
    return "\(b[b.characters.prefix(0)] )"
}

You can also get the first character and then cast it to a String (without the forced unwrapping):

func firstLetter(b: String) -> String {
    return "\(String(b.characters.first))"
}
nicholasdevereaux
nicholasdevereaux
16,353 Points

Jcorum thanks for sharing, this really helped!