Swift基础知识汇总【1】

Swift 学习笔记

1. for循环的使用


//// 开区间
for i in 1 ..< 5{
    print(i)  //1 - 4
}
//// 闭区间
for i in 1 ... 5{
    print(i) //1 - 5
}

2. 单侧区间


let names = ["Anna", "Alex", "Brian", "Jack"]

for name in names[2...]{ //从下标 2开始 到数组结束 包含2
    print(name)
}

for name in names[...2]{ //从下标0 开始到下标2结束 包含2
    print(name)
}
还可以这样用

let range  = ...5 //从负的无穷大到5

let isContain = range.contains(-1000)

print(isContain)

let range2 = 5... //从5到正的无穷大

let isContain2 = range2.contains(10000)
print(isContain2)



3. 逻辑运算符 与 或 非

4. 字符串操作
var variableString = "Horse"
variableString += " and Carriage"
print(variableString)


var word = "cafe"
print(word.count)

/// 使用String特定索引访问指定的字符
let greeting = "Grten Tag!"
print(greeting[greeting.startIndex])

print(greeting[greeting.index(before: greeting.endIndex)])

///从某个索引偏移多少
let index = greeting.index(greeting.endIndex, offsetBy: -7)
print(greeting[index])

hasPrefix(_:)和hasSuffix(_:) 方法来检查字符串是否拥有特定前缀/后缀

5. 数组操作


var shoppingList = ["a","b"]

shoppingList += ["c","d"]

//print(shoppingList)


for item in shoppingList{
    print(item)
}

for(index,value ) in shoppingList.enumerated(){
    print("item\(String(index + 1)) value:\(value)")
}


6.字典操作


//字典

var nameDic =  ["key":"value"]
//更新键值对
nameDic["key1"] = "value1"

if let oldValue = nameDic.updateValue("hhhh", forKey: "key1"){ //如果原来的key下存在value。则返回原来的值 否则返回nil
    print(oldValue)
}
// MARK --- 删除键值对的
nameDic["key1"] = nil

nameDic.removeValue(forKey: "key1") //这个方法在键值对存在的情况下会移除该键值对并且返回被移除的值或者在没有值的情况下返回nil

7.条件控制语句
- for循环


for index in 1...5{ // 1 2 3 4 5
    print(index)
}

for index in 1..<5{// 1 2 3 4 
    print(index)
}
Switch

Switch (abc)
case "a","A":print("测试")
default:print("Not 测试")


guard let name = person["name"] else { //将变量或者常量的可选绑定作为guard语句的条件.以保护guard语句后面的代码
    return
}

你可能感兴趣的:(Swift基础知识汇总【1】)