Can't cast to NSMutableString in Swift

849 views Asked by At

I have Swift struct like this:

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;
    }

The error showing like this :

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

How can i solve this issue?

2

There are 2 answers

5
user2782993 On BEST ANSWER

If you need nameString to be a NSMutableString, then try this:

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

2
clemens On

The error comes from

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

because you can't downcast here. NSTaggedPointerString is a (private) subclass of NSString but not of NSMutableString. You should create a new mutable string instead:

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

But as @Sweeper said in the comments it should be better to use Swift strings.