Home swift access to the next element in Foreach in Swiftui

access to the next element in Foreach in Swiftui

Author

Date

Category

I have a cycle that is passed through all the elements of the array:

foreach (Messages, ID: \ .id) {Message in
  // Something happens
}

Is it possible to somehow access the following element and its fields (a la message.next.property ) without working with indexes?


Answer 1, Authority 100%

Option 1

  • Use the extension for the array (taken Hence )
extension bidirectionalcollection WHERE ITERATOR.ELEMENT: EQUATABLE {
  Typealias Element = Self.Iterator.Element
  Func After (_ Item: Element, Loop: Bool = False) - & gt; Element? {
    If Let Itemindex = Self.firstindex (OF: Item) {
      Let Lastitem: BOOL = (INDEX (After: ItemIndex) == Endindex)
      IF LOOP & AMP; & amp; LastItem {
        Return Self.first.
      } ELSE IF LastItem {
        Return Nil.
      } else {
        RETURN SELF [INDEX (After: ItemIndex)]
      }
    }
    Return Nil.
  }
  Func Before (_ Item: Element, Loop: Bool = False) - & gt; Element? {
    If Let Itemindex = Self.firstindex (OF: Item) {
      Let FirstItem: BOOL = (ItemIndex == StartIndex)
      IF LOOP & AMP; & amp; firstitem {
        Return Self.Last.
      } ELSE If FirstItem {
        Return Nil.
      } else {
        RETURN SELF [INDEX (Before: ItemIndex)]
      }
    }
    Return Nil.
  }
}

Example of structure

struct message: equatable {
  var id = uuid ()
  VAR TEXT: String
}

then we get for example

foreach (Messages, ID: \ .id) {Message in
  Text (Self.Messages.After (Message, Loop: True)!. Text)
}

option 2

  • Make your implementation Linked list (Example )

Then there will be such changes

class message: equatable {
  var id = uuid ()
  VAR TEXT: String
  WEAK VAR PREVIOUS: Message?
  Var Next: Message?
  Init (Text: String) {
    Self.Text = Text
  }
  // Mark: Equatable
  Static Func == (LHS: Message, RHS: Message) - & gt; BOOL {
    LHS.Text == Rhs.Text
  }
}

In this case, it will be necessary in any way to assign values ​​of the variable Next and Previous , for example, as shown below (here we also use the extension)

struct contentview: view {
  Let Messages = [Message (Text: "1"), Message (Text: "2"), Message (Text: "3"), Message (Text: "4")]
  Var Body: Some View {
    List {
      Foreach (getlinkedMessages (), ID: \ .id) {Message in
        Text ("\ (Message.Previous! .Text), \ (Message.Text), \ (message.next! .Text)")
      }
    }
  }
  Func getlinkedMessages () - & gt; [Message] {
    Messages.map {
      $ 0.Previous = Messages.Before ($ 0, Loop: True)
      $ 0.next = Messages.After ($ 0, Loop: True)
      Return $ 0.
    }
  }
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions