2014-09-30 107 views
0

我使用AVCaptureSession來掃描Swift應用程序中的QR碼。我想圍繞檢測到的QR代碼繪製一個框,但我無法將AVMetadataMachineReadableCodeObject的「角落」屬性轉換爲可用的東西。Swift中的CGPointMakeWithDictionaryRepresentation

var corners:[AnyObject]! {得到}

該屬性的值是CFDictionary對象的數組,其中每個 的已從CGPoint結構使用 CGPointCreateDictionaryRepresentation功能,相對於表示所述對象的角部的 座標創建它所在的 中的圖像。

我已經試過這(根據project by werner77),但我得到以下編譯器錯誤「'CGPoint?不等同於「CGPoint」」

// MARK: - AVCaptureMetadataOutputObjectsDelegate 
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { 

    let metadataObject = metadataObjects[0] as AVMetadataMachineReadableCodeObject; 
    var corners = metadataObject.corners as Array<NSDictionary>; 
    var topLeftDict = corners[0] as NSDictionary; 
    var topLeft : CGPoint? 

    // COMPILE ERROR: 'CGPoint?' is not identical to 'CGPoint' 
    CGPointMakeWithDictionaryRepresentation(topLeftDict, &topLeft) 
} 

任何幫助,將不勝感激。

回答

0

您通過了UnsafeMutablePointer<Optional<CGPoint>>,但它想要一個UnsafeMutablePointer<CGPoint>

var topLeft: CGPoint? 
var point = CGPointZero 
if CGPointMakeWithDictionaryRepresentation(topLeftDict, &point) { 
    topLeft = point 
} 
1

瞭解自選

任何類型都可以附加?,這意味着它也可以是nil。關於這一點的好處是,您必須明確地解決或忽略nil對象,而不像Objective-C中的對象可能導致無法跟蹤的錯誤。

從字典中獲取對象時,它必須是可選的,因爲字典中可能沒有該鍵。 CGPointMakeWithDictionaryRepresentation預計爲非可選項,因此您必須使用已初始化的非選項

// Playground: 
var point = CGPointMake(1, 2) 
var dictionary = CGPointCreateDictionaryRepresentation(point) 
var aPoint = CGPointZero 
CGPointMakeWithDictionaryRepresentation(dictionary, &aPoint) 
aPoint // x 1, y 2 
0

試試這個片斷:

let corners = metadataObject.corners.map{(point)->CGPoint in 
       let dict = point as! NSDictionary 
       let x = dict["X"]!.doubleValue 
       let y = dict["Y"]!.doubleValue 

       return CGPoint(x: x, y: y) 
      }