Search code examples
swiftfilteranyobject

How can use the AnyObject.filter method?


I tried to use the AnyObject.filter method, however the following error is returned:

Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored.

This is my code:

func listCaptureDevices(type: String?) -> [AnyObject]!
{

    // Initialize capture session
    let captureSession = AVCaptureSession()

    // List all capture devices
    captureSession.sessionPreset = AVCaptureSessionPresetLow
    let devices = AVCaptureDevice.devices()

    if type == nil
    {
        return devices
    }


    // Filter by device type
    return devices.filter() {
        if (device.hasMediaType(type == "audio" ? AVMediaTypeAudio : AVMediaTypeVideo))
        {
            return true
        }
    }

}

I observed that AnyObject accepts a predicated as parameter, however in the Swift examples I observed that is possible to use a closure (Examples with array of integers).


Solution

  • First, AnyObject doesn't have a filter method. That method is on SequenceType.

    There are a lot of problems in your code; we'll walk through them.

    return devices.filter() {
    

    While this technically works, you don't want the () here. It just creates confusion. You mean this:

    return devices.filter {
    

    Your next problem is that you refer to device which you didn't declare. You probably meant to add device in to your closure. Alternately, you can refer to the element as $0.

    Finally, your closure doesn't return anything in the false case. You always have to return something.

    You can simplify all of this to:

    return devices.filter { 
        $0.hasMediaType(type == "audio" ? AVMediaTypeAudio : AVMediaTypeVideo)
    }