复习Swift语言,总结一下知识点,记录下来,方便以后查阅。有哪里不对的地方,希望留言或回复指出,谢谢。
1.声明:
常量和变量必须在使用前声明,用let来声明常量,用var来声明变量。
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
你可以在一行中声明多个常量或者多个变量,用逗号隔开:
var x = 0.0,y = 0.0,z = 0.0
NOTE:
如果你的代码中有不需要改变的值,请使用
let
关键字将它声明为常量。只将需要改变的值声明为变量。
2.类型标注:
如果要添加类型标注,需要在常量或者变量名后面加上一个冒号和空格,然后加上类型名称。
var welcomeMessage: String
3.输出常量和变量
var friendlyWelcome = "Hello!" NSLog("欢迎消息是:%s”,friendlyWelcome)
Swift 用字符串插值(string interpolation)的方式把常量名或者变量名当做占位符加入到长字符串中,Swift 会用当前常量或变量的值替换这些占位符。将常量或变量名放入圆括号中,并在开括号前使用反斜杠将其转义:
!"println("The current value of friendlyWelcome is \(friendlyWelcome)")
// 输出 "The current value of friendlyWelcome is Hello
NOTE:常量必须有初始值。
示例代码:
import Foundation
println("Hello,World!")
//定义常量和变量
let name = "sn"
println(name)
var newName = "邵楠"
println(newName)
var age = 30
var age2:Double = 30
println(age2)
var Snow = "hello"
println(Snow)
println("Hello\(age)"+Snow)
let lable = "The width is"
let width = 94
let widthLable = lable + "\(width)"
var tus = ("hello",23,12,"sn")
println(tus.2)
func getName() -> (String,Int)
{
return ("Hi,Sn",32)
}
var tus2 = getName()
println(tus2)
let http404Error = (404,"No Found")
let (statusCode,statusMessage) = http404Error
println(" Code is \(statusCode)")
println(" Message is \(statusMessage)")
let (juststatusCode,_) = http404Error
println("Just Code is \(juststatusCode)")
let http200status = (statusCode:200,statusMessage:"OK")
println("Code is \(http200status.statusCode)")