David
David

Reputation: 55

String does not have a member named characters?

I was trying the Swift playground. When I tried the code below, it did not work and told me 'String' does not have a member named 'Characters'. I expect to print the number of characters in cafe is 4. Could you give me any tips? Thanks.

var word = "cafe"
print("the number of characters in \(word) is \(word.characters.count)")

Upvotes: 5

Views: 1782

Answers (4)

cjnevin
cjnevin

Reputation: 311

Also, to get the actual characters you can call:

let characters = Array(string)

You could then simply call:

let length = characters.count

However, you could also just use the count function if you don't need to iterate the characters or anything in Swift 1.2:

let length = count(string)

In Swift 2:

let length = string.count()

Upvotes: 0

Martin R
Martin R

Reputation: 539705

characters is a property of String in the "new" Swift 2 that comes with Xcode 7 beta.

You are probably using Xcode 6.3.2 with Swift 1.2, then it is

print("the number of characters in \(word) is \(count(word))")

Two things changed with Swift 2.0 here:

  • String does no longer conform to SequenceType, you have to access .characters explicitly,
  • The global count() function has been replaced by a "protocol extension" method count().

Upvotes: 13

thatthing
thatthing

Reputation: 676

Use the count characters method:

println(the number of characters in \(word) is \(count(word))")

With Swift 2:

word.characters.count

Upvotes: 0

Lucas Huang
Lucas Huang

Reputation: 4016

I think you are reading the Swift 2 tutorial from iBook. That's the new feature. And it will only work in Xcode 7.

Upvotes: 0

Related Questions