2016-05-03 29 views
0
import MapKit 
import UIKit 

class Point: NSObject, MKAnnotation { 
    var id: String? 
    var title: String? 
    var coordinate: CLLocationCoordinate2D 
    var subtitle: String? 



    init(id: String, dictionary: Dictionary<String, AnyObject>){ 


     self.id = id 

     if let title = dictionary["title"] as? String { 
      self.title = title 
     } 

     if let subtitle = dictionary["subtitle"] as? String { 
      self.subtitle = subtitle 
     } 

     if let coords = dictionary["coordinates"] as? [String:[String:Double]] { 
      var latitude = coords.values.first!["latitude"]! 
      var longitude = coords.values.first!["longitude"]! 
      var location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) 
      self.coordinate = location 
     } 

    } 

錯誤:屬性self.coordinate未在隱式生成的super.init調用時初始化。Custom MKAnnotation dictionary input(CLLocationCoordinate2d)

任何想法如何解決這個問題?

感謝您的一些建議。

+0

您的自定義構造函數的第一行應該是「super.init()」 [這正是錯誤的消息告訴你] –

+0

我加入這行,但它寫入同樣的錯誤:房產self.coordinate未初始化在super.init調用 –

+1

因爲'coordinate'不是可選的,所以必須對控制流的每個分支進行初始化。 – Moritz

回答

0

要麼你應該在

if let coords = dictionary["coordinates"] as? [String:[String:Double]] { 
... 
} else { 
self.coordinate = <assign a default location> 
} 

或者

其他情況下,指定一個默認值不應該,如果沒有座標創建對象。所以讓你的init是可選的。

init?(id: String, dictionary: Dictionary<String, AnyObject>){ 

     if let coords = dictionary["coordinates"] as? [String:[String:Double]] { 
      self.id = id 

      if let title = dictionary["title"] as? String { 
       self.title = title 
      } 

      if let subtitle = dictionary["subtitle"] as? String { 
       self.subtitle = subtitle 
      } 
      var latitude = coords.values.first!["latitude"]! 
      var longitude = coords.values.first!["longitude"]! 
      var location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) 
      self.coordinate = location 
     } else { 
      return nil 
     } 
}