ios - Calling a Method on an Objective-C Delegate from Swift -
i'm writing swift classes build upon functionality in our objective-c app. have objective-c class delegate conforms protocol. i'm trying call method on delegate inside of swift class i'm simplified down this.
fredtestprotocol.h:
@protocol fredtestprotocol - (void) dumbmethod; @end fredtestclass.h:
#import <foundation/foundation.h> #import "fredtestprotocol.h" @interface fredtestclass : nsobject <fredtestprotocol> @property (nonatomic, weak) nsobject <fredtestprotocol> *delegate; @end fredtestclass.m:
#import "fredtestclass.h" @implementation fredtestclass - (void) dumbmethod { nslog(@"boy, dumb method"); } @end fredswiftclass.swift
import foundation class fredswiftclass { func test() { let ocobject = fredtestclass() ocobject.delegate.dumbmethod() // error occurs here. } } the indicated line produces error "'nsobject' not have method named 'dumbmethod'" i've tried lot of ways eliminate error, no avail. i'm sure i'm missing fundamental. can tell me how should go calling delegate method swift?
when swift examines property delegate sees is nsobject , fact have noted implements protocol ignored. can't find specific documentation why case.
you can address in couple of ways.
first, can redefine delegate property use class anonymity, swift see object implements protocol -
fredtestclass.h
#import <foundation/foundation.h> #import "fredtestprotocol.h" @interface fredtestclass : nsobject <fredtestprotocol> @property id<fredtestprotocol> delegate; @end then swift code compile written.
or can leave delegate definition , tell swift want access delegate instance of object implements protocol via downcast -
fredtestswift.swift
import foundation class fredswiftclass { func test() { let ocobject = fredtestclass() let thedelegate=ocobject.delegate as! fredtestprotocol thedelegate.dumbmethod() } }
Comments
Post a Comment