ios - 遍历两个数组以输出值

标签 ios iphone swift

所以我有两个数组,一个名称数组和一个值数组,它们分别是一个字符串和一个 double 组。我希望用户能够在文本字段中键入并遍历名称数组直到匹配为止,然后输出与要输出的名称具有相同编号的值

这是我的代码:

    for(var i = 0; i<name.count; i++){
        if name[i] == typeFood{
            yieldOutput == percent[i]

        }
    } 

最佳答案

首先,使用find 找到值在name 数组中的位置,然后使用返回的索引查找百分比:

if let idx = find(name, typeFood) {
    yieldOutput = percent[idx]
}

您还可以将这两个操作与 map 组合在一起,以使用 let 声明输出变量:

if let foodPercentage = find(name, typeFood).map({ percent[$0] }) {
    // foodPercentage will have a value here
}
else {
    // not-found logic here
}

关于ios - 遍历两个数组以输出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737172/

相关文章:

ios - 如何快速调用另一个类的另一个方法?

ios - 检测 iOS 应用程序中的日期变化

iphone - 使用 NSMutableArray 与 NSArray 的缺点?

swift - 尝试创建图像幻灯片

ios - 将数据传递到嵌入式 TableView (Swift)

ios - "Fatal error: unexpectedly found nil while unwrapping an Optional value"- 将图像发布到 FaceBook

objective-c - 视频后未出现的持续时间

iOS 崩溃 : Terminating app due to uncaught exception reason: UIPopoverPresentationController should have a non-nil sourceView

ios - 简化的屏幕截图 : record video of only what appears within the layers of a UIView?

iphone - iPhone SDK:为AppStore构建应用