Swift 實作
types.swift
main.swift
[Code程式區 - types.swift]
// Protocol 練習
@objc protocol Adelegate {
func m1()
optional func m3()
}
protocol BDelegate {
func m2()
var demo : Int {get set}
}
// Protocol多重繼承
protocol CDelegate: Adelegate, BDelegate {
func m3()
}
// 宣告使用Protocol 就必須要實作
class A : Adelegate, BDelegate{
@objc func m1() {
print("print m1")
}
func m2() {
print("print m2")
}
var demo: Int {
get{
return 12
}
set{
}
}
}
extension NSDate{
convenience init(dateString:String) {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date : NSDate? = formatter.dateFromString(dateString)
self.init(timeInterval : 0, sinceDate: date ?? NSDate())
}
var year : Int{
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
let str = formatter.stringFromDate(self)
return Int(str)!
}
var month : Int{
let formatter = NSDateFormatter()
formatter.dateFormat = "MM"
let str = formatter.stringFromDate(self)
return Int(str)!
}
var day : Int{
let formatter = NSDateFormatter()
formatter.dateFormat = "dd"
let str = formatter.stringFromDate(self)
return Int(str)!
}
func showInfo() {
print("Date : \(year) /\(month)/\(day)")
}
}
[Code程式區 - main.swift]
// 練習擴充型別 Extension
let date = NSDate(dateString:"2010-10-10")
date.showInfo()
// 練習單一Prorocol
var v1 : Adelegate = A()
var v2 : BDelegate = A()
v1.m1()
v2.m2()
// 練習protocol多筆合成
let v3 : protocol<Adelegate, BDelegate> = A()
George Huang 烤蕃薯@Taipei 2016
沒有留言:
張貼留言