函数

func sayHello(name:String?) -> String{
    return "hello " + (name ?? "Guest")
}
sayHello("imooc")
var nickname: String? = nil
sayHello(nickname)

//没有返回值
func printHello() -> (){
    print("hello")
}
func printHello2() -> Void{
    print("hello")
}

使用元祖返回多个值

func findMaxAndMin( numbers: [Int]) -> (max:Int, min:Int)? {
//    if numbers.isEmpty{
//        return nil
//    }
    guard numbers.count > 0 else{
        return nil
    }
    var minValue = numbers[0]
    var maxValue = numbers[0]
    for number in numbers{
        minValue = minValue < number ? minValue : number
        maxValue = maxValue > number ? maxValue : number
    }
    return (maxValue, minValue)
}

var scores:[Int]? = [111, 232, 444, 133, 555, 289]//保证scores不是空的
scores = scores ?? []
if let result = findMaxAndMin( scores! ){
    print("The max score is \(result.max), The min score is \(result.min)")
}

命名

func sayHelloTo( name: String, greeting: String) -> String{
    return "\(greeting), \(name)"
}
sayHelloTo("Playground", greeting: "Hello")

func mutiply(num1:Int, _ num2:Int) -> Int{
    return num1*num2
}
mutiply(3, 3)

默认参数和可变参数

func sayHelloTo(name: String, withGreetingWord greeting:String = "hello", punctuation:String = "!") ->String{
    return "\(greeting), \(name)\(punctuation)"
}
sayHelloTo("imooc")
sayHelloTo("imooc", withGreetingWord: "hi", punctuation: "!!")

func sayHello(to name: String = "imooc", withGreetingWord greeting:String = "hello", punctuation:String = "!") ->String{
    return "\(greeting), \(name)\(punctuation)"
}
sayHello()

print("hello",1,2,3, separator: ",", terminator: ".")

//变长参数(参数的个数不确定)
func mean(numbers:Double ... ) ->Double{
    var sum:Double = 0
    //将变长参数当作一个数组
    for number in numbers{
        sum += number
    }
    return sum / Double(numbers.count)
}
mean(2)
mean(2,3)
mean(3,4,55,66)

常量参数,变量参数,inout参数

func toBinary(var num: Int) -> String{
    var res = ""
    repeat{
         res = String(num%2) + res
         num /= 2
    }while num != 0
    return res
}
toBinary(12)
var x = 100
toBinary(x)
x

//这样写没有进行交换
func swapTwoInts(var a:Int, var _ b:Int){
    let t:Int = a
    a = b
    b = t
}
var m:Int = 1
var n:Int = 2
swapTwoInts(m, n)
m
n
//这样写就可以交换
func swapTwoInts2(inout a:Int, inout _ b:Int){
    let t:Int = a
    a = b
    b = t
}
var s:Int = 1
var t:Int = 2
swapTwoInts2(&s, &t)
s
t

func initArray(inout arr: [Int], by value:Int){
    for i in 0..<arr.count{
        arr[i] = value
    }
}
var arr = [1,2,3,4,5]
initArray(&arr, by: 0)
arr

使用函数类型

func add(a:Int, _ b:Int) ->Int{
    return a+b
}
let anotherAdd:(Int,Int)->Int = add
anotherAdd(3,4)

func sayHelloTo(name:String){
    print("hello,\(name)")
}
let anotherSayHelloTo: String ->Void = sayHelloTo
anotherSayHelloTo

func sayHello(){
    print("hello")
}
let anotherSayHello1: ()->() = sayHello
let anotherSayHello2: ()->Void = sayHello
let anotherSayHello3: Void->() = sayHello
let anotherSayHello4: Void->Void = sayHello
//函数作为参数传入另一个函数
var arr:[Int] = []
for _ in 0..<100{
    arr.append(random()%1000)
}
arr
arr.sort()
arr
arr.sortInPlace()
arr
//自定义的排序
func biggerNumberFirst(a:Int, _ b :Int) -> Bool{
//    if a>b{
//        return true
//    }
//    return false
    return a > b
}
arr.sort(biggerNumberFirst)

func cmpByNumberString(a:Int, _ b:Int) -> Bool{
    return String(a) < String(b)
}
arr.sort(cmpByNumberString)

func near500(a:Int, _ b:Int) -> Bool{
    return abs(a-500) < abs(b-500) ? true:false
}
arr.sort(near500)

函数式的编程

func changeScore1(inout scores:[Int]){
    for (index,score) in scores.enumerate(){
        scores[index] = Int(sqrt(Double(score))*10)
    }
}

func changeScore2(inout scores:[Int]){
    for (index,score) in scores.enumerate(){
        scores[index] = Int(Double(score) / 150.0 * 100.0)
    }
}

var score1 = [36,61,78,89,99]
changeScore1(&score1)
var score2 = [88,101,124,137,150]
changeScore2(&score2)

*变成下面的

func changeScores(inout scores: [Int] , by changeScore:(Int) ->Int){
    for (index,score) in scores.enumerate(){
        scores[index] = changeScore(score)
    }
}
func changeScore1(score:Int) ->Int{
    return Int(sqrt(Double(score))*10)
}
func changeScore2(score:Int) ->Int{
    return Int(Double(score) / 150.0 * 100.0)
}
var score1 = [36,61,78,89,99]
changeScores(&score1, by: changeScore1)
var score2 = [88,101,124,137,150]
changeScores(&score2, by: changeScore2)

//map
var scores = [65,91,45,97,87,72,33]
//changeScores(&scores, by: changeScore1)

scores.map(changeScore1)

func isPassOrFaill(score:Int) ->String{
    return score < 60 ? "Fail" : "Pass"
}
scores.map(isPassOrFaill)
//filter
func fail(score:Int) -> Bool{
    return score<60
}
scores.filter(fail)
//reduce
func add(num1:Int, _ num2:Int) ->Int{
    return num1 + num2
}
scores.reduce(0, combine: add)
scores.reduce(0, combine: +)

func concatenate(str:String , num: Int) ->String{
    return str + String(num) + " "
}
scores.reduce("", combine: concatenate)

返回函数类型和函数嵌套

func tier1MailFeeByWeight(weight:Int) -> Int{
    return 1*weight
}
func tier2MailFeeByWeight(weight:Int) -> Int{
    return 3*weight
}
//func chooseMailFeeCalculationByWeight(weight:Int) -> (Int) -> Int{
//    return weight <= 10 ? tier1MailFeeByWeight : tier2MailFeeByWeight
//}
//func feeByUnitPrice(price:Int, weight:Int) ->Int{
//    let mailFeeByWeight = chooseMailFeeCalculationByWeight(weight)
//    return mailFeeByWeight(weight) + price * weight
//}

func feeByUnitPrice(price:Int, weight:Int) ->Int{
    func chooseMailFeeCalculationByWeight(weight:Int) -> (Int) -> Int{
        return weight <= 10 ? tier1MailFeeByWeight : tier2MailFeeByWeight
    }
    let mailFeeByWeight = chooseMailFeeCalculationByWeight(weight)
    return mailFeeByWeight(weight) + price * weight
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本章将会介绍 控制流For-In 循环While 循环If 条件语句Switch 语句控制转移语句 continu...
    寒桥阅读 746评论 0 0
  • 函数是用来完成特定任务的独立的代码块。给一个函数起一个合适的名字,用来标识函数做什么,并且当函数需要执行的时候,这...
    穷人家的孩纸阅读 816评论 2 1
  • 函数是执行特定任务的代码自包含块。给定一个函数名称标识, 当执行其任务时就可以用这个标识来进行”调用”。 Swif...
    透支未来阅读 252评论 0 1
  • [The Swift Programming Language 中文版]本页包含内容: 函数是用来完成特定任务的独...
    风林山火阅读 530评论 0 0
  • 夜越黑,月却明。
    ChanningQ阅读 147评论 0 0