函数

作者: 暖光照 | 来源:发表于2016-10-29 04:11 被阅读0次

    参数与返回值

    无参数
    func sayHelloWorld()->String{
        return "hello world"
    }
    
    一个参数
    func sayHello(personName:String)->String{
        return "hello ,\(personName)"
    }
    
    可变参数
    func meanValue(numbers: Double...) -> Double {
        var total: Double = 0
        for number in numbers {
            total += number
        }
        return total / Double(numbers.count)
    }
    meanValue(1, 2, 3, 4, 5)
    meanValue(3, 8, 19)
    
    无返回值
    func sayGoodbye(personName : String){
        print("Goodbye , \(personName)")
    }
    
    多个返回值
    //计算元音辅音
    func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
        var vowels = 0, consonants = 0, others = 0
        for character in string.characters {
            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: " ")
    
    带默认值的
    //带默认值,可省略参数,省略的话使用默认值
    func join(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String {
        return s1 + joiner + s2
    }
    join(string: "Hello", toString: "World")
    

    常量参数与变量参数

    函数参数的默认值都是常量。试图改变一个函数参数的值会让这个函数体内部产生一个编译时错误。

    可以通过指定一个或多个参数作为变量参数,而不是避免在函数内部为自己定义一个新的变量,并给函数中新修改的参数的值的提供一个副本。

    //给string前添加count个pad
    func alignRight(var string: String, count: Int, pad: Character) -> String {
        for _ in 1...count {
            string = String(pad) + string//string为var可变
        }
        return string
    }
    let originalString = "hello"
    let paddedString = alignRight(originalString, count: 10, pad: "-")
    print(paddedString)//----------hello
    print(originalString)//hello
    

    输入输出参数

    只能传入var,在函数体内对inout参数的修改影响到函数外。
    需要在参数前加&符号

    func swapTwoInts( inout a: Int , inout b: Int) {
        let temporaryA = a
        a = b
        b = temporaryA
    }
    var a = 1
    var b = 2
    swapTwoInts(&a, b: &b)
    print("a :  \(a)   b:  \(b)" )//a :  2   b:  1

    相关文章

      网友评论

          本文标题:函数

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