//: 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
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/wa1065908163/article/details/46710895