DEV Community

Discussion on: 🤘🏻 TUTORIAL: Metal HelloTriangle using Swift 5 and no Xcode

Collapse
 
codrut_popescu_22f5f2fd34 profile image
Codrut Popescu

I stopped at "Running this will give us a window with an nice red background." I get an error:

AppDelegate.swift:25:3: error: cannot find 'window' in scope
window?.contentViewController = ViewController()

Any ideas? Unfortunately I'm a beginner.
Here are my files:

cat Package.swift
// swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "MetalHelloTriangle",
platforms: [ .macOS(.v12) ],
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: "MetalHelloTriangle",
dependencies: []),
.testTarget(
name: "MetalHelloTriangleTests",
dependencies: ["MetalHelloTriangle"]),
]
)

cat Sources/MetalHelloTriangle/main.swift
import Cocoa

let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)

cat Sources/MetalHelloTriangle/AppDelegate.swift
import Cocoa

let WIDTH = 800
let HEIGHT = 600

class AppDelegate: NSObject, NSApplicationDelegate
{
private var mWindow: NSWindow?

func applicationDidFinishLaunching(_ aNotification: Notification)
{
    let screenSize = NSScreen.main?.frame.size ?? .zero
    let rect = NSMakeRect((screenSize.width  - CGFloat(WIDTH))  * 0.5,
                      (screenSize.height - CGFloat(HEIGHT)) * 0.5,
                      CGFloat(WIDTH),
                      CGFloat(HEIGHT))
    mWindow = NSWindow(contentRect: rect,
                   styleMask:   [.miniaturizable,
                                 .closable,
                                 .resizable,
                                 .titled],
                    backing:    .buffered,
                    defer:      false)
    mWindow?.title = "Hello Triangle"
    window?.contentViewController = ViewController()
    mWindow?.makeKeyAndOrderFront(nil)
}
Enter fullscreen mode Exit fullscreen mode

}

cat Sources/MetalHelloTriangle/ViewController.swift
import Cocoa

class ViewController : NSViewController
{
override func loadView()
{
let rect = NSRect(x: 0, y: 0, width: WIDTH, height: HEIGHT)
view = NSView(frame: rect)
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.red.cgColor
}
}%