在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
函数:完成特定任务的代码块,通过名字来表示函数做什么 func 函数名(形参:形参类型)->返回类型 command +option+0 隐藏右边的框 //定义函数 func sayHello(name:String)->String{ let greeting = "hello " + name + "!" return greeting } println(sayHello("Anno"))
// 多个参数 func minusResult(start:Int,end:Int)->Int{ return end - start } println(minusResult(1,10))
//无参数 func sayHelloWorld() ->String{ return "Helo World" } println(sayHelloWorld())
// 无返回值 Void = 空元组(tuple) func sayGoodbye(name:String){ println("Goodby,\(name)") } println(sayGoodbye("Dave")) // 多重返回值函数 func count(str:String) ->(vs:Int,cs:Int,os:Int){ var vowels = 0,consonants = 0,others = 0 for Character in str{ 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","t","s","t","v","w","x","y","z": ++consonants default: ++others } } return (vowels,consonants,others) } let total = count("some arbitrary string!") println("\(total.vs) vowels and \(total.cs) consonants")
// 外部参数名 把两个字符串连在一起 func join(s1:String, s2:String,joiner:String) ->String{ return s1 + joiner + s2 } println(join("hello","world",",")) // 不使用外部参数的时候,这三个参数不清楚到底是干什么的 func joins(outSting s1:String,toSting s2:String, withJoiner joiner:String) ->String{ return s1 + joiner + s2 } println(joins(outSting:"hello",toSting:"world",withJoiner:",")) // 带来问题:调用函数的时候 写太多,解决办法 看下边
// 简写 外部参数名 参数名前 加# // func joins1(outSting s1:String,toSting s2:String, withJoiner joiner:String) ->String{ // return s1 + joiner + s2 // } // println(joins1(outSting:"hello",toSting:"world",withJoiner:",")) func containsCharacter(#string:String,#characterToFind:Character) ->Bool{ for character in string{ if character == characterToFind{ return true } } return false } let containsAVee = containsCharacter(string: "qwertyuiop", characterToFind: "y") println(containsAVee)
// 给默认参数 func joinss(outSting s1:String,toSting s2:String, withJoiner joiner:String = ",") ->String{ return s1 + joiner + s2 } // 第三个参数 没写 直接使用默认值 let str1 = joinss(outSting: "nihao", toSting: "heri") println(str1)
// 注意会出错 func joinbb(outSting s1:String,toSting s2:String, withJoiner joiner:String = "") ->String{ return s1 + joiner + s2 } // 第三个参数 没写 直接使用默认值 let str2 = joinbb( outSting: "haha", toSting: "zheli", withJoiner: "+") println(str2) // 可变参数 传入不确定数量来输入参数 变量名类型 ... = 数组常量
|
请发表评论