swift - 如何调用带参数的函数?
问题描述
我正在使用 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
解决方案
您定义它的方式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)
推荐阅读
- php - 在 php 中正确运行 curl
- javascript - 循环异步抓取
- python - 如何使用 p 标签抓取地址(逗号分隔的文本) - Python 中的 BeautifulSoup
- swift - 增加 CURRENT 指示器 UIPageController 的大小(适用于 iOS 12.4)
- azure - 使用声明主体访问 Asp.NET Web 核心应用程序中以前经过身份验证的用户
- python - ImageDataGenerator 给出的结果与 cv2 不同
- java - 尝试使用插入排序更快地进行快速排序
- c++ - mysql。部分克隆数据库
- tensorflow - Tensorflow:将 H5 层模型转换为 TFJS 版本导致未知层:TensorFlowOpLayer 在 TS 中工作时出错
- python - 使用不断更改的名称重命名目录