Swift基础篇——函数

2016-11-29  本文已影响15人  沫简影
//函数的声明
//有返回值,有参数
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..<scores.count]{
        curMax = max(curMax,score)
        curMin = min(curMin,score)
    }
    return(curMax,curMin)
}
var userScores:[Int]? = [12,220,573,35489,249]
userScores = userScores ?? []
if let result = maxminScore(scores: userScores!){
    print("This maximum user score is:\(result.maxScore)")
    print("This maximum user score is:\(result.minScore)")
}
//参数的默认值
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)
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
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.count{
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
}

上一篇 下一篇

猜你喜欢

热点阅读