Reversing a string in Swift 4.2

Viewed 2040

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?

5 Answers

You should unwrap the str variable before set newStr:

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

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

if let str = self.label?.text {
    let newStr = String(str.reversed())
}
extension Optional where Wrapped == String {
    func reversed() -> String? {
        guard let str = self else { return nil }
        return String(str.reversed())
    }
}

Usage:

str?.reversed()

Plenty of variations on a theme here so far, so you know the basic issue – str is optional. We'll add a couple more (guard & map free ;-))...

For those who dream in C:

let newStr = str == nil ? nil : String(str!.reversed())

If you're not expecting nil and/or want a String back regardless you could use:

let newStr = String((str ?? "").reversed())

which is probably about as short as you can go.

Reverse a text value You can pass a textfield value to another textfield by reversing

First View controller

  class ViewController: UIViewController {

  var str = NSString()


@IBOutlet weak var txt1: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func button1(_ sender: Any) {


    let story: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let new = story.instantiateViewController(withIdentifier: "RevViewController")as! RevViewController


    let str = txt1.text!
    new.txtvalue = String(str.reversed())


    self.navigationController?.pushViewController(new, animated: true)


    }

   }

Second view controller

   class RevViewController: UIViewController {

 var txtvalue = String()

@IBOutlet weak var textfld2: UITextField!



override func viewDidLoad() {
    super.viewDidLoad()

    textfld2.text = txtvalue

}


}
Related