swift从入门到精通19-字面量

334 阅读1分钟

1.字面量

常见字面量的默认类型有:
ppublic typealias IntegerLiteralType = Int 

ppublic typealias FloatLiteralType = Double 

ppublic typealias BooleanLiteralType = Bool 

ppublic typealias StringLiteralType = String

例子:

var num = 10
var name = "wwj"

2.字面量协议

Swift自带类型之所以能够通过字面量初始化,是因为它们遵守了对应的协议。

  • Bool : ExpressibleByBooleanLiteral
  • Int : ExpressibleByIntegerLiteral
  • Float、Double : ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral
  • Dictionary : ExpressibleByDictionaryLiteral
  • String : ExpressibleByStringLiteral
  • Array、Set : ExpressibleByArrayLiteral p Optional : ExpressibleByNilLiteral

3.字面量协议应用

struct literalDemo{
    var x = 0.0
    var y = 0.0
}


extension literalDemo: 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 d1: literalDemo = [2.0,3.0]
print(d1.x,d1.y)
var d2: literalDemo = ["x":4.0,"y":5.0]
print(d2.x,d2.y)


上一篇文章:swift从入门到精通18-访问控制和内存管理

下一篇文章:swift从入门到精通20-模式匹配