Swift學習筆記(二十九)——函式的使用1

乞力馬紮羅的雪CYF發表於2015-09-16

(1)引數型別為可選型Optional.  如果引數為空,則輸出??後面的字串,否則輸出可選型的引數值。

import Foundation

func sayHello(name:String?)->String{

  let result = "Hello," + (name ?? "無名氏")
  return result

}

var nickname:String?
nickname = "Jack"
println(sayHello(nickname))

(2)函式如果沒有返回值,可以在後面加上->Void。


(3)使用元祖讓函式返回多個值。

import Foundation

let userScores = [12,90,45,3,213,45]

func maxMinScores(scores:[Int]) -> (maxScores:Int,minScores:Int){

  var curmax = scores[0]
  var curmin = scores[0]
  
  for score in scores[1 ..< scores.count]{

    curmax = max(curmax,score)//Swift中的全域性函式;
    curmin = min(curmin,score)
    
    
  }
  
  return (curmax,curmin)
  
}

let result = maxMinScores(userScores)
println("最大值:\(result.maxScores)" )
println("最小值:\(result.minScores)" )

或者:

import Foundation

let userScores = [12,90,45,3,213,45]

func maxMinScores(scores:[Int]) -> (Int,Int){

  var curmax = scores[0]
  var curmin = scores[0]
  
  for score in scores[1 ..< scores.count]{

    curmax = max(curmax,score)//Swift中的全域性函式;
    curmin = min(curmin,score)
    
    
  }
  
  return (curmax,curmin)
  
}

let result = maxMinScores(userScores)
println("最大值:\(result.0)" )
println("最小值:\(result.1)" )

上述例子如果返回值為空,則需要進行如下的優化:

import Foundation

let userScores = [12,90,45,3,213,45]

func maxMinScores(scores:[Int]) -> (maxScore:Int , minScore:Int)?{

  //如果傳入的引數陣列為空,則返回nil;
  if scores.isEmpty{
  
    return nil
  }
  
  
  var curmax = scores[0]
  var curmin = scores[0]
  
  for score in scores[1 ..< scores.count]{

    curmax = max(curmax,score)//Swift中的全域性函式;
    curmin = min(curmin,score)
    
    
  }
  
  return (curmax,curmin)
  
}

//返回的是一個可選型;
if let result = maxMinScores(userScores){

  println("最大值:\(result.maxScore)" )
  println("最小值:\(result.minScore)" )
  
}

如果傳入的陣列引數為空,再次進行優化:

import Foundation

var userScores:[Int]? = [1,2,3,4,5,6]

func maxMinScores(scores:[Int]) -> (maxScore:Int , minScore:Int)?{
  
  //如果傳入的引數陣列為空,則返回nil;
  if scores.isEmpty{
    
    return nil
  }
  
  
  var curmax = scores[0]
  var curmin = scores[0]
  
  for score in scores[1 ..< scores.count]{
    
    curmax = max(curmax,score)//Swift中的全域性函式;
    curmin = min(curmin,score)
    
    
  }
  
  return (curmax,curmin)
  
}

//返回的是一個可選型;

userScores = userScores ?? []
if let result = maxMinScores(userScores!){
  
  println("最大值:\(result.maxScore)" )
  println("最小值:\(result.minScore)" )
  
}



github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!

相關文章