2016-01-20 61 views
-1

如何将此类的代码转换为Swift?如何将自定义的初始化函数从ObjC转换为Swift

.h文件中

@interface SARCoordinate : NSObject 
@property(nonatomic)CLLocationCoordinate2D coordinate; 
-(instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate; 
    @end 

.m文件

#import "SARCoordinate.h" 
@implementation SARCoordinate 

-(instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate { 
    self = [super init]; 
    self.coordinate = coordinate; 
    return self; 
} 
+0

你是什么意思的“转换”? – Arc676

+0

我想把这段代码写入swift。 –

+0

你为什么不发表你试过的东西? –

回答

0

未经测试,但这样的事情:

var coordinate:CLLocationCoordinate2D 

    func initWithCoordinate(coordinate: CLLocationCoordinate2D) -> instancetype{ 
     super.init() 
     self.coordinate = coordinate 
     return self 
    } 
+0

nsobject类不占用CLLocationCoordinate2D对象。 –

+0

你应该清楚你想要达成的目标,而不是要求人们转换代码。你在做什么的目的是问题的重要部分。 –

+0

必须在上面发布的问题中快速生成对象类。 –

2

,你可以这样做:

var coordinate : CLLocationCoordinate2D 
// your init method 
init (2Dcoordinate : CLLocationCoordinate2D) { 
    coordinate = 2Dcoordinate 
} 
//required init method 
required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 
+0

它不适合我。请在nsobject类中检查以下方法,它在第一行显示错误 - “使用undeclare类型” –

+0

它对我来说工作正常..您是否已导入基础,并且您可以清楚地了解错误,因为我一直在正确使用它 –

+0

请导入CoreLocation –

0

下面的代码可能会对您有所帮助。

import CoreLocation 

    class YOURCLASSNAME: NSObject { 
     var coordinate : CLLocationCoordinate2D 
     init(coordinate: CLLocationCoordinate2D) { 
      self.coordinate = coordinate 
      super.init() 
     } 
     convenience override init() { 
      self.init(coordinate: CLLocationCoordinate2DMake(100.00, 100)) // calls above mentioned controller with default name 
     } 
    } 

请在this链接找到更多的链接。