Having an issue with a return statement

Viewed 38

With the code below I keep getting this error under return and cannot seem to find a solution.

Cannot convert value of type '[AnyHashable : Any]?' to expected argument type '[UINib.OptionsKey : Any]?'

//
//  Created by Stevoo 10/17/2022
//  From: https://github.com/mac-cain13/R.swift.Library
//  License: MIT License
//

import Foundation
import UIKit

public extension NibResourceType {
  /**
   Instantiate the nib to get the top-level objects from this nib

   - parameter ownerOrNil: The owner, if the owner parameter is nil, connections to File's Owner are not permitted.
   - parameter options: Options are identical to the options specified with -[NSBundle loadNibNamed:owner:options:]

   - returns: An array containing the top-level objects from the NIB
   */
  public func instantiate(withOwner ownerOrNil: Any?, options optionsOrNil: [AnyHashable : Any]? = [:]) -> [Any] {
    return UINib(resource: self).instantiate(withOwner: ownerOrNil, options: optionsOrNil)
  }
}
1 Answers

You are trying to call UINib.instantiate(withOwner:options:). The options parameter needs to be of type [UINib.OptionsKey : Any].

You could change your function's optionsOrNil parameter to be of type [UINib.OptionsKey : Any]? instead of [AnyHashable : Any]? or you could try to cast it to that type with as?:

  public func instantiate(withOwner ownerOrNil: Any?, options optionsOrNil: [UINib.OptionsKey : Any]? = [:]) -> [Any] {
    return UINib(resource: self).instantiate(withOwner: ownerOrNil, options: optionsOrNil)
  }

or

  public func instantiate(withOwner ownerOrNil: Any?, options optionsOrNil: [AnyHashable : Any]? = [:]) -> [Any] {
    let castOptions = optionsOrNil as? [UINib.OptionsKey : Any]
    return UINib(resource: self).instantiate(withOwner: ownerOrNil, options: castOptions)
  }

Changing your function to take the correct type seems like the better solution.

Related