iosxcodeswiftuipickerviewuipickerviewcontroller

Trouble with scope and arrays SWIFT


Hi Im developing an app with Parse and when the user creates an account there's an UIPickerView with different strings the user has to choose from. Im trying to save their choice in a string. I've got it working with but that saves a number not a string.

let myRank = picker.selectedRowInComponent(0)

When i try

let myRank = pickerArray[row]

i get an error saying "Use of unresolved identifier "row". This I guess is because of scope but I don't know how to solve it!

Here's my code:

let pickerArray: NSArray = ["- Välj din kompetens -", "Assistent", "Instruktör", "Biträdande Kurschef", "Kurschef"]

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerArray.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return "\(pickerArray[row])"
}

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
    // selected value in Uipickerview in Swift
    let rank = pickerArray[row]

}

@IBAction func registerButtonPressed(sender: UIButton) {

    let myRank = pickerArray[row]

    var user = PFUser()
    user.username = email
    user.password = password
    user.email = email
    user[PF_USER_RANK] = myRank
    user[PF_USER_EMAILCOPY] = email
    user[PF_USER_FULLNAME] = name
    user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError!) -> Void in
        if error == nil {
            PushNotication.parsePushUserAssign()
            ProgressHUD.showSuccess("Succeeded.")
            self.dismissViewControllerAnimated(true, completion: nil)
        } else {
            if let userInfo = error.userInfo {
                ProgressHUD.showError(userInfo["error"] as String)
            }
        }
    }
}

Solution

  • You won't have access to row unless you store it as an instance variable.

    I think this is a case where it would be unnecessary, though. You're half-way there. You have already discovered how to retrieve the selected row index from your picker and you already know how to select a specific string from your pickerArray based on an index. Just combine the two:

    let myRank = pickerArray[picker.selectedRowInComponent(0)]