1、一行中声明多个变量或常量,用逗号分隔
var x = 0.0, y = 0.0, z = 0.0
var red, green, blue: Double
2、推荐使用 Double 类型、Int类型。
3、Int(string)返回一个可选的 Int ,而不是 Int 。可选的 Int 写做 Int? ,而不是 Int 。问号明确了它储存的值是一个可选项,意思就是说它可能包含某些 Int 值,或者可能根本不包含值。(他不能包含其他的值,例如 Bool 值或者 String 值。它要么是 Int 要么什么都没有。)
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"
4、通过给可选变量赋值一个 nil 来将之设置为没有值,在函数参数使用时可以把参数定义为可选项,然后给默认值为nil,来在调用时省略参数
var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value
func requestData(_ itemIds:[String]? = nil, _ month:Int? = nil, _ year:Int? = nil, _ state:Int? = nil) {
////////
}
调用 requestData()
5、善用 if let 、guard let 可选绑定的关键字
guard let constantName = optionalValue else {
// optionalValue 不包含值的情况,提前返回或处理错误。
// 必须在此处退出当前函数、循环或代码块
}
// 在此处使用 constantName,它是一个非可选的值
let optionalName: String? = "Alice"
if let name = optionalName {
print("Hello, \(name)!") // 输出 "Hello, Alice!"
} else {
print("The name is missing.")
}
6、通过检查布尔量 isEmpty属性来确认一个 String值是否为空
var emptyString = "" // empty string literal
var anotherEmptyString = String()
if emptyString.isEmpty {
print("Nothing to see here")
}
// prints "Nothing to see here"
7、范型
函数使用
// 指明函数的泛型参数(形式参数)需要使用'T'这个类型(T自己定义的一个类型)
func swapTwoValues<T>(_ a: T, _ b: T)
除了泛型函数,Swift允许你定义自己的泛型类型。它们是可以用于任意类型的自定义类、结构体、枚举,和 Array 、 Dictionary 方式类似。
struct IntStack {
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
}
用泛型改写:
struct Stack<Element> {
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
}
使用实例
通过在尖括号中写出存储在栈里的类型,来创建一个新的 Stack 实例。例如,创建一个新的字符串栈,可以写 Stack<String>() :
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
// the stack now contains 4 strings
8、循环 for-in 、forEach、(while、repeat-while 了解)
// 数组
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
🌟map 和 forEach 是 Swift 中用于处理序列(比如数组)的两个常见方法
map 转换每个元素并生成新的序列,而 forEach 只是对每个元素进行操作,不返回新序列(简单的来说就是map有返回值,forEach无返回值)。
🌟map 和 forEach使用如下:
============================================
let numbers = [1, 2, 3, 4, 5]
// 使用 map 转换每个元素,并返回一个新的序列
let multipliedByTwo = numbers.map { $0 * 2 }
print(multipliedByTwo) // 输出 [2, 4, 6, 8, 10]
// 使用 forEach 对每个元素执行操作
numbers.forEach { print($0) } // 输出 1 2 3 4 5
=============================================
// 字典
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
// 角标
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
let minutes = 60
for tickMark in 0..<minutes {
// render the tick mark each minute (60 times)
}
// stride 函数使用
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
// render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}
//闭区间也同样适用,使用 stride(from:through:by:) 即可
9、 .first(where: ...) 是一个用于在集合中查找满足指定条件的第一个元素的方法。它的使用方式如下:
便利的循环条件筛选 使用 is 来判断
eg:1
let numbers = [1, 2, 3, 4, 5]
if let firstEvenNumber = numbers.first(where: { $0 % 2 == 0 }) {
print("The first even number is \(firstEvenNumber)")
} else {
print("No even number found")
}
eg:2
if let targetViewController = UINavigationController.jk_topNav().viewControllers.first(where: { $0 is JKHealthReportController}) {
UINavigationController.jk_topNav().popToViewController(targetViewController, animated: false)
UINavigationController.jk_topNav().pushViewController(JKHealthReportFilesController(title: "原始资料"), animated: true)
}
🌟在 Swift 闭包中,$0 是一种特殊的语法,用于表示闭包的第一个参数。它可以用于简化闭包的书写。
10、Switch
let anotherCharacter: Character = "a"
let message :String
switch anotherCharacter {
case "a":
"The first letter of the Latin alphabet"
case "z":
"The last letter of the Latin alphabet"
default:
"Some other character"
}
// 🌟没有隐式贯穿,不需要break
// 匹配多个值可以用逗号分隔
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
}
// 可以区间条件匹配
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approximateCount {
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
// switch 情况可以将匹配到的值临时绑定为一个常量或者变量
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
11、类型检查
is :来检查一个实例是否属于一个特定的子类
as? 或 as! :向下类型转换至其子类类型
举个例子(Movie和Song同时继承父类MediaItem,library是MediaItem的数组)
//前提
let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// "library" 的类型被推断为[MediaItem]
// is使用如下
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
// as? 或 as!使用如下
for item in library {
if let movie = item as? Movie {
print("Movie: '\(movie.name)', dir. \(movie.director)")
} else if let song = item as? Song {
print("Song: '\(song.name)', by \(song.artist)")
}
}
Any 和 AnyObject 的类型转换
- AnyObject 可以表示任何类类型的实例。
- Any 可以表示任何类型,包括函数类型。
as 和 as? as! swift中区别如下:
在 Swift 中,as 关键字是用于转换类型的。它有如下三种形式:
as?:可选转换,将一个实例转换为一个可选的目标类型。如果实例可以转换为该类型,则返回可选值,否则返回 nil。
as!:强制转换,将一个实例强制转换为目标类型。如果实例不能转换为该类型,则会在运行时引发异常。
as :条件转换,将一个实例转换为目标类型。如果实例不能转换为该类型,则返回 nil。
因此,这三种形式的 as 在 Swift 中有不同的含义和使用方法。一般来说,当您确定转换一定可以成功时,使用 as! 进行强制转换会更加方便;而当您无法确定转换是否可以成功时,使用 as? 进行可选转换会更加安全。而 as 则需要根据实际情况进行选择,如果您希望在失败时返回 nil,那么使用 as,否则可以使用 as! 或者 try! 等方式。
🌟需要注意的是,在使用 as 进行转换时,目标类型必须是可选类型或允许为空的类型(比如 Optional,Any 和 AnyObject),否则编译器会报错。
进一步说明as 和 as?区别
在 Swift 中,as 和 as? 都是用于类型转换的关键字,但它们在转换失败时的处理方式不同。
在进行类型转换时,如果转换目标类型不能完全匹配原始类型,那么就需要进行类型转换。
当使用 as 进行类型转换时,如果无法将原始类型转换为目标类型,则会返回一个可选类型,其值为 nil,表示类型转换失败。
而当使用 as? 进行类型转换时,如果无法将原始类型转换为目标类型,则会返回 nil,而不是一个可选类型。这意味着,在使用 as? 进行类型转换时,您需要在代码中明确地处理类型转换失败的情况;而在使用 as 进行类型转换时,则可以使用可选绑定或空合运算符等机制来处理转换失败的情况。
let value: Any = 42
// 使用 as? 进行类型转换
if let intValue = value as? Int {
print("The integer value is \(intValue)")
} else {
print("Cannot convert to integer")
}
// 使用 as 进行类型转换
let intValue = value as Int?
if intValue != nil {
print("The integer value is \(intValue!)")
} else {
print("Cannot convert tinteger")
}
网友评论