1、常量与变量的定义
在swift中,常量的命名用let关键字来创建,变量的命名用关键字var来创建
//常量的命名
let name = "HelloWorld"
print("常量是:\(name)")
//变量的命名
var nickName = String()
nickName = "Bird"
print("变量是:\(nickName)")
输出:
常量是:
HelloWorld
变量是: Bird
变量是: Bird
2、字符串串接及类型转换
在swift中,支持“+”运算符,用它可以对两个字符串进行连接
let label = "the width is "
let width = 94
let widthLabel = label + String(width);
print(widthLabel);
输出:
the width is 94
3、数组和字典
在swift中,数组和字典都使用“[]”中括符,并且可以通过索引或key/value的方式存储。
//数组
var array = ["d","df","cs","ea","fees"]
print(array)
//利用索引对数组进行修改
array[1] = "ABC"
print(array)
输出:
["d", "df", "cs", "ea", "fees"]
["d", "ABC", "cs", "ea", “fees”]
["d", "ABC", "cs", "ea", “fees”]
// 字典
var dictionary = [String:String]();
dictionary["adc"] = "ADC"
dictionary["aaa"] = "AAA"
print(dictionary)
输出:
["aaa": "AAA", "adc": “ADC”]
//数组中的增删改查
var arr = ["a","b","c","d","e","f"]
//增加某个元素
arr.append("AA")
print(arr)
arr.append(contentsOf: ["1","2","3"])
print(arr)
arr.insert("ABC", at: 5)
print(arr)
arr.insert(contentsOf: ["AAAAA","BBBBB","CCCCC"], at: 3)
print(arr)
//删除序号处的元素
arr.remove(at: 2)
print(arr)
//全部删除
arr.removeAll()
print(arr)
//改
arr = ["ABC","ABD","ABF","ABE","ABG","ABH"]
print(arr)
arr[2] = "11111"
print(arr)
arr.replaceSubrange(1...3, with: ["222","333","444","555"])
print(arr)
arr.replaceSubrange(1...3, with: ["BMW"])
print(arr)
//数组的长度
print(arr.count)
//遍历数组
for ele in arr{
print(ele)
}
输出:
["a", "b", "c", "d", "e", "f", "AA"]
["a", "b", "c", "d", "e", "f", "AA", "1", "2", "3"]
["a", "b", "c", "d", "e", "ABC", "f", "AA", "1", "2", "3"]
["a", "b", "c", "AAAAA", "BBBBB", "CCCCC", "d", "e", "ABC", "f", "AA", "1", "2", "3"]
["a", "b", "AAAAA", "BBBBB", "CCCCC", "d", "e", "ABC", "f", "AA", "1", "2", "3"]
[]
["ABC", "ABD", "ABF", "ABE", "ABG", "ABH"]
["ABC", "ABD", "11111", "ABE", "ABG", "ABH"]
["ABC", "222", "333", "444", "555", "ABG", "ABH"]
["ABC", "BMW", "555", "ABG", "ABH"]
5
ABC
BMW
555
ABG
ABH
["a", "b", "c", "d", "e", "f", "AA", "1", "2", "3"]
["a", "b", "c", "d", "e", "ABC", "f", "AA", "1", "2", "3"]
["a", "b", "c", "AAAAA", "BBBBB", "CCCCC", "d", "e", "ABC", "f", "AA", "1", "2", "3"]
["a", "b", "AAAAA", "BBBBB", "CCCCC", "d", "e", "ABC", "f", "AA", "1", "2", "3"]
[]
["ABC", "ABD", "ABF", "ABE", "ABG", "ABH"]
["ABC", "ABD", "11111", "ABE", "ABG", "ABH"]
["ABC", "222", "333", "444", "555", "ABG", "ABH"]
["ABC", "BMW", "555", "ABG", "ABH"]
5
ABC
BMW
555
ABG
ABH
//swift中字典的运用
var dict : [String:String] = ["a":"1","b":"2"]
//添加
dict["c"] = "3"
print(dict)
dict["c"] = "333"
print(dict)
dict .removeValue(forKey: "c")
print(dict)
dict.updateValue("AAAAA", forKey: "a")
print(dict)
let abc = Array(dict.keys)
let abc1 = Array(dict.values)
print("\(abc)==\(abc1)");
输出:
["b": "2", "a": "1", "c": "3"]
["b": "2", "a": "1", "c": "333"]
["b": "2", "a": "1"]
["b": "2", "a": "AAAAA"]
["b", "a"]==["2", “AAAAA”]
["b": "2", "a": "1", "c": "333"]
["b": "2", "a": "1"]
["b": "2", "a": "AAAAA"]
["b", "a"]==["2", “AAAAA”]