//
// main.swift
// classTest
//
// Created by 小强 on 15/12/8.
// Copyright © 2015年 小强. All rights reserved.
//
// 函数
func sayHello(personName: String) -> String {
let greeting = "Hello, " + personName + "!";
return greeting;
}
print(sayHello("Tom"));
//多输入形参
func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start;
}
print(halfOpenRangeLength(1, end: 10));
func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2;
}
print(join(string: "Hello", toString: "world", withJoiner: ","));
// 可变形参
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));
// 常量形参和变量形参
func alignRight(var string: String, count: Int, pad: Character)
-> String
{
let amountToPad = count - string.characters.count;
for _ in 1...amountToPad {
string = String(pad) + string;
}
return string;
}
let originalString = "hello";
let paddedString = alignRight(originalString, count:10, pad:"-");
print(paddedString);
func swapTowInts(inout a: Int, inout b: Int) {
let temporaryA = a;
a = b;
b = temporaryA;
}
var a = 3, b = 107;
swapTowInts(&a, b: &b);
print("a is now \(a), b is now \(b)");
func addTwoInts(a: Int, b: Int) -> Int {
return a + b;
}
var addFunction: (Int, Int) -> Int = addTwoInts;
print(addFunction(2, 3));
func printMathResult(mathFunction:(Int, Int)->Int, a: Int, b: Int)
{
print("Result: \(mathFunction(a, b))");
}
printMathResult(addFunction, a: 3, b: 5);
// 作为返回类型的函数类型
func isOdd(a: Int) -> Bool {
if a % 2 == 1 {
return true;
} else {
return false;
}
}
func isEven(a: Int) -> Bool {
if a % 2 == 0 {
return true;
} else {
return false;
}
}
func evenNum(num: Int) -> (Int) -> Bool {
if num % 2 == 0 {
return isEven;
} else {
return isOdd;
}
}
func stepForward(input: Int) -> Int {
return input + 1;
}
func stepBackward(input: Int) -> Int {
return input - 1;
}
func chooseStepFuction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward;
}
// 嵌套函数的实现
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;
}
// 闭包
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"];
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2;
}
// 闭包
var reversed = names.sort( {(s1: String, s2: String) -> Bool in
return s1 > s2;});
print(reversed);
// 根据上下文推断
reversed = names.sort({s1, s2 in return s1 > s2})
print(reversed);
// 单行表达式闭包可以省略 return
reversed = names.sort( { s1, s2 in s1 > s2} )
print(reversed);
// 参数名简写
reversed = names.sort( {$0 > $1} );
print(reversed);
// 运算符函数
reversed = names.sort(>);
print(reversed);
// Trailing 闭包
reversed = names.sort() { $0 > $1};
print(reversed);