Swift通用类示例
示例
具有类型参数的泛型类Type
class MyGenericClass<Type>{
var value: Type
init(value: Type){
self.value= value
}
func getValue() -> Type{
return self.value
}
func setValue(value: Type){
self.value= value
}
}现在我们可以使用类型参数创建新对象
let myStringGeneric = MyGenericClass<String>(value: "My String Value")
let myIntGeneric = MyGenericClass<Int>(value: 42)
print(myStringGeneric.getValue()) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”"My String Value"
print(myIntGeneric.getValue()) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”42
myStringGeneric.setValue("Another String")
myIntGeneric.setValue(1024)
print(myStringGeneric.getValue()) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”"Another String"
print(myIntGeneric.getValue()) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”1024泛型也可以使用多个类型参数创建
class AnotherGenericClass<TypeOne, TypeTwo, TypeThree>{
var value1: TypeOne
var value2: TypeTwo
var value3: TypeThree
init(value1: TypeOne, value2: TypeTwo, value3: TypeThree){
self.value1 = value1
self.value2 = value2
self.value3 = value3
}
func getValueOne() -> TypeOne{return self.value1}
func getValueTwo() -> TypeTwo{return self.value2}
func getValueThree() -> TypeThree{return self.value3}
}并以相同的方式使用
let myGeneric = AnotherGenericClass<String, Int, Double>(value1: "Value of pi", value2: 3, value3: 3.14159) print(myGeneric.getValueOne() is String) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”true print(myGeneric.getValueTwo() is Int) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”true print(myGeneric.getValueThree() is Double) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”true print(myGeneric.getValueTwo() is String) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”false print(myGeneric.getValueOne()) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”"Value of pi" print(myGeneric.getValueTwo()) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”3 print(myGeneric.getValueThree()) //“pi的值”“pi的值”“另一个字符串”“另一个字符串”“我的字符串值”3.14159
热门推荐
10 女宝宝满月简短祝福语
11 学生小升初祝福语简短励志
12 疫情高考父母祝福语简短
13 同学朋友吃饭祝福语简短
14 搬家寄语祝福语大全简短
15 晦气的生日祝福语简短
16 中考花束祝福语霸气简短
17 生日贺卡手绘祝福语简短
18 广东考试祝福语朋友简短