I am observing a problem while using the map function
on an Array
; map
keeps allocating memory and never returns.
The problem can be reproduced with the following code, with two conditional code blocks A
and B
.
@main
enum MapTest {
static func main () async throws {
#if true // A
let pointer: UnsafeMutablePointer<Int>
let M = 8
pointer = .allocate(capacity: M)
pointer.initialize(repeating: 5, count: M)
print (pointer)
print (pointer.pointee)
for i in 0..<M {
print (i, pointer[i])
}
#endif
#if true // B
var values : [any Number] = [Int (2), Int (3), Int (5)]
values.append (Int (7))
values.append (Int (0))
print (values)
let v = values.map {$0.isEven}
print (v)
#else
test ()
#endif
}
}
// -----------------------------------------------
//
protocol Number {
var isEven: Bool {get}
}
extension Int: Number {
var isEven: Bool {
self & 1 == 0
}
}
// -------------------------------------------------------
//
func test () {
var values : [any Number] = [Int (2), Int (3), Int (5)]
values.append (Int (7))
values.append (Int (0))
print (values)
let v = values.map {$0.isEven}
print (v)
}
Note that the code inside the test
function is identical to the one in code block B
.
The problem occurs when:
code block A is enabled
code block B is enabled
However, the problem does not occur when:
code block A disabled
// or
code block A is enabled
code block B is disabled
I am stumped for an explanation. What am I doing wrong?