Инициализатор 'init (_ :)' требует, чтобы 'Decimal' соответствовал 'BinaryInteger' - PullRequest
0 голосов
/ 08 апреля 2020

Я пытаюсь создать приложение калькулятора сложных процентов, и я получаю эту ошибку, когда возвращаю формулу сложного процента -> Инициализатор 'init (_ :)' требует, чтобы 'Decimal' соответствовал 'BinaryInteger'

Ошибка возникает при реализации формулы сложного процента: возвратный баланс * pow ((1 + ставка / 100), Int (mounths))

struct CompoundView: View {
@State var accountBalance: Decimal?
@State var percentagePerMounth: Decimal?
@State var numberOfMounths: Decimal?

@State var totalCompoundInterest = " "

var total: Decimal {
    guard let balance = self.accountBalance, let rate = self.percentagePerMounth, let mounths = self.numberOfMounths else {
        return 0
    }
    return balance * pow((1 + rate / 100), Int(mounths))
}

// Currency Formater
static var currencyFormatter: NumberFormatter {
    let nf = NumberFormatter()
    nf.numberStyle = .currency
    nf.isLenient = true
    return nf
}

// Percent Formatter
static var percentFormatter: NumberFormatter {
    let nf = NumberFormatter()
    nf.numberStyle = .percent
    // preserve input as-is, otherwise 10 becomes 0.1, which makes
    // sense but is less intuitive for input
    nf.multiplier = 1
    nf.isLenient = true
    return nf
}

// Months Formatter
static var monthsFormatter: NumberFormatter {
    let nf = NumberFormatter()
    nf.numberStyle = .decimal
    nf.isLenient = true
    return nf
}

// Compound Interest View
var body: some View {

    VStack {
        HStack {
            Text("Start Balance")
                .font(.subheadline)
                .padding(.vertical)
            Spacer()
            DecimalField("$0.00", value: $accountBalance, formatter: Self.currencyFormatter)
                .keyboardType(.decimalPad)
                .font(.largeTitle)
                .multilineTextAlignment(.trailing)
        }
        .foregroundColor(.white)
        Divider().background(Color.white)

        HStack {
            Text("Percentage per month")
                .font(.subheadline)
                .padding(.vertical)
            Spacer()
            DecimalField("0%", value: $percentagePerMounth, formatter: Self.percentFormatter)
                .keyboardType(.decimalPad)
                .font(.largeTitle)
                .multilineTextAlignment(.trailing)
        }
        .foregroundColor(.white)
        Divider().background(Color.white)

        HStack {
            Text("Number of months")
                .font(.subheadline)
                .padding(.vertical)
            Spacer()
            DecimalField("0", value: $numberOfMounths, formatter: Self.monthsFormatter)
                .keyboardType(.decimalPad)
                .font(.largeTitle)
                .multilineTextAlignment(.trailing)
        }
        .foregroundColor(.white)
        Divider().background(Color.white)

        // Calculate Button
        Button(action: {
            hideKeyboard()
            self.totalCompoundInterest = Self.currencyFormatter.string(for: self.total)!

        }) {
            Text("Calculate")
                .font(.body)
                .foregroundColor(Color.white)
        }

        Text(self.totalCompoundInterest)
            .foregroundColor(.white)
            .font(.largeTitle)
            .padding()

        Spacer()
    }
} 

}

1 Ответ

1 голос
/ 08 апреля 2020

Вам необходимо правильно преобразовать mounths в Int. Вот так:

Int(truncating: mounths as NSNumber))

Итак, ваша последняя строка в init будет выглядеть так:

return balance * pow((1 + rate / 100), Int(truncating: mounths as NSNumber))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...