Swift app crash with mutateError on NSMutableString object

Here's my codes:

extension NSMutableString {
    
    func clear() {
        replaceCharacters(in: NSRange(location: 0, length: length), with: String(data: Data.init(repeating: 0, count: length), encoding: .utf8)!)
        replaceCharacters(in: NSRange(location: 0, length: length), with: "")
    }
    
}

My app receive some random rare crash report on the line: replaceCharacters(in: NSRange(location: 0, length: length), with: String(data: Data.init(repeating: 0, count: length), encoding: .utf8)!)

Crash logs:

Last Exception Backtrace:
0   CoreFoundation                	0x19f228870 __exceptionPreprocess + 164 (NSException.m:249)
1   libobjc.A.dylib               	0x197543c00 objc_exception_throw + 60 (objc-exception.mm:356)
2   CoreFoundation                	0x19f2f0d10 _CFThrowFormattedException + 108 (CFObject.m:2245)
3   CoreFoundation                	0x19f26094c mutateError + 96 (CFObject.m:599)
4   CoreFoundation                	0x19f185770 -[__NSCFString replaceCharactersInRange:withString:] + 72 (CFObject.m:608)
5   MyApp                    	0x10122c67c NSMutableString.clear() + 224 (NSMutableString.swift:22)
6   MyApp                    	0x1012974f4 UserData.loggedOut() + 56 (UserData.swift:58)
7   MyApp                    	0x100fac7dc AuthenticationManager.didLogout(isSessionExpired:preventAutoLoginByFaceID:) + 60 (AuthenticationManager.swift:200)

The thing is I couldn't reproduce it and the crash is rare so I run out of idea, and would hope to receive some suggestions from the forum. Thank you.

Internally, -replaceCharactersInRange:withString: calls through to a CF-level function, __CFStringCheckAndReplace. If that fails, it calls this mutateError routine which throws an exception. AFAIK that part is not open source, but the __CFStringCheckAndReplace is. You can find it in the Swift Foundation source code here. That should give you some idea as to the potential causes for this failure.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Swift app crash with mutateError on NSMutableString object
 
 
Q