Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

I'm trying to reverse string in Swift 2.0 but I get an error on the string ifself.

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

    return buffer
}

The error:

Type 'String' does not conform to protocol 'SequenceType'
like image 330
ytpm Avatar asked Oct 02 '15 14:10

ytpm


1 Answers

Easy 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() has been renamed to reversed()

Swift 4:

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

func reverseString(string: String) -> String {
    return String(string.reversed())
}
like image 50
vadian Avatar answered Oct 21 '22 17:10

vadian