Search code examples
ioscalayerswift2

Custom variable 'layer' used before being initialized


I would like to create a custom CALayer to set items corner radius.

func getLayerCorner(radius:CGFloat) -> CALayer
{
    let layer:CALayer
    layer.cornerRadius = radius
    layer.masksToBounds = true

    return layer
}

I'm getting Variable 'layer' used before being initialized

I'm still learning Swift and not sure how to init it.


Solution

  • The error exactly states what is wrong with your code. You need to initialise the layer before using:

    func getLayerCorner(radius:CGFloat) -> CALayer
    {
        let layer           = CALayer()
        layer.cornerRadius  = radius
        layer.masksToBounds = true
        return layer
    }