fengsh998 Original address:http://blog.csdn.net/fengsh998/article/details/30314359 Reprint Please indicate the source Assuming that the article is helpful to you, please support me by leaving a message or paying attention to the public account fengsh998 . Thank you.
Some of the questions in the previous section have not been clarified, write it yourself, do a bit of verification, and hope to help the reader.
See Example:
The sample contains
Declaration and use of the callback function
Functions are passed as a form of participation
function as return value
Functions support generics, and of course class is supported.
Import Foundationtypealias point = (int, int.) Let Origin:point = (0, 0)//initialization function with Func Willdoit (Sender:callbackmanager) { println ("Willdoit defaulft.")} Func Diddoit (Sender:callbackmanager) {println ("Diddoit defaulft.")} Class callbackmanager{//declaration of two function variables var willdoitcallback: (Callbackmanager)---() = willdoit var Diddoitcallbac K: (Callbackmanager)-() = diddoit var callbackname = "Hello World" init () {} func TESTC All () {self.willdoitcallback (self) callbackname = "Reset Data" println ("to do something.") ) Self.diddoitcallback (self)}//function address as a form-pass func testparams (addfunc: (int,int)-(Int), Instru ction:string)->bool {println ("3 + 5 = \ (Addfunc (3,5)), the second value is: \ (instruction)") return True} function as return value func Testfunctionreturn (instruction:string)-(int,int), Int {func multiplicatio N (a:int,b:int)->int { Return a * b} return multiplication}//self-active closure type//Call Simpleassert (testnumber% 2 = = 0 , "Testnumber isn ' t an even number.") Func Simpleassert (Condition: @auto_closure (), Bool, message:string) {if!condition () {println (M essage)}}//Variable parameter func unknowparam (slist:string ...) {var ret:string = "" For USB in Slist {println (USB) RET + = (usb + ",") }}//Using generic//simplemin (17, 42)//Integer parameters//simplemin (3.14159, 2.71828)///float func Simplemin<t:comparable> (X:t, y:t), T {if x < y {return y} return x }}
Call:
Class Viewcontroller:uiviewcontroller { func willcallback (Callback:callbackmanager) { println ("pre-callback result \ (Callback.callbackname) }} func Didcallback (Callback:callbackmanager) { println ("post-callback result \ ( callback.callbackname) } func Add (a:int,b:int), Int { return a + b } override Func Viewdidload () { super.viewdidload () var test = Callbackmanager () test.willdoitcallback = Willcallback test.diddoitcallback = Didcallback test.testcall () test.testparams (add,instruction: "Test function as a reference") Let funcmulti = Test.testfunctionreturn ("Return function address") let ret = Funcmulti (5,5) println ("5 * 5 = \ (ret)")
return;}}
A study of Swift language learning notes four-2 (some legacy of the previous section is processed)