swiftPunk
swiftPunk

Reputation: 1

How can I have a variable and a function with same name in Swift

I want to have a variable and a function with same name, therefore I have this codes:

var testString: String = "some string from variable!"
// use case: print(testString)

func testString() -> String {

    return "some string from function!"

}
// use case: print(testString())

As you can see there is a big difference in both use cases! one like testString and the other with testString(), but xCode complain this to me:

Invalid redeclaration of 'testString()'

Which I do not know why it has to be an issue! one thing is a variable and other is function!

How ever I done a little hack and I deformed the function to this one in down, now it compile and no issue! the use case is still the same like testString()

func testString(_ value: String? = nil) -> String {

    return "some string from function!"

}
// use case: print(testString())

Now I have the things I wanted, but I have unwished initializer for function! how can I solve this issue in general?

Upvotes: 2

Views: 297

Answers (1)

BoygeniusDexter
BoygeniusDexter

Reputation: 2252

it's not possible, as they share the same namespace:

https://forums.swift.org/t/why-doesnt-swift-allow-a-variable-and-a-function-with-the-same-name/5038

Upvotes: 2

Related Questions