17
import UIKit
import Metal
import QuartzCore

class ViewController: UIViewController {

var device: MTLDevice! = nil
var metalLayer: CAMetalLayer! = nil

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    device = MTLCreateSystemDefaultDevice()
    metalLayer = CAMetalLayer()          // 1
    metalLayer.device = device           // 2
    metalLayer.pixelFormat = .BGRA8Unorm // 3
    metalLayer.framebufferOnly = true    // 4
    metalLayer.frame = view.layer.frame  // 5
    view.layer.addSublayer(metalLayer)   // 6
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

When I have this in my ViewController.swift, I get the error "Use of undeclared type CAMetalLayer" even though I've imported Metal and QuartzCore. How can I get this code to work?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
Pocketkid2
  • 803
  • 1
  • 11
  • 16

3 Answers3

58

UPDATE:
Simulator support is coming this year (2019)

Pre Xcode 11/iOS 13:
Metal code doesn't compile on the Simulator. Try compiling for a device.

Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
2

If your app has a fallback or mode that doesn't depend on Metal, and you want to compile your app for the simulator, you can do something like this:

#if targetEnvironment(simulator)
// dummy, do-nothing view controller for simulator
class ViewController: UIViewController {

}
#else
class ViewController: UIViewController {

    var device: MTLDevice! = nil
    var metalLayer: CAMetalLayer! = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        device = MTLCreateSystemDefaultDevice()
        metalLayer = CAMetalLayer()
        ...
    }

}
#endif

Then your code will at least compile for both device and simulator, which can ease your non-Metal development.

nevyn
  • 7,052
  • 3
  • 32
  • 43
0

The same problem may appear if you name your XCode project "Metal".

In that case compiler will be confused and you'll receive the same error message.

fewlinesofcode
  • 3,007
  • 1
  • 13
  • 30