属性 无法声明为开放,因为其类型使用了内部类型 (Typealias)
Property cannot be declared open because its type uses an internal type (Typealias)
我已经看到这个技巧来实现与平台无关的接口(比如)图像 classes UIImage/NSImage:
#if os(iOS)
import UIKit
typealias Image = UIImage
#elseif os(macOS)
import Cocoa
typealias Image = NSImage
#endif
现在我正在尝试将它应用到一个框架中。假设我有一个像这样的 class:
public final class MyClass {
public var image: Image // < Compiler Error (see below)
init?(imageURL: URL) {
guard let image = Image(contentsOf: imageFileURL) else {
return nil
}
self.image = image
}
}
我收到错误:
Property cannot be declared open because its type uses an internal type
"internal type"是指NSImage吗? 我该如何解决这个问题?
注意:我不认为这是 的副本:我正在使用 typealias,它是不明显 what 声明我应该标记为 "public".
在这种特定情况下(在框架目标中使用时),使 typealias
public 无法解决问题。声明图片属性时也需要使用平台条件检查,如下:
#if os(iOS)
import UIKit
typealias Image = UIImage
#elseif os(macOS)
import Cocoa
typealias Image = NSImage
#endif
public final class MyClass {
#if os(iOS)
public var image: UIImage
#elseif os(macOS)
public var image: NSImage
#endif
init?(imageURL: URL) {
guard let image = Image(contentsOf: imageFileURL) else {
return nil
}
self.image = image
}
}
这同样适用于使用此类型的任何 public 方法,无论它是参数还是函数的 return 类型。
Offtopic:确保在背景 queue/thread 上初始化此 class 以避免在下载图像时阻塞主线程并冻结 UI .
我已经看到这个技巧来实现与平台无关的接口(比如)图像 classes UIImage/NSImage:
#if os(iOS)
import UIKit
typealias Image = UIImage
#elseif os(macOS)
import Cocoa
typealias Image = NSImage
#endif
现在我正在尝试将它应用到一个框架中。假设我有一个像这样的 class:
public final class MyClass {
public var image: Image // < Compiler Error (see below)
init?(imageURL: URL) {
guard let image = Image(contentsOf: imageFileURL) else {
return nil
}
self.image = image
}
}
我收到错误:
Property cannot be declared open because its type uses an internal type
"internal type"是指NSImage吗? 我该如何解决这个问题?
注意:我不认为这是
在这种特定情况下(在框架目标中使用时),使 typealias
public 无法解决问题。声明图片属性时也需要使用平台条件检查,如下:
#if os(iOS)
import UIKit
typealias Image = UIImage
#elseif os(macOS)
import Cocoa
typealias Image = NSImage
#endif
public final class MyClass {
#if os(iOS)
public var image: UIImage
#elseif os(macOS)
public var image: NSImage
#endif
init?(imageURL: URL) {
guard let image = Image(contentsOf: imageFileURL) else {
return nil
}
self.image = image
}
}
这同样适用于使用此类型的任何 public 方法,无论它是参数还是函数的 return 类型。
Offtopic:确保在背景 queue/thread 上初始化此 class 以避免在下载图像时阻塞主线程并冻结 UI .