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, migration of constructorsObjective-c is:
| 12 |
HanggeMenuItem*starMenuItem1 = [[HanggeMenuItemalloc] initWithImage:storyMenuItemImage highlightedContentImage:nil]; |
Swift:
| 1 |
varstarMenuItem1 = HanggeMenuItem(image:storyMenuItemImage, highlightedContentImage:nil) |
2, definition of variablesObjective-c is:
| 1 |
UIImage*starImage = [UIImageimageNamed:@"icon-star.png"]; |
Swift:
| 1 |
varstarImage = UIImage(named:"icon-star.png") |
3, array Objective-c is:
| 1 |
NSArray*menus = [NSArrayarrayWithObjects:starMenuItem1, starMenuItem2, starMenuItem3]; |
Swift:
| 1 |
varmenus = NSArray(objects:starMenuItem1, starMenuItem2, starMenuItem3) |
4, the method of implementing the Protocol Objective-c is:
| 1234567 |
-(void) Awesomemenu: ( awesomemenu *) menu Didselectindex: ( nsinteger ) idx { nslog (@ "Selected the index:%d" ,idx); } -(void) Awesomemenudidfinishanimationclose: ( awesomemenu *) menu {      nslog " menu was closed! " |
Swift:
| 12345678 |
func awesomeMenu(menu:AwesomeMenu, idx:Int){ println("Selected the index : %d",idx)}func awesomeMenuDidFinishAnimationClose(menu:AwesomeMenu){ println("Menu was closed!")} |
5, detect whether the agent implements a method The OBJECTIVE-C protocol inherits from the Nsobjectprotocol protocol, and if the protocol requires a callback and detects whether an agent implements a method, use Nsobjectprotocol's Respondstoselector method:
| 123 |
if ( self .delegate.respondstoselector ( selector ( " Hanggeswiftmenuwillanimateclose: "      self .delegate. hanggeswiftmenuwillanimateclose ( self Code class= "Swift plain" > |
and use it in Swift?
| 1 |
self.delegate?.HanggeSwiftMenuWillAnimateClose(self) |
(Attached: Online code conversion tool)
Convert ojective-c code to SWIFT code