简体   繁体   English

在Swift 3中扩展ObjC泛型

[英]Extending ObjC generic in Swift 3

Swift 3 comes with SE-0057 implemented that, among other things, means that: Swift 3随附SE-0057实现,这意味着:

By default, extensions of parameterized Objective-C classes cannot reference the type parameters in any way. 默认情况下,参数化Objective-C类的扩展不能以任何方式引用类型参数。 For example: 例如:

 extension MySet { func someNewMethod(x: T) { ... } // error: cannot use `T`. } 

... where MySet is declared in ObjC as @interface MySet<T : id<NSCopying>> : NSObject . ...其中MySet在ObjC中声明为@interface MySet<T : id<NSCopying>> : NSObject

All that is clear (and there is some sort of workaround possible even). 一切都清楚了(甚至还有某种解决方法)。 However, the following does not compile despite that I am not using any type parameters from ObjC class that I am trying to extend. 但是,尽管我没有使用我试图扩展的ObjC类的任何类型参数,但以下内容无法编译。 I am only using another unrelated Swift class as a return parameter to the extension method: 我只使用另一个不相关的Swift类作为扩展方法的返回参数:

class Foo { }
struct Bar { }

extension MySet {
    func foo() -> Foo { return Foo() } // Both produce: Extension of a generic
    func bar() -> Bar { return Bar() } // Objective-C class cannot access the 
}                                      // class's generic parameters at runtime

Is this a bug? 这是错误吗? Or am I missing something? 还是我错过了什么?

Details 细节

xCode 8.3.1, swift 3.1 xCode 8.3.1,快速3.1

Sample 样品

MySet.h MySet.h

#import <Foundation/Foundation.h>

@interface MySet<T : id<NSCopying>> : NSObject

@end

typedef struct ObjCStruct
{
    __unsafe_unretained NSString* str;
    int num;
} ObjCStruct;

MySet.m MySet.m

#import "MySet.h"

@implementation MySet

@end

MySetExtension.swift MySetExtension.swift

import Foundation

class Foo: NSObject {
    var str = "Foo"
    var num = 1
}

extension ObjCStruct {

    init() {
        num = 2
        str = Unmanaged.passRetained("ObjCStruct")
    }
}

extension MySet {
    func foo() -> Foo { return Foo() }
    func bar() -> ObjCStruct { return ObjCStruct() }
}

Bridging-Header 桥接头

#import "MySet.h"

Usage 用法

NSLog(@"%@", [set foo].str);
NSLog(@"%@", [set bar].str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM