Swift and JavaScript comparison snippets - Classes

unbug

unbug

Posted on August 30, 2019

Swift and JavaScript comparison snippets - Classes

GitHub: https://github.com/unbug/sj

Classes

Swift

// class definition
class Counter {
    var count = 0
    func increment() {
        count += 1
    }
    func increment(by amount: Int) {
        count += amount
    }
    func reset() {
        count = 0
    }
}

// class instance
let counter = Counter()
// the initial count value is 0
counter.increment()
// the count's value is now 1
counter.increment(by: 5)
// the count's value is now 6
counter.reset()
// the count's value is now 0

print("The count property value is \(counter.count)")

JavaScript

// class definition
class Counter {
    contructor() {
        this.count = 0
    }
    function increment() {
        this.count += 1
    }
    function increment(amount) {
        this.count += amount
    }
    function reset() {
        this.count = 0
    }
}

// class instance
let counter = Counter()
// the initial count value is 0
counter.increment()
// the count's value is now 1
counter.increment(5)
// the count's value is now 6
counter.reset()
// the count's value is now 0

console.log(`The count property value is ${counter.count}`)
💖 💪 🙅 🚩
unbug
unbug

Posted on August 30, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related