大佬教程收集整理的这篇文章主要介绍了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"
例如
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 }
以上是大佬教程为你收集整理的Swift官文阅读记录一(基础)全部内容,希望文章能够帮你解决Swift官文阅读记录一(基础)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。