Does the string have no name with a name?

I tried the Swift playground. When I tried the code below it didn't work and told me 'String' does not have a member named 'Characters' . I look forward to printing the number of characters in cafe is 4 . Could you give me some advice? Thanks.

 var word = "cafe" print("the number of characters in \(word) is \(word.characters.count)") 
+5
source share
4 answers

characters is a String property in the "new" Swift 2, which ships with Xcode 7 beta.

You are probably using Xcode 6.3.2 with Swift 1.2 and then

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

In Swift 2.0, two things have changed here:

  • String no longer matches SequenceType , you need to access .characters explicitly,
  • The global function count() been replaced by the protocol extension method count() .
+13
source

I think you are reading the Swift 2 tutorial from the iBook. This is a new feature. And it will only work in Xcode 7 .

0
source

Use the count count method:

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

With Swift 2:

 word.characters.count 
0
source

Alternatively, to get valid characters, you can call:

 let characters = Array(string) 

Then you can simply call:

 let length = characters.count 

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

 let length = count(string) 

In Swift 2:

 let length = string.count() 
0
source

All Articles