'String' type does not conform to 'SequenceType' protocol - Swift 2.0

I am trying to change a line in Swift 2.0, but I get an error in the ifself line.

func reverseString(string: String) -> String { var buffer = "" for character in string { buffer.insert(character, atIndex: buffer.startIndex) } return buffer } 

Error:

 Type 'String' does not conform to protocol 'SequenceType' 
+5
source share
2 answers

A simple solution:

 func reverseString(string: String) -> String { return String(string.characters.reverse()) } 

Your code works with this change

 for character in string.characters { 

Swift 3:

In Swift 3, reverse() been renamed reversed()

Swift 4:

In Swift 4 characters can be omitted because String returns to behave like a sequence.

 func reverseString(string: String) -> String { return String(string.reversed()) } 
+22
source

Like Swift 2, String does not match SequenceType .

You can add an extension.

 extension String: SequenceType {} 
0
source

Source: https://habr.com/ru/post/1232805/


All Articles