Swift 2 Unable to remove optional binding

纵饮孤独 提交于 2020-01-24 13:14:06

问题


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>?

For fetch data from pList -

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

SHDataAccess class -

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 -

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 -


回答1:


This will remove that Optional() text:

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.

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




回答2:


You might also consider not making your dataObj array optional? 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.




回答3:


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

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]?

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



来源:https://stackoverflow.com/questions/33749681/swift-2-unable-to-remove-optional-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!