B
B
blessmemary2021-05-08 23:56:26
Swift
blessmemary, 2021-05-08 23:56:26

Optimize Swift code?

Please help to optimize the code, I would like to get rid of the repetition of the code block with the "for" loop, but I don't know how.

Code objective:
Given two strings containing a sequence of letters and keystrokes "backspace" (ie period).
You need to compare them and display the result.
(The str1 and str2 given in the code are equal)

I would be grateful, have a nice day!

import Foundation

/* --User Input Data-- */
var str1 = "aaa"
var str2 = "aaa..aa"
/* --User Input Data-- */

var newStr1 = ""
var newStr2 = ""

let sep1 = str1.components(separatedBy:".")
let sep2 = str2.components(separatedBy:".")

var index = 0
for var part in sep1{
  if !part.isEmpty{
    if index != 0{
      part.removeLast()
      newStr1 += part
      index += 1
    } else {
      newStr1+=part
      index+=1
    }
  } else {
    newStr1.removeLast()
    index += 1
  }
}

index = 0
for var part2 in sep2{
  if !part2.isEmpty{
    if index != 0{
      part2.removeLast()
      newStr2 += part2
      index += 1
    } else {
      newStr2+=part2
      index+=1
    }
  } else {
    newStr2.removeLast()
    index += 1
  }
}

print(newStr1==newStr2)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Golovin, 2021-05-10
@blessmemary

Hey!
Just write a function once and call it as many times as you need. Have you worked with functions before?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question