Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

ios - Issue with conforming to Objective-C protocol from Swift NSObject subclass

This piece of code works absolutely fine in Swift 1.1

// Obj-C

@import Foundation;

@protocol HashableObject <NSObject>
- (NSUInteger)hash;
@end

// Swift

import Foundation

@objc class Object: NSObject, HashableObject {

    func hash() -> UInt {
        return 0
    }
}

However, in latest Swift 1.2 and XCode 6.3beta2 the compiler complains that Method 'hash()' overrides Objective-C method 'hash' from superclass 'NSObject'

Is that a bug, or something else has fundamentally changed and the code is wrong? Are there any workarounds to this? I have numerous things in my code that need to conform to certain protocols from Objective-C libraries and this essentially breaks everything with no apparent solution other than wait for the next Swift release.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

NSObject already has hash property:

protocol NSObjectProtocol {
    var hash: Int { get }

And, Swift 1.2 detects these erroneous overrides. From the release notes:

Swift now detects discrepancies between overloading and overriding in the Swift type system and the effective behavior seen via the Objective-C runtime. (18391046, 18383574)

For example, the following conflict between the Objective-C setter for “property” in a class and the method “setProperty” in its extension is now diagnosed:

class A : NSObject {
  var property: String = "Hello" // note: Objective-C method 'setProperty:’
                                 // previously declared by setter for
                                 // 'property’ here
}
extension A {
    func setProperty(str: String) { } // error: method ‘setProperty’
                                      // redeclares Objective-C method
                                      //'setProperty:’
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...