Home > Mobile >  Swift terminator cannot be found in for loop scope
Swift terminator cannot be found in for loop scope

Time:10-28

So, I started learning Swift recently, but when I was trying to execute the following code I receive error that terminator cannot be found in scope!

var intArray = [1,2,3,4,5,6,67,8,9,8,7,7,7,7,4,4,577,4,2,6,78,3,78,]
var counter = 0
for a in intArray{
    print(a, terminator:" ")
    if(counter%5==0){
        print("\n")
    }
counter =1
}

but outside the "for loop" it works perfect?

CodePudding user response:

terminator=" " for a parameter in function call is not valid Swift syntax.

You probably mean:

print(a, terminator: " ")

CodePudding user response:

If I understand correctly, you want to print the items in the Array and then have a new line. For swift, argument labels (keyword arguments if you are more familiar with python) don't use "=", they just have a ":" after them.

print(a, terminator: " ") //in your case it would look like this.

Additionally, the issue of scope is two fold. Swift is looking for both a variable "terminator" in the scope of your function and it will also look for the variable counter in your function. Based on the code above, neither are there.

I'm not exactly sure what end result you want to achieve, but you could restructure your code like this:

var intArray = [1,2,3,4,5,6,67,8,9,8,7,7,7,7,4,4,577,4,2,6,78,3,78,]
for a in intArray{
    print(a, terminator: " ")//argument label uses ":"
}
print("\n") //no need for counter, just prints when the for loop completes

thus removing any scope issues.

  • Related