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 Functions in Swift Functions in Swift Return Types

Surinder Singh
Surinder Singh
274 Points

how to write a function that takes string input and returns number of characters

function that takes string input and returns number of characters and characters as well

7 Answers

Thomas Dobson
Thomas Dobson
7,511 Points

Surinder,

That was the full code:

//Function Body
func countString (byNumberOfCharactures count: String) -> Int {
    let myString = count
    let countMyString = myString.characters.count

    return countMyString
}

//Calling the function on string "This is a Duck"
countString(byNumberOfCharactures: "This is a Duck")
//returns 14
Thomas Dobson
Thomas Dobson
7,511 Points

Hi Surinder,

try something like this

func countString (byNumberOfCharactures count: String) -> Int {
    let myString = count
    let countMyString = myString.characters.count

    return countMyString
}

countString(byNumberOfCharactures: "This is a Duck")
//returns 14

I didn't know this either, but as always there is lots of good documentation provided by apple.

Here is where I found this information: Swift Standard Library: Strings and text

I hope this helps

Surinder Singh
Surinder Singh
274 Points

Its showing the error >>>> result of call to 'countString(byNumberOfCharacters;)' is unused

Thomas Dobson
Thomas Dobson
7,511 Points

not sure what your seeing, the above function and call statement are compiling in Xcode 8 and Xcode 9 for me?

Surinder Singh
Surinder Singh
274 Points

can you please send me complete code

Surinder Singh
Surinder Singh
274 Points

Thank you Thomas! Its working fine.

Surinder Singh
Surinder Singh
274 Points

what if I have to display number of words besides number of character?