user3069232
user3069232

Reputation: 8995

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?

Upvotes: 4

Views: 2676

Answers (5)

Faizal Nowshad KN
Faizal Nowshad KN

Reputation: 109

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

}


}

Upvotes: 1

CRD
CRD

Reputation: 53000

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.

Upvotes: 3

RahmiBozdag
RahmiBozdag

Reputation: 138

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

Usage:

str?.reversed()

Upvotes: 4

Ilya Kharabet
Ilya Kharabet

Reputation: 4621

You should unwrap the str variable before set newStr:

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

Upvotes: 13

Daniil Subbotin
Daniil Subbotin

Reputation: 6708

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

if let str = self.label?.text {
    let newStr = String(str.reversed())
}

Upvotes: 7

Related Questions