无法转换为 Swift 中的 NSMutableString

Can't cast to NSMutableString in Swift

我有这样的 Swift 结构:

if(isSearching == true){
    let contactDict :NSDictionary = self.filteredArray?.object(at: indexPath.row) as! NSDictionary;
    let strArray :NSArray = contactDict.object(forKey: kName) as! NSArray
    nameString = strArray.componentsJoined(by: "") as! NSMutableString

    //nameString = (contactDict.object(forKey: kName) as? String as! NSMutableString)
    companyNameString = (contactDict.object(forKey: kCompanyName) as AnyObject).object(at: 0) as? NSString;
    designationString = (contactDict.object(forKey: kDesignation) as AnyObject).object(at: 0) as? NSString;
    profileImage = contactDict.object(forKey: kProfilePic) as? UIImage;
    connectStatus = contactDict.value(forKey: kLinkStatus) as? NSString;

    if(profileImage?.accessibilityIdentifier == "Img_placeholder"){
        profileImage = nil;
    }

错误显示如下:

Could not cast value of type 'NSTaggedPointerString' (0x1b5b89900) to 'NSMutableString' (0x1b5b959c0)

我该如何解决这个问题?

错误来自

nameString = strArray.componentsJoined(by: "") as! NSMutableString

因为这里不能垂头丧气。 NSTaggedPointerStringNSString 的(私有)子类,但不是 NSMutableString 的子类。您应该改为创建一个新的可变字符串:

nameString = NSMutableString(string: strArray.componentsJoined(by: ""))

但正如@Sweeper 在评论中所说,使用 Swift 字符串应该更好。

如果你需要 nameString 成为 NSMutableString,那么试试这个:

nameString: NSMutableString = strArray.componentsJoined(by:"").mutableCopy()