Mobile Dev

Swift vs Kotlin: Ngôn Ngữ Nào Cho Native Mobile Development?

So sánh chi tiết Swift và Kotlin - hai ngôn ngữ hiện đại nhất cho phát triển ứng dụng iOS và Android native

9 phút đọc
NhiTuyen Tech Blog Team
Swift vs Kotlin: Ngôn Ngữ Nào Cho Native Mobile Development?

Swift vs Kotlin: Chọn Ngôn Ngữ Nào?

Khi quyết định làm native mobile development, bạn sẽ gặp hai ngôn ngữ hiện đại nhất: Swift cho iOS và Kotlin cho Android. Cả hai đều rất tốt, nhưng có gì khác nhau? Hãy cùng tìm hiểu!

Swift vs Kotlin

Giới Thiệu

Swift - Ngôn Ngữ Của Apple

Chú thích: Swift ra đời năm 2014, thay thế Objective-C để làm cho iOS development dễ dàng và an toàn hơn.

  • 🍎 Chính thức từ Apple
  • ⚡ Performance gần như C/C++
  • 🛡️ Type-safe và memory-safe
  • 📱 Cho iOS, macOS, watchOS, tvOS
// Swift - Clean và Modern
import SwiftUI

struct ContentView: View {
    @State private var count = 0
    
    var body: some View {
        VStack {
            Text("Đếm: \(count)")
                .font(.largeTitle)
            
            Button("Tăng") {
                count += 1
            }
            .buttonStyle(.borderedProminent)
        }
        .padding()
    }
}

// SwiftUI - Declarative UI! 🎨

Kotlin - Ngôn Ngữ Của Google

Chú thích: Kotlin ra đời năm 2011 bởi JetBrains, Google chọn làm ngôn ngữ chính thức cho Android từ 2017.

  • 🤖 Official cho Android
  • ☕ Interop hoàn toàn với Java
  • 🚀 Concise và expressive
  • 🌐 Multiplatform (KMM)
// Kotlin - Concise và Powerful
import androidx.compose.runtime.*
import androidx.compose.material3.*
import androidx.compose.foundation.layout.*

@Composable
fun ContentView() {
    var count by remember { mutableStateOf(0) }
    
    Column(
        modifier = Modifier.padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Đếm: $count",
            style = MaterialTheme.typography.headlineLarge
        )
        
        Button(onClick = { count++ }) {
            Text("Tăng")
        }
    }
}

// Jetpack Compose - Declarative UI! 🎨

Android Development

Syntax Comparison

Variables & Constants

// Swift
let constant = "Không đổi"      // let = constant
var variable = "Có thể đổi"      // var = variable

var name: String = "John"        // Explicit type
var age = 25                     // Type inference

// Optionals - Xử lý nil an toàn
var email: String? = nil
if let email = email {
    print("Email: \(email)")
}
// Kotlin
val constant = "Không đổi"      // val = constant (value)
var variable = "Có thể đổi"     // var = variable

var name: String = "John"       // Explicit type
var age = 25                    // Type inference

// Nullability - Xử lý null an toàn
var email: String? = null
email?.let {
    println("Email: $it")
}

Chú thích: Cả hai đều có null safety built-in, giúp tránh crash do null pointer!

Functions

// Swift
func greet(name: String, age: Int = 18) -> String {
    return "Xin chào \(name), \(age) tuổi"
}

// Trailing closure
func performTask(completion: () -> Void) {
    // Do work
    completion()
}

performTask {
    print("Done!")
}

// Multiple return values
func minMax(numbers: [Int]) -> (min: Int, max: Int) {
    return (numbers.min()!, numbers.max()!)
}
// Kotlin
fun greet(name: String, age: Int = 18): String {
    return "Xin chào $name, $age tuổi"
}

// Lambda
fun performTask(completion: () -> Unit) {
    // Do work
    completion()
}

performTask {
    println("Done!")
}

// Destructuring
data class MinMax(val min: Int, val max: Int)
fun minMax(numbers: List<Int>): MinMax {
    return MinMax(numbers.minOrNull()!!, numbers.maxOrNull()!!)
}
val (min, max) = minMax(listOf(1, 2, 3))

Code Comparison

Classes & Structs

// Swift - Classes và Structs
struct User {  // Value type
    var name: String
    var age: Int
}

class ViewController: UIViewController {  // Reference type
    var user: User?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    private func setupUI() {
        // Setup views
    }
}

// Protocol (Interface)
protocol Drawable {
    func draw()
}

extension ViewController: Drawable {
    func draw() {
        // Implementation
    }
}
// Kotlin - Classes
data class User(  // Data class - auto toString, equals, copy
    var name: String,
    var age: Int
)

class MainActivity : AppCompatActivity() {
    private var user: User? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setupUI()
    }
    
    private fun setupUI() {
        // Setup views
    }
}

// Interface
interface Drawable {
    fun draw()
}

class MainActivity : AppCompatActivity(), Drawable {
    override fun draw() {
        // Implementation
    }
}

Collections

// Swift
var fruits = ["Táo", "Chuối", "Cam"]  // Array
fruits.append("Xoài")

var scores = ["John": 95, "Jane": 87]  // Dictionary
scores["Bob"] = 92

// Map, filter, reduce
let evenNumbers = [1, 2, 3, 4, 5].filter { $0 % 2 == 0 }
let doubled = evenNumbers.map { $0 * 2 }
let sum = doubled.reduce(0, +)

// For loop
for (index, fruit) in fruits.enumerated() {
    print("\(index): \(fruit)")
}
// Kotlin
val fruits = mutableListOf("Táo", "Chuối", "Cam")  // List
fruits.add("Xoài")

val scores = mutableMapOf("John" to 95, "Jane" to 87)  // Map
scores["Bob"] = 92

// Map, filter, reduce
val evenNumbers = listOf(1, 2, 3, 4, 5).filter { it % 2 == 0 }
val doubled = evenNumbers.map { it * 2 }
val sum = doubled.reduce { acc, i -> acc + i }

// For loop
fruits.forEachIndexed { index, fruit ->
    println("$index: $fruit")
}

Collections

Async Programming

Swift - async/await

Chú thích: Swift 5.5+ có async/await native, giống JavaScript!

// Swift Concurrency
func fetchUser(id: Int) async throws -> User {
    let url = URL(string: "https://api.com/users/\(id)")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode(User.self, from: data)
}

// Sử dụng
Task {
    do {
        let user = try await fetchUser(id: 1)
        print("User: \(user.name)")
    } catch {
        print("Error: \(error)")
    }
}

// Parallel tasks
async let user1 = fetchUser(id: 1)
async let user2 = fetchUser(id: 2)

let users = try await [user1, user2]  // Chạy song song! ⚡

Kotlin - Coroutines

Chú thích: Kotlin Coroutines là cách xử lý async mạnh mẽ, lightweight hơn threads.

// Kotlin Coroutines
suspend fun fetchUser(id: Int): User {
    val response = client.get("https://api.com/users/$id")
    return response.body()
}

// Sử dụng
lifecycleScope.launch {
    try {
        val user = fetchUser(1)
        println("User: ${user.name}")
    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}

// Parallel tasks
val users = coroutineScope {
    val user1 = async { fetchUser(1) }
    val user2 = async { fetchUser(2) }
    
    listOf(user1.await(), user2.await())  // Chạy song song! ⚡
}

Async Programming

UI Development

SwiftUI (iOS)

import SwiftUI

struct ProfileView: View {
    @State private var name = ""
    @State private var isFollowing = false
    
    var body: some View {
        VStack(spacing: 20) {
            Image(systemName: "person.circle.fill")
                .resizable()
                .frame(width: 100, height: 100)
                .foregroundColor(.blue)
            
            TextField("Tên", text: $name)
                .textFieldStyle(.roundedBorder)
                .padding(.horizontal)
            
            Toggle("Theo dõi", isOn: $isFollowing)
                .padding(.horizontal)
            
            Button("Lưu") {
                saveProfile()
            }
            .buttonStyle(.borderedProminent)
        }
        .navigationTitle("Hồ sơ")
    }
    
    func saveProfile() {
        // Save logic
        print("Saved: \(name)")
    }
}

// Declarative, reactive UI! 🎨

Jetpack Compose (Android)

import androidx.compose.material3.*
import androidx.compose.runtime.*

@Composable
fun ProfileView() {
    var name by remember { mutableStateOf("") }
    var isFollowing by remember { mutableStateOf(false) }
    
    Column(
        modifier = Modifier.padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp)
    ) {
        Icon(
            imageVector = Icons.Default.Person,
            contentDescription = null,
            modifier = Modifier.size(100.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        
        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text("Tên") }
        )
        
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text("Theo dõi")
            Switch(
                checked = isFollowing,
                onCheckedChange = { isFollowing = it }
            )
        }
        
        Button(onClick = { saveProfile(name) }) {
            Text("Lưu")
        }
    }
}

fun saveProfile(name: String) {
    println("Saved: $name")
}

// Declarative, reactive UI! 🎨

UI Development

Ecosystem & Tools

Swift Ecosystem

// Package Manager: Swift Package Manager
// dependencies: [
//     .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.8.0")
// ]

import Alamofire

// Networking
AF.request("https://api.com/users").responseJSON { response in
    print(response)
}

// Popular Libraries:
// - Alamofire: Networking
// - Kingfisher: Image loading
// - SnapKit: Auto Layout
// - Realm: Database

Kotlin Ecosystem

// Package Manager: Gradle
// implementation 'com.squareup.retrofit2:retrofit:2.9.0'

import retrofit2.*

// Networking
interface ApiService {
    @GET("users")
    suspend fun getUsers(): List<User>
}

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.com/")
    .build()

// Popular Libraries:
// - Retrofit: Networking
// - Coil: Image loading
// - Room: Database
// - Koin: Dependency injection

Development Tools

Performance

Memory Management

// Swift - ARC (Automatic Reference Counting)
class Person {
    var name: String
    weak var bestFriend: Person?  // weak để tránh retain cycle
    
    init(name: String) {
        self.name = name
    }
    
    deinit {
        print("\(name) is being deinitialized")
    }
}

// Memory tự động quản lý! 🎯
// Kotlin - Garbage Collection (JVM)
class Person(val name: String) {
    var bestFriend: Person? = null
    
    protected fun finalize() {
        println("$name is being finalized")
    }
}

// GC tự động dọn dẹp! 🎯

Chú thích: Swift dùng ARC (đếm references), Kotlin dùng GC (quét memory). Cả hai đều tự động!

Testing

Swift Testing

import XCTest

class CalculatorTests: XCTestCase {
    var calculator: Calculator!
    
    override func setUp() {
        super.setUp()
        calculator = Calculator()
    }
    
    func testAddition() {
        let result = calculator.add(2, 3)
        XCTAssertEqual(result, 5, "2 + 3 phải bằng 5")
    }
    
    func testDivisionByZero() {
        XCTAssertThrowsError(try calculator.divide(10, by: 0))
    }
}

// Xcode có UI Testing built-in! ✅

Kotlin Testing

import org.junit.Test
import org.junit.Assert.*
import org.junit.Before

class CalculatorTest {
    private lateinit var calculator: Calculator
    
    @Before
    fun setup() {
        calculator = Calculator()
    }
    
    @Test
    fun `addition should work correctly`() {
        val result = calculator.add(2, 3)
        assertEquals("2 + 3 phải bằng 5", 5, result)
    }
    
    @Test(expected = ArithmeticException::class)
    fun `division by zero should throw exception`() {
        calculator.divide(10, 0)
    }
}

// Android Studio có Espresso cho UI testing! ✅

Testing

Platform Features

Swift - iOS Features

// FaceID / TouchID
import LocalAuthentication

let context = LAContext()
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
                       localizedReason: "Xác thực để tiếp tục") { success, error in
    if success {
        print("Xác thực thành công!")
    }
}

// ARKit - Augmented Reality
import ARKit

let arView = ARView(frame: .zero)
let anchor = AnchorEntity(plane: .horizontal)
arView.scene.addAnchor(anchor)

// HealthKit, Core ML, SiriKit...

Kotlin - Android Features

// Biometric Authentication
import androidx.biometric.BiometricPrompt

val biometricPrompt = BiometricPrompt(this,
    executor,
    object : BiometricPrompt.AuthenticationCallback() {
        override fun onAuthenticationSucceeded(
            result: BiometricPrompt.AuthenticationResult
        ) {
            println("Xác thực thành công!")
        }
    }
)

val promptInfo = BiometricPrompt.PromptInfo.Builder()
    .setTitle("Xác thực")
    .setNegativeButtonText("Hủy")
    .build()

biometricPrompt.authenticate(promptInfo)

// ARCore, ML Kit, Google Pay...

So Sánh Tổng Quan

Tiêu chíSwiftKotlin
Nền tảngiOS, macOS, watchOS, tvOSAndroid, JVM, Native
SyntaxClean, expressiveConcise, pragmatic
Learning CurveMediumEasy (nếu biết Java)
Performance⭐⭐⭐⭐⭐ Native⭐⭐⭐⭐ JVM overhead
Null Safety✅ Optionals✅ Nullable types
Asyncasync/awaitCoroutines
UI FrameworkSwiftUIJetpack Compose
IDEXcode (Mac only)Android Studio (đa nền tảng)
CommunityLớn (iOS dev)Rất lớn (Android + Java)
Job MarketCao (iOS dev)Rất cao (Android dev)

Comparison

Khi Nào Chọn Gì?

Chọn Swift nếu:

  • ✅ Muốn làm iOS developer
  • ✅ Thích Apple ecosystem
  • ✅ Cần performance tối đa
  • ✅ Build app cho iPhone/iPad/Mac

Chọn Kotlin nếu:

  • ✅ Muốn làm Android developer
  • ✅ Đã biết Java
  • ✅ Cần multiplatform (KMM)
  • ✅ Thích open-source ecosystem

Học Cả Hai? 💪

// Swift developer
let me = iOSDeveloper()
me.skills = ["Swift", "SwiftUI", "UIKit"]
// Kotlin developer  
val me = AndroidDeveloper()
me.skills = listOf("Kotlin", "Compose", "Android SDK")

Chú thích: Nếu muốn làm full-stack mobile, học cả hai! Syntax tương tự nhau, học cái thứ 2 rất nhanh.

Full Stack Mobile

Kết Luận

Cả SwiftKotlin đều là ngôn ngữ hiện đại, mạnh mẽ:

  • 🎯 Syntax clean và type-safe
  • ⚡ Performance tốt
  • 🛡️ Null safety built-in
  • 🎨 Declarative UI frameworks
  • 💪 Community support mạnh
// Your choice?
let career = [
    "iOS": "Swift",
    "Android": "Kotlin",
    "Both": "Ultimate Mobile Dev! 🚀"
]

print("Choose your path and start coding! 💻")

Bạn đang học Swift hay Kotlin? Chia sẻ trải nghiệm! 💬

Tags

#Swift #Kotlin #iOS #Android #MobileDevelopment #NativeDevelopment #Programming

Tags:

#Swift #Kotlin #iOS #Android #Native Development #Mobile

Chia sẻ bài viết:

Bài viết liên quan

Bài viết liên quan 1
Bài viết liên quan 2
Bài viết liên quan 3