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

Viewed 160

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?

1 Answers
Related