2014-11-27 13 views
22

여기 내 코드. CGRectMake(..)에 두 값을 전달하고 가져 오는 중에 오류가 발생했습니다.Int32 값을 신속하게 CGFloat로 변환하는 방법은 무엇입니까?

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` 
어떻게 오류를 반환하지 Int32 CGFloat에 변환 할 수

?

답변

51

숫자 데이터 형식 사이의 변환하려면 매개 변수로 소스 값을 전달, 대상 유형의 새 인스턴스를 만듭니다. 그래서 변환하는 Int32CGFloat A를 : 당신이 중 하나를 수행 할 수 있습니다 귀하의 경우에는

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

:

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) 

나 : 암시 적 또는 명시 적 형 변환이 없다는 것을

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)) 

주 swift에서 숫자 형식 사이에 있으므로 IntInt32 또는으로 변환 할 때도 같은 패턴을 사용해야합니다.210 등

+1

고맙습니다. – iosLearner

+0

32 비트 시스템에서이 변환을하는 것이 안전할까요?'int32'는 (여전히) 32 비트이지만,'CGFloat'도 32 비트입니다. 후자가 부동 소수점이고 [이 답변] (http://stackoverflow.com/a/30260843/1492173)을 고려하면 정밀도가 떨어집니다. 내가 틀렸다면 나를 바로 잡아주세요. –

2

그냥 명시 적으로 CGFloat's 초기화를 사용 CGFloatwidthheight 변환 :

myLayer?.frame = CGRectMake(0, 0, CGFloat(width), CGFloat(height))