简体   繁体   English

Swift 2无法删除可选绑定

[英]Swift 2 Unable to remove optional binding

I am new in Swift and don't have much more idea on optional (! , ?). 我是Swift的新手,对可选(!,?)没有更多的了解。 I tried to fetch data from plist, create Model and show to UITableView . 我试图从plist提取数据,创建Model并显示给UITableView Table data shows perfectly, but it shows with Optional() binding. 表数据显示得很完美,但是显示了Optional()绑定。 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>?

For fetch data from pList - 为了从pList fetch数据-

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

SHDataAccess class - 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
    }

}

And UITableView delegates - 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
}

Here is the output - 这是输出-

在此处输入图片说明

This will remove that Optional() text: 这将删除该Optional()文本:

if let q = q.question as? String {

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

} else {

    aCell.lblQuestion.text = ""

}

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

I've added support for the nil case if the question string is not defined. 如果问题字符串未定义,我将添加对nil支持。

You might also consider not making your dataObj array optional? 您可能还考虑不将dataObj数组设置为可选? what purpose does it serve to be optional? 它是可选的目的是什么? Seems to me that if you need to add items to the array then you know it should exist and since you've initialized it it will always exist but then may be empty. 在我看来,如果您需要向数组中添加项目,那么您就知道它应该存在,并且由于您已经对其进行了初始化,因此它始终存在,但是可能为空。 Instead just make it implicitly unwrapped and then return nil if there's no data, then the objects of the array won't all be optional. 而是只是隐式地将其展开,如果没有数据,则返回nil,那么数组的对象将不是全部可选的。

if you have a default in mind that you would want the optional string to fall back to, a simple fix would be something like: 如果您有一个默认值,想让可选字符串回落,那么一个简单的解决方法将是:

"\\(q.question ?? "")"

which will default to an empty string if q.question is nil 如果q.question为nil,则默认为空字符串

also: be careful of all of your force unwraps. 还:小心所有力量解开。 it might make more sense to have some guard statements or if let unwraps. 包含一些保护声明或让我们拆开可能更有意义。

and swift array's can be written like so: var dataArray : [SHQuesAns]? 快速数组可以这样写: var dataArray : [SHQuesAns]?

but there aren't many situations where you need to differentiate between a nil array and an empty array so you can just do var dataArray = [SHQuesAns]() and save yourself the need to unwrap 但是在很多情况下,您不需要在nil数组和空数组之间进行区分,因此您可以执行var dataArray = [SHQuesAns]()并节省var dataArray = [SHQuesAns]()的必要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM