Swift 2无法删除可选绑定 [英] Swift 2 Unable to remove optional binding

查看:74
本文介绍了Swift 2无法删除可选绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手,对可选(!,?)没有更多的了解.我试图从plist中获取数据,创建Model并显示为UITableView.表数据显示完美,但显示为Optional()绑定.我试图改变!到 ?但无法打开.能否请您指导我解决这个问题.

I am new in Swift and don't have much more idea on optional (! , ?). I tried to fetch data from plist, create Model and show to UITableView. Table data shows perfectly, but it shows with Optional() binding. I tried change ! to ? but unable to unwrap. Could you please, guide me to solve this problem.

这是我的代码&输出-

Here is my code & output -

var fileName : String?
var dataArray : Array<SHQuesAns>?

对于pList-

func loadTableView(){
    dataArray = SHDataAccess.init(fname: fileName).arrayFromPlist()
    self.questionTableView.dataSource = self
    self.questionTableView.delegate=self
    self.questionTableView.reloadData()
}

SHDataAccess类-

import UIKit

var fileName : String!
class SHDataAccess: NSObject {

    init(fname:String?) {
        super.init()
        fileName = fname
    }

    func arrayFromPlist() -> Array <SHQuesAns>?{
        let dataPlists = NSMutableArray(contentsOfFile:NSBundle.mainBundle().pathForResource(fileName, ofType: "plist")!)
        var dataObj : Array <SHQuesAns>? = Array()
        for data in dataPlists! {
            dataObj?.append(SHQuesAns.init(_dic: data as! NSDictionary))
        }
        return dataObj
    }

}

UITableView代表-

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return  dataArray == nil ? 0 : dataArray!.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let aCell = self.questionTableView.dequeueReusableCellWithIdentifier("qcell",forIndexPath: indexPath) as! SHQuestionCell
    let q : SHQuesAns = dataArray![indexPath.row]
    aCell.lblQuestion.text = "\(q.question)"
    return aCell
}

这是输出-

推荐答案

这将删除该Optional()文本:

This will remove that Optional() text:

if let q = q.question as? String {

    aCell.lblQuestion.text = "\(q.question!)"

} else {

    aCell.lblQuestion.text = ""

}

关键是解开问题对象中包含的字符串,以便在将其分配给标签的文本时,将不包括Optional()部分.

The key is to unwrap the string contained in the question object so that when it is assigned to the text of the label, the Optional() part will not be included.

如果问题字符串未定义,我将增加对nil情况的支持.

I’ve added support for the nil case if the question string is not defined.

这篇关于Swift 2无法删除可选绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆