我试图通过if条件让字符串属性显示不同的语言。最后一个语句显示错误!我如何获得会员价值?
struct EN {
let hello = "Hello!"
}
struct CN {
let hello = "Hi!"
}
var stringObj:Any?
var language = "CN"
if language == "EN" {
stringObj = EN()
}
if language == "CN" {
stringObj = CN()
}
print(stringObj!) // "CN(hello: "Hi!")\n" on playground
print(stringObj!.hello) // error! has no member "hello"
答案 0 :(得分:3)
当您使用类型function findBiggestFraction( a , b ) {
a > b ? console.log("a: ", a): ("b: ", b);
}
var firstFraction = 3/4;
var secondFraction = 5/7;
findBiggestFraction(firstFraction, secondFraction); // a: 0.75
findBiggestFraction(7/16, 13/25); // b: 0.52
findBiggestFraction(1/2, 3/4); // a: 0.75
function findBiggestFraction( a , b ) {
if (a > b) {
console.log("a: ", a);
} else {
console.log("b: ", b);
}
}
var firstFraction = 3/4;
var secondFraction = 5/7;
findBiggestFraction(firstFraction, secondFraction); // a: 0.75
findBiggestFraction(7/16, 13/25); // b: 0.52
findBiggestFraction(1/2, 3/4); // a: 0.75
声明stringObj
时,Swift编译器不知道它的实际类型是什么或它具有什么属性。
如果Any?
和CN
这两种类型都有公共属性,您可以使用协议来指定:
EN