Does Swift support implicit conversion? Does Swift support implicit conversion? ios ios

Does Swift support implicit conversion?


There is no implicitly cast in Swift.

Easy way of conversion in swift is using constructor of particular type.

Like if you want to get Float from double then you can use Float(doubleValue) and Same way if you want to convert float to integer then you can use Int(floatValue).

In your case:

let intValue = UInt8(doubleValue)

Beware that you will lose any value after the decimal point. So, choose a better way. Above conversion is just to help you in understanding.

Note that Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.


Swift doesn't support implicitly cast anymore in Xcode6 GM. Following answer only apply to Xcode6 beta version.


I don't want to talk about implicitly cast is good or bad, but you can have it if you really want with __conversion()

e.g. If you need UInt8 and Int be able to convert from Double

extension Double {    func __conversion() -> UInt8 { return UInt8(self) }    func __conversion() -> Int { return Int(self) }    // add more if you need to}

xcrun swiftWelcome to Swift!  Type :help for assistance.  1> extension Double {  2.     func __conversion() -> UInt8 { return UInt8(self) }  3. }  4> var d = 1.0d: Double = 1  5> var u8 : UInt8 = du8: UInt8 = 1  6>

Note: I won't put this in my production code. I only want to point out it if possible but not recommending it.


using bridgeToObjectiveC() method you can call the methods provided in Objective - C to convert from one primitive data type to another for e.g.

variable_name.bridgeToObjectiveC().intValue

will convert that variable named variable_name to integer


matomo