函数:
完成某个特定任务的代码块, 给代码起一个合适的名称称之为函数名称.
以后需要执行代码块只需要利用函数名称调用即可.
好比每个人都有一个名字, 叫名字就能找到对应的人
OC:
不带参数
- (void)say
{
NSLog(@"hello");
{
NSLog(@"hello");
}
带有一个参数
- (void)sayWithName:(NSString *)name
{
NSLog(@"hello %@", name);
{
NSLog(@"hello %@", name);
}
带有多个参数
- (void)sayWithName:(NSString *)name age:(NSInteger)age
{
NSLog(@"hello %@ , I'm %tu years old", name, age);
{
NSLog(@"hello %@ , I'm %tu years old", name, age);
}
有返回值
- (NSString *)info
{
return @"name = qbs, age = 30";
}
有返回值,并且带有返回值
- (NSString *)infoWithName:(NSString *)name age:(NSInteger)age
{
{
return [NSString stringWithFormat:
@"name = %@,
age = %tu", name, age];
}
swift:
格式:
func 函数名称(参数名:参数类型, 参数名:参数类型...) -> 函数返回值 {函数实现部分}
无参无返回值
func say() -> Void
{
print("hello")
}
{
print("hello")
}
say()
输出结果: hello
func say1()如果没有返回值可以不写
{
print("hello")
}
print("hello")
}
say1()
输出结果: hello
有参无返回值
func sayWithName(name:String)
{
print("hello (name)")
}
{
print("hello (name)")
}
sayWithName("qbs")
输出结果: hello qbs
带有多个参数
func sayWithName(name:String, age:Int)
{
print("hello (name) , I'm (age) years old ")
}
{
print("hello (name) , I'm (age) years old ")
}
sayWithName("qbs", age: 30)
输出结果: hello qbs , I'm 30 years old
无参有返回值
func info() -> String
{
{
return "name = qiaobusi, age = 30"
}
print(info())
输出结果: name = qiaobusi, age = 30
有参有返回值
func info(name:String, age:Int) -> String
{
return "name = (name), age = (age)"
}
{
return "name = (name), age = (age)"
}
print(info("qbs", age:30))
输出结果: name = qbs, age = 30
嵌套函数
var arr:Array<String> = ["qbs","qiaobusi”,"250"]
func showArray(array:[String])
{
for number in array
{
print("(number), ")
}
{
for number in array
{
print("(number), ")
}
}
showArray(arr)
输出结果:
qbs,
qiaobusi,
250,
func bubbleSort(inout array:[Int])
{
func swap(inout a:Int, inout b:Int)
{
let temp = a
a = b
b = temp
{
func swap(inout a:Int, inout b:Int)
{
let temp = a
a = b
b = temp
}
let count = array.count;
for var i = 1; i < count; i++
{
for var j = 0; j < (count - i); j++
{
if array[j] > array[j + 1]
{
swap(&array[j], b: &array[j + 1])
}
}
}
for var i = 1; i < count; i++
{
for var j = 0; j < (count - i); j++
{
if array[j] > array[j + 1]
{
swap(&array[j], b: &array[j + 1])
}
}
}
}
var arr:Array<Int> = [50,20,30,80]
bubbleSort(&arr)
bubbleSort(&arr)
print(arr)
输出结果: [20, 30, 50, 80]