這篇文章為您講述Swift_函數的相關介紹,具體代碼請看下文
Swift_函數點擊查看源碼
定義和調用函數//定義和調用函數
func testDefiningAndCallingFunctions() {
func sayHello(_ personName: String) -> String {
let greeting = "Hello " + personName + "!"
return greeting
}
print(sayHello("XuBaoAiChiYu"))
/* print
Hello XuBaoAiChiYu!
*/
}
無參數函數
//無參數函數
func testFunctionsWithoutParameters() {
//無參數 只有一個String類型的返回值
func sayHelloWorld() -> String {
return "hello world!"
}
print(sayHelloWorld())
/* print
hello world!
*/
}
多參數函數
//多參數函數
func testFunctionsWithMultipleParameters() {
//傳入兩個參數 並返回一個String類型的數據
func sayHello(_ personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return "Hello again \(personName)!"
} else {
return "Hello \(personName)!"
}
}
print(sayHello("XuBaoAiChiYu", alreadyGreeted: true))
/* print
Hello again XuBaoAiChiYu!
*/
}
函數無返回值
//函數無返回值
func testFunctionsWithoutReturnValues() {
//傳入一個String類型的數據 不返回任何數據
func sayGoodbye(_ personName: String) {
print("Goodbye \(personName)!")
}
sayGoodbye("XuBaoAiChiYu")
/* print
Goodbye XuBaoAiChiYu!
*/
}
函數多返回值
//函數多返回值
func testMultipleReturnValues() {
//返回一個Int類型的數據
func printAndCount(_ stringToPrint: String) -> Int {
print(stringToPrint)
return stringToPrint.characters.count
}
print(printAndCount("hello world"))
//返回元組合數據
func minMax(_ array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
let bounds = minMax([8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
/* print
hello world
11
min is -6 and max is 109
*/
}
返回類型可選
//返回類型可選
func testOptionalTupleReturnTypes() {
//返回一個元組或Nil
func minMax(_ array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty {
return nil
}
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
if let bounds = minMax([8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.min) and max is \(bounds.max)")
}
/* print
min is -6 and max is 109
*/
}
指定外部參數名
//指定外部參數名
func testSpecifyingExternalParameterNames() {
//指定外部參數名to和and
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
/* print
Hello Bill and Ted!
*/
}
省略外部參數名
//省略外部參數名
func testOmittingExternalParameterNames() {
//使用 _ 省略外面參數名,
func someFunction(_ firstParameterName: Int, _ secondParameterName: Int) {
print("\(firstParameterName) and \(secondParameterName)")
}
someFunction(2, 3)
/* print
2 and 3
*/
}
默認參數值
//默認參數值
func testDefaultParameterValues() {
//設置默認值 當用戶不傳入時 使用默認值
func someFunction(_ parameterWithDefault: Int = 12) {
print("\(parameterWithDefault)")
}
someFunction(6)
someFunction()
/* print
6
12
*/
}
可變參數
//可變參數
func testVariadicParameters() {
//傳入的參數類型已知Double 個數未知
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
print("\(arithmeticMean(1, 2, 3, 4, 5))")
print("\(arithmeticMean(3, 8.25, 18.75))")
/* print
3.0
10.0
*/
}
常量和變量參數
//常量和變量參數
func testConstantAndVariableParameters() {
//默認為let常量參數 也可聲明var可變參數 在函數內直接修改
func alignRight(_ string: String, totalLength: Int, pad: Character) -> String {
var string = string
let amountToPad = totalLength - string.characters.count
if amountToPad < 1 {
return string
}
let padString = String(pad)
for _ in 1...amountToPad {
string = padString + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, totalLength: 10, pad: "-")
print("originalString:\(originalString); paddedString:\(paddedString);")
/* print
originalString:hello; paddedString:-----hello;
*/
}
In-Out參數
//In-Out參數
func testInOutParameters() {
//使用inout聲明的參數 在函數內修改參數值時 外面參數值也會變
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
/* print
someInt is now 107, and anotherInt is now 3
*/
}
使用函數類型
//使用函數類型
func testUsingFunctionTypes() {
//加法
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
//乘法
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
return a * b
}
// 函數體賦值為參數
var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")
// 函數體指向替換
mathFunction = multiplyTwoInts
print("Result: \(mathFunction(2, 3))")
// 函數體傳遞
let anotherMathFunction = addTwoInts
print("\(anotherMathFunction)")
/* print
Result: 5
Result: 6
(Function)
*/
}
函數做參數類型
//函數做參數類型
func testFunctionTypesasparameterTypes() {
//加法
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
//其中一個參數為一個函數體
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
/* print
Result: 8
*/
}
函數做返回類型
//函數做返回類型
func testFunctionTypesAsReturnTypes() {
//加1
func stepForward(_ input: Int) -> Int {
return input + 1
}
//減1
func stepBackward(_ input: Int) -> Int {
return input - 1
}
//使用函數體做返回類型
func chooseStepFunction(_ backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
// 此時moveNearerToZero指向stepForward函數
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// 調用函數體
currentValue = moveNearerToZero(currentValue)
print("\(currentValue)... ")
/* print
2...
*/
}
嵌套函數
//嵌套函數
func testNestedFunctions() {
//函數體內部嵌套函數 並做返回類型
func chooseStepFunction(_ backwards: Bool) -> (Int) -> Int {
//嵌套函數
func stepForward(_ input: Int) -> Int {
return input + 1
}
//嵌套函數
func stepBackward(_ input: Int) -> Int {
return input - 1
}
return backwards ? stepBackward : stepForward
}
var currentValue = -2
let moveNearerToZero = chooseStepFunction(currentValue > 0)
currentValue = moveNearerToZero(currentValue)
print("\(currentValue)... ")
/* print
-1...
*/
}
多多關注本站,我們將為您收集更多的Android開發相關文章.
【Swift_函數】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!