Swift - 命名空间
2024-12-24 本文已影响0人
追梦赤子心Year
关于命名空间,Swift与其他语言在概念上有所不同,但是共同的作用:避免命名冲突。与Objective-C更不同,因为OC就没有命名空间。
在OC中我们在创建类的时候往往都加上前缀(公司名缩写?项目名缩写?自己名字缩写?),目的一个是标记,但最主要的目的就是防止与其他框架下的代码类名冲突。因为在OC中没有命名空间,所有的代码、静态库都编译到了一起。如果引用的库中创建了两个一样名字的类,那就会冲突。
像Swift,有了命名空间,我们的每一个Target都有各自的命名空间,两个Target中,即使存在相同的类,也不会冲突。在引用其他库的时候,及时有文件名相同的文件存在,也不会因为冲突报错。
![](https://img.haomeiwen.com/i1943974/9cc8d3eeec9dba10.png)
![](https://img.haomeiwen.com/i1943974/b83cbd02f71ca753.png)
self的命名空间是target。它实际的名字是target名+文件名
对于日常开发的影响:
用swift做类似OC字符串映射的时候,我们不能直接将文件名的字符串映射成文件。因为前面多了一个命名空间
以点击tableViewCell跳往不同的页面
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
/*
数据源
listDic = [["vcName":"FirstVC",
"vcTitle":"页面一"],
["vcName":"SecondVC",
"vcTitle":"页面二"],
["vcName":"ThirdVC",
"vcTitle":"页面三"]]
*/
// 1. 获取去命名空间,由于项目肯定有info.plist文件所有可以机型强制解包.
guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { return print("没有获取到命名空间")}
print("命名空间为:",nameSpace)
// 2. 拼写命名空间.类名(比如)
let vcName = nameSpace + "." + listDic[indexPath.row]["vcName"]!
print("文件名:", vcName)
// 3. 将类名转化成类
guard let classType = NSClassFromString(vcName) else { return print("\"\(vcName)\" is not class") }
// 4. 将类转化成UIViewController
guard let vcType = classType as? UIViewController.Type else { return print("\"\(vcName)\" is not UIViewController") }
// 5. 用vcType实例化对象
let vc = vcType.init()
// 6. 跳转
navigationController?.pushViewController(vc, animated: true)
}