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

1,构造函数的迁移
Objective-C为:
HanggeMenuItem *starMenuItem1 = [[HanggeMenuItem alloc] initWithImage:storyMenuItemImage
                                                        highlightedContentImage:nil];
Swift:
var starMenuItem1 =  HanggeMenuItem(image:storyMenuItemImage, highlightedContentImage:nil)
2,变量的定义
Objective-C为:
UIImage *starImage = [UIImage imageNamed:@"icon-star.png"];
Swift:
var starImage =  UIImage(named:"icon-star.png")
3,数组
Objective-C为:
NSArray *menus = [NSArray arrayWithObjects:starMenuItem1, starMenuItem2, starMenuItem3];
Swift:
var menus =  NSArray(objects:starMenuItem1, starMenuItem2, starMenuItem3)
4,实现协议的方法
Objective-C为:
- (void)awesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx
{
    NSLog(@"Selected the index : %d",idx);
}
- (void)awesomeMenuDidFinishAnimationClose:(AwesomeMenu *)menu {
    NSLog(@"Menu was closed!");
}
Swift:
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方法:
if(self.delegate.respondsToSelector(Selector("HanggeSwiftMenuWillAnimateClose:"))){
    self.delegate.HanggeSwiftMenuWillAnimateClose(self)
}
而在Swift中使用?即可
self.delegate?.HanggeSwiftMenuWillAnimateClose(self)

在线代码转换工具

你可能感兴趣的:(将Ojective-C代码移植转换为Swift代码)