quantumpotato
quantumpotato

Reputation: 9767

Cast from int to unrelated type fails

 convenience init(_ xx: Int, _ yy : Int) {
        let w = UIScreen.main.bounds.width
        let size = w / 7

        let f = CGRect(x: size * (xx as! CGFloat), y: size * (yy as! CGFloat), width: size, height: size)
        self.init(frame: f)


    }

if I get rid of the as! CGFloat, it will not compile. So why is this warning here?

Upvotes: 0

Views: 621

Answers (1)

Alexander
Alexander

Reputation: 63167

As the error suggests, you can't cast xx, a variable of type Int, into a CGFloat, which is an unrelated type.

You need to use the initializer on CGFloat which does so:

 convenience init(_ xx: Int, _ yy: Int) {
    let w = UIScreen.main.bounds.width
    let size = w / 7

    let f = CGRect(x: size * CGFloat(xx), y: size * CGFloat(yy),
                   width: size, height: size)
    self.init(frame: f)


}

Upvotes: 3

Related Questions