Swift中添加了两种类型别名
Any:可表示随意类型,(Int、Double等值类型)。
AnyObject:可表示随意class类型实例, 一个不论什么对象类型的数组
Any类型:
class Calculate
{
var NumberA:Any!
var NumberB:Any!
init(Numbera:Any,Numberb:Any)
{
self.NumberA=Numbera
self.NumberB=Numberb
}
func douberNumberAdd()->Any!
{
var Result:Any!
if((NumberA as? Int) != nil && (NumberB as? Int) != nil)
{
var A=NumberA as? Int
var B=NumberB as? Int
var Result:Int
Result=A!+B!
return Result
}
var A=NumberA as? Double
var B=NumberB as? Double
var Resul:Double
Resul=A!+B!
return Resul
}
}
var a1=Calculate(Numbera: 10, Numberb: 10)
var b1=a1.douberNumberAdd()
print("(b1)")
var a2=Calculate(Numbera: 10.00011, Numberb: 10.00011)
var b2=a2.douberNumberAdd()
print("(b2)")
输出值:
20
20.00022
上面用到了Any类型实现了同一个函数方法能够使用Int类型的參数或Double类型的參数,在函数实现内部运用as?推断详细的參数类型。调用该调用的方法。
AnyObject类型
AnyObject类型相似于Object-C中的id类型,能够用AnyObject类型取代随意class类型。
结合上面的代码运用AnyObject
var anyObjectArray:[AnyObject]=[
Calculate(Numbera: 10.00011, Numberb: 10.00011),
Calculate(Numbera: 10, Numberb: 10) ]
for anyObject in anyObjectArray
{
let anyobj=anyObject as? Calculate
print("NumberA:(anyobj!.NumberA),NumberB:(anyobj!.NumberB)")
}
输出值:
NumberA:10.00011,NumberB:10.00011
NumberA:10,NumberB:10