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

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!