1

I'm trying to get familiar with Xcode and Swift by writing a simple hello world program that has no UI.

When I create a new empty project in Xcode, there is no Target (scheme?), so I can't build and run. How can I create a target/scheme to satisfy the minimal build requirements? Steps to reproduce:

  1. Xcode > New > Project > Other > Empty
  2. code = print ("TEST")
  3. build/run disabled

Alternatively, when I create a new App project it has UI that I can't seem to ignore. Where can I insert a function and print statement without getting a compile time error?
Steps to reproduce:

  1. Xcode > New Project > Mac/iOS/TVos/watchOS > App
  2. Put a print statement virtually anywhere in any file gives a compiler error
torpedo51
  • 182
  • 2
  • 13

3 Answers3

4

If all you need is just writing a simple swift program, then you can create a swift file as simple as below:

test.swift

print("hello world")

Then run swift test.swift in your terminal.

If you want to use Xcode, then you can create a simple command-line app by selection: Xcode -> File -> Project -> mac OS -> Command Line Tool. Then Xcode will create a project with a swift file call main.swift which contains a simple print statement. Just build and run your project and check the console out.

congnd
  • 1,168
  • 8
  • 13
3

If you just code without UI you can use Playground:

Xcode -> File -> New -> Playground
aturan23
  • 4,798
  • 4
  • 28
  • 52
  • But you can't set breakpoints, etc. in playground. How do you create a C-like swift program in Xcode with a 'main()' that you can run and watch the results in the Console? No GUI. – Kaplan Sep 30 '21 at 12:38
1

I'm trying to get familiar with Xcode and Swift by writing a simple hello world program that has no UI.

One way is to create a macOS Command Line Tool:

  1. Go to "File" > "New" > "Project", or CmdShiftN.

  2. Select "macOS" > "Command Line Tool"

    enter image description here

  3. Enter the details of your project as usual

  4. After the project is created, you will see a main.swift file. This is your program's entry point. You will see a print call already written there for you.

Alternatively, when I create a new App project it has UI that I can't seem to ignore. Where can I insert a function and print statement without getting a compile time error?

You can do this in the viewDidLoad method in the ViewController.swift which is automatically generated.

override func viewDidLoad() {
    super.viewDidLoad()
    // write your code here:
    print("Hello World!")
}

But I would recommend just creating a command line tool, or a playground as aturan23 said if you just want to get familiar with Swift, since they have less distractions.

Sweeper
  • 213,210
  • 22
  • 193
  • 313