2

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?

8
  • There is no way to accomplish what you want. If you assign the result of it to another var what would you expect to happen? A new String object or a new func object? Commented Aug 23, 2021 at 14:49
  • String for sure, so what u mean? Commented Aug 23, 2021 at 14:50
  • let result = testString can result in let result: () -> String as well Commented Aug 23, 2021 at 14:50
  • 2
    I wonder why would you need to use the exact same name for a method and a variable. Just use different names. I mean would you accomplish something greater using the same namespace? Commented Aug 23, 2021 at 15:08
  • 1
    You are right! I have to use your advice, for me was good to have 'testString' and 'testString()' but it is hard and difficult for xcode. thanks Commented Aug 23, 2021 at 15:10

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.