(代码好像没有高亮显示,是这个markdown的问题)
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet(name: "Bob", day: "Tuesday")
标准输出:
Hello Bob, today is Tuesday.
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
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
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
print(returnFifteen())
标准输出:
15
内嵌的函数可以使用外部函数的变量
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
print(increment(7))
标准输出:
8
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
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]
下面的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]
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
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"]
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]
不同类型的数组不能拼接,比如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]
也可以使用+=对数组进行拼接
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
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
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"]
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"]
var array = ["a", "b", "c", "d", "e"]
print(array)
array.remove(at: 3)
print(array)
标准输出:
["a", "b", "c", "d", "e"]
["a", "b", "c", "e"]
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
var letters = Set()
print(letters.count)
标准输出:
0
var letters = Set()
letters.insert("a")
print(letters)
letters = []
print(letters)
letters=[]并不会改变类型,依然是集合,而不是数组
标准输出:
["a"]
[]
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
var words: Set = ["index", "elastic", "java", "python"]
for word in words{
print("\(word)")
}
标准输出:
java
index
python
elastic
var words: Set = ["index", "elastic", "java", "python"]
for word in words.sorted(){
print("\(word)")
}
标准输出:
elastic
index
java
python
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]
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
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"]
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)
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进行排序