Xcode downloads client crash reports for string interpolation (_StringGuts.append)

57 Views Asked by At

Xcode contains several crash reports downloaded from users of my app. Thread 1 apparently crashes while performing a string interpolation. All the other threads only contain calls to system code.

The String.appendingPathComponent(_:) that appears in the stacktrace is defined as follows:

extension String {

    func appendingPathComponent(_ pathComponent: String) -> String {
        return pathComponent == "" ? self : self == "" || self == "/" ? "\(self)\(pathComponent)" : "\(self)/\(pathComponent)"
    }

}

What could cause such a crash?

Thread 1 Crashed:
0   CoreFoundation                  0x00007ff81566f9df __CFStringEncodeByteStream + 120 (CFStringEncodings.c:692)
1   Foundation                      0x00007ff8164c95aa -[NSString(NSStringOtherEncodings) getBytes:maxLength:usedLength:encoding:options:range:remainingRange:] + 204 (NSStringEncodings.m:341)
2   libswiftCore.dylib              0x00007ff822c6c1e0 String.UTF8View._foreignDistance(from:to:) + 208 (StringUTF8View.swift:507)
3   libswiftCore.dylib              0x00007ff822c56715 _StringGuts.append(_:) + 1445 (StringGutsRangeReplaceable.swift:191)
4   MyApp                           0x00000001010c3c0f String.appendingPathComponent(_:) + 15 (<compiler-generated>:0)
1

There are 1 best solutions below

4
Pierre Janineh On

Your crash could be due to multiple reasons:

  1. Unsafe string manipulation - Most likely
  2. String encoding issue
  3. Thread safety issue - Less likely

You might wanna try a safer string manipulation method. And as long as you're dealing with directories..

Try this

extension String {
    func appendingPathComponent(_ pathComponent: String) -> String {
        return (
            pathComponent == "" ?
            self :
                URL(filePath: self)
                .appendingPathComponent(pathComponent)
                .path
        )
    }
}

This also handles all conditions in order for you to remove the boilerplate code of your nested conditional operators.