在 Swift 的 switch / case 函数中使用数组

Posted

技术标签:

【中文标题】在 Swift 的 switch / case 函数中使用数组【英文标题】:Using an array within a switch / case function in Swift 【发布时间】:2016-07-03 08:57:51 【问题描述】:

我正在尝试向我现有的应用程序添加一个选择器视图。然而,我遇到了一个障碍。我还是 Swift 的新手,我不知道如何描述这一点,但希望你能充分理解以下内容,以便提出适当的问题来解决这个问题。

我收到的错误消息是“致命错误:索引超出范围”:

cell.txtField_PickData.text = self.arrayTemprature[indexPath.row].valueForKey("tempValue") as? String

myTitleArry 等于两个输入“气温”或“水温”

这是围绕此错误的代码部分。如果需要更多代码来帮助识别问题,很乐意提供:

import UIKit

class DiveDetailsViewController: UITableViewController, LocationDelegate, ItemDataSelectedProtocol, UITextFieldDelegate , UIPickerViewDataSource , UIPickerViewDelegate


let numberOfComponents: Int             = 2
let temperatureComponentRows: Int       = 131
let temperatureSymbolComponentRows: Int = 2

let Fahrenheit: String                  = "F"
let Celsius: String                     = "C"
let minDegrees                          = -10
let maxDegrees                          = 120

private var degrees = [Int]()

var temperature: Int                    = 26    // our default temperature
var temperatureType: String             = "C"   // our default type is Farenheit


//   let myTitleArray = ["Air temperature" , "Water temperature"]
var pickerView : UIPickerView!
var pickerViewFarCel : UIPickerView!


var dictTemprature = [String : String]()

var arrayTemprature = [AnyObject]()

var tempIndex = 0
var tempSymbolIndex = 0

var arraySymbol = ["C" , "F"]

var tempratureOfAir : String = ""
var tempratureOfWater : String = ""



private typealias ItemDefaults = [ItemTypes : String]

private let NumberOfSections: Int                       = 7
private let NumberOfRowsInSection0: Int                 = 2
private let NumberOfRowsInSection1: Int                 = 7
private let NumberOfRowsInSection2: Int                 = 4
private let NumberOfRowsInSection3: Int                 = 6
private let NumberOfRowsInSection4: Int                 = 3
private let NumberOfRowsInSection5: Int                 = 4
private let NumberOfRowsInSection6: Int                 = 1


//
//  Section 0 Cells
//
private let DiveNumberIndex: NSIndexPath                = NSIndexPath(forRow: 0, inSection: 0)  

private let DiveNameIndex: NSIndexPath                  = NSIndexPath(forRow: 1, inSection: 0)

 //  Section 1 Cells

private let DiveWaterIndex: NSIndexPath                 = NSIndexPath(forRow:  0, inSection: 1)
private let DiveVisibilityIndex: NSIndexPath            = NSIndexPath(forRow:  1, inSection: 1)
private let DiveCurrentsIndex: NSIndexPath              = NSIndexPath(forRow:  2, inSection: 1)
private let AirTempPickerIndex: NSIndexPath             = NSIndexPath(forRow:  3, inSection: 1)
private let WaterTempPickerIndex: NSIndexPath           = NSIndexPath(forRow:  4, inSection: 1)
private let DiveWeatherIndex: NSIndexPath               = NSIndexPath(forRow:  5, inSection: 1)
private let DiveSurfaceIndex: NSIndexPath               = NSIndexPath(forRow:  6, inSection: 1)


//  Section 2 Cells

private let DiveLocationIndex: NSIndexPath              = NSIndexPath(forRow:  0, inSection: 2)
private let DiveBodyOfWaterIndex: NSIndexPath           = NSIndexPath(forRow:  1, inSection: 2)
private let DiveCityIndex: NSIndexPath                  = NSIndexPath(forRow:  2, inSection: 2)
private let DiveCountryIndex: NSIndexPath               = NSIndexPath(forRow:  3, inSection: 2)

//  Section 3 Cells

private let DiveCircuitIndex: NSIndexPath               = NSIndexPath(forRow:  0, inSection: 3)
private let DiveStartingPressureIndex: NSIndexPath      = NSIndexPath(forRow:  1, inSection: 3)
private let DiveEndingPressureIndex: NSIndexPath        = NSIndexPath(forRow:  2, inSection: 3)
private let DiveWeightIndex: NSIndexPath                = NSIndexPath(forRow:  3, inSection: 3)
private let DiveDiveSuitIndex: NSIndexPath              = NSIndexPath(forRow:  4, inSection: 3)
private let DiveEquipmentIndex: NSIndexPath             = NSIndexPath(forRow:  5, inSection: 3)

//  Section 4 Cells

private let DiveEntryTypeIndex: NSIndexPath             = NSIndexPath(forRow:  0, inSection: 4)
private let DiveDiveTypeIndex: NSIndexPath              = NSIndexPath(forRow:  1, inSection: 4)
private let DiveRatingIndex: NSIndexPath                = NSIndexPath(forRow:  2, inSection: 4)

//  Section 5 Cells

private let DiveDiveMasterIndex: NSIndexPath             = NSIndexPath(forRow:  0, inSection: 5)
private let DiveDiveBoatOperatorIndex: NSIndexPath       = NSIndexPath(forRow:  1, inSection: 5)
private let DiveDiveCenterIndex: NSIndexPath             = NSIndexPath(forRow:  2, inSection: 5)
private let DiveTripOperatorIndex: NSIndexPath           = NSIndexPath(forRow:  3, inSection: 5)

//  Section 6 Cells

private let DiveNotesIndex: NSIndexPath                 = NSIndexPath(forRow:  0, inSection: 6)



private let location: Location              = Location()
private var isSelected: Bool                = false
private var defaultValues: ItemDefaults     = ItemDefaults()
private var selectedItemType: ItemTypes     = ItemTypes.None
private var longitude: Double               = 0.0
private var latitude: Double                = 0.0


var diveModel: DiveModel = DiveModel()

override func viewDidLoad()

    super.viewDidLoad()

    // Array of the Degree :

    for i in self.minDegrees ..< self.maxDegrees+1
        self.degrees.append(i)
    
    print(self.degrees)

    // Array of Table

    self.dictTemprature = ["tempValue" : "" , "tempSymbol" : ""]

    arrayTemprature = [self.dictTemprature , self.dictTemprature]

    print(arrayTemprature)

    print(self.arrayTemprature[0].valueForKey("tempValue"))


    //
    self.registerCustomTableViewCells()

    self.defaultValues =  self.getDefaultValues()

    print(self.diveModel)



override func viewWillAppear(animated: Bool)

    super.viewWillAppear(animated)

    location.delegate = self
    location.start()


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

    var cell: UITableViewCell!

    switch indexPath
    

    case DiveNumberIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveNumberCell)
        (cell as! DiveNumberTableViewCell).textField.placeholder = Strings.DiveNumber.localized
        //I realize this will be autoentered, but needs to be displayed


    case DiveNameIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveSiteCell)
        (cell as! DiveSiteTableViewCell).textField.placeholder = Strings.Name.localized
        //This will need to be the data entered from the previous screen and not editable


    case AirTempPickerIndex:

        let cell : AirTemperatureTableViewCell = tableView.dequeueReusableCellWithIdentifier("AirTemperatureCell", forIndexPath: indexPath) as! AirTemperatureTableViewCell
        cell.txtField_PickData.tag    =  indexPath.row
        cell.textField_TempSymbol.tag =  indexPath.row

        cell.txtField_PickData.placeholder = "Air"

        cell.textField_TempSymbol.placeholder = ""
        cell.txtField_PickData.text = self.arrayTemprature[indexPath.row].valueForKey("tempValue") as? String
        cell.textField_TempSymbol.text = self.arrayTemprature[indexPath.row].valueForKey("tempSymbol") as? String
        return cell


    case WaterTempPickerIndex:

        let cell : WaterTemperatureTableViewCell = tableView.dequeueReusableCellWithIdentifier("WaterTemperatureCell", forIndexPath: indexPath) as! WaterTemperatureTableViewCell
        cell.txtField_PickData.tag    =  indexPath.row
        cell.textField_TempSymbol.tag =  indexPath.row

        cell.txtField_PickData.placeholder = "Water"

        cell.textField_TempSymbol.placeholder = ""
        cell.txtField_PickData.text = self.arrayTemprature[indexPath.row].valueForKey("tempValue") as? String
        cell.textField_TempSymbol.text = self.arrayTemprature[indexPath.row].valueForKey("tempSymbol") as? String
        return cell


    case DiveLocationIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.LocationCell)
        cell.textLabel!.text = Strings.Location.localized
        cell.detailTextLabel!.text = String(format: "%f, %f", self.latitude, self.longitude)

    case DiveWeatherIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Weather.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.Weather]

    case DiveVisibilityIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Visibility.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.Visibility]

    case DiveEntryTypeIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.EntryType.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.EntryType]

    case DiveWaterIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Water.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.Water]

    case DiveDiveSuitIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.DiveSuit.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.DiveSuit]

    case DiveNotesIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveNoteCell)

    case DiveRatingIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Rating.localized
        cell.detailTextLabel!.text = ""

    case DiveCurrentsIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Currents.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.Currents]

    case DiveSurfaceIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Surface.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.Surface]

    case DiveBodyOfWaterIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.BodyOfWater.localized
        cell.detailTextLabel!.text = ""

    case DiveCityIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.City.localized
        cell.detailTextLabel!.text = ""

    case DiveCountryIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Country.localized
        cell.detailTextLabel!.text = ""

    case DiveCircuitIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Circuit.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.Circuit]

    case DiveStartingPressureIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.StartingTankUsageCell)
        (cell as! StartingTankUsageCell).startingPressureTextField.placeholder = Strings.Start.localized

    case DiveEndingPressureIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.EndingTankUsageCell)
        (cell as! EndingTankUsageCell).textField.placeholder = Strings.Finish.localized

    case DiveDiveMasterIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.DiveMaster.localized
        cell.detailTextLabel!.text = ""

    case DiveWeightIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.WeightsCell)
        (cell as! WeightsTableViewCell).textField.placeholder = Strings.Weight.localized

    case DiveEquipmentIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.Equipment.localized
        cell.detailTextLabel!.text = ""

    case DiveDiveTypeIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.DiveType.localized
        cell.detailTextLabel!.text = self.defaultValues[ItemTypes.DiveType]

    case DiveDiveBoatOperatorIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.BoatOperator.localized
        cell.detailTextLabel!.text = ""

    case DiveDiveCenterIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.DiveCenter.localized
        cell.detailTextLabel!.text = ""

    case DiveTripOperatorIndex:
        cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveItemCell)
        cell.textLabel!.text = Strings.TripOperator.localized
        cell.detailTextLabel!.text = ""


    default:
        cell = nil
    


    return cell



override func numberOfSectionsInTableView(tableView: UITableView) -> Int

    return self.NumberOfSections



override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

    if section == 0
    
        return self.NumberOfRowsInSection0
    
    else if section == 1
    
        return self.NumberOfRowsInSection1
    
    else if section == 2
    
        return self.NumberOfRowsInSection2
    
    else if section == 3
    
        return self.NumberOfRowsInSection3
    
    else if section == 4
    
        return self.NumberOfRowsInSection4
    
    else if section == 5
    
        return self.NumberOfRowsInSection5
    
    else if section == 6
    
        return self.NumberOfRowsInSection6
    
    else
    
        return 0
    




override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?

    //
    //  It the row that is going to be selected is of an item type, then we save off the 
    //  selectedItemType so it can be used during the segue.
    //
    switch indexPath
    
    case DiveWeatherIndex:
        self.selectedItemType = ItemTypes.Weather

    case DiveVisibilityIndex:
        self.selectedItemType = ItemTypes.Visibility

    case DiveEntryTypeIndex:
        self.selectedItemType = ItemTypes.EntryType

    case DiveWaterIndex:
        self.selectedItemType = ItemTypes.Water

    case DiveDiveSuitIndex:
        self.selectedItemType = ItemTypes.DiveSuit

    case DiveDiveTypeIndex:
        self.selectedItemType = ItemTypes.DiveType

    case DiveCurrentsIndex:
        self.selectedItemType = ItemTypes.Currents

    case DiveSurfaceIndex:
        self.selectedItemType = ItemTypes.Surface

    case DiveCircuitIndex:
        self.selectedItemType = ItemTypes.Circuit

    default:
        self.selectedItemType = ItemTypes.None
    

    return indexPath




override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

    let cell = tableView.cellForRowAtIndexPath(indexPath)
    if cell is DiveEditTableViewCell
    
        (cell as! DiveEditTableViewCell).textField.userInteractionEnabled = true
        (cell as! DiveEditTableViewCell).textField.becomeFirstResponder()
    
    else if cell is DiveNoteTableViewCell
    
        (cell as! DiveNoteTableViewCell).textView.userInteractionEnabled = true
        (cell as! DiveNoteTableViewCell).textView.becomeFirstResponder()
    
    else if cell is StartingTankUsageCell
    
        (cell as! StartingTankUsageCell).startingPressureTextField.userInteractionEnabled = true
        (cell as! StartingTankUsageCell).startingPressureTextField.becomeFirstResponder()
    
    else if cell is EndingTankUsageCell
    
        (cell as! EndingTankUsageCell).textField.userInteractionEnabled = true
        (cell as! EndingTankUsageCell).textField.becomeFirstResponder()
    
    else if cell is WeightsTableViewCell
    
        (cell as! WeightsTableViewCell).textField.userInteractionEnabled = true
        (cell as! WeightsTableViewCell).textField.becomeFirstResponder()
    



override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath)


    let cell = tableView.cellForRowAtIndexPath(indexPath)
    if cell is DiveEditTableViewCell
    
        (cell as! DiveEditTableViewCell).textField.userInteractionEnabled = false
        (cell as! DiveEditTableViewCell).textField.resignFirstResponder()
    
    else if cell is DiveNoteTableViewCell
    
        (cell as! DiveNoteTableViewCell).textView.userInteractionEnabled = false
        (cell as! DiveNoteTableViewCell).textView.resignFirstResponder()
    
    else if cell is StartingTankUsageCell
    
        (cell as! StartingTankUsageCell).startingPressureTextField.userInteractionEnabled = false
        (cell as! StartingTankUsageCell).startingPressureTextField.becomeFirstResponder()
    
    else if cell is EndingTankUsageCell
    
        (cell as! EndingTankUsageCell).textField.userInteractionEnabled = false
        (cell as! EndingTankUsageCell).textField.becomeFirstResponder()
    
    else if cell is WeightsTableViewCell
    
        (cell as! WeightsTableViewCell).textField.userInteractionEnabled = false
        (cell as! WeightsTableViewCell).textField.becomeFirstResponder()
    




override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

    var height = tableView.rowHeight


    if indexPath == self.DiveNotesIndex
    
        let cell = tableView.dequeueReusableCellWithIdentifier(Resource.DiveNoteCell)
        height = CGFloat((cell?.bounds.size.height)!)
    

    return height


func fahToCel(tempInF:Double) ->Double 
    let celsius = (tempInF - 32.0) * (5.0/9.0)
    return celsius as Double


func celToFah(tempInC:Double) ->Double 
    let fahrenheit = (tempInC * 9.0/5.0) + 32.0
    return fahrenheit as Double



func pickerFarCal(textField : UITextField)

    self.tempSymbolIndex = 0

    pickerViewFarCel = UIPickerView(frame:CGRectMake(0, 0, self.view.frame.size.width, 216))
    pickerViewFarCel.delegate = self
    pickerViewFarCel.dataSource = self
    pickerViewFarCel.backgroundColor = UIColor.whiteColor()
    textField.inputView = pickerViewFarCel
    pickerViewFarCel.tag =  textField.tag

    let toolBar = UIToolbar()
    toolBar.barStyle = .Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
    toolBar.sizeToFit()
    // Adds the buttons

    let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: #selector(DiveDetailsViewController.doneClickSymbol))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(DiveDetailsViewController.cancelClickSymbol))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true
    textField.inputAccessoryView = toolBar



func doneClickSymbol()

    self.view.endEditing(true)

    print(self.arraySymbol[tempSymbolIndex])

    if self.arrayTemprature[pickerViewFarCel.tag].valueForKey("tempValue") as! String == ""
        print("Not Convert")
    else if self.arrayTemprature[pickerViewFarCel.tag].valueForKey("tempSymbol") as! String == self.arraySymbol[tempSymbolIndex]
        print("Not Convert")
    else
        print("Convert")

        if self.arraySymbol[tempSymbolIndex] == "C"
            let value = Double(self.arrayTemprature[pickerViewFarCel.tag].valueForKey("tempValue") as! String)
            let convertedValue = self.fahToCel(value!)
            let myValue = String(format: "%.1f", convertedValue)
            self.dictTemprature["tempValue"] = myValue
            self.dictTemprature["tempSymbol"] = self.arraySymbol[tempSymbolIndex]
        else
            let value = Double(self.arrayTemprature[pickerViewFarCel.tag].valueForKey("tempValue") as! String)
            let convertedValue = self.celToFah(value!)
            let myValue = String(format: "%.1f", convertedValue)
            self.dictTemprature["tempValue"] = myValue
            self.dictTemprature["tempSymbol"] = self.arraySymbol[tempSymbolIndex]
        
        self.arrayTemprature[pickerViewFarCel.tag] = self.dictTemprature

        tableView.reloadData()

    


func cancelClickSymbol()
    self.view.endEditing(true)



// PickerView

func pickerViewTemprature(textField : UITextField)

    // Index

    self.tempSymbolIndex = 0
    self.tempIndex = 276

    pickerView = UIPickerView(frame:CGRectMake(0, 0, self.view.frame.size.width, 216))
    pickerView.delegate = self
    pickerView.dataSource = self
    pickerView.backgroundColor = UIColor.whiteColor()
    textField.inputView = pickerView
    pickerView.tag = textField.tag
    pickerView.selectRow(276, inComponent: 0, animated: true)


    let toolBar = UIToolbar()
    toolBar.barStyle = .Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
    toolBar.sizeToFit()
    // Adds the buttons


    let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: #selector(DiveDetailsViewController.doneClickMaterial))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(DiveDetailsViewController.cancelClickMaterial))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true
    textField.inputAccessoryView = toolBar




func doneClickMaterial()

    self.view.endEditing(true)

    self.dictTemprature["tempValue"] = "\(self.degrees[tempIndex])"
    self.dictTemprature["tempSymbol"] = self.arraySymbol[tempSymbolIndex]
    self.arrayTemprature[pickerView.tag] = self.dictTemprature

    self.tableView.reloadData()

func cancelClickMaterial()
    self.view.endEditing(true)


// MARK: delegate

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int 
    if (pickerViewFarCel != nil)
        return 1
    else
        return 2
    


func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat

    return 100


func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int 

    if (pickerViewFarCel != nil)
        return self.temperatureSymbolComponentRows
    else
        if component == 0
            return self.degrees.count
        
        else
            return self.temperatureSymbolComponentRows
        

    


func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? 

    if (pickerViewFarCel != nil)
        return self.arraySymbol[row]
    else
        if component == 0 
            return "\(self.degrees[row])"
         else 
            return self.arraySymbol[row]
        
    


func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 

    if (pickerViewFarCel != nil)
        tempSymbolIndex = row
    else
        if component == 0 
            tempIndex = row
         else 
            tempSymbolIndex = row
        

    


更新: 我删除了标题数组并简单地添加了另一个动态单元格并将驱动两者的数据分开。

标题的索引超出范围会消失,但现在会为该行创建相同的错误: cell.txtField_PickData.text = self.arrayTemprature[indexPath.row].valueForKey("tempValue") as?字符串

此功能不需要额外的行,所以现在我想知道错误是否在于数组收集数据的方式。

我已经添加了大部分代码。必须减少一些才能达到 30k 的限制。

【问题讨论】:

问题只是myTitleArray 没有与indexPath.row 值关联的项目。所以看看行号是多少,然后看看你在那个数组中有多少项。如果该数组只有两项,则行号只能是零或一(无论如何,考虑到该行当前的写入方式)。 再次,为了诊断,您必须分享 (a) indexPath.row 的值是什么; (b) arrayTemprature [原文如此] 包含的内容。 row 似乎超出了该数组中的项目数。 【参考方案1】:

您的问题是由错误的numberOfRowsInSection 实现引起的。

根据official documentation:

告诉数据源返回给定节中的行数 表格视图。

注意此方法并进行所需的所有更改,以使您的数据源发生所有可能的变化。

这里你可以看到一个例子:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    if let count = self. myTitleArray?.count as Int 
        return (count)
     else 
        //myTitleArray is nil, so just return 0
        return 0
    

更新:(在您对主要问题进行新的编辑之后)

似乎有一个错误: 第 1 节单元格有 6 个元素,但您已声明:

private let NumberOfRowsInSection1: Int                 = 5

更多详情关于您的问题:

您的问题很典型:“索引超出范围”,这是什么意思?您的数组,在这种情况下 self.arrayTemprature 没有语句期间所需的索引,例如,如果您有一个包含 3 个元素的数组并且您请求第 4 个元素,这就是您将看到的错误。但是,当您不初始化数组并假装请求不存在的元素(您的数组为 nil 并且您始终希望第 4 个元素:索引超出范围)时,也会发生此错误。因此,请从声明、初始化、使用断点开始检查您的 self.arrayTemprature 并检查出现此错误的原因。

【讨论】:

亚历山德罗,现在我有以下内容。由于本节有 7 行,不知道如何实现上述内容。我目前有: else if section == 1 return self.NumberOfRowsInSection1 您能否在您的问题中添加 numberOfRowInSection 和 numberOfSections 方法? 是的,我尝试了不同的数字。没有 tempPicker,有 5 行。我的想法(就在粘贴代码之前)是设置 5 并将 myTitleArray.count 添加到部分中的行数中。 原来的数字是6,我试过6+1; 5 + myTitleArray.count。 .仅供参考,我已将其分配给单个动态单元格 让我们continue this discussion in chat.

以上是关于在 Swift 的 switch / case 函数中使用数组的主要内容,如果未能解决你的问题,请参考以下文章

Swift如何更灵活的使用switch...case操作符

Swift如何更灵活的使用switch...case操作符

case语言怎么用

switch是啥意思

swift-分支语句

Swift 运算符循环流程控制 for-in, while, if-else, switch-case, guard-else