Swift Misc Operators
Special purpose operators in Swift
🔧 What are Misc Operators?
Miscellaneous operators in Swift include special-purpose operators like nil-coalescing (??), ternary conditional (?:), identity operators (===, !==), and pattern matching operators for specific programming scenarios and convenience operations.
// Nil-coalescing operator
let name = optionalName ?? "Unknown"
// Ternary operator
let result = condition ? "Yes" : "No"
Types of Misc Operators
Nil-Coalescing
Provides default value for optionals
let name = optional ?? "Default"
Ternary Conditional
Shorthand if-else statement
let result = condition ? "Yes" : "No"
Identity Operators
Check if objects are identical
obj1 === obj2 // Same instance
obj1 !== obj2 // Different instance
Pattern Match
Used in switch statements
1...5 ~= 3 // true
"a"..."z" ~= "m" // true
🔹 Nil-Coalescing Operator (??)
The nil-coalescing operator provides a default value when an optional is nil:
// Basic usage
var optionalName: String? = nil
let displayName = optionalName ?? "Guest"
print("Hello, \(displayName)!") // Output: Hello, Guest!
// With non-nil value
optionalName = "Alice"
let displayName2 = optionalName ?? "Guest"
print("Hello, \(displayName2)!") // Output: Hello, Alice!
// Chaining nil-coalescing
let firstName: String? = nil
let lastName: String? = nil
let nickname: String? = "Ace"
let name = firstName ?? lastName ?? nickname ?? "Anonymous"
print("Name: \(name)") // Output: Name: Ace
Output:
Hello, Alice!
Name: Ace
🔹 Ternary Conditional Operator (?:)
The ternary operator is a shorthand for simple if-else statements:
// Basic ternary operator
let age = 18
let status = age >= 18 ? "Adult" : "Minor"
print("Status: \(status)") // Output: Status: Adult
// Comparing with if-else
let score = 85
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"
print("Grade: \(grade)") // Output: Grade: B
// In function calls
func getDiscount(isMember: Bool) -> Double {
return isMember ? 0.15 : 0.05
}
let memberDiscount = getDiscount(isMember: true)
let regularDiscount = getDiscount(isMember: false)
print("Member: \(memberDiscount), Regular: \(regularDiscount)") // Output: Member: 0.15, Regular: 0.05
Output:
Grade: B
Member: 0.15, Regular: 0.05
🔹 Identity Operators (=== and !==)
Identity operators check if two references point to the same instance:
// Class for demonstration
class Person {
let name: String
init(name: String) {
self.name = name
}
}
let person1 = Person(name: "John")
let person2 = Person(name: "John")
let person3 = person1
// Identity comparison
print(person1 === person2) // Output: false (different instances)
print(person1 === person3) // Output: true (same instance)
print(person1 !== person2) // Output: true (not identical)
// Equality vs Identity
print(person1.name == person2.name) // Output: true (same content)
print(person1 === person2) // Output: false (different objects)
Output:
true
true
true
false
🔹 Pattern Matching Operator (~=)
The pattern matching operator is used internally by switch statements:
// Range pattern matching
let number = 42
let inRange = 1...50 ~= number
print("42 is in range 1...50: \(inRange)") // Output: 42 is in range 1...50: true
// Character range matching
let letter = "m"
let isLowercase = "a"..."z" ~= letter
print("'m' is lowercase: \(isLowercase)") // Output: 'm' is lowercase: true
// Using in switch statements (implicit ~=)
let grade = 85
switch grade {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
default:
print("Below C")
}
// Output: B
// Custom pattern matching
func ~= (pattern: String, value: String) -> Bool {
return value.lowercased().contains(pattern.lowercased())
}
let text = "Hello World"
switch text {
case "hello":
print("Contains hello")
case "world":
print("Contains world")
default:
print("No match")
}
// Output: Contains hello
Output:
'm' is lowercase: true
B
Contains hello
🔹 Practical Examples
Real-world usage of miscellaneous operators:
// User profile with optional data
struct UserProfile {
let username: String
let email: String?
let age: Int?
let isVerified: Bool
}
let user = UserProfile(username: "john_doe", email: nil, age: 25, isVerified: true)
// Using nil-coalescing for display
let displayEmail = user.email ?? "No email provided"
let displayAge = user.age != nil ? "\(user.age!) years old" : "Age not specified"
let verificationStatus = user.isVerified ? "✓ Verified" : "⚠Not verified"
print("User: \(user.username)")
print("Email: \(displayEmail)")
print("Age: \(displayAge)")
print("Status: \(verificationStatus)")
// Grade calculator with ternary operators
func calculateGrade(score: Int) -> String {
return score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" : "F"
}
let studentScore = 87
print("Grade: \(calculateGrade(score: studentScore))") // Output: Grade: B
Output:
Email: No email provided
Age: 25 years old
Status: ✓ Verified
Grade: B