Swift基础篇——函数

  • 函数的基本的创建方法及使用
//函数的声明
//有返回值,有参数
func sayHello(name:String?,greenting:String) -> String
{
    let result = greenting + (name ?? "Guest")+"!"
    return result
}

//有返回值、无参数
func sayWelcome() -> String
{
    return "welcome"
}

//无返回值
func endConversation()
{
    print("#the contversion is over#")
}

func endConversation1() -> Void
{
    print("#the contversion is over#")
}

func endConversation2() -> ()
{
    print("#the contversion is over#")
}

//函数的调用
var nickName : String?
nickName = "Nick"
print( sayHello(name: nickName, greenting: "Good morning"))
print( sayWelcome() )
  • 有多个返回值的函数
//使用元组让函数返回多个值
func maxminScore ( scores:[Int] ) -> (maxScore:Int,minScore:Int)?
{
    if scores.isEmpty {
        return nil
    }
    var curMax = scores[0], curMin = scores[0]
    for score in scores[1..
  • 有默认参数值的函数
//参数的默认值
func sayHai(name:String?,  greenting:String = "hello" ,other:String = "how do you do") -> String
{
    let result = greenting + (name ?? "Guest")+"!"+other
    return result
}

sayHai(name: "bobobo", greenting: "hi")
sayHai(name: "nihao")
sayHai(name: "nihao",other:"how are you")
  • 参数可变的函数
    一个函数最多只能设置一个可变参数,并且这个可变的参数必须放在整个函数的参数列表的最后的位置;
    正常来说函数的参数列表应该为:必须的参数,具有默认值的参数,可变的参数
//参数可变的函数
func add(a:Int,b:Int,others:Int ...) -> Int
{
    var result = a+b
    for number in others
    {
        result += number
    }
    return result
}
var res = add(a: 2 , b: 3)
res = add(a: 2, b: 3, others: 4, 5)
  • 函数的参数类型
  • 常量参数
    swift函数中的参数,默认是不可修改的,这类参数为常量参数
  • 变量参数(在swift 3中不被允许)
    不管是字典还是数组等类型的参数,在swift的函数中被改变后,传入的参数本身是不会发生变化的,即参数的传递都是值传递;
    在swift 3 中要想使用并改变传入的参数,只能用下面的办法,如:
func toBinary( num:Int) -> String
{
    var num = num
    var result:String = ""
    while num != 0 {
      
        result = String( num % 2) + result
        num /= 2
    }
    return result
}

 var num = 5

toBinary(num: num)

num //结果还是5
  • inout 参数
    要想通过函数彻底改变传入的参数的值,需要将参数类型声明为inout类型,如:
func swapTwoInts( a:inout Int ,b:inout Int)
{
  let t = a
  a = b
  b = t
}
var x = 0, y = 100
swapTwoInts(a: &x, b: &y)
x // 100
y //0
  • 函数类型
    即函数同时也是一种参数,可以存在一个变量中,其主要应用:

  • 将一个函数作为一个参数传递到另外一个函数中

func add( a:Int,b:Int) -> Int
{
return a+b
}
let anotherAdd = add
anotherAdd(3,4)
let anotheradd1:(Int,Int)->Int
let anotherSayhello:(String)->()
func changeScores(op:(Int)->Int, scores:inout [Int]){
for i in 0.. scores[i] = op(scores[i])
}
}
func op1(x:Int)->Int{
return Int(sqrt(Double(x))*10)
}
var scores = [34,34,67,89,90]
changeScores(op: op1, scores: &scores)
scores
var arr = Int
for _ in 1...20{
arr.append(Int(arc4random()%100))
}
//sorted 函数默认是升序排序
arr.sorted()
func compareTwoInts(a:Int,b:Int)->Bool
{
return a>b
}
//降序排序
arr.sorted(by: compareTwoInts)
var strArr = ["d","c","df","hdjkfs","dhfj","i"]
strArr.sorted()
func compareTwoString(s1:String,s2:String)->(Bool)
{
return s1.characters.count < s2.characters.count
}
//按字符串长度排序
strArr.sorted(by: compareTwoString)

- 将函数作为返回值返回
主要意义在于解耦,提高代码易读性和易维护性

func tierlMailTee(weight:Int)->Int{
return 1weight
}
func tier2MailTree(weight:Int)->Int{
return 2
weight
}
func totalPrice(price:Int,weight:Int) -> Int
{
func chooseMailFeeCalcmethod(weight:Int) -> (Int)->Int
{
return weight <= 10 ?tierlMailTee : tier2MailTree
}
let mailFeeCalc:(Int)->Int = chooseMailFeeCalcmethod(weight: weight)
return mailFeeCalc(weight) + price*weight
}

你可能感兴趣的:(Swift基础篇——函数)