字面量
常见字面量的默认类型

可以通过typealias修改字面量的默认类型
public typealias IntegerLiteralType = Int
public typealias FloadLiteralType = Float
swift自带类型之所以能够通过字面量初始化 是因为他们遵守了对应的协议

字面量的应用
extension Int: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = value ? 1 : 0
}
}
var num: Int = true
print(num)
1
extension Int: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = Int(value) ?? 0
}
}
var ma: Int = "dadad"
print(ma)
0
//CustomStringConvertible 描述协议
class Student: ExpressibleByIntegerLiteral,ExpressibleByFloatLiteral,ExpressibleByStringLiteral,CustomStringConvertible {
var name: String = ""
var score: Double = 0
required init(floatLiteral value: Double) {
self.score = value
}
required init(stringLiteral value: String) {
self.name = value
}
required init(unicodeScalarLiteral value: String) {
self.name = value
}
required init(extendedGraphemeClusterLiteral value: String) {
self.name = value
}
required init(integerLiteral value: Int) {
self.score = Double(value)
}
var description: String {
return "name = \(name),score=\(score)"
}
}
var stu: Student = 90
print(stu)
stu = 98.5
print(stu)
struct Point {
var x = 0.0,y = 0.0
}
extension Point: ExpressibleByArrayLiteral,ExpressibleByDictionaryLiteral {
init(arrayLiteral elements: Double...) {
guard elements.count > 0 else {return}
self.x = elements[0]
guard elements.count > 1 else {return}
self.y = elements[1]
}
init(dictionaryLiteral elements: (String, Double)...) {
for (k,v) in elements {
if k == "x" {
self.x = v
}else if k == "y" {
self.y = v
}
}
}
}
var p: Point = [10.5,20.5]
print(p)
p = ["x": 11,"y": 22]
print(p)
Point(x: 10.5, y: 20.5)
Point(x: 11.0, y: 22.0)
网友评论