//
// main.swift
// testFunctions
//
// Created by 朱立志 on 14-6-11.
// Copyright (c) 2014年 zlz. All rights reserved.
//
import Foundation
println("Hello, World!")
//单个参数输入函数
func sayHello(personName : String ) -> String{
return "hello func "+personName+"!"
}
println(sayHello("zlz"))
// 多个参数传入
func halfOpenRangeLength(start : Int , end : Int ) -> Int{
return start + end
}
println(halfOpenRangeLength(2, 4))
// 没有返回值的函数
func sayGoodBye(personName :String ) {
println("good bye "+personName)
}
sayGoodBye("zlz")
// 多个返回值函数
func count(inputStr : String) ->(vowels : Int , consonants : Int , others : Int){
var vowels = 0 , consonants = 0, others = 0
for charset in inputStr {
switch String(charset).lowercaseString {
case "a","e","i","o":
++vowels
case "b","c","d","f","l","k":
++consonants
default :
others++
}
}
return (vowels , consonants , others)
}
println(count("abdefiolkzwn"))
// 参数别名 #表示函数参数名和函数内部参数名 // “local parameter name and the external parameter name”
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
for character in string {
if character == characterToFind {
return true
}
}
return false
}
// 给函数参数定义 默认值
func join (string s1: String , toString s2 : String , withJoiner joiner : String = "") -> String{
return s1+s2+joiner
}
println(join(string : "zhu",toString: " lizhi ",withJoiner: " joiner"))
// 可变参数
func arithmeticMean (numbers : Double ...) -> Double {
var total:Double = 0
for number in numbers {
total += number
}
return total
}
println(arithmeticMean(3,2,5,7,9,13))
func addTwoInts(a : Int , b : Int)-> Int{
return a+b
}
var mathFunction : (Int ,Int) -> Int = addTwoInts
println(mathFunction(3,2))
// 函数参数是函数的函数
func printMathResult(mathFunction:(Int,Int) -> Int , a : Int , b : Int){
println("result \(mathFunction(a,b))")
}
println(printMathResult(mathFunction , 4 , 5))