swift 不存在隱式轉(zhuǎn)換,只有顯式轉(zhuǎn)換。數(shù)據(jù)轉(zhuǎn)換,比如把int 轉(zhuǎn)換float或者double類型
/*
swift 不存在隱式轉(zhuǎn)換,只有顯式轉(zhuǎn)換
*/
//let 名字:類型 = ***
let number1:Double = 10.0
let number2:Int = 10
//如果number1和number2相加的話,要把他們的類型變成一致才可以相加
//var sum = number1 + number2 //這種寫法是報錯的
/*
要把number類型轉(zhuǎn)換double類型
int 轉(zhuǎn)換double 使用 Double(轉(zhuǎn)換的對象)
*/
var sum = number1 + Double(number2)
查看Double()方法可以發(fā)現(xiàn)
extension Double {
public init(_ v: UInt8)
public init(_ v: Int8)
public init(_ v: UInt16)
public init(_ v: Int16)
public init(_ v: UInt32)
public init(_ v: Int32)
public init(_ v: UInt64)
public init(_ v: Int64)
public init(_ v: UInt)
public init(_ v: Int)
}
extension Double {
/// Construct an instance that approximates `other`.
public init(_ other: Float)
/// Construct an instance that approximates `other`.
public init(_ other: Float80)
}
可以將這些UInt8 Int8 ......這些類型轉(zhuǎn)換
其他類型的轉(zhuǎn)換不在一一累述,同樣的道理。
其他的一些轉(zhuǎn)換例子:
//字符串轉(zhuǎn)換int
let numberString = "100"
var numberInt = Int(numberString)
//字符串轉(zhuǎn)換double
let doubleString = "100.00"
var numberDouble = Double(numberString)