import Foundation
enum Gender {
case Male
case Famale
}
class Employee {
var id: String
var name: String
var gender: Gender
var tel: String?
weak var dept: Department?
init(id: String, name: String, gender: Gender ) {
self.id = id
self.name = name
self.gender = gender
}
func work() {
print("工号为\(id)的\(name)正在工作")
}
func haveRest() {
print("工号为\(id)的\(name)正在休息")
}
}
import Foundation
class Department {
var id: String
var name: String
var empArray: [Employee] = []
var numberOfEmps: Int {
get { return empArray.count }
}
init(id: String, name: String) {
self.id = id
self.name = name
}
func addEmp(emp: Employee) {
empArray.append(emp)
}
func removeEmp(id: String) -> Bool {
if let index = empArray.indexOf({$0.id == id}) {
empArray.removeAtIndex(index)
return true
}
return false
}
}
import Foundation
func generateArithmeticProgression(starValue: Int, commonDifference: Int, numberOfElements: Int) -> [Int] {
var array = [Int](count: numberOfElements, repeatedValue: 0)
for i in 0..<array.count {
array[i] = starValue + commonDifference * i
}
return array
}
print(generateArithmeticProgression(4, commonDifference: 3, numberOfElements: 4))
import Foundation
func isProgression(array: [Int]) -> Bool {
if array.count > 2 {
let newArray = array.sort(<)
let commonDiff = newArray[1] - newArray[0]
for i in 1..<newArray.count - 1 {
if newArray[i + 1] - newArray[i] != commonDiff {
return false
}
}
}
return true
}
print(isProgression([3, 6, 12, 9, 18]))
import Foundation
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(6))
}
代理法:
import Foundation
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()
委托回调法:
import Foundation
protocol Examinee: class {
func exam()
}
class Student {
var name: String
weak var delegate: QiangShou?
init(name: String) {
self.name = name
}
func sExam() {
print("姓名: \(name)")
delegate?.exam()
}
}
class QiangShou: Examinee {
func exam() {
print("考试必过")
}
}
let stu1 = Student(name: "王大锤")
let gun = QiangShou()
stu1.delegate = gun
stu1.sExam()