Avoiding stack overflow when nesting String.withCString { ... } (how to handle an arbitrary number of temp values in general)

What's supposed to happen when you prevented it? a "safe" crash (e.g. precondition)? a throw?

You can check remaining stack size and act accordingly, although this is rarely done.

Do you see these stack overflows in practice? What's the relevant stack frame size of your functions? How much stack size is used per one level? For example if available stack size is 200K and one parameter eats 1K it'll take some 200 parameters before overflowing stack.


Here's a different approach that sidesteps recursion altogether by utilising the older autoreleased c-strings obtained via NSString API:

extension String {
    var cstring: UnsafePointer<CChar> {
        (self as NSString).cString(using: String.Encoding.utf8.rawValue)!
    }
}

let a = "Arthur, King of Britain".cstring
let b = "Barbara of Portugal".cstring
let c = "Charles, Prince of Wales".cstring
print(strlen(a), strlen(b), strlen(c)) // 23 19 24