You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Swift代码转为终端可执行二进制文件与脚本文件

How to Turn Your Swift Code into a Terminal-Runnable Binary and Script

Hey there! First, let's fix a small syntax error in your code—there's a typo in the last "Part" line that'll cause a crash when running. Here's the corrected version:

struct Person {
    let firstName: String
    let lastName: String
    func sayHello() {
        print("Part 1")
        print(firstName)
        print(lastName)
        print()
        print("Part 2")
        print(firstName, lastName, separator:"\n")
        print()
        print("Part 3")
        print(firstName, lastName)
        print()
        print("Part 4")
        print(firstName, terminator: " ")
        print(lastName)
        print()
    }
}
let aPerson = Person(firstName: "x", lastName: "z")
aPerson.sayHello()

Now let's break down both ways to make this runnable from your terminal:

1. Compile to a Binary Executable

This creates a standalone file you can run anytime without needing the Swift compiler to interpret it each time:

  • Save the corrected code above into a file named Person.swift (use any text editor like VS Code, nano, or vim).
  • Open your terminal, navigate to the folder where you saved the file, then run this command to compile it:
    swiftc Person.swift -o person
    
    • swiftc is the official Swift compiler command
    • -o person tells the compiler to output the executable file named person (you can name it anything you want)
  • Now run the executable with:
    ./person
    
    You'll see your expected print output in the terminal right away.

2. Create a Runnable Swift Script

This lets you run the code directly as a script, no pre-compile step needed (great for quick testing and modifications):

  • Take the corrected code, and add this line at the very top of the file (this is called a "shebang"—it tells your system which program to use to execute the file):
    #!/usr/bin/env swift
    
  • Save the file (let's name it person_script.swift for clarity).
  • In your terminal, navigate to the folder with the file, then give it executable permissions with:
    chmod +x person_script.swift
    
  • Now run the script directly with:
    ./person_script.swift
    
    You'll get the exact same output as the binary version.

Quick Tips

  • If you get a "command not found" error for swiftc, make sure you have Xcode or the standalone Swift toolchain installed on your system.
  • The binary is faster for repeated runs since it's pre-compiled, while the script is quicker to tweak and test without re-compiling.

内容的提问来源于stack exchange,提问作者hellothere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:49:18