swift2.0笔记2
发布时间:2020-12-14 07:17:22 所属栏目:百科 来源:网络整理
导读:函数 1. 函数定义 func sayHello (personName: String) - String{ let greeting = "Hello," +personName+ "!" ; return greeting;} 函数参数和返回值 swift中可以定义任意类型的函数, 无参函数 只带一个参数或多个参数 带有表达性参数名 参数是一个函数 fun
函数1. 函数定义 func sayHello(personName: String) -> String{
let greeting = "Hello,"+personName+"!";
return greeting;
}
func sayHello(personName: String,alreadyGreeted: Bool) -> String{
if (alreadyGreeted)
{
print("Hello again,"+personName+"!");
}else{
print(sayHello(personName));
}
}
当调用超过一个参数的函数时,第一个参数后的参数根据其对应的参数名称标记。 print(sayHello("Tim",alreadyGreeted: true));
func sayGoodbye(personName: String){
print("Goodbye "+personName)
}
print(sayGoodbye("Dave"));
//在一个Int数组中查找最大值和最小值
func minMax(array: [Int]) -> (min: Int,max: Int){
var curentMin = array[0];
var currentMax = array[0];
for value in array[1..<array.count]{
if value < curentMin{
curentMin = value;
}else if value > currentMax{
currentMax = value;
}
}
return (curentMin,currentMax);
}
let bounds = minMax([8,-6,109,3,71]); //bounds是元组
//元组的成员值已经被命名,所以直接用"."语法访问元组中的值
print("min is (bounds.min) and max is (bounds.max)");
func minMax(array: [Int]) -> (min: Int,max: Int)? {
if array.isEmpty {
return nil;
}
var curentMin = array[0];
var currentMax = array[0];
for value in array[1..<array.count]{
if value < curentMin{
curentMin = value;
}else if value > currentMax{
currentMax = value;
}
}
return (curentMin,currentMax);
}
//用if let可选绑定来检查返回的是一个实际的元组还是一个nil
if let bounds = minMax([8,71]){
//bounds是元组
//元组的成员值已经被命名,所以直接用"."语法访问元组中的值
print("min is (bounds.min) and max is (bounds.max)");
}
2. 函数的参数名称 func someFunction(firstPataeterName: Int,secondParameterName: Int){
// your code here
}
someFunction(1,secondPatameterName: 2);
func sayHello(to personName: String,and anotherPersonName: String) -> String{
return "Hello "+personName+",and "+anotherPersonName;
}
print(sayHello(to: "Mike",and: "Tim"));
//在调用sayHello()时,两个外部参数名都必须写出来
func someFunction(firstPataeterName: Int,_ secondParameterName: Int){
// your code here
}
someFunction(1,2); //忽略了第二个参数名
func someFunction(defaulValue: Int = 12){
//your code
}
someFunction(6); //defaulValue = 6
someFunction(); //defaulValue= 12
// 计算一组任意长度数字的算术平均数
func arithmeticMean(numbers: Double...) -> Double{
var total: Double = 0;
for number in numbers{
total += numbers;
}
return total / Double(numbers.count);
}
func alignRight(var string: String,totalLength: Int) -> String{
//string可作为变量使用
}
3.函数类型 1)定义:由函数的参数类型和返回值类型组成 2) 可将一个函数赋值给一个函数类型的变量 // 两个函数:
func addTwoInts(a: Int,_ b: Int) -> Int{
return a+b;
}
函数的类型为:(Int,Int) -> Int 定义一个函数类型的变量: var mathFunction: (Int,Int) -> Int = addTwoInts
//把一个函数赋值给一个函数类型的变量
print("结果为:(mathFunction(2,3))");
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |