Reputation: 782
I am using external SDK(by including their xcode project in my project). The SDk was working properly in objective-c, but when I switched to swift, I am getting following problem.
Whenever I implementing delegate method where parameter is of type protocol, xcode suddenly gives error to object declaration of that Class which declared globally i.e. not in any function. If I comment that particular delegate method I will not get any error and it compile/executes successfully.
Please check the following swift code followed by my # comments
//CustomView is subclass of UIView
var customview : CustomView = CustomView() // #1 error as : Use of undeclared type CustomView
@IBAction func showCustomView(sender: AnyObject)
{
// CustomView configurations
}
#pragma CustomView Delegates
func CustomViewShown(view: AnyObject!) /// #2 delegate work properly
{
}
func CustomView(view: AnyObject!, didFailWithError error: NSError!)
// #3 if I keep this method uncommented it gives error to #1 line
// if I commented this method all other works fine without error.
{
}
Surprising thing is all the above delegate and SDK works fine for objective-C but not for swift.
On the basis of my little research, I am concluding that, We can not use the Class name and method name same in swift, i.e. in my case its CustomView. If I am using CustomView for declaring object, I can not use it as method name.
so someone please verify that, I am correct or not ? and what is solution for this issue.
Upvotes: 1
Views: 700
Reputation: 51911
It's essentially a name conflicting problem.
Inside of your class declaration, CustomView
is a method name, but not a class name. So, basically, your assumption is correct.
But, you have a workaround.
Let's suppose CustomView
is declared in the SDK. And that is a framework named SomeSDK
. Then you can reference the CustomView
like this:
import SomeSDK
class ViewController: UIViewController {
var customview: SomeSDK.CustomView = SomeSDK.CustomView()
func CustomView(view: AnyObject!, didFailWithError error: NSError!) {
}
}
If you don't want to prefix SomeSDK.
everywhere, you can typealias
it:
import SomeSDK
typealias SDKCustomView = CustomView // you can use `CustomView` here because there is no conflicting name.
class ViewController: UIViewController {
var customview: SDKCustomView = SDKCustomView()
func CustomView(view: AnyObject!, didFailWithError error: NSError!) {
}
}
Upvotes: 2
Reputation: 2269
I may be wrong, but it seems in swift you can also explicitly call the init function.
Instead of calling:
var customview : CustomView = CustomView()
you can call:
var customview : CustomView = CustomView.init()
This works in my Playground, let me know how it works out for you. This would allow you to use your function named as it is.
Upvotes: 0