//带返回值的函数
func greet(_ person: String, on day:String) -> String {
let bb = "hello \(person) \(day)"
print(bb)
return bb
}
greet("小明", on: "2月3")
//返回值是元组的函数(多个返回值)
func duoGeFanHuiZhi(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 result = duoGeFanHuiZhi(scores: [3,4,5,33,44,666,232])
print(result.max)
//可变个数参数的函数
func keBianGeShuDeHanShu(numbers:Int...) -> Int {
var sum = 0
for number in numbers {
sum += number;
}
return sum
}
keBianGeShuDeHanShu(numbers: 0)
keBianGeShuDeHanShu(numbers: 3, 4, 5)
//写一个计算平均值的函数
func calculateAverage(numbers: Int...) -> Int{
var sum = 0
for number in numbers {
sum += number
}
let count = numbers.count
let average = sum / count
return average
}
calculateAverage(numbers: 2, 4, 6)
//函数作为返回值
func makeIncrementer() -> ((Int) -> Int) {
//被返回的函数
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
//函数作为参数
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,3]
hasAnyMatches(list: numbers, condition: lessThanTen)
numbers.map({
(number: Int) -> Int in
let result = 3 * number;
return result
})
let allAddOne = numbers.map({number in number + 1})
print(allAddOne)
//数组排序
let sortedNumbers = numbers.sorted(){ $0 < $1 }
print(sortedNumbers)
//字符串数组
let strings:[String] = ["sss", "bbbbb", "cccccc"]
let a = "aaa"
//获取字符串长度
print(a.characters.count)
let sortedStrings = strings.sorted { (a, b) -> Bool in
return a.characters.count > b.characters.count
}
let sortedStrings2 = strings.sorted(){$0.characters.count > $1.characters.count}
print(sortedStrings)
print(sortedStrings2)
网友评论