如何将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 personswiftcis the official Swift compiler command-o persontells the compiler to output the executable file namedperson(you can name it anything you want)
- Now run the executable with:
You'll see your expected print output in the terminal right away../person
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.swiftfor 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:
You'll get the exact same output as the binary version../person_script.swift
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
相关产品推荐
相关产品推荐

