当前位置: 首页 > 工具软件 > canDB.swift > 使用案例 >

swift5函数和Collection

赵夕
2023-12-01

(代码好像没有高亮显示,是这个markdown的问题)

一、函数

1.使用func声明函数:

func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}
greet(name: "Bob", day: "Tuesday")

标准输出:

Hello Bob, today is Tuesday.

2.返回多个返回值

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0

    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }

    return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
print(statistics.min)

标准输出:

120
120
3

3.可变参数

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
print(sumOf())
print(sumOf(numbers: 2, 1, 3))

标准输出:

0
6

参数不能是数组,只能是多个Int

4.函数内部可以内嵌一个函数

func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
print(returnFifteen())

标准输出:

15

内嵌的函数可以使用外部函数的变量

4.函数的返回值可以是函数

func makeIncrementer() -> ((Int) -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()
print(increment(7))

标准输出:

8

5.函数参数可以是函数

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
print(hasAnyMatches(list: numbers, condition: lessThanTen))

标准输出:

true

6.用{}创建闭包

var numbers = [20, 19, 7, 12]
print(numbers.map({
    (number: Int) -> Int in
    let result = 3 * number
    return result
}))
print(numbers)

用in区分开参数和函数体

标准输出:

[60, 57, 21, 36]
[20, 19, 7, 12]

7.闭包的其他写法

下面的map和sort

var numbers = [20, 19, 7, 12]
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
let sortedNumbers = numbers.sort{ $0 > $1 }
print(sortedNumbers)
print(numbers)
[60, 57, 21, 36]
()
[20, 19, 12, 7]

二、Collection

1.Array

1.1创建一个空数组:
var someInts = [Int]()
print(someInts.count)
let someInts2 = [Int]()
print(someInts2.count)

标准输出:

0
0

用let声明的类型都是不可变的,对象内存地址已经固定

var someInts = [Int]()
print(someInts.count)
let someInts2 = [Int]()
print(someInts2.count)

someInts.append(2)
someInts2.append(2)

编译错误:

Main.swift:7:11: error: cannot use mutating member on immutable value: 'someInts2' is a 'let' constant
someInts2.append(2)
~~~~~~~~~ ^
Main.swift:3:1: note: change 'let' to 'var' to make it mutable
let someInts2 = [Int]()
^~~
var
1.2用[]定义数组
var shopList: [String] = ["egg", "potato", "milk"]
print(shopList)

标准输出:

["egg", "potato", "milk"]
var shopList: [String]? = ["egg", "potato", "milk"]
print(shopList)

标准输出:

Optional(["egg", "potato", "milk"])

如果数组元素都是一个类型,比如String,swift会自动识别这个数组类型为String

var shopList = ["egg", "potato", "milk"]
print(shopList)

标准输出:

["egg", "potato", "milk"]
1.3创建一个数组并为数组赋初始值
var Doubles = Array(repeating: 1.0, count: 10)
print("the Doubles are: \(Doubles)")

标准输出:

the Doubles are: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
1.4数组拼接

不同类型的数组不能拼接,比如Int和Double

var array1 = Array(repeating: 2.5, count: 3)
var array2 = [1, 2, 3, 4, 5]
var sumArray = array1 + array2
print(sumArray)

编译错误:

Main.swift:3:25: error: cannot convert value of type '[Int]' to expected argument type 'Array'
var sumArray = array1 + array2
                        ^
Main.swift:3:25: note: arguments to generic parameter 'Element' ('Int' and 'Double') are expected to be equal
var sumArray = array1 + array2
var array1 = Array(repeating: 2.5, count: 3)
var array2 = [1.0, 2, 3, 4, 5]
var sumArray = array1 + array2
print(sumArray)

标准输出:

[2.5, 2.5, 2.5, 1.0, 2.0, 3.0, 4.0, 5.0]

也可以使用+=对数组进行拼接

1.5使用.count对数组计数
var shopList: [String]? = ["egg", "potato", "milk"]
print(shopList.count)

编译错误:

Main.swift:2:7: error: value of optional type '[String]?' must be unwrapped to refer to member 'count' of wrapped base type '[String]'
print(shopList.count)
      ^
Main.swift:2:7: note: chain the optional using '?' to access member 'count' only for non-'nil' base values
print(shopList.count)
      ^
              ?
Main.swift:2:7: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
print(shopList.count)
      ^
              !
var shopList: [String] = ["egg", "potato", "milk"]
print(shopList.count)

标准输出:

3
1.6使用.isEmpty判断数组是否为空
1.7使用append增加元素
1.8数组索引
var shopList: [String] = ["egg", "potato", "milk"]
shopList[0] = "apple"
print(shopList)

标准输出:

["apple", "potato", "milk"]
var shopList: [String]? = ["egg", "potato", "milk"]
shopList[0] = "apple"
print(shopList)

编译错误:

Main.swift:2:1: error: value of optional type '[String]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[String]'
shopList[0] = "apple"
^
Main.swift:2:1: note: chain the optional using '?' to access member 'subscript' only for non-'nil' base values
shopList[0] = "apple"
^
        ?
Main.swift:2:1: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
shopList[0] = "apple"
^
        !
Main.swift:3:7: warning: expression implicitly coerced from '[String]?' to 'Any'
print(shopList)
      ^~~~~~~~
Main.swift:3:7: note: provide a default value to avoid this warning
print(shopList)
      ^~~~~~~~
               ?? <#default value#>
Main.swift:3:7: note: force-unwrap the value to avoid this warning
print(shopList)
      ^~~~~~~~
              !
Main.swift:3:7: note: explicitly cast to 'Any' with 'as Any' to silence this warning
print(shopList)
      ^~~~~~~~
               as Any
1.9批量修改
var array = ["a", "b", "c", "d", "e"]
print(array)
array[1...3] = ["1", "2", "3"]
print(array)

标准输出:

["a", "b", "c", "d", "e"]
["a", "1", "2", "3", "e"]
1.10插入元素
var array = ["a", "b", "c", "d", "e"]
print(array)
array.insert("index", at: 1)
print(array)
["a", "b", "c", "d", "e"]
["a", "index", "b", "c", "d", "e"]
1.11移除元素
var array = ["a", "b", "c", "d", "e"]
print(array)
array.remove(at: 3)
print(array)

标准输出:

["a", "b", "c", "d", "e"]
["a", "b", "c", "e"]
1.12遍历数组
var array = ["a", "b", "c", "d", "e"]
for i in array{
    print(i)
}

for(index, value) in array.enumerated(){
    print("Element \(index + 1): \(value)")
}

标准输出:

a
b
c
d
e
Element 1: a
Element 2: b
Element 3: c
Element 4: d
Element 5: e

2.Set

2.1创建一个空Set
var letters = Set<Character>()
print(letters.count)

标准输出:

0
2.2插入元素
var letters = Set<Character>()
letters.insert("a")
print(letters)
letters = []
print(letters)

letters=[]并不会改变类型,依然是集合,而不是数组

标准输出:

["a"]
[]
2.3集合初始化,自动推断类型和一些常见函数
var words: Set = ["index", "elastic", "java", "python"]
print(words)
print(words.count)
print(words.isEmpty)
print(words.remove("java"))
print(words)
print(words.contains("python"))

标准输出:

["elastic", "java", "index", "python"]
4
false
Optional("java")
["elastic", "index", "python"]
true
2.4集合遍历
var words: Set = ["index", "elastic", "java", "python"]
for word in words{
    print("\(word)")
}

标准输出:

java
index
python
elastic
2.5排序
var words: Set = ["index", "elastic", "java", "python"]
for word in words.sorted(){
    print("\(word)")
}

标准输出:

elastic
index
java
python
2.6集合运算
var oddDigits: Set = [1, 3, 5, 7, 9]
var evenDigits: Set = [0, 2, 4, 6, 8]
var primeNumbers = [2, 3, 5, 7]

print(oddDigits.union(evenDigits).sorted())
print(oddDigits.intersection(evenDigits).sorted())
print(oddDigits.subtracting(primeNumbers).sorted())
print(oddDigits.symmetricDifference(primeNumbers).sorted())

标准输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[]
[1, 9]
[1, 2, 9]
2.7集合之间的关系
var oddDigits: Set = [1, 3, 5, 7, 9]
var evenDigits: Set = [0, 2, 4, 6, 8]
var primeNumbers: Set = [3, 5, 7]

print(primeNumbers.isSubset(of: oddDigits))
print(oddDigits.isSuperset(of: primeNumbers))
print(oddDigits.isDisjoint(with: evenDigits))

标准输出:

true
true
true

3. Dictionary

3.1创建字典和赋值
var nameOfIntegers = [Int: String]()
print(nameOfIntegers)
nameOfIntegers[2] = "two"
nameOfIntegers[3] = "three"
print(nameOfIntegers)
nameOfIntegers = [:]
print(nameOfIntegers)

var nameOfIntegers2 = [1:"one", 2:"two"]
print(nameOfIntegers2)

标准输出:

[:]
[2: "two", 3: "three"]
[:]
[2: "two", 1: "one"]
3.2常用函数
var nameOfIntegers = [1:"one", 2:"two"]
print(nameOfIntegers)
print(nameOfIntegers.count)
print(nameOfIntegers.isEmpty)

if let oldvalue = nameOfIntegers.updateValue("new one", forKey: 1){
    print("The old value for 1 was \(oldvalue)")
}

标准输出:

[1: "one", 2: "two"]
2
false
The old value for 1 was one
var nameOfIntegers = [1:"one", 2:"two"]
print(nameOfIntegers)

if let three = nameOfIntegers[3]{
    print("has 3")
}
else{
    print("no 3")
}

标准输出:

[1: "one", 2: "two"]
no 3
var nameOfIntegers = [1:"one", 2:"two"]
print(nameOfIntegers)

nameOfIntegers[1] = nil
print(nameOfIntegers)

标准输出:

[2: "two", 1: "one"]
[2: "two"]

也可以使用nameOfIntegers.removeValue(forKey: 1)

3.3遍历
var nameOfIntegers = [1:"one", 2:"two"]
print(nameOfIntegers)

for (key, value) in nameOfIntegers{
    print("\(key): \(value)")
}

for key in nameOfIntegers.keys{
    print(key)
}
for value in nameOfIntegers.values{
    print(value)
}

标准输出:

[1: "one", 2: "two"]
1: one
2: two
1
2
one
two

字典没有前面数组和集合的排序方法,要想对它排序遍历,可以对keys进行排序

 类似资料: