本文主要介绍了Swift中协议的使用以及几个常见协议,还有类型判断(is)和强转(as)的使用和元类型
主要内容:
- 协议的使用
- 常见协议
- 类型判断和强转
- 元类型
协议可以用来定义方法、属性、下标的声明,但是只有声明没有实现。协议可以被枚举、结构体、类遵守(多个协议之间用逗号隔开)
代码:
/*
1、基本定义
提供方法、计算属性、下标
*/
protocol Drawable {
func draw()
var x: Int { get set }
var y: Int { get }
subscript(index: Int) -> Int {get set}
}
说明:
static:
代码:
/*
2、关键字
*/
//static 可以看到类中可以使用static也可以使用class,struct只能使用static
protocol Drawable2 {
static func draw()
}
class Person1 : Drawable2 {
class func draw(){
print("Person1 draw")
}
}
class Person2 : Drawable2 {
static func draw() {
print("Person2 draw")
}
}
struct Person3 : Drawable2 {
static func draw() {
print("Person3 draw")
}
}
Person1.draw()
Person2.draw()
Person3.draw()
说明:
mutating
代码:
//mutating 类本身就可以进行修改,不需要mutating标记,结构体需要使用mutating标记
protocol Drawable3 {
mutating func draw()
}
class Size: Drawable3 {
var width: Int = 0
func draw() {
width = 10
}
}
struct Point : Drawable3 {
var x: Int = 0
mutating func draw() {
x = 10
}
}
说明:
代码:
/*
3、属性
协议中的属性需要指明是否可读可写,类在实现时只要能够实现可读可写就行,可以是计算属性也可以是存储属性
*/
protocol Drawable4 {
func draw()
var x: Int { get set}
var y: Int { get }
subscript(index: Int) -> Int { get set }
}
class Person31: Drawable4 {
var x: Int = 0
let y: Int = 0
func draw() {
print("Person31 draw")
}
subscript(index: Int) -> Int {
set { }
get { index }
}
}
class Person32: Drawable4 {
var x: Int {
get { 0 }
set { }
}
var y: Int { 0 }
func draw() {
print("Person32 draw")
}
subscript(index: Int) -> Int {
set { }
get { index }
}
}
说明:
协议中还可以定义初始化器,遵守该协议的类以及子类都必须实现初始化器,所以需要使用required来修饰。
代码:
/*
4、init
Student的init既重写协议又重写父类的init,此时必须同时加上required和override
*/
protocol Livable {
init(age: Int)
}
class Person41 {
init(age: Int) {
print("Person init")
}
}
class Student: Person41, Livable {
required override init(age: Int) {
super.init(age: age)
print("Student init")
}
}
//Person init
//Student init
let stu = Student.init(age: 10)
说明:
init、init?、init!的区别
protocol Livable2 {
init()
init?(age: Int)
init?(no: Int)
}
class Person42: Livable2 {
required init() {
print("Person42 init")
}
required init?(age: Int) {
print("Person42 init?")
}
required init!(no: Int) {
print("Person42 init!")
}
}
let p1 = Person42.init()
let p2 = Person42.init(age: 10)
let p3 = Person42.init(no: 100)
/*
协议.Person42
Optional(协议.Person42)
Optional(协议.Person42)
*/
print(p1.self)
print(p2.self)
print(p3.self)
说明:
代码:
/*
5、继承
*/
protocol Runnable {
func run()
}
protocol Livable : Runnable {
func breath()
}
class Person : Livable {
func breath() {}
func run() {}
}
代码:
/*
6、协议组合
*/
protocol Livable6 {}
protocol Runnable6 {}
class Person6 {}
// 1、接收Person或者其子类的实例
func fn0(obj: Person6) {}
// 2、接收遵守Livable协议的实例
func fn1(obj: Livable6) {}
// 3、接收同时遵守Livable、Runnable协议的实例
func fn2(obj: Livable6 & Runnable6) {}
// 4、接收同时遵守Livable、Runnable协议、并且是Person或者其子类的实例
func fn3(obj: Person6 & Livable6 & Runnable6) {}
//5、也可以直接定义一下使用
typealias RealPerson = Person6 & Livable6 & Runnable6
// 接收同时遵守Livable、Runnable协议、并且是Person或者其子类的实例
func fn4(obj: RealPerson) {}
说明:
代码:
/*
7、CaseIterable,遍历枚举
*/
enum Season : CaseIterable {
case spring, summer, autumn, winter
}
let seasons = Season.allCases
print(seasons.count) // 4
for season in seasons {
print(season)
} // spring summer autumn winter
说明:
代码:
//CustomStringConvertible ,自定义打印字符串
//CustomDebugStringConvertible,打印debug字符串
class Person : CustomStringConvertible, CustomDebugStringConvertible {
var age = 0
var description: String { "person_\(age)" }
var debugDescription: String { "debug_person_\(age)" }
}
var person = Person()
print(person) // person_0
debugPrint(person) // debug_person_0
说明:
包括Any、AnyObject、AnyClass三种,Any表示任意类型,包括枚举、结构体、类、函数类型。AnyObject表示任意的类,AnyClass表示任意类的类型
Any实现
/*
8、任意类型
*/
var stu81: Any = 10
stu81 = "Jack"
var stu82: AnyObject = person
stu82 = Person42()
var classType: AnyClass = Person.self
说明:
代码:
/*
9、类型判断
*/
protocol Runnable9 {
func run()
}
class Person9 { }
class Student9 : Person9, Runnable9 {
func run() {
print("Student run")
}
func study() {
print("Student study")
}
}
//is
var stu9: Any = 10
print(stu9 is Int) // true
stu9 = "Jack"
print(stu9 is String) // true
stu9 = Student9()
print(stu9 is Person9) // true
print(stu9 is Student9) // true
print(stu9 is Runnable9) // true
说明:
代码:
//as
var stu92: Any = 10
(stu92 as? Student9)?.study() // 返回nil,不会调用study
stu92 = Student9()
(stu92 as? Student9)?.study() // 解包,Student study
(stu92 as! Student9).study() // 自动解包 ,可能会报错 Student study
(stu92 as? Runnable9)?.run() // 解包,Student run
说明:
代码:
元类型其实就是类的类型
/*
10、元类型
*/
class Person10 {}
class Student10 : Person10 {}
var perType: Person10.Type = Person10.self//拿到Person10的类型赋值给perType变量
var stuType: Student10.Type = Student10.self
perType = Student10.self//因为是继承关系,所以可以这样赋值
var anyType: AnyObject.Type = Person10.self
anyType = Student10.self//任意类型
public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person10.self
anyType2 = Student10.self
var per = Person10()
var perType2 = type(of: per) // Person.self
print(Person10.self == type(of: per)) // true
说明:
这里通过类类型可以同时对类进行处理
代码:
//应用
class Animal { required init() {} }
class Cat : Animal {}
class Dog : Animal {}
class Pig : Animal {}
func create(_ clses: [Animal.Type]) -> [Animal] {
var arr = [Animal]()
for cls in clses {
arr.append(cls.init())
}
return arr
}
print(create([Cat.self, Dog.self, Pig.self]))
Self表示当前类型,self表示当前对象,需要注意区分
代码:
protocol Runnable {
func test() -> Self
}
class Person : Runnable {
required init() {}
func test() -> Self { type(of: self).init() }
}
class Student : Person {}
说明:
1、因继承关系中都可以使用,必须使用required
2、返回类型为了在继承中匹配使用Self
3、type(of: self).init()这种方式也是为了继承中匹配类型
我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
在Ruby类中,我重写了三个方法,并且在每个方法中,我基本上做同样的事情:classExampleClassdefconfirmation_required?is_allowed&&superenddefpostpone_email_change?is_allowed&&superenddefreconfirmation_required?is_allowed&&superendend有更简洁的语法吗?如何缩短代码? 最佳答案 如何使用别名?classExampleClassdefconfirmation_required?is_a
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
可能已经问过了,但我找不到它。这里有2个常见的情况(对我来说,在编程Rails时......)用ruby编写是令人沮丧的:"astring".match(/abc(.+)abc/)[1]在这种情况下,我得到一个错误,因为字符串不匹配,因此在nil上调用[]运算符。我想找到的是比以下内容更好的替代方法:temp="astring".match(/abc(.+)abc/);temp.nil??nil:temp[1]简而言之,如果不匹配,则简单地返回nil而不会出错第二种情况是这样的:var=something.very.long.and.tedious.to.writevar=some
我正在学习Ruby的基础知识(刚刚开始),我遇到了Hash.[]method.它被引入a=["foo",1,"bar",2]=>["foo",1,"bar",2]Hash[*a]=>{"foo"=>1,"bar"=>2}稍加思索,我发现Hash[*a]等同于Hash.[](*a)或Hash.[]*一个。我的问题是为什么会这样。是什么让您将*a放在方括号内,是否有某种规则可以在何时何地使用“it”?编辑:我的措辞似乎造成了一些困惑。我不是在问数组扩展。我明白了。我的问题基本上是:如果[]是方法名称,为什么可以将参数放在括号内?这看起来几乎——但不完全是——就像说如果你有一个方法Foo.d