例如,我们有Java代码如下;
enum Job {
NINJA(3000000){
public void attack() {
//use Shuriken
}
},
SAMURAI(4000000){
public void attack() {
//use Sword
}
};
public final int salary;
public abstract void attack();
private Job(int salary) {
this.salary = salary;
}
}
Run Code Online (Sandbox Code Playgroud)
在Swift中,我认为我们不能定义构造函数并且有任何枚举方法.
我发现在下面的Swift代码中我们可以有类似的结构,但是没有任何方法.
class Job {
class Store {
let salary : Int
init(int salary) {
self.salary = salary
}
}
class var NINJA: Store{
return Store(3000000)
}
class var SAMURAI: Store{
return Store(4000000)
}
}
// Job.NINJA.salary
Run Code Online (Sandbox Code Playgroud)
当然,我知道Swift枚举可以拥有自己的属性.
但是如果在下列情况下你有更多的属性,我们必须在每个属性上有这么多的开关.我认为这不聪明.
enum Job {
var salary: Int{
switch self{
case NINJA:
return 3000000
case SAMURAI:
return 4000000
}
}
case NINJA
case SAMURAI
}
Run Code Online (Sandbox Code Playgroud)
所以,如果你是我,在这种情况下你如何编写Swift代码?
以下是如何Job
在 Swift 中调整类,使其表现得像enum
在 Java 中一样:
class Job {
class Store: Equatable {
let salary: Int
@private init(_ salary:Int) { // hope Swift will have private accessors one day
self.salary = salary
}
func atack() ->() {}
}
class var NINJA: Store {
class Ninja: Store {
override func atack() ->() {
println("Attack with shuriken.")
}
}
return Ninja(3000000)
}
class var SAMURAY: Store {
class Samuray: Store {
override func atack() ->() {
println("Attack with sword.")
}
}
return Samuray(4000000)
}
class func CUSTOM(salary: Int) -> Store {
return Store(salary)
}
}
func == (lhs: Job.Store, rhs: Job.Store) -> Bool {
return lhs.salary == rhs.salary
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
var ninja = Job.NINJA
var samuray = Job.SAMURAY
var custom = Job.CUSTOM(23)
if (ninja == samuray) {
println("Impossible")
} else {
println("OK")
}
if (ninja == Job.NINJA) {
println("Ninja salary: \(ninja.salary)")
} else {
println("Impossible")
}
println("Object salary: \(Job.SAMURAY.salary)")
samuray.atack()
Run Code Online (Sandbox Code Playgroud)
操场上的输出:
好的
忍者工资:3000000
对象薪资:400万
用剑攻击。
顺便说一句:如果您需要比较工资值,您可以Comparable
在类中实现接口Store
。对于排序很有用。
归档时间: |
|
查看次数: |
4002 次 |
最近记录: |