【问题标题】:How would I change the value of a specific element in an array?如何更改数组中特定元素的值?
【发布时间】:2021-03-27 16:24:34
【问题描述】:

这是一个很受欢迎的post,但它没有回答我的问题,因为我们的查询方法不同。

假设我有一个数组:

final class SomeClass: ObservableObject {
   @Published var myArray = ["cat","dog","mouse"]

   func changeValueFor(index: Int, to newName: String) {
     //Dont know what to put here, See below for the picture of the method I thought I could use
   }

}

我想访问它的属性并在我的视图中更改它:

struct MyView: View {
   @ObservedObject var vm: SomeClass 
   index: Int
   var body: some View { 
       Text(vm.myArray[index])

       Button("Change Name To") {vm.changeValueFor(index: index, to: "goat" }
       
   

   }
}

访问数组以在视图上显示的正常方法只是从一些提供的迭代器(如ForEach)传入Int,但在这种情况下,我不知道该怎么做......

我以为我可以用这个????,但显然不能

希望我足够清楚,但如果我需要更多解释我的问题,请告诉我。

【问题讨论】:

    标签: arrays swift swiftui


    【解决方案1】:

    您可以安全地使用此代码,而该功能没有问题:


    func changeValueFor(index: Int, to newName: String) {
        
        if myArray.indices.contains(index) {
            myArray[index] = newName
        }
        else {
            print("Error! there is no such index found!")
        }
        
    }
    

    【讨论】:

    • 我还有一个关于数组的问题,但我认为我应该为此创建另一个问题
    • 我会尽力帮忙的。
    【解决方案2】:

    快速高效。

    func changeValueFor(index: Int , to newName: String)   {
        if myArray.count > index,
           index > -1 {
            myArray[index] = newName
        }
        else {
            print("index out of range")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多