Home > Net >  Beginner Project Setup for Swift Code Challenges
Beginner Project Setup for Swift Code Challenges

Time:04-15

I am new to Xcode and Swift. I'm learning by doing the Advent of Code challenges. I'm struggling to setup Xcode in a way that will let me create simple classes that access text files within the project. I know that I can use Playgrounds, but I want to learn the debugger as part of this, and Playgrounds don't seem to allow use of the true debugger.

My two questions:

  1. What kind of Project template should I use? I don't ever want to run this on an iPhone simulator, or render it as a Mac app. I just want to execute some code and see the "print" statement results.

  2. Are there any special considerations for accessing text files stored within the project? I've tried this and my code can't ever access the files because it can't find them. I suspect this is a permissions issue, but I"m not sure.

CodePudding user response:

I was rank 92 on the overall AoC 2021 leaderboard. I did all of the problems in Swift. I recommmend setting up a Swift Package Manager package.

mkdir ~/aoc2021
cd ~/aoc2021
swift package init --type executable --name day01

Now you have a package containing a single executable target named day01. You can find the source code in ~/aoc2021/Sources/day01/main.swift. If you ask Xcode to open the folder ~/aoc2021, it will parse the Swift package as a project.

Instead of worrying about reading input from a file, just copy your input from https://adventofcode.com/2021/day/1/input into a string literal. Example:

let theInput = """
187
195
199
218
221
222
219
225
226
227
...
"""

When you're ready to move on to day 2, you'll need to manually create the folder ~/aoc2021/Sources/day02 and create a new main.swift in that folder. Then edit ~/aoc2021/Package.swift and add another executable target:

let package = Package(
    name: "day01",
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .executableTarget(
            name: "day01",
            dependencies: []),

// ADD THE FOLLOWING THREE LINES
        .executableTarget(
            name: "day02",
            dependencies: []),

        .testTarget(
            name: "day01Tests",
            dependencies: ["day01"]),
    ]
)

Don't forget to change your Xcode scheme (in the status bar) to day02 so it'll run the new day's code.

  • Related