Reputation: 51
I'm now learning a function which is written in Objective-C. But I don't know Objective-C language. When I'm converting the code to Swift, I got stuck at the delegate functions.
The code in .h file is:
#import <UIKit/UIKit.h>
@protocol SCPopViewDelegate <NSObject>
@optional
- (void)viewHeight:(CGFloat)height;
- (void)itemPressedWithIndex:(NSInteger)index;
@end
@interface SCPopView : UIView
@property (nonatomic, weak) id <SCPopViewDelegate>delegate;
@property (nonatomic, strong) NSArray *itemNames;
@end
and I'm trying to convert the code as:
protocol popViewDelegate: class {
func itemPressedWithIndex(index: Int)
func viewHeight(height: CGFloat)
}
but for the three last sentences, i don’t know how to deal with them, especially the one with id
and delegate
.
Can I get any help, please? I will do more effort to learn Swift. Thank you very much!
Upvotes: 0
Views: 765
Reputation: 5467
Converted Code for Swift 4.2
protocol SCPopViewDelegate: class {
func viewHeight(_ height: CGFloat)
func itemPressed(with index: Int)
}
extension SCPopViewDelegate {
func viewHeight(_ height: CGFloat) {}
func itemPressed(with index: Int) {}
}
class SCPopView: UIView {
weak var delegate: SCPopViewDelegate?
var itemNames: [Any] = []
}
This code is based on code converted by an online code conversion tool, the link to the original generated code.
Upvotes: 1
Reputation: 2587
import UIKit
@objc protocol SCPopViewDelegate{
optional func viewHeight(height: Float)
optional func itemPressedWithIndex(index : Int)
}
class DGViewController: UIViewController {
var delegate:SCPopViewDelegate! = nil
override func viewDidLoad() {
super.viewDidLoad()
delegate?.viewHeight?(Float(self.view.frame.size.height))
}
And in the class that implements the delegate
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
var vc = DGViewController()
vc.delegate = self
vc.view.frame = self.view.frame;
vc.view.backgroundColor = (UIColor.redColor())
self.presentViewController(vc, animated: true) { () -> Void in}
}
func viewHeight(height: Float) {
println(height)
}
Upvotes: 0
Reputation: 131408
The definition of the protocol ends with the first @end statement.
The @interface after that is the definition of an Objective-C class, SCPopView.
You don't need to care about the latter part if you're just trying to define the protocol in Swift.
FYI:
@interface someClass: NSObject
is equivalent to
class someClass: NSObject
In Swift.
Upvotes: 0