【问题标题】:How to declare generic function inside protocol如何在协议中声明泛型函数
【发布时间】:2017-06-30 00:10:01
【问题描述】:

这是我的代码

protocol sharedFunction {

      func transformDictionary<Element>(postDictionary:[Element:Element], key: Element) -> Element


}


class newUser: sharedFunction {

var email:String?
var username:String?
var uid: String?

func transformDictionary(postDictionary: [String : Any], key: String) -> newUser {

 }
}

但我不断收到此错误“Type newUser”不符合协议““sharedFunction”

【问题讨论】:

    标签: ios swift function protocols generic-programming


    【解决方案1】:

    错误的发生仅仅是因为您的类型不符合消息明确指出的协议。我会像这样重写你的代码:

    protocol SharedFunction {
        associatedtype Element: Hashable
        func transformDictionary(postDictionary: [Element:Element], key: Element) -> Element
    }
    
    class NewUser: SharedFunction {
    
        typealias Element = Int
    
        var email: String?
        var username: String?
        var uid: String?
    
        func transformDictionary(postDictionary: [Element : Element], key: Element) -> Element {
            return 1
        }
    
    }
    

    我不知道这段代码的上下文是什么,所以我不知道我的代码对你是否有意义,但我想你明白了。

    【讨论】:

      【解决方案2】:

      将您的协议声明更改为

      protocol sharedFunction {
      
            func transformDictionary<Element>(postDictionary:[Element: Any], key: Element) -> Any
      
      }
      

      您没有在课堂上遵循您的协议声明。这就是出错的原因。

      【讨论】:

      • 但是我想在函数中返回一些东西
      • 是的,这应该可以。您是否尝试用我上面的代码替换您的协议?错误信息是什么?它返回“任何”,如我的代码所示。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多