skip to Main Content

Good day everyone I want to create a function that takes an array of strings and return an array, sorted from shortest to longest but I’m getting a terminated by signal 4 error. I’m using an online swift compiler on my windows laptop if that somehow matters.

here’s the code I wrote:

var siliconvalley = ["Google", "Apple", "Microsoft"]
var elementamount: Int = siliconvalley.count
var newarray: [String] = [] //new array created to store the newly sorted array
var a = siliconvalley[0].count // this variable was created to count the letters of the first string in the array

var temporary: String = "" // this was created to store the largest string so that I can use it to append the new array 

func longestelement () -> [String] {
    repeat {
        if siliconvalley[1].count > a {
            print (siliconvalley[1])
            temporary = siliconvalley[1]
            siliconvalley.remove(at:1)
    
        }
        else if siliconvalley[2].count > a {
            print (siliconvalley[2])
            temporary = siliconvalley[2]
            siliconvalley.remove(at:2)
        }
        else {
            print (siliconvalley[0])
            temporary = siliconvalley[0]
            siliconvalley.remove(at:0)
        }
        newarray.append(temporary)
        elementamount = elementamount - 1
    } while elementamount > 0 
    return newarray
}
print (longestelement())

2

Answers


  1. here’s the issue:

    while elementamount > 0 
    

    Consider rechecking the code for possible illogical loop termination condition.

    P.S: elementamount is always greater than 0.

    Login or Signup to reply.
  2. You know swift has built-in sorting? You can do:

    siliconvalley.sorted(by: {$0.count < $1.count})
    

    and then if you just want the longest use .last

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search