Swift exercise "Windowing System": cannot create a new window

If I create and populate the mainWindow instance of Window I get the “expressions are not allowed at the top level” compile error because it seems that Swift doesn’t accept expressions outside function and methods unless it’s in the main file but if I remove the statements needed to create and configure the new window I get the “cannot find ‘mainWindow’ in scope” compile error.

I’m stuck and I’m not sure if there’s something I don’t understood or its a bug in the exercise.

import Foundation

struct Size {
    var width = 80
    var height = 60

    mutating func resize(newWidth: Int, newHeight: Int) {
        width = newWidth
        height = newHeight
    }
}

struct Position {
    var x = 0
    var y = 0

    mutating func moveTo(newX: Int, newY: Int) {
        x = newX
        y = newY
    }
}

class Window {
    var title = "New Window"
    let screenSize = Size(width: 800, height: 600)
    var size = Size()
    var position = Position()
    var contents: String? = nil

    func resize(to:Size) {
        size.width = max(min(to.width, screenSize.width - position.x), 1)
        size.width = max(min(to.height, screenSize.height - position.y), 1)
    }
    func move(to:Position) {
        position.x = max(min(to.x, screenSize.width - size.width), 0)
        position.y = max(min(to.y, screenSize.height - size.height), 0)
    }

    func update(title:String) {
        self.title = title
    }
    func update(text:String) {
        self.contents = text
    }

    func display() -> String {
        return "\(title)\nPosition: (\(position.x), \(position.y)), Size: (\(size.width) x \(size.height))\n\(contents ?? "[This window intentionally left blank]")\n"
    }
}

var mainWindow = Window()
mainWindow.update(title: "Main Window")
mainWindow.resize(to: Size(width: 400, height: 300))
mainWindow.move(to: Position(x: 100, y: 100))
mainWindow.update(text: "This is the main window")
1 Like