简体   繁体   中英

Convert custom type to CGFloat in swift

I have my own little class:

class EPPercent {
    init(_: CGFloat) {

    }
}

Now I want to convert an element of this class to CGFloat:

var percent: Any = 0
percent = EPPercent(100)
var toCGFloat = CGFloat(percent)

This gives an Error:

"Cannot invoke initializer for type 'CGFloat' with an argument list of type '(EPPercent)'"

How do I do this?

Thank you for your help ;)

You can create an extension of CGFloat and create a custom initializer that accepts an EPPercent instance.

class EPPercent {
    let value: CGFloat
    init(_ value: CGFloat) {
        self.value = value
    }
}

extension CGFloat {
    init(_ percent: EPPercent) {
        self = percent.value
    }
}

var percent = EPPercent(100)
var toCGFloat = CGFloat(percent)

Let me know in case you face any issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM