Veronica G Veronica G - 1 year ago 98
Swift Question

Wrong order in string array

I have this code that passes the entries from textfield and adds them to a string array in another view controller. The problem is, the order is not correct.

This is my code:

@IBOutlet weak var text1: UITextField!
@IBOutlet weak var text2: UITextField!
@IBOutlet weak var text3: UITextField!
@IBOutlet weak var text4: UITextField!
@IBOutlet weak var text5: UITextField!
@IBOutlet weak var text6: UITextField!

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.

//Delegates each textfield
text1.delegate = self
text2.delegate = self
text3.delegate = self
text4.delegate = self
text5.delegate = self
text6.delegate = self

//Tags each textfield
text1.tag = 1
text2.tag = 2
text3.tag = 3
text4.tag = 4
text5.tag = 5
text6.tag = 6


func textFieldShouldReturn(textField: UITextField) -> Bool {

let nextTag: NSInteger = textField.tag + 1;

if let nextResponder: UIResponder! = textField.superview!.viewWithTag(nextTag){


else {



return false


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

let destination = segue.destinationViewController as! secondView

if segue.identifier == segueID {

//Adds the textfield entries to the string array on the second view controller
destination.stringArray = view.subviews.flatMap { ($0 as? UITextField)?.text }

destination.delegate = self



But I have no idea what is wrong with my code, why would it send the incorrect order to my array. My array looks like this:

["q", "w", "e", "t", "y", "r"]

when it should be...

["q", "w", "e", "r", "t", "y"]

This is just random letters I chose, the entries could be anything really. But the order is important. Could someone check my code, see where did I go wrong? Thank you in advance.

Answer Source

You need to sort the UITextField(s) you are retrieving

So replace this

destination.stringArray = view.subviews.flatMap { ($0 as? UITextField)?.text }

with this

destination.stringArray = view
    .flatMap { $0 as? UITextField }
    .sort { $0.0.tag < $0.1.tag }
    .flatMap { $0.text }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download