Swift官文阅读记录一(基础)
——
一、常量和变量let maximumNumberOfLoginAttempts = 10 var currentLoginAttempt = 0
一次性定义一堆变量并赋予初始值 var x = 0.0,y = 0.0,z = 0.0 如果不赋予初始值则需要指定值类型 var welcomeMessage: String var red,green,blue: Double 常量以及变量的名称几乎可以包含任何字符 let π = 3.14159 let 你好 = "你好世界" let ???? = "dog cow" 打印常量和变量
print(friendlyWelcome)
print("The current value of friendlyWelcome is (friendlyWelcome)") 二、几种注释的方式// this is a comment /* this is also a comment,but written over multiple lines */ /* this is the start of the first multiline comment /* this is the second,nested multiline comment */ this is the end of the first multiline comment */ 三、数值整数的边界值 let minValue = UInt8.min // minValue is equal to 0,and is of type UInt8 let maxValue = UInt8.max // maxValue is equal to 255,and is of type UInt8 Int && Uint
同理浮点型被分为了 Float 和 Double 四、类型安全和类型推断
为了避免每次定义变量都要声明类型,Swift引入了类型推断,在编译的时候帮你推断出变量的类型,例如 let meaningOfLife = 42 //推断为Int类型 let pi = 3.14159 //推断为Double类型(Swift 会推断为Double而不是Float) 强制类型转换
let integerPi = Int(pi) 类型别名
typealias AudioSample = UInt16 var maxAmplitudeFound = AudioSample.min 五、元组
let http404Error = (404,"Not Found") //http404Error为(Int,String)类型的元组,值为(404,"Not Found") 可以分解元组中的值 let (statusCode,statusMessage) = http404Error print("The status code is (statusCode)") // Prints "The status code is 404" print("The status message is (statusMessage)") // Prints "The status message is Not Found" 如果你只需要元组中的一部分值,那么分解元组的时候可以用“_”来忽略相应的部分 let (justTheStatusCode,_) = http404Error print("The status code is (justTheStatusCode)") // Prints "The status code is 404" 当然,也可以通过Index来取元组中的值 print("The status code is (http404Error.0)") // Prints "The status code is 404" print("The status message is (http404Error.1)") // Prints "The status message is Not Found" 也可以在定义的时候单独命名元素,然后以名称取值。 let http200Status = (statusCode: 200,description: "OK") print("The status code is (http200Status.statusCode)") // Prints "The status code is 200" print("The status message is (http200Status.description)") // Prints "The status message is OK"
六、可选值 Optionals
例如 let possibleNumber = "123" let convertedNumber = Int(possibleNumber) // convertedNumber is inferred to be of type "Int?",or "optional Int"
可选值的运用 let possibleString: String? = "An optional string." let forcedString: String = possibleString! // requires an exclamation mark let assumedString: String! = "An implicitly unwrapped optional string." let implicitString: String = assumedString // no need for an exclamation mark
if assumedString != nil { print(assumedString) } if let definiteString = assumedString { print(definiteString) }
七、捕获异常func canThrowAnError() throws { // this function may or may not throw an error } //调用方法 do { try canThrowAnError() // no error was thrown } catch { // an error was thrown }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |