How to call the typealias in Swift

1.9k views Asked by At

I've just started learning swift 3 and I'm converting this code in objective-c to swift 3 and I'm stuck at typealias. I've searched for it and there may be right help already available but it didn't solved my issue.

This is the line in objective-c:

typedef void (^TagBlock)(NSString *tagText, NSInteger idx);

And there is a property for it as @property (nullable, copy) TagBlock tapBlock; in objective-c.
Now I've converted the above line as:

typealias TagBlock = (_ tagText: NSString,_ idx: NSInteger) -> Void

Which is something I understand very well syntax wise and the property is var tapBlock: TagBlock! in case of swift.

Now as I try to call it in one of the @IBAction methods as:

if (tapBlock != nil) {
    self.setTapBlock(tapBlock: (tagButton.titleLabel?.text,tag) -> Void)
}

This gives an error as:

Expected type before '->'

This line in objective is:

if (_tapBlock) {
    _tapBlock(sender.titleLabel.text, self.tag);
  }



UPDATE After import UIKit I've added typealias TagBlock = ((String, Int) -> Void)? and after that var tapBlock: TagBlock!
In class TagView: UIView I'm calling in in an @IBAction as

@IBAction func tagTapped(_ sender: Any) {
    if (tapBlock != nil) {
            tapBlock?(sender.titleLabel.text, self.tag)
        }
    }

So at tapBlock?(sender.titleLabel.text, self.tag) it give me the error:

Cannot call value of non-function type 'TagBlock'`

1

There are 1 answers

5
vadian On

nullable is an optional in Swift, and in Swift 3 don't use underscores and parameter labels.

The equivalent is:

typealias TagBlock = ((String, Int) -> Void)?

and you can call it simply

tapBlock?(sender.titleLabel.text, self.tag)

Due to optional chaining the closure will not be called if tapBlock is nil.