如何更改数组值取决于Swift中的条件?

时间:2018-12-07 10:29:04

标签: ios swift

我有这样的数组

var country = ["America","Germany","China"]

我需要的是这个数组是否有美国

我想让它成为“美国”

希望结果

["US","Europe","Asia"]

请勿使用country[0] = "US"

因为每次数组的顺序都不同

我给的使用条件

我应该怎么做?

6 个答案:

答案 0 :(得分:1)

创建一个字典,其中需要替换国家/地区中的字符串。

let countriesToRegions = ["America": "US", "Germany": "Europe", "China": "Asia"]

然后,当您需要将国家/地区转换为地区时,可以在字典中查找它们。

var countries = ["America", "Germany", "China"]

let regions = countries.map { country in
    countriesToRegions[country] ?? country
}

这里的最后一位?? country正在处理该国家不在countriesToRegions词典中的可能性。

答案 1 :(得分:0)

尝试-

let requiredIndex = country.index(where: { $0 is "America" }) {
            country[requiredIndex] = "US"
        }

答案 2 :(得分:0)

您可以使用Map或获得更多说明的版本,可以使用以下功能

func replaceOccuranceInArray(inArray:[String], of originalString: String, with replacementString: String) -> [String] {

   var arrayToBeReturned = inArray

   var indexes = [Int]()

   for currentIndex in 0...inArray.count - 1 {

    if inArray[currentIndex] == originalString {
         indexes.append(currentIndex)
      }

  }

  for eachIndex in indexes {
      arrayToBeReturned[eachIndex] = replacementString
  }

  return arrayToBeReturned

}

我为以下内容附加了游乐场输出

https://docs.flutter.io/flutter/widgets/TextEditingController-class.html

答案 3 :(得分:0)

一个简单的解决方案:

获取要替换的值的索引,如果存在则替换它:

<item name="android:textColor">#000000</item>     
<item name="android:textColorHint">#666666</item>     

答案 4 :(得分:0)

这里是一种方法(内嵌评论):

Private Sub CommandButton1_Click()


Dim LR As Long, i As Long
    With Sheets("Savings Q4")
        LR = .Range("R" & Rows.Count).End(xlUp).Row
        For i = 1 To LR
            With .Range("R" & i)
                If .Value = "Y" Then
            With .Range("B" & i)
                If .Value = "January" Then
                    Sheets("Savings Q4").Range("G:G").Copy Destination:=Sheets("Cifas Loadings").Range("A:A")
              End If
            End With
        Next i
    End With


End Sub
let country = ["USA", "Germany", "China", "Fakeland"]

// use a dictionary for the replacements   
let continentForCountry = ["USA": "North America", "Germany": "Europe", "China": "Asia"]

// use map to replace each item and set a default value if the
// replacement is not found
let result = country.map { continentForCountry[$0, default: "unknown continent"] }

print(result)

答案 5 :(得分:0)

有些建议,您可以使用.map功能的强大功能。

这是一个简单的解决方案,您可以将国家/地区映射到大陆:

let americanCountries = ["US", "Argentina", "Brasil"]
let asianCountries = ["China", "Japan", "Korea"]
let europeanCountries = ["Germany", "France", "Spain"]

let countries = ["US","Germany","China"]

let continents = countries.map { country -> String in
    if americanCountries.contains(country) {
        return "America"
    } else if asianCountries.contains(country) {
        return "Asia"
    } else if europeanCountries.contains(country) {
        return "Europe"
    } else {
        return "Unknown continent"
    }
}

下一步是尝试使用枚举。