【问题标题】:Type "Patient" has no subscript member“患者”类型没有下标成员
【发布时间】:2016-01-30 05:58:06
【问题描述】:

我有一个名为“Patient”的全局类和一个“Patient”类型的全局变量

class Patient{
var id: Int
var name: String
var mileage: Double

init(id:Int, name:String, mileage:Double){
    self.id = id
    self.name = name
    self.mileage = mileage
}

}

var pSample: Patient?

这就是我将 pSample 分配给类的方式

for var i=0; i<nou; ++i{                   
                pSample = Patient(id: json[0][i]["ID"].intValue, name: json[0][i]["Name"].stringValue, mileage: json[0][i]["Mileage"].doubleValue)   
            }

我打算在表格单元格中使用它

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as UITableViewCell

    //everything refers to this
    if pSample != nil {
        let patient = pSample![indexPath.row] //error1
        if let nameLabel = cell.viewWithTag(102) as? UILabel{
            nameLabel.text = patient.name
        }

        if let scoreLabel = cell.viewWithTag(103) as? UILabel{
            scoreLabel.text = String(patient.mileage)
        }
    }else{
        let patient = patientSample[indexPath.row] as Patient
        if let nameLabel = cell.viewWithTag(102) as? UILabel{
            nameLabel.text = patient.name
        }

        if let scoreLabel = cell.viewWithTag(103) as? UILabel{
            scoreLabel.text = String(patient.mileage)
        }
    }

为什么会出现这个错误?

Error1: Type Patient 没有下标成员

【问题讨论】:

    标签: ios swift generics swift2


    【解决方案1】:

    您是否对[pSample]pSample 感到困惑?您在 for 循环中所做的只是更新您拥有的一个 Patient 实例。

    var pSample: [Patient] = []
    
    for var i=0; i<nou; ++i{                   
        pSample += [Patient(id: json[0][i]["ID"].intValue, name: json[0][i]["Name"].stringValue, mileage: json[0][i]["Mileage"].doubleValue)]   
    }
    

    【讨论】:

    • 在应用您的代码后,我遇到了另一个错误 - 类型“元素”(又名“(字符串,JSON)”)没有下标成员
    • 好吧,我刚刚使用了.forEach。其实我从来没有使用过json。我将重新编辑并改用你的 for 循环
    猜你喜欢
    • 2021-06-05
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多