paresh
paresh

Reputation: 128

Difference between "\(string)" and string?

    callfunc(string: "\(string)")

    callfunc(string: string)

I am calling the same function with same string value but different approach.... let me know what is the difference in it? and also I want to know in terms of memory consumption.

Upvotes: 0

Views: 123

Answers (3)

paresh
paresh

Reputation: 128

callfunc(string: string)

In the above syntax its a normal function call with a string.

callfunc(string: "(string)")

But here when we will pass "(string)" as a parameter, internally "(string)" creates a new string and pass it as a parameter. So in that particular point of time the memory will go high because of memory allocation for the string, which will again deallocated immediately.

Normally you won't be able to observe it with a small string, but if you will convert an image into base64 and try to pass it as a string. you can able to see the difference.

Apart from that there is no difference in functionality.

Upvotes: 0

Kubba
Kubba

Reputation: 3438

There's a difference when your string is implicitly unwrapped optional. Consider example:

func some(string: String)
{
    print(string)
}

let string: String! = "s"

some(string: string)
some(string: "\(string)")

The output will be:

s
Optional("s")

Upvotes: 0

JuicyFruit
JuicyFruit

Reputation: 2668

there is no difference, "\()" is used if your string is something like

let someInt: Int = 20
print("my integer is \(someInt)") //"my integer is 20"

i.e. not String in first place.

there is no memory difference because String in Swift is not reference type, it is Struct, so you pass copy of string to your callfunc, not reference to it.

Upvotes: 2

Related Questions