How to concatenate an integer variable with string variables

Hello:


I am using Swift 5.1.3. I can't get a simple Int variable to concatenate with String variables.

Any help will be appreciated. I want to include a percentage from two numbers with a string of Strings. Belowis my code:


I am getting an error on line 12: Binary operator '+' cannot be applied to operands of type 'String' and 'Int' --

referencing "groupPercent"


func getPercent(){
               
                let groupPercent: Double = Double(qmSum) / Double(qaSum) * 100
                
                 print ("Percent is \(groupPercent)")
               
                 }
                getPercent()
               
                let firstPart = (groupNameItem) + (" ")
                let secondPart = ("Group Score") + (" ")
                let newLine = (firstPart + secondPart + groupPercent)
                studentsText?.string = studentsText!.string + newLine + "\n"


Thanks.

Accepted Reply

+ between strings means "concatenate"

+ with Int means add

you cannot mix the 2 and add strings with int (what would you expect ? String, Int ?), so just convert number to String:


let newLine = (firstPart + secondPart + String(groupPercent))


If groupPercent was Double, you can format to have a fixed number of digits after dot (here 2)


let newLine = (firstPart + secondPart + String(format: "%.2f", groupPercent))


you can express another way:

let newLine2 = "\(firstPart)\(secondPart)\(groupPercent)"


Here, var are automatically converted to String : nothing for firstPart and secondPart, automatic conversion from Int to String for groupPercent

Replies

+ between strings means "concatenate"

+ with Int means add

you cannot mix the 2 and add strings with int (what would you expect ? String, Int ?), so just convert number to String:


let newLine = (firstPart + secondPart + String(groupPercent))


If groupPercent was Double, you can format to have a fixed number of digits after dot (here 2)


let newLine = (firstPart + secondPart + String(format: "%.2f", groupPercent))


you can express another way:

let newLine2 = "\(firstPart)\(secondPart)\(groupPercent)"


Here, var are automatically converted to String : nothing for firstPart and secondPart, automatic conversion from Int to String for groupPercent

Thanks.


The second option works for me.