【问题标题】:Swift enum pattern matching with associated values - cannot invoke functionSwift枚举模式与关联值匹配 - 无法调用函数
【发布时间】:2015-09-21 16:22:33
【问题描述】:

尝试在带有枚举的 switch case 中调用 count() 函数时出现一个我无法解释的错误:

enum Token{

    case Name(String)

    var count:Int{ 
        switch self{
        case .Name(let string):
            return count(string)
        }
    }
}

错误是Cannot invoke 'count' with an argument list of type '((String))'

我也试过

case .Name(let string):
      return string.characters.count

出现错误'String' does not have a member named 'characters'

有人知道我做错了什么吗?

【问题讨论】:

    标签: ios swift enums pattern-matching


    【解决方案1】:

    Swift 认为您正在尝试访问 count 属性,而不是调用全局 count 函数。你可以通过调用Swift.count(string)来解决这个问题:

    Swift 1.2:

    enum Token{
    
        case Name(String)
    
        var count:Int{
            switch self{
            case .Name(let string):
                return Swift.count(string)
            }
        }
    }
    

    对于 Swift 2:

    您尝试的第二种语法实际上对于 Swift 2 是正确的:

            case .Name(let string):
                return string.characters.count
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多