如何在字幕和某些单词之间的逗号之间添加空格?
问题描述:
我如何在字幕和某些单词之间的逗号之间添加空格?我使用SWIFT 3.如何在字幕和某些单词之间的逗号之间添加空格?
override
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
cell.detailTextLabel?.text = selectedItem.subThoroughfare! + selectedItem.thoroughfare!
+ selectedItem.locality! + selectedItem.administrativeArea! + selectedItem.postalCode!
return cell
}
答
你得到崩溃的原因是因为你强制包装可选属性CLPlacemark
,同样如果你想加入地址尝试这样的事情。使String?
的数组与您正在尝试制作地址的所有可选属性无关,!
之后flatMap
数组忽略nil
,然后简单地使用分隔符,
加入数组。
override public tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
let addressArray = [selectedItem.subThoroughfare, selectedItem.thoroughfare, selectedItem.locality, selectedItem.administrativeArea, selectedItem.postalCode].flatMap({$0})
if addressArray.isEmpty {
cell.detailTextLabel?.text = "N/A" //Set any default value
}
else {
cell.detailTextLabel?.text = addressArray.joined(separator: ", ")
}
return cell
}
答
您正在使用的值被迫展开,从而有可能使价值之一是nil
由于你越来越当代码试图来连接字符串nil
崩溃值。
我也崩溃了 – Brandon