为什么会出现错误?

时间:2015-12-09 04:32:09

标签: ios swift metal

错误是说nil不是一个选项,但那么我还会放什么呢?

import UIKit
import Metal
import QuartzCore

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var device: MTLDevice! = nil
    device = MTLCreateSystemDefaultDevice()
    var metalLayer: CAMetalLayer! = nil
    metalLayer = CAMetalLayer()
    metalLayer.device = device
    metalLayer.pixelFormat = .BGRA8Unorm
    metalLayer.framebufferOnly = true
    metalLayer.frame = view.layer.frame
    view.layer.addSublayer(metalLayer)

    let vertexData:[Float] = [
        0.0, 1.0, 0.0,
        -1.0, -1.0,0.0,
        1.0, 1.0, 0.0
    ]

    var vertexBuffer: MTLBuffer! = nil
    let dataSize = vertexData.count * sizeofValue(vertexData[0])
    vertexBuffer = device.newBufferWithBytes(vertexData, length: dataSize, options: nil)
}

2 个答案:

答案 0 :(得分:4)

如果您没有提供[],则应该options:

答案 1 :(得分:0)

如果您声明一个非可选类型的变量,则不必对其进行初始化。但是,如果您希望此变量是可选的,则需要将其声明为let metalLayer: CAMetalLayer?,然后您可以将其设置为nil。