2015-10-02 14 views
5

Sto provando a invertire la stringa in Swift 2.0 ma ottengo un errore sulla stringa ifself.Tipo 'String' non conforme al protocollo 'SequenceType' - Swift 2.0

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

    return buffer 
} 

L'errore:

Type 'String' does not conform to protocol 'SequenceType' 

risposta

22

soluzione facile:

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

Il tuo codice funziona con questo cambiamento

for character in string.characters { 

Swift 3:

In Swift 3 reverse() è stato rinominato reversed()

Swift 4:

In Swift 4 characters può essere omesso perché String rinviato a comportarsi come una sequenza.

func reverseString(string: String) -> String { 
    return String(string.reversed()) 
} 
0

Come di Swift 2, String non è conforme al SequenceType.

È possibile aggiungere un'estensione.

extension String: SequenceType {} 
+0

Nota: SequenceType 'è stato rinominato in' Sequenza '. La conformità di "String" al protocollo "Sequence" era già stata stabilita nel modulo del tipo "Swift" –

Problemi correlati