Veronica G Veronica G - 5 months ago 7
Swift Question

Array of strings function error, can't print the order correctly

I have a problem with my code. I need to print the last default case in alphabetical order, but I'm not sure why it's not working. I have to take my stringArray, append two more strings to it and print out the correct case in my code. Apparently from what I was told I was printing against the original, unsorted list. But I'm not sure what I did wrong here. The error is in the last print (//Switch >6 Strings)... I think :/

Here is my code

//Original String
var stringArray = ["zebra", "JAGUAR", "apple"]

func thirdFunction(par1: [String]) {

var parVariable = par1
var containerArray = [String]()

switch par1.count{

//Reverses strings in the array
case 1...3:
for j in par1 {
let reverse = j.characters.reverse()
containerArray.append(String(reverse))
}
print(containerArray)

//Reverse the element order
case 4...6:
for _ in 1...par1.count{

containerArray.append(parVariable.popLast()!)
}
print(containerArray)

//Prints strings in alphabetical order
default:
for i in par1 {
containerArray.append(i.lowercaseString)
}
containerArray = containerArray.sort()
for p in par1 {
print(p)
}
}
}

print("//Switch 1-3 Strings")
thirdFunction(stringArray)

print("//Switch 4-6 Strings")
stringArray.append("Blue")
stringArray.append("eMerald")
thirdFunction(stringArray)

print("//Switch >6 Strings")
stringArray.append("beads")
stringArray.append("BEAR")
thirdFunction(stringArray)


The output should be:

//Switch 1-3 Strings

["arbez", "RAUGAJ", "elppa"]

//Switch 4-6 Strings

["eMerald", "Blue", "apple", "JAGUAR", "zebra"]

//Switch >6 Strings

apple

beads

BEAR

Blue

eMerald

JAGUAR

zebra


but my last print shows up as...

zebra

JAGUAR

apple

Blue

eMerald

beads

BEAR

Answer

You got a typo:

default:
    for i in par1 {
        containerArray.append(i.lowercaseString)
    }
    containerArray = containerArray.sort()
    for p in containerArray { // instead of par1
        print(p)
    }
}
Comments