swfit各种Function表现形式
Posted mfmdaoyou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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: ";")
//常量參数和变量參数
//函数參数的默认值都是常量。
试图改变一个函数參数的值会让这个函数体内部产生一个编译时错误。
这意味着您不能错 误地改变參数的值。
//在參数名称前用keyword 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
以上是关于swfit各种Function表现形式的主要内容,如果未能解决你的问题,请参考以下文章