我觉得写作
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UserDatabaseUpdated"), object: nil);
非常丑陋且容易出错。所以我想这样做:
enum NotifyTypes : NSNotification.Name {
case userDatabaseUpdated = NSNotification.Name (rawValue: "UserDatabaseUpdated");
}
NotificationCenter.default.post(name: NotifyTypes.userDatabaseUpdated, object: nil);
但Xcode给了我错误:
'NotifyTypes' declares raw type 'NSNotification.Name', but does not conform to RawRepresentable and conformance could not be synthesized
这真的无法实现吗?我该如何解决这个问题?感谢。
PS:我知道我可以这样做:enum NotifyTypes {
case userDatabaseUpdated;
}
NotificationCenter.default.post(name: NSNotification.Name (rawValue: NotifyTypes.UserDatabaseUpdated.rawValue), object: nil);
但这更加丑陋,我想摆脱NSNotification.Name (rawValue:)
。
答案 0 :(得分:2)
您可以使用file = urllib2.urlopen('url')
with open('filename','w') as f:
for x in file:
f.write(x)
轻松实现此目的。
定义结构如:
struct
并使用它:
struct NotifyTypes
{
static let userDatabaseUpdated = NSNotification.Name("UserDatabaseUpdated")
}
编辑:如您在评论中提到的那样使用开关案例,您可以使用以下方式。
带有计算属性的枚举声明,用于返回通知名称:
NotificationCenter.default.post(name: NotifyTypes.userDatabaseUpdated, object: nil);
通知发布代码:
enum NotifyType : String
{
case userDatabaseUpdated = "UserDatabaseUpdated"
// Computed property which returns notification name
public var name: Notification.Name
{
return Notification.Name(self.rawValue)
}
}
通知捕获方法和切换案例如下所示:
NotificationCenter.default.post(name: NotifyType.userDatabaseUpdated.name, object: nil);
答案 1 :(得分:0)
这是我们目前正在做的方法,我想它看起来更好一点:
extension Notification.Name {
static let userDatabaseUpdated = Notification.Name("UserDatabaseUpdated")
}
NotificationCenter.default.post(name: .userDatabaseUpdated, object: nil)
此外,您不必保留单独的struct / enum /或任何其他数据结构,只需随时随地扩展Notification.Name
。
答案 2 :(得分:0)
最好的方法是使用Extension然后在那里添加你的结构
extension Notification.Name {
struct NotifyType {
static let userDatabaseUpdate = Notification.Name(rawValue: "userDatabaseUpdate")
}
}
现在可以在任何地方使用它,您可以像这样调用通知本身
NotificationCenter.default.post(name: NSNotification.Name.NotifyType.userDatabaseUpdate, object: nil)
答案 3 :(得分:0)
从 Swift 5 开始,更接近 OP 原始目标的更简洁的方法是:
enum NotifyTypes {
static let userDatabaseUpdated = NSNotification.Name("userDatabaseUpdated")
}
然后发布它会是:
NotificationCenter.default.post(name: userDatabaseUpdated, object: nil)