//
// AnyObjectType.swift
// SwiftCode
//
// Created by Alisa on 2022/4/12.
// Copyright © 2022 Alisa. All rights reserved.
//
import Foundation
/*
在实际开发中,开发者经常会使用一些通用类型。例如在ios的Cocoa框架中,NSObject类是大部分类的基类,在Objective-C语言中,使用id类型来描述通用的对象类型,在某些情况下,使用通用类型将为开发带来很大的方便
在Swift中,通用类型有两种:AnyObject、Any
** AnyObject
AnyObject来作为引用类型的通用类型,它不可以用来描述值的类型。比如不可以用于结构体、枚举等
** Any
Any可以用来描述任意类型,包括值类型和引用类型
*/
//枚举:门店的类型
enum StoreType{
case Food
case Daily
case Other
}
//结构体:门店的牌子
struct Brand{
var color:String
let hasLamp:Bool
let type:StoreType
//展示晚上的灯光效果
func showTheNightStyle(){
print("showTheNightStyle, the color is: \(self.color)")
}
}
class Street{
var stores:Array<AnyObject> //这里使用AnyObject来定义数组中每个元素为引用的通用类型
init() {
self.stores = []
}
deinit{
print("Street Deinit!")
}
}
class FoodStore{
var name:String
init() {
self.name = "Food Store"
}
deinit{
print("FoodStoren Deinit!")
}
}
class DailyExpensesStore{
var name:String
init() {
self.name = "Daily Expenses Store"
}
deinit{
print("DailyExpensesStore Deinit!")
}
}
class AnyObjectType{
//AnyObject通用类型的使用
func useAnyObject(){
let f_store = FoodStore()
let de_store = DailyExpensesStore()
let street = Street()
street.stores.append(f_store)
street.stores.append(de_store)
street.stores.append(de_store)
street.stores.append(f_store)
for storeOne in street.stores{
if storeOne is DailyExpensesStore{
print("current store type is DelayedExecution")
}
if storeOne is FoodStore{
print("current store type is FoodStore")
}
}
/* 打印信息:
current store type is FoodStore
current store type is DelayedExecution
current store type is DelayedExecution
current store type is FoodStore
Street Deinit!
DailyExpensesStore Deinit!
FoodStoren Deinit!
*/
}
//Any通用类型的使用
func useAny(){
let f_store = FoodStore()
let de_store = DailyExpensesStore()
let street = Street()
let brandOne = Brand(color: "yellow", hasLamp: true, type: StoreType.Food)
let brandTwo = Brand(color: "blue", hasLamp: false, type: StoreType.Food)
let typeOne = StoreType.Daily
let typeTwo = StoreType.Other
let things:Array<Any> = [f_store, de_store, street, brandTwo, brandOne, typeOne, typeTwo]
for one in things{
if one is FoodStore{
print("FoodStore!")
}
if one is Street{
print("Street!")
}
if one is Brand{
print("Brand")
let oneThing:Brand = one as! Brand
oneThing.showTheNightStyle()
}
if one is StoreType{
let oneThing:StoreType = one as! StoreType
print("this store type is: \(oneThing)")
}
}
/* 打印信息:
FoodStore!
Street!
Brand
showTheNightStyle, the color is: blue
Brand
showTheNightStyle, the color is: yellow
this store type is: Daily
this store type is: Other
Street Deinit!
DailyExpensesStore Deinit!
FoodStoren Deinit!
*/
}
}
03-16
1339
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)