Search code examples
swiftios8.1cgfloatint32

how to convert Int32 value to CGFloat in swift?


Here my code. I am passing two values into CGRectMake(..) and getting and error.

let width = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width
// return Int32 value

let height = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height
// return Int32 value

myLayer?.frame = CGRectMake(0, 0, width, height)
// returns error: '`Int32`' not convertible to `CGFloat`

How can I convert Int32 to CGFloat to not return an error?


Solution

  • To convert between numerical data types create a new instance of the target type, passing the source value as parameter. So to convert an Int32 to a CGFloat:

    let int: Int32 = 10
    let cgfloat = CGFloat(int)
    

    In your case you can either do:

    let width = CGFloat(CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width)
    let height = CGFloat(CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height)
    
    myLayer?.frame = CGRectMake(0, 0, width, height)
    

    or:

    let width = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width
    let height = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height
    
    myLayer?.frame = CGRectMake(0, 0, CGFloat(width), CGFloat(height))
    

    Note that there is no implicit or explicit type casting between numeric types in swift, so you have to use the same pattern also for converting a Int to Int32 or to UInt etc.