0

Basically what´s the difference between String() and ""

var x = "Test"
x = String()
x = ""

Will there be any difference between these two lines above?

user5855868
  • 97
  • 2
  • 15

2 Answers2

4

According to the Apple documentation, the strings are equivalent:

Initializing an Empty String

To create an empty String value as the starting point for building a longer string, either assign an empty string literal to a variable, or initialize a new String instance with initializer syntax:

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax
Zachary Espiritu
  • 937
  • 7
  • 23
-2

My understanding is when you set a String literal

var aString = ""

will at some point be converted, at least functionally, to

var aString: String = String("")

So you're technically adding a meaningless amount of work at compile time, but nothing that should matter in pretty much any circumstance.

GetSwifty
  • 7,568
  • 1
  • 29
  • 46
  • 1
    Nonsense. That's a recursive definition. If `""` means `String("")`, then `String("")` must mean `String(String(""))` and eventually you end up infinitely recursing to `String(String(String...""...)))` – Alexander Sep 09 '16 at 01:52
  • Or it just doesn't do it if it's in a string initializer...? The compiler's not that dumb... – GetSwifty Sep 09 '16 at 12:09
  • Then how does it know what to do with the `""`? My point is, your proposed definition of `""` as `String("")` can't work. – Alexander Sep 13 '16 at 00:50
  • my recommendation would be to use this fancy thing called "programming" e.g., if "" is in between () { don't change it } – GetSwifty Sep 13 '16 at 05:21
  • Yep. And that's different from what you said. – Alexander Sep 13 '16 at 15:44