整数
1.分为有符号整数和无符号整数;
2.有符号: Int8 Int16 Int32 Int64 Int;
3.无符号: UInt8 UInt16 UInt32 UInt64 UInt。
整数类型区别
1.在内存占用空间不同(sizeof(Type)获取);
2.表达的数据范围不同(可用min,max属性获取)。
Tips
1.特殊整数类型Int,长度与当前平台原生字长一致;
2.32位机,sizeof(Int)等于sizeof(Int32);
3.64位机,sizeof(Int)等于sizeof(Int64);
4.UInt类似;
5.习惯在一般情况下使用Int,来提高代码一致性和可复用性。
浮点数
1.Float 32位浮点数;
2.Double 64位浮点数。
布尔值
Bool(true false)
其他
1.类型转换;
2.类型别名;
3.类型安全。
swift是类型安全的语言,在编译时进行类型检查。
代码实例
//: Playground - noun: a place where people can play
import UIKit
//:声明整数并观察类型推倒结果
let intVal = 1
intVal.dynamicType
let int8Val : Int8 = 1
let int16Val : Int16 = 1
let int32Val : Int32 = 1
let int64Val : Int64 = 1
let intVal1 : Int = 1
print("Int8 \t size: \(sizeof(Int8)) \t min: \(Int8.min) \t\t\t\t\t max: \(Int8.max)")
print("Int16 \t size: \(sizeof(Int16)) \t min: \(Int16.min) \t\t\t\t max: \(Int16.max)")
print("Int32 \t size: \(sizeof(Int32)) \t min: \(Int32.min) \t\t\t max: \(Int32.max)")
print("Int64 \t size: \(sizeof(Int64)) \t min: \(Int64.min) max: \(Int64.max)")
print("Int \t size: \(sizeof(Int)) \t min: \(Int.min) \t max: \(Int.max)")
var uint8Val : UInt8 = 1
var uint16Val : UInt16 = 1
var uint32Val : UInt32 = 1
var uint64Val : UInt64 = 1
print("UInt8 \t size: \(sizeof(UInt8)) \t min: \(UInt8.min) \t max: \(UInt8.max)")
print("UInt16 \t size: \(sizeof(UInt16)) \t min: \(UInt16.min) \t max: \(UInt16.max)")
print("UInt32 \t size: \(sizeof(UInt32)) \t min: \(UInt32.min) \t max: \(UInt32.max)")
print("UInt64 \t size: \(sizeof(UInt64)) \t min: \(UInt64.min) \t max: \(UInt64.max)")
print("UInt \t size: \(sizeof(UInt)) \t min: \(UInt.min) \t max: \(UInt.max)")
let dVal = 1.1
dVal.dynamicType
let floatVal : Float = 1.1
let DoubleVal : Double = 1.1
print("Float \t size: \(sizeof(Float))")
print("Double \t size: \(sizeof(Double))")
let decimalVal = 10
let binaryVal = 0b1010
let octVal = 0o110
let hexval = 0x10
let exponentDouble1 = 12.12e1
let exponentDouble2 = 12.12e-1
let hexDecimalDouble = 0x12.3p1
//uint8Val = intVal
//uint8Val = UInt8.max + 1
uint8Val = UInt8(intVal)
let doubleRes = 1.34 + 5
let double1 = 1.34
let int1 = 5
let res = double1 + Double(int1)
typealias Distance = Int
let longDistance : Distance = 1
longDistance.dynamicType
Distance.min
Distance.max
let amiICool = true
if amiICool {
print("tks")
}
var doubleVal1 = 1.1