Reversing a string in Swift 4.2

  • A+
Category:Languages

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?

 


You should unwrap the str variable before set newStr:

guard let unwrappedStr = str else { return } let newStr = String(unwrappedStr.reversed()) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: