gpt4 book ai didi

arrays - 将字符串参数传递给函数以访问数组的属性

转载 作者:行者123 更新时间:2023-11-30 14:15:30 26 4
gpt4 key购买 nike

我正在用 Swift 编写一个数据收集和操作程序(我第一次尝试用 Swift 编程)。

我有一个函数(defineHeighestColumnValue),我向它传递两个参数;一个数组,其中包含从核心数据持久存储加载的字典对象,以及一个表示我想要从该数组中特定索引处的字典对象访问的属性键的字符串。

每个字典对象看起来都类似于:

{
debtorDays = "-";
debtors = "-";
eacFees = 284680;
eacToDateContribution = 117159;
eacToDateContributionPerFees = "41%";
eacToDateOtherCosts = 6985;
eacToDateReimburseable = 10640;
eacToDateSalary = 171176;
lastInvoice = NA;
lastRevisionDate = "11-Jun-15";

etc etc

我正在尝试弄清楚如何将 key 作为字符串传递,然后使用它通过 if 语句中的这段代码“pprFiles[index].item.toDouble()”来访问关联的数组值以下。 “.toDouble()”是一个字符串扩展,它返回字符串的 double 值。该函数确定列高,因此在字典对象中传递和访问的值都是字符串形式的数字值 - 因此转换为 Double。

当我使用专门键入的“item”参数作为键运行代码时,代码可以正常工作。但是,作为传递的参数,我在 if 语句上收到编译器错误。

任何关于如何传递字符串值并使 if 语句工作的想法将不胜感激。

函数代码为:

 func determineHeighestColumnValue(pprFiles: Array<PPRRowData>, item: String) ->Array<Double>{

var tempArray: [Double] = []
let count = pprFiles.count

for var index = 0; index < count; index++ {

// ******* need to work out how to get the reference right in the next line for item to be index.item
if pprFiles[index].item.toDouble() != nil {
tempArray.append(item.toDouble()!)
} else {
tempArray.append(0)
}
}
let highestColumn = maxElement(tempArray.map({abs($0)}))
if highestColumn != 0 {
tempArray = tempArray.map({$0 / highestColumn})
} else {
tempArray = tempArray.map({$0 * 0})
}
return tempArray
}

最佳答案

您可以对 Core Data 托管对象使用键值编码:

if let val = pprFiles[index].valueForKey(item) as? String {
// ...
}

关于arrays - 将字符串参数传递给函数以访问数组的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31244090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com