Convert ojective-c code to SWIFT code2015-03-09 15:07 release: Yuhang Browse: 201 More concise than the Objective-c,swift language. Sometimes we need to convert some of the original objective-c code into Swift, which summarizes a variety of common scenarios. 1, the migration objective-c of the constructor is: 1 hanggemenuitem *starmenuitem1 = [[Hanggemenuitem alloc] Initwithimage:storymenuitemimage 2 Swift: 1 var starMenuItem1 = Hanggemenuitem (Image:storymenuitemimage, Highlightedcontentimage:nil)
2, the definition of a variable is objective-c: 1 UIImage *starimage = [UIImage imagenamed:@ "icon-star.png"];Swift: 1 var starimage = UIImage (named:"icon-star.png")3, the array objective-c is: 1 nsarray *menus = [Nsarray arraywithobjects:starmenuitem1, STARMENUITEM2, starMenuItem3];Swift: 1 var menus = Nsarray (objects:starmenuitem1, starMenuItem2, starMenuItem3)
4, the method to implement the Protocol Objective-c is:
1- (void) Awesomemenu: (Awesomemenu *) Menu Didselectindex: (nsinteger) IDX2 {3NSLog (@"Selected The index:%d", idx);4 }5- (void) Awesomemenudidfinishanimationclose: (Awesomemenu *) Menu {6NSLog (@"Menu was closed!");7}
Swift:
1 func awesomemenu (Menu:awesomemenu, IDX : Int) 2 { 3 println ( " selected the index:%d " ,idx) 4 5 func awesomemenudidfinishanimationclose (menu:awesomemenu) 6 { 7 println ( " menu was closed! " ) 8 }
5, detect whether the agent implements a method Objective-c protocol inherits from the Nsobjectprotocol protocol, if the Protocol needs to callback and detect whether an agent implements a method, Using the Nsobjectprotocol Respondstoselector method:
1 if (self.) delegateRespondstoselector (Selector ("hanggeswiftmenuwillanimateclose:" )) {2self . Delegate. Hanggeswiftmenuwillanimateclose (self)3 }
and use it in Swift? 1 self. delegate?. Hanggeswiftmenuwillanimateclose (self)
Of course, if there are some things you do not want to write, or have some experience with OC, then recommend you use, excellent network of a conversion tool, although there are still some bugs, but the general conversion can be achieved: Http://www.ucai.cn/tools/oc2swift
iOS development--Mixed Swift &OC ported to Swift