如何在副标题之间添加 space 并在某些单词之间添加逗号?

How to add a space between the subtitle and a comma between some of the words?

如何在副标题之间添加 space 并在某些单词之间添加逗号?我正在使用 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
}

您正在对值使用强制解包,其中一个值可能是 nil,因此当代码尝试将字符串连接到 nil 值时您会遇到崩溃.

您崩溃的原因是因为您强行包装了 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({[=10=]})
    if addressArray.isEmpty {
        cell.detailTextLabel?.text = "N/A" //Set any default value
    }
    else {
        cell.detailTextLabel?.text = addressArray.joined(separator: ", ")       
    }
    return cell
}