Help with map function

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?

Doesn't hang for me, although I had to get rid of @main and add try! await MapTest.main() to the end, as the compiler erroneously refuses to work otherwise:

/tmp/test.swift:1:1: error: 'main' attribute cannot be used in a module that contains top-level code

swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

1 Like

Thank you, @wadetregaskis.

I just got rid of the async bit, and the problem disappeared. Very interesting. :slight_smile:

I am still on Swift version 5.9. I will be back after upgrading the Xcode.

Not reproducible with Xcode 15.2 (Swift 5.9) on my computer.

Btw, I must change the source file name in my demo because:

A main.swift file is always considered to be an entry point, even if it has no top-level code. Because of this, placing the @main -designated type in a main.swift file is an error.

1 Like

Thank you for checking, @wadetregaskis, @CrystDragon.

I am still using Swift 5.9, Xcode 15.0 running on a 2018 Mac mini with 6-Core Intel Core i7.