代理模式讲解
protocol ExamCandidate: class {
func answerTheQuestion()
}
class LazyStudent: ExamCandidate {
var name: String
init(name: String) {
self.name = name
}
func answerTheQuestion() {
}
}
class Gunman: ExamCandidate {
var name: String
var target: LazyStudent?
init(name: String) {
self.name = name
}
func answerTheQuestion() {
if let stu = target {
print("姓名: \(stu.name)")
print("奋笔疾书答案")
print("提交试卷")
}
}
}
let stu = LazyStudent(name: "王大锤")
let gun = Gunman(name: "骆昊")
gun.target = stu
gun.answerTheQuestion()
委托回调模式讲解
protocol ExamDelegate: class {
func answerTheQuestion()
}
class LazyStudent {
var name: String
weak var delegate: ExamDelegate?
init(name: String) {
self.name = name
}
func joinExam() {
print("姓名: \(name)")
delegate?.answerTheQuestion()
}
}
class Gunman: ExamDelegate {
func answerTheQuestion() {
print("奋笔疾书各种答案")
}
}
let stu = LazyStudent(name: "王大锤")
let gun = Gunman()
stu.delegate = gun
stu.joinExam()
字符串中各个数字或字母的获取
extension String {
var length: UInt32 {
get { return UInt32(self.characters.count) }
}
subscript(index: Int) -> Character {
get { return self[self.startIndex.advancedBy(index)] }
}
}
func randomInt(min: UInt32, _ max: UInt32) -> Int {
return Int(arc4random_uniform(max - min + 1) + min)
}
func generateVerificationCode(length: Int) -> String {
var code = ""
if length > 0 {
let str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for _ in 0..<length {
code.append(str[randomInt(0, str.length - 1)])
}
}
return code
}
for _ in 1...10 {
print(generateVerificationCode(4))
}