-1

I am using the following class and it has method to extract all emails inside a string, I am new to swift and its giving me an error. Can someone please explain as to why this error is coming..? Thanks

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("+abc@gmail.com heyyyyy cool +def@gmail.com") {
            print(results)
        }
    }

    func extractEmailFromString(string:NSString) -> [String]? {
        let pattern = "(\\+[a-zA-Z0-9._-]+@[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

Ankit Srivastava
  • 12,347
  • 11
  • 63
  • 115

1 Answers1

1

So, your block is asking for a NSTextCheckingResult!, but the signature expects an NSTextCheckingResult?. If you change the block to usingBlock: { (result: NSTextCheckingResult?, _, _) in, that silences the compiler.

I have no idea why the compiler is giving that error though.

Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • It's for the very reason you gave: the signature doesn't match what the OP wrote. There should be few or no cases at this point where an implicitly unwrapped optional arrives from Cocoa. The Cocoa APIs are marked up so that either a thing isn't an optional or, if it might be nil, it's a normal optional (with a question mark, not an exclamation mark). – matt Apr 26 '16 at 18:06
  • @matt : Yes, but that error doesn't seem to applicable here. The correct error is around the type mismatch, not around generic parameter inference. – Adam Wright Apr 26 '16 at 18:10
  • You're saying you're surprised that the Swift compiler has given a misleading description of the problem? You must not have been using Swift very long, if you're that naive! That sort of thing happens all the time. — The particular problem here is that, with that type not matching, and no other types provided (the OP has blanked them all out), Swift doesn't recognize this anonymous function as matching the expected Block type for this method at all. Thus the types of the anonymous function are not inferable. – matt Apr 26 '16 at 18:50