Search code examples
iosanimationlottie

ios: Initializer for conditional binding must have Optional type, not 'LOTAnimationView'


I keep getting this error: Initializer for conditional binding must have Optional type, not 'LOTAnimationView' on the if let animationView = LOTAnimationView(name: "pop_heart") { line of code. I think the format of the code may be wrong. Can anyone guide me in the right direction? Thanks :)

override func viewDidLoad() {
    super.viewDidLoad()
    print("view loaded")

    if let animationView = LOTAnimationView(name: "pop_heart") {
        animationView.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
        animationView.center = self.view.center
        animationView.contentMode = .scaleAspectFill
        animationView.loopAnimation = true
        animationView.animationSpeed = 0.5
        view.addSubview(animationView)

        animationView.play()
    }}

Solution

  • Simply remove if let from your code. To use if let you must have an Optional variable.

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view loaded")
    
         animationView = LOTAnimationView(name: "pop_heart") 
         animationView.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
         animationView.center = self.view.center
         animationView.contentMode = .scaleAspectFill
         animationView.loopAnimation = true
         animationView.animationSpeed = 0.5
         view.addSubview(animationView)
         animationView.play()
    }
    

    or if you want to use if let you can use if like this.

    if let value = someMethodWhichReturnsAny as? String {
        //In above like there is a method which returns a string but in the form of type `Any` so I downcast it to String with optional and remove the nil case with if let
    }