Could not cast value of type 'CALayer' (0x1a89c32a8) to 'CAGradientLayer'
<p>Since migrating my project to Swift 3 I am getting a runtime crash with the following error in the console. </p>

<pre><code>Could not cast value of type 'CALayer' (0x1a89c32a8) to 'CAGradientLayer'
</code></pre>

<p>I have a ViewController where I change the class of the view to my custom gradient class. </p>

<p>The problem is the following line; </p>

<pre><code>let layer = self.layer as! CAGradientLayer
</code></pre>

<p>However I do not understand why because self.layer is type <code>CALayer</code> and <code>CAGradientLayer</code> is a subclass of <code>CALayer</code> so my understanding is casting the type types should be ok.. as it was in swift 2.2. </p>

<p>Can anyone help me out where I am going wrong so I can understand the issue a little more ? </p>

<p>Here's my full gradient class</p>

<pre><code>@IBDesignable public class JGradientView: UIView {

@IBInspectable public var topColor: UIColor? {
    didSet {
        configureGradientView()
    }
}
@IBInspectable public var bottomColor: UIColor? {
    didSet {
        configureGradientView()
    }
}
@IBInspectable var startX: CGFloat = 0.0 {
    didSet{
        configureGradientView()
    }
}
@IBInspectable var startY: CGFloat = 1.0 {
    didSet{
        configureGradientView()
    }
}
@IBInspectable var endX: CGFloat = 0.0 {
    didSet{
        configureGradientView()
    }
}
@IBInspectable var endY: CGFloat = 0.0 {
    didSet{
        configureGradientView()
    }
}

public class func layeredClass() -&gt; AnyClass {
    return CAGradientLayer.self
}

public required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    configureGradientView()
}

override init(frame: CGRect) {
    super.init(frame: frame)
    configureGradientView()
}

public override func tintColorDidChange() {
    super.tintColorDidChange()
    configureGradientView()
}

func configureGradientView() {

    let color1 = topColor ?? self.tintColor as UIColor
    let color2 = bottomColor ?? UIColor.black as UIColor
    let colors: Array &lt;AnyObject&gt; = [ color1.cgColor, color2.cgColor ]
    let layer = self.layer as! CAGradientLayer

    layer.colors = colors
    layer.startPoint = CGPoint(x: startX, y: startY)
    layer.endPoint = CGPoint(x: endX, y: endY)
}
}
</code></pre>