我想只使用一个简单的for循环

时间:2018-04-05 14:27:41

标签: arrays swift

for i in 0..<self.etype.count{
    let item = self.etype[i]
    if (self.etype.contains("VALUE ACTIVITY")){
        print(self.etype.index(of: "VALUE ACTIVITY"))
    }

etype = [string]()

我的etype包含以下5个值:

  

[“价值活动”,“奖金活动”,“”杰克事件“,”价值活动“,”杰克事件“]

我想用“值”替换包含“VALUE ACTIVITY”的数组,用“Jackpot”替换“JACKPOT EVENTS”,用“Bonus”代替“BONUS ACTIVITY”。

print(self.etype.index(of: "VALUE ACTIVITY"))总是给我1

2 个答案:

答案 0 :(得分:1)

它如何以简单的形式运作:

for index in 1...5 {

    print("\(index) times 5 is \(index * 5)")

}

你的例子:

for i in 0..<self.etype.count {

    let item = self.etype[i]

    if (self.etype.contains("VALUE ACTIVITY")){

    print(self.etype.index(of: "VALUE ACTIVITY"))

}

etype = [string]()

答案 1 :(得分:0)

您正尝试实现以下目标:

import Foundation

let input = ["VALUE ACTIVITY", "BONUS ACTIVITY", "JACKPOT EVENTS", "VALUE ACTIVITY", "JACKPOT EVENTS"]

var output = [String]()

for element in input {
    if element.contains("VALUE ACTIVITY") {
        output.append(element.replacingOccurrences(of: "VALUE ACTIVITY", with: "Value"))
    } else if element.contains("JACKPOT EVENTS") {
        output.append(element.replacingOccurrences(of: "JACKPOT EVENTS", with: "Jackpot"))
    } else if element.contains("BONUS ACTIVITY") {
        output.append(element.replacingOccurrences(of: "BONUS ACTIVITY", with: "Bonus"))
    } else {
        output.append(element)
    }

}

print(output)

但在您的具体情况下,您可以使用更短,更有效的解决方案:

import Foundation

let input = ["VALUE ACTIVITY", "BONUS ACTIVITY", "JACKPOT EVENTS", "VALUE ACTIVITY", "JACKPOT EVENTS"]

let output = input.map { $0.prefix(1).uppercased() + $0.split(separator: " ")[0].lowercased().dropFirst() }

print(output)