如何将自定义初始化函数从ObjC转换为Swift

时间:2016-01-20 11:09:35

标签: ios swift

如何将此类的代码转换为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;
}

3 个答案:

答案 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")
}

答案 1 :(得分:0)

没有经过测试但是这样的事情:

var coordinate:CLLocationCoordinate2D 

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

答案 2 :(得分: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链接上找到更多信息。