Convert ojective-c code to SWIFT code

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.