Avatar
withCString(:_) とか withUnsafeBytes(:_) をリストで扱いたいと思って、つまり let array: [String] = [...] array.with(each: String.withCString) { cStrings/*: [UnsafePointer<CChar>] */ in cFunctionReceivingCStringArray(cStrings) } こういうのがやりたくて、邪悪なものを生み出してしまった。 extension BidirectionalCollection { func with<U, R>( each mapFn: (Element) -> ((U) throws -> R) throws -> R, _ fn: ([U]) throws -> R ) rethrows -> R { try withoutActuallyEscaping(fn) { fn in try withoutActuallyEscaping(mapFn) { mapFn in var stash: [U] = [] stash.reserveCapacity(count) let closure = reversed().reduce({ try fn(stash) }) { closure, elem in { try mapFn(elem)() { val in stash.append(val) return try closure() } } } return try closure() } } } } (edited)