Reputation: 137
let roomSize = "medium"
let sofasize = "large"
if roomSize == "large" {
print ("can fit")
} else if roomSize == "medium" && ( sofasize == "medium" || sofasize == "small") {
print ("can fit")
} else if roomSize == "small" && sofasize == "small" {
print ("can fit")
} else {
print("nope, cannot fit")
}
What is the optimal way to format this program in swift?
Upvotes: 0
Views: 65
Reputation: 386018
Well, “best” and “optimal” are subjective. My recommendation is to avoid stringly-typed programming. Use an enum
.
I assume you'll get strings like "small"
and "large"
from an external source (maybe some JSON). If you make the enum
using String
as its raw value, it can parse the strings for you. Then you can add a rank
property of some Comparable
type like Int
or Double
, and use the rank
to make the enum
itself Comparable
.
enum Size: String {
case small
case medium
case large
}
extension Size: Comparable {
var rank: Int {
switch self {
case .small: return 0
case .medium: return 1
case .large: return 2
}
}
static func ==(_ a: Size, _ b: Size) -> Bool { return a.rank == b.rank }
static func <(_ a: Size, _ b: Size) -> Bool { return a.rank < b.rank }
}
if let roomSize = Size(rawValue: "medium"), let sofaSize = Size(rawValue: "large") {
if roomSize >= sofaSize {
print("if it fits, I sits")
} else {
print("if the sofa don't fit, you must acquit")
}
} else {
print("what is this I don't even")
}
Upvotes: 4
Reputation: 24031
one of the possible ideas:
enum MySize: Int {
case small = 1, medium = 2, large = 3
}
let myRoomSize: MySize = .medium
let mySofaSize: MySize = .large
if mySofaSize.rawValue <= myRoomSize.rawValue {
debugPrint("can fit")
} else {
debugPrint("nope, cannot fit")
}
but... I think that other concepts are completely valid too.
Upvotes: 1