本文共 2342 字,大约阅读时间需要 7 分钟。
在Swift中,常量和变量是编程中的基础概念。常量通过let
声明,不可修改,而变量通过var
声明,可修改。以下是常量和变量的基本使用示例:
// 常量的定义let a : Int = 10// 变量的定义var b : Int = 20// 修改变量值b = 30
let btn : UIButton = UIButton(type: .Custom)btn.backgroundColor = UIColor.blueColor()btn.setTitle("按钮", for: .Normal)btn.frame = CGRect(x: 20, y: 20, width: 60, height: 30)view1.addSubview(btn)
在Swift中,数据类型是程序中数据操作的基础。可以通过类型推导或显式注明。
var i = 20 // i 为 Intvar j = 3.33 // j 为 Double// 变量赋值如下会导致错误// i = 30.5// 正确写法var j = 3.33j = 6.66
let m : Int = 10let n : Double = 3.14let a = 10let b = 3.14let c = Double(a) + blet d = a + Int(b)
let score = 87if score < 60 { print("不及格")} else if score < 70 { print("及格")} else if score < 80 { print("良好")} else if score < 90 { print("优秀")} else { print("完美")}
var a = 10var b = 50var result = a > b ? a : bprintln(result)
func online(age: Int) { guard age >= 18 else { print("回家去") return } print("可以上网")}online(18)
let m = 5let n = 10var result = 0let operation = "+"switch operation {case "+": result = m + ncase "-": result = m - ncase "*": result = m * ncase "/": result = m / ndefault: result = 0}print(result)
for i in 0..<10 { print(i)}for i in 0...10 { print(i)}for _ in 0..<10 { print("hello")}
var a = 0while a < 10 { a += 1}let b = 0repeat { print(b) b += 1} while b < 20
let str = "Hello, Swift"for c in str.characters { print(c)}
let str1 = "Hello"let str2 = "World"let str3 = str1 + str2let name = "why"let age = 18let info = "my name is \(name), age is \(age)"let time = String(format: "%02d:%02d", min: 3, second: 4)
let myStr = "www.520it.com"var subStr = String(myStr[myStr.index(myStr.startIndex, offsetBy: 4)]var subStr2 = String(myStr[..
var array : [String] = []let array2 : [NSObject] = ["why", 18]
array.append("yz")// 删除元素array.removeFirst()
for i in 0..
var dict1 : [String: NSObject] = [:]let dict2 = ["name" : "why", "age" : 18]dict = ["name" : "why", "age" : 18]
dict["age"] = 20dict.removeValue(forKey: "age")
for value in dict.values { print(value)}
let tuple = (1001, "张三", 30, 90)
let error = (404, "Not Found")print(error.0)print(error.1)
转载地址:http://cqroz.baihongyu.com/