Swift的學習 函式

2021-07-22 20:05:34 字數 1549 閱讀 2927

函式 執行某個特定任務的**塊;

swift 函式有乙個type,包含了兩個內容,函式的引數型別與返回值型別;

函式可以作為引數傳遞、也可以作為返回值;還可以巢狀使用

//定義乙個無引數函式 引數在()內,返回值型別用->表示 函式的宣告 func,sayhello為函式名

func sayhello()->string

//呼叫函式

let result2=sayhello()

print(result2)

//定義乙個有引數的函式 params 外部解釋,params內部使用

func greet(params params1:string,params params2:string) ->

string

func greet(loc:string, externalparams locaparams:string) ->

string

print(greet(params: "hello", params: "你好"))

print(greet("hello", externalparams: "你好"))

//在swift中,函式的引數與返回值非常靈活;你既可以定義簡單的函式,比如只有乙個未命名的引數組成,也可以定義乙個非常複雜的函式,比如,引數都命名,返回乙個函式型別;
1)無參函式 有返回值
func sayhellowworld()->string

print(sayhellowworld())

2)無參函式 無返回值

func sayhellowworld()
3)多引數 函式,引數在()內,用逗號「,」隔開;

func greet(person:string,alreadygreeted:bool)->string

else

}print(greet("lia", alreadygreeted: true))

4)函式返回值會被忽略,當函式被呼叫,沒有接受的變數的時候

func printandcont(params:string)->

string

printandcont("函式返回值會被忽略,當函式被呼叫,沒有接受的變數的時候")

func printwithoutcount(params:string)

printwithoutcount("函式返回值會被忽略,當函式被呼叫,沒有接受的變數的時候")

5)函式 多個返回值(利用元組返回 多個值)

func minmax(array:[int])->(min:int,max:int)

else

ifvalue>max

}return(min,max)

}let minmaxr=minmax([1,5,12,44,44,-2])

print(minmaxr)

未完待續

swift學習之函式

1.定義函式func sayhello personname string string sayhello iyaqi hello,iyaqi 2.引數和返回值 2.1 無引數 func sayhelloagain string sayhelloagain hello,iyaqi 2.2 無返回值 ...

swift函式學習

函式的定義與呼叫 定義 func sayholle personname string string 呼叫 print sayholle nick 函式引數與返回值 多重引數 func halfopenrangelength start int,end int int print halfopenr...

swift學習之函式

當然在程式開發的時候最重要的是方法了 在swift中如何建立 使用函式 無引數函式的形式 func 方法名字 返回值 當返回值為空的時候 返回值用 void 當返回值為空的時候 void 可以省略 函式方法的建立 func sayhellow void 函式方法的呼叫 sayhellow 有引數函式...