iOS-swift4学习(基础类型)

2018-07-10  本文已影响52人  木马不在转

一:字符串知识点

  1. 字符穿插输出
let friendlyWelcome = "Hello!"
print("The current value of friendlyWelcome is \(friendlyWelcome)")
  1. 类型别名 赋值一个新的类型名
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
  1. 函数错误处理 - throws
func canTrowAnError() throws {
    // 这个函数有可能抛出错误
}

do {
    try canTrowAnError()
     // 没有错误消息抛出
} catch {
    // 有一个错误消息抛出
}
  1. 断言进行调试 & 强制执行先决条件
    • assert 开发阶段
    • precondition 生产环境
let age = 1
assert(age > 0, "age 大于0了")

let index = 1
precondition(index > 0, "index 小于0了")
  1. 三目运算 & 空合运算符(a ?? b)
var a: String?
let b: String? = "123"
a != nil ? a! : b
let c = a ?? b
  1. 区间运算符
 闭区间运算符(a...b)定义一个包含从 a 到 b(包括 a 和 b)的所有值的区间
 半开区间运算符(a..<b)定义一个从 a 到 b 但不包括 b 的区间
 单侧区间 (a...) || (...a) || (a<..)||(..<a) 可以表达往一侧无限延伸的区间
  1. 多行字符串字面量
let quotation = """
The White Rabbit put on his spectacles.  "Where shall I begin,
please your Majesty?" he asked.

"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""
print(quotation)

字符串字面量的特殊字符

 转义字符\0(空字符)
 \\(反斜线)
 \t(水平制表符)
 \n(换行符)
 \r(回车符)
 \"(双引号)
 \'(单引号)
  1. 字符串 isEmpty属性来判断该字符串是否为空
let textValue = "String"
if textValue.isEmpty {
    print("Nothing to see here")
}
  1. String Array、Dictionary 和 Set 的基本操作。
var greeting = "Guten Tag!"
print(greeting.startIndex)//G 第一个
print(greeting.endIndex)//! 最后一个
print(greeting.index(after: greeting.startIndex))//u -after 后面一个索引
print(greeting.index(before: greeting.endIndex))//! -before 前面一个索引
print(greeting.index(greeting.startIndex, offsetBy: 7))//a -greeting 对应偏移量的索引
print(greeting.insert("w", at: greeting.startIndex)) // 插入一个字符
print(greeting.insert(contentsOf: "ni hao", at: greeting.startIndex)) // 插入一段字符串
print(greeting.remove(at: greeting.endIndex)) // 删除一个字符
let range = greeting.index(greeting.endIndex, offsetBy: -6)..<greeting.endIndex
print(greeting.removeSubrange(range)) // 删除一段字符串
  1. 字符前缀&后缀 判断
let hasString = "The White Rabbit put on his spectacles"

if hasString.hasPrefix("The") {
    print("如果前缀是 The")
}
if hasString.hasSuffix("spectacles") {
    print("如果后缀是 spectacles")
}

二:集合类型小结

  1. 创建一个带有默认值的数组
var threeDoubles: [Int] = Array(repeating: 0, count: 6)
/*等价于 [0, 0, 0, 0, 0, 0]*/
  1. 数组添加一个值
threeDoubles.append(2)
/* 000000 -> 0000002*/
  1. 利用下标来一次改变一系列数据值
threeDoubles[2...5] = [2,4] 
/* 00000002 -> 002502 */
  1. 数组的遍历 - enumerated()
for (index, value) in threeDoubles.enumerated() {
    
     print("Item \(String(index + 1)): \(value)")
}
  1. 集合set的顺序遍历
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"] // 集合必须显示声明

for value in favoriteGenres.sorted() {
    print("\(value)")
}
  1. 集合set的基本操作
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
  1. 集合set成员关系和相等
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
houseAnimals == favoriteGenres // false
houseAnimals.isSubset(of: farmAnimals)// true
farmAnimals.isSuperset(of: houseAnimals)// true
houseAnimals.isStrictSubset(of: farmAnimals)// true
farmAnimals.isStrictSuperset(of: houseAnimals)// true
farmAnimals.isDisjoint(with: cityAnimals)// true
  1. 字典更新值且返回旧值 - updateValue
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
let DUBValue = airports.updateValue("Airport", forKey: "DUB")
 /*newDUB = 有旧值就输出旧值 Dublin  没有就输出 nil*/
  1. 获取字典所有值或键
let airportCodes = [String](airports.keys) /* ["YYZ", "LHR"] */
let airportNames = [String](airports.values) /* ["Toronto Pearson", "Airport"] */

三:小知识点

  1. stride() 函数 循环跳过不需要的标记。
let minutes = 60 // 源
let minuteInterval = 5 // 间隔
let fromValue = 0 // 起点值

for _ in stride(from: fromValue, to: minutes, by: minuteInterval){
    // 0..<60 每5分钟渲染一个刻度线 (0, 5, 10, 15 ... 45, 50, 55)
}
for _ in stride(from: fromValue, through: minutes, by: minuteInterval) {
    // 0...60 每5分钟渲染一个刻度线 (0, 5, 10, 15 ... 45, 50, 55,60)
}
  1. While 循环的二种方式
/* while循环,每次在循环开始时计算条件是否符合;*/
while condition {
    statements
}

/* repeat-while循环,每次在循环结束时计算条件是否符合。*/
repeat {
    statements
} while condition

  1. switch
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}
  1. 控制转移语句
enum VendingMachineError: Error {
    case invalidSelection                     //选择无效
    case insufficientFunds(coinsNeeded: Int) //金额不足
    case outOfStock                             //缺货
}
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)//代码抛出一个错误,提示贩卖机还需要5个硬币:
  1. guard
func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }
    print(name)
}
  1. 检测 API 可用性
if #available(iOS 10, macOS 10.12, *) {
    // 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
} else {
    // 使用先前版本的 iOS 和 macOS 的 API
}
  1. 过滤某些对象 - compactMap
let stringAry = ["0","1","2"]
let str = stringAry.compactMap { (item) -> Bool? in
    // 条件过滤
    return  Int(item)! > 1 
}
print("stringAry = \(stringAry)")

swift学习电梯:
swift-基础类型
swift-函数
swift-类和结构体

swift
上一篇 下一篇

猜你喜欢

热点阅读