2014-11-27 11 views
22

Hier mein Code. Ich übergebe zwei Werte in CGRectMake(..) und bekomme und Fehler.Wie konvertiert man den Int32-Wert in CGFloat in swift?

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` 

Wie kann ich Int32-CGFloat konvertieren einen Fehler nicht zurück?

Antwort

51

zwischen verschiedenen Arten numerischen Daten konvertieren erstellen Sie eine neue Instanz des Zieltyp, den Wert Quelle als Parameter übergeben. So konvertiert ein Int32 zu einem CGFloat:

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

In Ihrem Fall können Sie entweder tun:

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) 

oder:

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

Hinweis, dass es keine implizite oder explizite Typumwandlung zwischen numerischen Typen in swift, so müssen Sie das gleiche Muster auch für die Konvertierung von Int zu Int32 oderverwenden 210 usw.

+1

Danke, es funktioniert gut! – iosLearner

+0

Ich frage mich, ist es sicher, diese Konvertierung auf 32-Bit-Systemen zu tun, wo "Int32" ist (noch) 32 Bits, jedoch "CGFloat" ist auch 32 Bits. Wenn man berücksichtigt, dass Letzteres ein Gleitkomma ist und [diese Antwort] (http://stackoverflow.com/a/30260843/1492173), wird es einen Genauigkeitsverlust geben. Bitte korrigiere mich wenn ich falsch liege. –

2

einfach konvertieren explizit width und height zu CGFloat die CGFloat's initializer mit:

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