Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a string in Swift 4.2

iOS 11, Swift 4.2, Xcode 10

Looking at SO and indeed googling all seem to suggest this should work, but it doesn't.

let str = self.label!.text
let newStr = String(str?.reversed())

I get an error message Cannot invoke initializer for type 'String' with an argument list of type '(ReversedCollection?)... so how do I get my string back?

like image 954
user3069232 Avatar asked Nov 27 '22 13:11

user3069232


2 Answers

You should unwrap the str variable before set newStr:

guard let unwrappedStr = str else { return }
let newStr = String(unwrappedStr.reversed())
like image 167
Ilya Kharabet Avatar answered Dec 06 '22 02:12

Ilya Kharabet


You can't create String from optional ReversedCollection. You need to unwrap str.

if let str = self.label?.text {
    let newStr = String(str.reversed())
}
like image 39
subdan Avatar answered Dec 06 '22 01:12

subdan