GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Decimal Confusion

Forums > 100 Days of SwiftUI


When I had "cost" as a Double everything was happy,
but when I changed "cost" to Decimal (becuase it's money)
I get errors when I assign a value of 10000.00 to cost.
Isn't decimal a numeric value like Double? Says it doesn't conform.

I'm lost & confused.

import Foundation

protocol Building {
    var rooms: Int { get set}
    var cost: Decimal { get set }
    var agent: String { get set }

    func printSalesSummary(rooms: Int, cost: Decimal, agent: String) 

}

struct House: Building {
    var rooms = 10
    var cost = 10000.00
    var agent = "Jim Jones"

    func printSalesSummary(rooms: Int, cost: Decimal, agent: String) {
        print("Sales Summary: Rooms \(rooms) Cost \(cost) Agent \(agent)")
    }

}

   

Hello,

I understand how frustrating type mismatches can be, especially when dealing with numerical types in Swift.

    var cost1: Decimal = 10000.00 // <- Decimal
    var cost2 = Decimal(10000.00) // <- Decimal
    var cost3 = 10000.00 // <- Double

You will be working with Decimal in Project 10, maybe it can help you understand more?

1      

Do this:

var cost = Decimal(10000.00)

Question: Why does your printSalesSummary method take arguments? Isn't it supposed to be printing the properties of the particular House instance it is called on? You wouldn't want to have to pass in the values every time you call it, nor would you want to be able to print out random values passed in that aren't the values held by a particular House instance.

   

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.