swfit各种Function表现形式

//: Playground - noun: a place where people can play


import UIKit

//多返回值函数

func countss(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)

}

let countsss = countss("qwertyuiopasdfghj!234")

countsss.consonants

countsss.others

//外部参数名

func join(s1: String, s2: String, joiner: String) -> String {

    return s1 + joiner + s2

}

//当你调用这个函数,你传递给函数的三个字符串的目的就不是很清楚了:

join("hello", "world", ",")

//为了使这些字符串值的目的更为清晰,为每个 join 函数参数定义外部参数名称:

func joiners(string s1: String, toString s2: String, withJoiner joiner: String) -> String {

    return s1 + joiner + s2

}

joiners(string: "hello", toString: "world", withJoiner: ":")

//外部参数名称速记

func containsCharacter(#string: String, characterToFind: Character) -> Bool {

    for character in string {

        if character == characterToFind {

            return true

        }

    }

    return false

}

containsCharacter(string: "aaabbccc", "f")

//参数的默认值

func joinerss(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String {

    return s1 + joiner + s2

}

joinerss(string: "hello", toString: "world")

joinerss(string: "hello", toString: "world", withJoiner: "-")

//有默认值的外部名称参数

func joinersss(s1: String, s2: String, joiner: String = " ") -> String {

    return s1 + joiner + s2

}

joinersss("hello", "world")

joinersss("hello", "world", joiner: ";")

//常量参数和变量参数

//函数参数的默认值都是常量。试图改变一个函数参数的值会让这个函数体内部产生一个编译时错误。这意味着您不能错 误地改变参数的值。

//在参数名称前用关键字 var 定义变量参数:

func alignRight(var string: String, countw: Int, pad: Character) -> String {

    let amountToPad = countw - count(string)

    for _ in 1...amountToPad {

        string = String(pad) + string

    }

    return string

}

alignRight("hello", 10, "-")

//输入-输出参数

//方法的参数都是常量,不能修改;要声明变量必须在参数名前加 var

func swapTwoInts(inout a: Int,inout b: Int) {

    let temporaryA = a

    a = b

    b = temporaryA

}

var someInt = 5

var anotherInt = 190

swapTwoInts(&someInt, &anotherInt)

someInt

anotherInt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值