首页
学习
活动
专区
圈层
工具
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Swift3.0 - 空间命名

  • 为什么要使用空间命名

如果你不想给类名加前缀,然后又想避免出现类名冲突,这个时候,就可以使用它了

代码示例

代码语言:javascript
复制
struct MyClassContrainer1{
    class Student {
        func getName() -> String {
            return "name"
        }
    }
}
struct MyClassContrainer2{
    class Student {
        func getName() -> String {
            return "name"
        }
    }
}

let student1 = MyClassContrainer1.Student()
let student2 = MyClassContrainer1.Student()

应用场景1:

我们想通知中心发送一条消息

代码语言:javascript
复制
 NotificationCenter.default.post(name: Notification.Name("SocketConnectFailure"), object: ["errorCode":000])

我们注册通知的写法是下面这样的

代码语言:javascript
复制
NotificationCenter.default.addObserver(self, selector: #selector(SocketConnectFailure(notification:)), name: Notification.Name("SocketConnectFailure"), object: nil)

思考: 我们如果能够更加直观的知道SocketConnectFailure 是哪一类消息呢?

命名空间优雅的写法

代码语言:javascript
复制
extension Notification.Name {
    /// 使用命名空间的方式
    public struct SocketTask {
        public static let connectFailure = Notification.Name(rawValue: "SocketConnectFailure")
        public static let connectSuccess = Notification.Name(rawValue: "SocketConnectSuccess")
  }
}

使用:

代码语言:javascript
复制
//   想通知中心post 消息
 NotificationCenter.default.post(name: Notification.Name.SocketTask.connectFailure, object: ["errorCode":000])
//   增加观察者
NotificationCenter.default.addObserver(self, selector: #selector(SocketConnectFailure(notification:)), name: Notification.Name.SocketTask.connectFailure, object: nil)
下一篇
举报
领券