我是 Swift 新手,对可选 (!, ?) 没有更多的想法。我尝试从 plist 中获取数据,创建模型并显示UITableView
。表格数据显示完美,但显示为Optional()
捆绑。我尝试过改变!到 ?但无法解开。您能指导我解决这个问题吗?
这是我的代码和输出 -
var fileName : String?
var dataArray : Array<SHQuesAns>?
For fetch
数据来自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
}
}
And 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()文本:
if let q = q.question as? String {
aCell.lblQuestion.text = "\(q.question!)"
} else {
aCell.lblQuestion.text = ""
}
关键是解开问题对象中包含的字符串,这样当它分配给标签的文本时,Optional() 部分就不会被包含在内。
我添加了对nil
如果未定义问题字符串的情况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)