//swift恒等运算符
//===恒等,不等!==
//运用这两个运算符检测两个常量或者变量是否引用同一个实例
//“等价于”表示两个类类型(class type)的常量或者变量引用同一个类实例。
//等于”表示两个实例的值“相等”或“相同”,判定时要遵照设计者定义的评判标准,因此相对于“相 等”来说,这是一种更加合适的叫法。
//类和结构体的选择
//属性的存储只能是类或者是结构体
//常量属性
struct FixedLengthRange {
var first: Int
let length: Int
}
var range = FixedLengthRange(first: 5,length: 69)
range.first = 7
//对于常量赋值则不允许
//常量结构体的存储属性
//延迟存储属性:延迟存储属性是指当第一次被调用的时候才会计算其初始值的属性。
class DataImporter {
var fileName = "lihuan.txt"
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()//提供数据管理功能
}
let manager = DataManager()
manager.data.append("some data")
manager.data.append("some more data")
print(manager.importer.fileName)
//存储属性和实例变量
//计算属性
struct Point {
var x = 0.0,y = 0.0
}
struct Size {
var width = 0.0,height = 0.0
}
struct Rect {
var origin = Point()
var size = Size ()
var center:Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x:centerX,y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0,y: 0.0),size:Size(width: 10.0,height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0,y: 15.0)
print("square.origin is now at (\(square.origin.x),\(square.origin.y))")
//只读计算属性,只读计算属性的声明可以去掉get关键字和花括号
struct Cuboid {
var width = 0.0,height = 0.0,depth = 0.0
var volume:Double {
return width*height*depth
}
}
let fourByFiveByTwo = Cuboid(width: 4.0,height: 5.0,depth: 2.0)
print("\(fourByFiveByTwo.volume)")
//属性观察器:属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新的值和现在的值相同的时候也不例外
//可以为除了延迟存储属性之外的其他存储属性添加属性观察器,也可以通过重写属性的方式为继承的属性(包括 存储属性和计算属性)添加属性观察器
// willSet在新的值被设置之前调用,didSet在新的值被设置之后立即调用
class StepCounter {
var totalSteps:Int = 0 {
willSet(newTotalSteps){
print("will set \(newTotalSteps)")
}
didSet{
if totalSteps > oldValue {
print("did set \(totalSteps - oldValue)")
}
}
}
}
let setpCounter = StepCounter()
setpCounter.totalSteps = 200
setpCounter.totalSteps = 360
//全局变量和局部变量
struct SomeStructure {
static var storedTypeProperty = "some value"
static var computedTypeProperty: Int {
return 6
}
}
class SomeClass {
static var storedTypeProperty = "some value"
static var computedTypeProperty: Int {
return 104
}
}
print(SomeStructure.storedTypeProperty)
SomeStructure.storedTypeProperty = "another value"
print(SomeStructure.storedTypeProperty)
print(SomeClass.computedTypeProperty)
//eg
struct AudioChannel {
static let thresholdLevel = 10
static var maxInputLevelForAllChannels = 0
var currentLevel: Int = 0 {
didSet {
if currentLevel > AudioChannel.thresholdLevel {
currentLevel = AudioChannel.thresholdLevel
}
if currentLevel > AudioChannel.maxInputLevelForAllChannels {
AudioChannel.maxInputLevelForAllChannels = currentLevel
}
}
}
}
var leftChannel = AudioChannel()
var rightChannel = AudioChannel()
leftChannel.currentLevel = 7
print(leftChannel.currentLevel)
//方法
class Counter {
//类中定义了三个实例话方法
var count = 0
func increment() {
count += 1
}
func incrementBy(amount:Int) {
self.count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
counter.incrementBy(5)
counter.reset()
print(counter.count)
class CounterTwo {
var count: Int = 0
func incrementBy(amount:Int,numberOfTimes:Int) {
count += amount*numberOfTimes
}
}
//默认的情况下第一个参数被认为是局部名称,第二个参数被认为既可以看作内部也可以看做外部
let counterTwo = CounterTwo()
counterTwo.incrementBy(5,numberOfTimes:9)
print(counterTwo.count)
//self属性
//类型方法调用也是.语法 实例方法是被类型的某个实例调用的方法。你也可以定义类型本身调用的方法,这种方法就叫做类型方法
class SomeOtherClass {
static func someMethod() {
print("类型方法")
}
}
SomeOtherClass.someMethod()
//水平
struct LevelTracker {
static var highestUnlockedLevel = 1
static func unlockLevel(level:Int){
highestUnlockedLevel = level
}
static func levelIsUnlocked(level:Int) -> Bool {
return level <= highestUnlockedLevel
}
var currentLevel = 1
mutating func advanceToLevel(level:Int) -> Bool {
if LevelTracker.levelIsUnlocked(level) {
currentLevel = level
return true
}else {
return false
}
}
}
//监测进度
class Player {
var tracker = LevelTracker()
let playName:String
func completedLevel(level:Int){
LevelTracker.unlockLevel(level + 1)
tracker.advanceToLevel(level + 1)
}
init(name:String) {
playName = name
}
}
var player = Player(name:"lihuan")
if player.tracker.advanceToLevel(6) {
print("player is now on level 6")
}
else{
print("level 6 has not yet been unlocked")
}
//下标脚本下标脚本 可以定义在类(Class)、结构体(structure)和枚举(enumeration)这些目标中,可以认为是访问 集合(collection),列表(list)或序列(sequence的快捷方式,使用下标脚本的索引设置和获取值,不需要 再调用实例的特定的赋值和访问方法。举例来说,用下标脚本访问一个数组(Array)实例中的元素可以这样写 meArray[index],访问字典(Dictionary)实例中的元素可以这样写 someDictionary[key]
//下标脚本语法
//subscript(index:Int) -> Int {
// get{
// //返回与入参匹配的Int类型的值
// }
// set(newValue){
//
// //执行赋值操作
//
//}
//eg
struct TimesTable {
let multiplier:Int
subscript(index:Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
//根据角标找到然后返回
print("3的6倍是\(threeTimesTable[6])")
//下标脚本用法
var numberOfLegs = ["splider":8,"ant":6,"cat":4]
numberOfLegs["bird"] = 2
print(numberOfLegs)
//继承
//基类:不继承其它类的类
class Vehicle {
var currentSpeed = 0.0
var description:String {
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
//
print("我有噪音");
}
}
let someVehicle = Vehicle()
print("vehicle :\(someVehicle.description)")
//子类生成 子类生成(Subclassing)指的是在一个已有类的基础上创建一个新的类
class Bicycle:Vehicle {
//继承父类的子类
var hasBasket = false
}
let bicycle = Bicycle()
bicycle.hasBasket = true;
bicycle.currentSpeed = 15.0
print("vehicle :\(bicycle.description)")
class Tandem: Bicycle {
var currentNumberOfPages = 0
override func makeNoise() {
print("hello")
}
}
let tandem = Tandem()
tandem.hasBasket = true
tandem.currentSpeed = 22.0
print("\(tandem.hasBasket)")
tandem.makeNoise()
//重写属性,防止重写的话天假final
//构造过程
//存储属性的初赋值
//构造器构造器在创建某特定类型的新实例时调用。它的最简形式类似于一个不带任何参数的实例方法,以关键字 init 命 名。
struct Fathreheit {
var temperature :Double
init() {
temperature = 32.0
}
}
var f = Fathreheit()
print("\(f.temperature)")
//默认属性值
//自定义构造过程
原文链接:https://www.f2er.com/swift/323866.html