相比于Objective-C,Swift语言更加简练。有时我们需要把原来写的一些Objective-C代码转换成Swift,下面总结了各种常见的情况。
Swift:
2,变量的定义
Swift:
3,数组
Swift:
4,实现协议的方法
Swift:
5,检测代理是否实现某个方法
而在Swift中使用?即可
(附:在线代码转换工具)
1,构造函数的迁移
Objective-C为:
1
2
|
HanggeMenuItem *starMenuItem1 = [[ HanggeMenuItem alloc] initWithImage:storyMenuItemImage highlightedContentImage: nil ]; |
1
|
var starMenuItem1 = HanggeMenuItem (image:storyMenuItemImage, highlightedContentImage: nil ) |
2,变量的定义
Objective-C为:
1
|
UIImage *starImage = [ UIImage imageNamed:@ "icon-star.png" ]; |
1
|
var starImage = UIImage (named: "icon-star.png" ) |
3,数组
Objective-C为:
1
|
NSArray *menus = [ NSArray arrayWithObjects:starMenuItem1, starMenuItem2, starMenuItem3]; |
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!" ); } |
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 ) } |
1
|
self .delegate?. HanggeSwiftMenuWillAnimateClose ( self ) |
(附:在线代码转换工具)