Function: A block of code that completes a specific task, by name, to indicate what the function does
Func function name (formal parameter: parameter type)--return type
Command +option+0 hide the box to the right
Defining functions
func SayHello (name:string),string{
let greeting = "Hello" + name + "!"
return Greeting
}
println(sayHello("Anno"))
// multiple parameters
func minusresult (start:int, end:int),int{
return End-start
}
println(minusresult(1,ten))
// no parameters
func SayHelloWorld (),String{
return "Helo World"
}
println(sayhelloworld())
// no return value Void = empty tuple (tuple)
func Saygoodbye (name:String) {
println("Goodby,\ (name)")
}
println(saygoodbye("Dave"))
// multiple return value functions
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")
/// external parameter name to connect two strings together
func Join (S1:string, s2:string, Joiner:string),string{
return s1 + joiner + s2
}
println(join("Hello","World", ","))
// do not use external parameters, these three parameters are not clear what exactly is the
func joins (outsting S1:string, tosting s2:string, Withjoiner joiner:string), String{
return s1 + joiner + s2
}
println(joins(outsting: "hello", tosting:"World", Withjoiner:","))
// problem: When calling a function , write too much, the solution to see below
// shorthand external parameter name parameter name plus #
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)
// to default parameters
func joinss (outsting s1:string, tosting s2:string, Withjoiner joiner:string = ","),String{
return s1 + joiner + s2
}
//The third parameter is not written directly using default values
let str1 = joinss(outsting: "Nihao", tosting: "Heri")
println(str1)
// attention will go wrong
func joinbb (outsting s1:string, tosting s2:string, Withjoiner joiner:string = "" ),String{
return s1 + joiner + s2
}
//The third parameter is not written directly using default values
let str2 = joinbb(outsting: " haha", tosting: " zheli", Withjoiner: "+") /c9>
println(str2)
// variable parameter passed in an indeterminate number to enter the parameter variable name type ... = array constant
Swift Basics-4