2020-11-16-分支、循环、字符串、数组、字典

2020-11-16  本文已影响0人  pluskok

逻辑分支

###if用法

1.if后面的()可以省略
2.判断句不再有非0/nil即真,判断句必须有明确的的真假(Bool --> true/false)
###switch基本用法

1.switch后面的()可以省略
2.case语句结束后,break可以省略
3.如果系统想在一个case中产生case穿透,可以在case结束后跟上fallthrough
4.可以判断多个条件
let sex = 1
switch sex {
case 0,1:
//正常人
default:
//其他
}

###特殊用法

1.可以判断浮点型
2.可以判断字符串
3.支持区间 0..10,0...10

let score = 88
switch score {
case 0..<60:
  print("不及格")
case 60..<80:
  print("及格")
case 80..<90:
  print("良好")
default:
  print("优秀")
}

循环

#for
for var i = 9; i >= 0; i-- {
  print(i)
}

for i in 0..<10 {
  print(i)
}

for _ in 0..<10 {
  print("hello")
}
#while/repeat while
OC写法
while (a) {
//...
}

#swift写法
1.while后面()可以省略
2.while后面的判断没有非0即真
while a > 0{
//...
}
#do while
//oc写法
do {//..
} while(a)

//swift写法
repeat {
//...
} while (a)

字符串

【一】定义
let str = "hello world"

【二】遍历
for c in str.characters {
  print(c)
}

【三】拼接
//1.字符串和字符串
let str2 = str + "..."

//2.字符串和其他标识符
let name = "张三"
let book = "平凡的世界"
let demo = "\(name) likes \(book)."

【四】字符串格式化
let min = 2
let second = 8
let timeStr = String(format: "%02d:%02d", arguments: min,second)

【五】字符串截取
let urlString = "www.baidu.com"
let header = urlString.substringToIndex(index:Index)
let header2 = (urlString as NSString).substringToIndex(3)


数组

【一】定义
let array = ["this", "is", "not" ,"mutable", "array"]
var arrayM = Array<String>()
var arrayM = [String]()


【二】可变数组基本操作:增删改查
arrayM.append("append element")
arrayM.removeAtIndex(0)
arrayM[0] = "replace"
arrayM[0] //query


【三】遍历
1.根据下标值
for i in 0..<array.cout {
  print(array[i])
}
2.直接遍历数组元素
for name in array {
  print(name)
}
3.遍历数组中前两个元素
//for i in 0..<2 {
//  print(array[i])
//}
for name in array[0..<2] {
  print(name)
}
for (index,item) in array.enumerated() {
    print(index,item)
    print(item.offset,item.element)
}

【四】合并
let array1= ["why",18,1.88] as [Any]
let array2 = ["why", "not"]
let result  = array1 + array2

字典

【一】定义
let dict = Dictionary<String : Any>()
let dict = [String : Any]()

var dict = ["name" : "张三", "height" : 1.88]


【二】可变字典基本操作
dict["nick"] = "狗蛋儿"
dict.removeValueForKey("height")
dict["name"] = "张小六"
dict["name"]

【三】遍历
for key in dict.keys {
  print(key)
}
for value in dict.values {
  print(value)
}
for (key,value) in dict {
  print(key,value)
}

【四】合并
#即使相同类型也不能相加
var dict1 = ["name" : "tom", "height" : 170]
var dict2 = ["nick" : "cat","weight" : 150]
for (key,value) in dict2 {
  dict1[key] = value
}
上一篇下一篇

猜你喜欢

热点阅读