Home > OS >  swiftui view: if statement with potential index out of range
swiftui view: if statement with potential index out of range

Time:09-17

I want to not show a swiftui view under several conditions, e.g. a[3]==3 or b[17]==3. This can be implemented as:

if a[3]!=3 && b[17]!=3 {
    Text("show view")
}

However, the number of elements of a and b is variable and 3 or 17 might be out of range. Therefore, one might think of the following code:

if true {
    if a.count > 3 {
        if a[3]==3 {
            break
        }
    }
    if b.count>17 {
        if b[17]==7 {
            break
        }
    }
    Text("show view")
}

However, in a swiftui view, break is not available. Furthermore, this code does not really look elegant.

CodePudding user response:

One way is to write a safe subscript and use that to access the array:

// from https://stackoverflow.com/a/30593673/5133585
extension Collection {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

// in your view...
if a[safe: 3] != 3 && b[safe: 17] != 3 {
    Text("show view")
}

Now a[safe: 3] would be of type Int? (assuming a is an [Int]). An out-of-range access will give you nil. Comparing that to 3 still works, because != and == are defined for all T? where T is Equatable.

CodePudding user response:

ViewModel :

@Published var showView : Bool = false

func checkShowView(){

   if a.count > 3 && b.count> 17 {
      if a[3]!=3 && b[17]!=3 {
          showView = true
      }
   }else if a.count > 3 {
      if a[3]!=3{
         showView = true
      }
   }else if b.count>17 {
      if b[17]!=3 {
           showView = true
      }
   }else {
      showView = true
   }
}

View :

@StateObject var viewModel = ViewModel()

if viewModel.showView {
   Text("show View")
}
  • Related