2016-04-26 38 views
-1

我正在使用下面的類,它有方法來提取字符串中的所有電子郵件,我是新的swift和它給我一個錯誤。有人可以請解釋爲什麼這個錯誤即將到來..? 感謝「通用參數'元素'無法被推斷出來」錯誤在迅速...?

import UIKit 
import Foundation 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 

     if let results = extractEmailFromString("[email protected] heyyyyy cool [email protected]") { 
      print(results) 
     } 
    } 

    func extractEmailFromString(string:NSString) -> [String]? { 
     let pattern = "(\\+[a-zA-Z0-9._-][email protected][a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)" 


     let regexp = try! NSRegularExpression(pattern: pattern, 
               options: [.CaseInsensitive]) 


     var results = [String]() 
     regexp.enumerateMatchesInString(string as String, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length:string.length), usingBlock: { (result: NSTextCheckingResult!, _, _) in 
      results.append(string.substringWithRange(result.range)) 
     }) 

     return results 
    } 
} 

enter image description here

+1

問題是什麼? – matt

+0

@matt抱歉,提交時丟失了問題,我編輯了該問題。 –

回答

1

所以,你的塊被要求一個NSTextCheckingResult!,但簽名預計的NSTextCheckingResult?。如果將塊更改爲usingBlock: { (result: NSTextCheckingResult?, _, _) in,則會使編譯器無聲。

我不知道爲什麼編譯器會給出這個錯誤。

+0

這就是你給出的原因:簽名與OP寫的不一致。此時應該很少或根本沒有從Cocoa中獲得隱式解包選項的情況。 Cocoa API被標記爲使得事物不是可選的,或者如果它可能是零,它是正常的可選項(帶有問號而不是感嘆號)。 – matt

+0

@matt:是的,但是這個錯誤似乎並不適用於此。正確的錯誤是圍繞類型不匹配,而不是圍繞泛型參數推斷。 –

+0

你說你很驚訝Swift編譯器給出了一個誤導性的問題描述?如果你太天真,你一定不會很長時間使用Swift!這種事情總是發生。 - 這裏的特殊問題是,如果這種類型不匹配,並且沒有提供其他類型(OP已將它們全部清空),則Swift不會將此匿名函數識別爲匹配此方法的預期塊類型。因此,匿名函數的類型不可推斷。 – matt