Search code examples
arraysswiftsubstringinit

SwiftUI 5.5 Init array with substring of string?


I've written sample data for my view and it looks/works but now i want to replace my sample data with actual data. I've successfully passed in two strings. I'm trying to substring it and replace the wDD and wRead elements of the NamedWeek array with the actual data. Can someone help me how to do that?

my incoming strings look like: for the wDD -

let string1 =  "21|22|23|24|25|26|27"

for the wRead -

let string2 = "Dan 9|Rev 14|Eze 38|Matt 24|Joel 2|Gen 3|Jer 18"
struct NamedWeek: Identifiable {
   let wDay: String
   var wDD: String
   var wRead: String
   var id: String { wDay }
}

  var namedWeeks: [NamedWeek] = [
   NamedWeek(wDay: "Sun", wDD: "15", wRead: "Leviticus 26"),
   NamedWeek(wDay: "Mon", wDD: "16", wRead: "Psalm 45"),
   NamedWeek(wDay: "Tue", wDD: "17", wRead: "Test 3"),
   NamedWeek(wDay: "Wed", wDD: "18", wRead: "Test 4"),
   NamedWeek(wDay: "The", wDD: "19", wRead: "Test 5"),
   NamedWeek(wDay: "Fri", wDD: "20", wRead: "Test 6"),
   NamedWeek(wDay: "Sat", wDD: "21", wRead: "Test 7")
     
 ]

I was trying to do something like

var token = string1.components(separatedBy: "|") 

and then replacing wDD with token[0] then token[1] or if i could insert a func (don't know if that is possible) Thanks


Solution

  • You can split by the | character, zip the arrays together, then append it to namedWeeks.

    Code:

    let string1 =  "21|22|23|24|25|26|27"
    let string2 = "Dan 9|Rev 14|Eze 38|Matt 24|Joel 2|Gen 3|Jer 18"
    
    let zipped = zip(string1.split(separator: "|"), string2.split(separator: "|"))
    let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
    
    var namedWeeks = [NamedWeek]()
    for (index, element) in zipped.enumerated() {
        namedWeeks.append(NamedWeek(wDay: weekdays[index], wDD: String(element.0), wRead: String(element.1)))
    }
    
    print(namedWeeks)