Home > Blockchain >  Compiler hangs indefinitely while compiling multiple files - Swift 5.5 Release
Compiler hangs indefinitely while compiling multiple files - Swift 5.5 Release

Time:12-15

As the question states, compiling and running the 2 files below makes the compiler hang indefinitely. Here are the CLI commands I have tried: swiftc *.swift -o combined && ./combined and cat *.swift | swift -.

The only 2 swift files in the directory are main.swift and Vehicle.swift.

I have tried compiling and running both files separately, Vehicle.class has no errors and compiles properly, main.swift has a error: cannot find 'Vehicle' in scope error, which is understandable since I need to compile them together. There is no other feedback from the compiler. What can cause the compiler to hang?

Code:

main.swift

// Stub program to demonstrate the Vehicle class
let vehicle1 = Vehicle(newNumOfDoors: 4, newMaxSpeed: 150,
    newLicensePlate: "ASDF404", newColour: "Red")

vehicle1.licensePlate = "FGHJ968"
vehicle1.colour = "Green"
vehicle1.accelerate(accelerateBy: 60)

print("\nLicense Plate: "   vehicle1.licensePlate
      "\nColour: "   vehicle1.colour
      "\nNumber of Doors: "   vehicle1.numOfDoors
      "\nMax Speed: "   vehicle1.maxSpeed
      "\nCurrent Speed: "   vehicle1.speed)

Vehicle.swift

public class Vehicle {

    // Properties Declaration
    let numOfDoors: Int
    let maxSpeed: Int
    private(set) var speed: Int
    var licensePlate: String
    var colour: String

    // Initializes a Vehicle
    init (newNumOfDoors: Int, newMaxSpeed: Int,
          newLicensePlate: String, newColour: String) {

        self.numOfDoors = newNumOfDoors
        self.licensePlate = newLicensePlate
        self.maxSpeed = newMaxSpeed
        self.colour = newColour
        self.speed = 0
    }

    func accelerate(accelerateBy: Int) {
        self.speed  = accelerateBy
    }

    func brake(brakeBy: Int) {
        self.speed -= brakeBy
    }
}

CodePudding user response:

The compiler is having issues with your print statement (which I determined by removing elements from the program until it worked). This is likely because it's struggling to figure out the type when using to concatenate everything.

One option is to use a multi-line string literal:

let vehicle1 = Vehicle(newNumOfDoors: 4, newMaxSpeed: 150,
    newLicensePlate: "ASDF404", newColour: "Red")

vehicle1.licensePlate = "FGHJ968"
vehicle1.colour = "Green"
vehicle1.accelerate(accelerateBy: 60)

let str = """
License Plate: \(vehicle1.licensePlate)
Colour: \(vehicle1.colour)
Number of Doors: \(vehicle1.numOfDoors)
Max Speed: \(vehicle1.maxSpeed)
Current Speed: \(vehicle1.speed)
"""

print(str)

Another option is to use interpolation rather than the :

print("\nLicense Plate: \(vehicle1.licensePlate)"
      "\nColour: \(vehicle1.colour)"
      "\nNumber of Doors: \(vehicle1.numOfDoors)"
      "\nMax Speed: \(vehicle1.maxSpeed)"
      "\nCurrent Speed: \(vehicle1.speed)")
  • Related