美文网首页
Swift基础学习(函数)

Swift基础学习(函数)

作者: whbsspu | 来源:发表于2016-08-01 15:34 被阅读17次

    函数结构

    • 函数结构
    func 函数名(参数)-> 函数返回类型{
       函数体
    }
    

    函数类型

    • 多参数函数:参数之间用逗号(,)隔开
    func halfOpenRangeLength(start: Int, end: Int) -> Int {
    return end - start
    }
    println(halfOpenRangeLength(1, 10))
    // prints "9"
    
    • 无参数函数:注意,即使一个函数不带有任何参数,函数名称之后也要跟着一对空括号()
    func sayHelloWorld() -> String {
    return "hello, world"
    }
    println(sayHelloWorld())
    // prints "hello, world"
    
    • 无返回值参数:无返回值函数后面可以不加返回箭头( – >)和返回类型
    func sayGoodbye(personName: String) {
    println("Goodbye, \(personName)!")
    }
    sayGoodbye("Dave")
    // prints "Goodbye, Dave!"
    
    • 多返回值函数:可以使用元组或者多返回值组成的复合作为返回值。
    func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
    var vowels = 0, consonants = 0, others = 0
    for character in string {
    switch String(character).lowercaseString {
    case "a", "e", "i", "o", "u":
    ++vowels
    case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
    "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    ++consonants
    default:
    ++others
    }
    }
    return (vowels, consonants, others)
    }
    

    外部参数名

    • 使用外部参数名称的初衷是为了在别人在调用函数时知道函数入参的目的。
    func join(string s1: String, toString s2: String, withJoiner joiner: String)
    -> String {
    return s1 + joiner + s2
    }
    
    join(string: "hello", toString: "world", withJoiner: ", ")
    // returns "hello, world"
    

    如果一个入参既是内部参数又是外部参数,那么只要在函数定义时参数前加#前缀即可。

    可变参数

    当传入的参数个数不确定时,可以使用可以参数,只需要在参数的类型名称后加上点字符(...)。

    func arithmeticMean(numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
    total += number
    }
    return total / Double(numbers.count)
    }
    arithmeticMean(1, 2, 3, 4, 5)
    // returns 3.0, which is the arithmetic mean of these five numbers
    arithmeticMean(3, 8, 19)
    // returns 10.0, which is the arithmetic mean of these three numbers
    

    注意:函数最多有一个可变参数的参数,而且必须出现在参数列表的最后以避免多参数调用时出现歧义。

    输入输出参数

    如果想用一个函数来修改参数的值,并且只在函数调用结束之后修改,则可以使用输入-输出参数。只要才参数定义时添加inout关键字即可表明是输入输出参数。

    相关文章

      网友评论

          本文标题:Swift基础学习(函数)

          本文链接:https://www.haomeiwen.com/subject/tonxsttx.html