swiftalpine-linuxmusl

How can I compile a simple Swift cli program for Alpine?


I have a simple cli written in Swift that I want to run on Alpine. I want the binary to be self-contained. How can I do that? I have tried:

The code of the program:


// The Swift Programming Language
// https://docs.swift.org/swift-book
func getSecret() -> String {
    let CharArr: [Character] = ["T", "h", "i", "s", " ", "a", " ", "s", "e", "c", "r", "e", "t"] 

    let newStr = String(CharArr) 
    return newStr
}
if(CommandLine.arguments.count == 2){
    if (CommandLine.arguments[1] == "spoil"){
        print(getSecret())
    } else {
        if (CommandLine.arguments[1] == getSecret()){
            print("This is correct! Congrats!");
        }else{
            print("This is incorrect. Try again");
        }
    }
} else if (CommandLine.arguments.count==1) {
    print("Welcome to the wrongsecrets Swift binary which hides a secret.");
    print("Use args spoil or a string to guess the password.");
} else {
    print("Too many arguments supplied.");
}

Can you help me please?


Solution

  • Update (2024-06): Swift 6 will support static Linux builds (which use musl). Instructions on (cross-compiling) static Linux binaries can be found on the Swift page (although the instructions use incorrect flags at the time of writing, but I reckon this will be fixed by the final release of Swift 6)


    As you figured out in the meantime, Swift doesn't run on musl-based systems, and can't generate musl binaries.

    While waiting for Alpine Linux support in Swift, the following 2 alternatives work for me: