Utku Dalmaz
Utku Dalmaz

Reputation: 10192

Accessing a swift property from objC

- (void) tapGesture: (id)sender
{
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
    NSInteger userID = gesture.view.tag;

    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                         bundle:nil];
    OthersProfile *vc = (OthersProfile*)[storyboard instantiateViewControllerWithIdentifier:@"othersprofile"];
    NSString *strUserID = [NSString stringWithFormat:@"%ld", (long)userID];

    vc.userID = strUserID;
    [self.viewController.navigationController pushViewController:vc
                                                        animated:YES];
}

It used to work with Xcode 8 / Swift 3 but seems like there is a problem with Xcode 9 and swift 4.

I am having property userID not found error.

In Swift file:

var userID : String = ""
override func viewDidLoad() {
    print(userID) //no value here
}

Anyone with any idea?

Upvotes: 3

Views: 1734

Answers (2)

Paulo Mattos
Paulo Mattos

Reputation: 19349

Try this instead:

@objc var userID : String = "

The rules for exposing Swift code to Objective-C have changed in Swift 4. As such, your code was okay in Swift 3 and hence the confusion you are facing ;)

The new design is fully detailed in the corresponding Swift Evolution proposal.

Upvotes: 5

Lu_
Lu_

Reputation: 2685

Addression your other question you should fix how you access controller:

This is because vc.user is nil when you are trying to set it, add a variable to swift controller and set it instead of `vc.user.text

vc.yourVariable = strUserID;
[self.viewController.navigationController pushViewController:vc
                                                    animated:YES];

then in viewDidAppear you will be able to set it with this variable

 @IBOutlet var user: UILabel!
 public var yourVariable: String = ""

 override func viewDidLoad() {
     user.text = yourVariable
     print(user.text!) //should be value

 }

Upvotes: 0

Related Questions