• 将Ojective-C代码移植转换为Swift代码


    相比于Objective-C,Swift语言更加简练。有时我们需要把原来写的一些Objective-C代码转换成Swift,下面总结了各种常见的情况。

    1,构造函数的迁移
    Objective-C为:
    1
    2
    HanggeMenuItem *starMenuItem1 = [[HanggeMenuItem alloc] initWithImage:storyMenuItemImage
                                                            highlightedContentImage:nil];
    Swift:
    1
    var starMenuItem1 =  HanggeMenuItem(image:storyMenuItemImage, highlightedContentImage:nil)

    2,变量的定义
    Objective-C为:
    1
    UIImage *starImage = [UIImage imageNamed:@"icon-star.png"];
    Swift:
    1
    var starImage =  UIImage(named:"icon-star.png")

    3,数组
    Objective-C为:
    1
    NSArray *menus = [NSArray arrayWithObjects:starMenuItem1, starMenuItem2, starMenuItem3];
    Swift:
    1
    var menus =  NSArray(objects:starMenuItem1, starMenuItem2, starMenuItem3)

    4,实现协议的方法
    Objective-C为:
    1
    2
    3
    4
    5
    6
    7
    - (void)awesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx
    {
        NSLog(@"Selected the index : %d",idx);
    }
    - (void)awesomeMenuDidFinishAnimationClose:(AwesomeMenu *)menu {
        NSLog(@"Menu was closed!");
    }
    Swift:
    1
    2
    3
    4
    5
    6
    7
    8
    func awesomeMenu(menu:AwesomeMenu, idx:Int)
    {
         println("Selected the index : %d",idx)
    }
    func awesomeMenuDidFinishAnimationClose(menu:AwesomeMenu)
    {
         println("Menu was closed!")
    }

    5,检测代理是否实现某个方法
    Objective-C中协议继承自NSObjectProtocol协议,如果协议需要回调和检测某个代理是否实现了某个方法,使用NSObjectProtocol的respondsToSelector方法:
    1
    2
    3
    if(self.delegate.respondsToSelector(Selector("HanggeSwiftMenuWillAnimateClose:"))){
        self.delegate.HanggeSwiftMenuWillAnimateClose(self)
    }
    而在Swift中使用?即可
    1
    self.delegate?.HanggeSwiftMenuWillAnimateClose(self)

    (附:在线代码转换工具)
  • 相关阅读:
    jquery
    模板库
    Luogu P1902 刺杀大使
    8.20模拟赛再次观光记
    Luogu P1122 最大子树和
    Luogu P1470 最长前缀 Longest Prefix
    8.18爆炸记
    Luogu P1388 算式
    Luogu P1103 书本整理
    8.17
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4838380.html
Copyright © 2020-2023  润新知