首页 技术 正文
技术 2022年11月15日
0 收藏 589 点赞 2,285 浏览 1363 个字

本篇分为两部分:

一、Swift 中 protocol 组合的使用

二、Swfit 中 static和class 的使用

  

一、Swift 中 protocol 组合的使用

  在 Swift 中我们可以使用 Any 来表示任意类型(public typealias Any = protocol<>),是一个 protocol<>的同名类型,需要实现空接口的接口,其实就是任意类型的意思。

protocol<ProtocolA, ProtocolB, ProtocolC> 等价于
protocol ProtocolD: ProtocolA, ProtocolB, ProtocolC {
//...
}

protocol 组合可以用 typealias 来命名的,于是上面的 ProtocolD 协议可以替换为

typealias ProtocolAll = protocol<ProtocolA, ProtocolB, ProtocolC>

如果某些接口我们只用一次的话,可以直接匿名化

struct ProtocolStruct {
static func test1(pro: protocol<ProtocolA, ProtocolB>) {
//...
}
static func test2(pro: protocol<ProtocolB, ProtocolC>) {
//...
}
}

如果实现多个接口时接口内的方法冲突的话只要在调用前进行类型转换就可以了

protocol A {
func wang() -> Int
}
protocol B {
func wang() -> String
}
class AnClass: A, B {
func wang() -> Int {
return
}
func wang() -> String {
return "强转"
}
}
let instance = AnClass()
let num = (instance as A).wang()
let str = (instance as B).wang()

二、Swfit 中 static和class 的使用

在 Swift1.2及以后,我们可以在 class 中使用 static 来声明一个类作用域的变量:

class MyClass {
static var bar: AnClass?
}

这种写法是合法的,有了这个特性之后,像单例的写法就很简单了

protocol MyProtocol {
static func foo() -> String
}
struct MyStruct: MyProtocol {
static func foo() -> String {
return "MyStruct"
}
}
enum MyEnum: MyProtocol {
static func foo() -> String {
return "MyEnum"
}
}
class TestClass: MyProtocol {
// 在 class 中可以使用 class
class func foo() -> String {
return "TestClass.foo()"
}
// 也可以使用 static
static func bar() -> String {
return "AnClass.bar()"
}
}

protocl 是比较特殊的,在 Swift 中 class, struct 和 enum 都是可以实现某个 protocol 的,这时候我们就会不知道在什么情况下使用 static,什么情况下使用 class。在 Swift2.0 之后,只要记住在任何时候使用 static 都是没有问题的。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,490
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,905
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,738
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,491
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,129
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,292