首页 > 解决方案 > 如何调用带参数的函数?

问题描述

我正在使用 xcode 游乐场玩弄一些代码,Use of unresolved identifier 'colorArray'当我尝试调用函数时出现此错误。我该如何解决这个问题,我知道它必须很简单。

import Foundation


class Solution{

var colorArray = ["Red","blue","green","black","red","blue","yellow","purple","Red","Red","Red","yellow","yellow","black","green","black","purple","black","yellow","purple","purple","blue","yellow","blue","green","green","yellow","pink"]

func getMostCommonColor(array: [String]) -> [String] {
    var topColors: [String] = []
    var colorDictionary: [String: Int] = [:]

    for color in array {
        if let count = colorDictionary[color] {
            colorDictionary[color] = count + 1

        }else{
            colorDictionary[color] = 1
        }
    }
    let highestValue = colorDictionary.values.max()

    for (color,count) in colorDictionary {
        if colorDictionary[color] == highestValue {
            topColors.append(color)
        }
    }

    return topColors
}
}
let solution = Solution()
solution.getMostCommonColor(array: colorArray) //This is where I get the error


标签: swift

解决方案


您定义它的方式colorArray是 的实例属性Solution,这意味着您需要通过Solution该类的某个实例来访问它。

您已经在下面创建了一个实例,因此您可以这样做:

let solution = Solution()
solution.getMostCommonColor(array: solution.colorArray)

但是,我怀疑您打算colorArray成为某种全局变量(毕竟这只是一个游乐场),因此另一种选择是退出colorArray 班级Solution

var colorArray = ["Red","blue","green","black","red","blue","yellow","purple","Red","Red","Red","yellow","yellow","black","green","black","purple","black","yellow","purple","purple","blue","yellow","blue","green","green","yellow","pink"]

class Solution {

    func getMostCommonColor(array: [String]) -> [String] {
        var topColors: [String] = []
        var colorDictionary: [String: Int] = [:]

        for color in array {
            if let count = colorDictionary[color] {
                colorDictionary[color] = count + 1

            }else{
                colorDictionary[color] = 1
            }
        }
        let highestValue = colorDictionary.values.max()

        for (color,count) in colorDictionary {
            if colorDictionary[color] == highestValue {
                topColors.append(color)
            }
        }

        return topColors
    }
}

let solution = Solution()
solution.getMostCommonColor(array: colorArray)

推荐阅读