Swift3.0 - 空间命名

Swift3.0 - 真的很简单
Swift3.0 - 数据类型
Swift3.0 - Array
Swift3.0 - 字典
Swift3.0 - 可选值
Swift3.0 - 集合
Swift3.0 - 流控制
Swift3.0 - 对象和类
Swift3.0 - 属性
Swift3.0 - 函数和闭包
Swift3.0 - 初始化和释放
Swift3.0 - 协议protocol
Swift3.0 - 类和结构体的区别
Swift3.0 - 枚举
Swift3.0 - 扩展
Swift3.0 - 下标
Swift3.0 - 泛型
Swift3.0 - 异常错误
Swift3.0 - 断言
Swift3.0 - 自动引用计数(strong,weak,unowned)
Swift3.0 - 检测API
Swift3.0 - 对象的标识
Swift3.0 - 注释
Swift3.0 - 元类型
Swift3.0 - 空间命名
Swift3.0 - 对象判等
Swift3.0 - 探究Self的用途
Swift3.0 - 类簇
Swift3.0 - 动态调用对象(实例)方法
Swift3.0 - 文本输出
Swift3.0 - 黑魔法swizzle
Swift3.0 - 镜像
Swift3.0 - 遇到的坑

  • 为什么要使用空间命名

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

代码示例

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:

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

 NotificationCenter.default.post(name: Notification.Name("SocketConnectFailure"), object: ["errorCode":000])

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

NotificationCenter.default.addObserver(self, selector: #selector(SocketConnectFailure(notification:)), name: Notification.Name("SocketConnectFailure"), object: nil)

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

命名空间优雅的写法

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

使用:

//   想通知中心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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值