【Xcode/SwiftUI】2進数 ⇆ 10進数コンバーターを作ってみる

実装

import SwiftUI

struct ContentView: View {
    @State private var input = ""
    @State private var output = ""
    @State private var isBinaryToDecimal = false

    var body: some View {
        VStack(spacing: 20) {
            Text(isBinaryToDecimal ? "Decimal to Binary" : "Binary to Decimal")
                .font(.system(size: 20))
                .bold()
                .padding()

            Toggle("Convert Mode", isOn: $isBinaryToDecimal)
                .font(.system(size: 20))
                .bold()
                .padding()

            TextField(isBinaryToDecimal ? "Enter Decimal Number" : "Enter Binary Number", text: $input)
                .font(.system(size: 20))
                .bold()
                .padding()
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(Color.black, lineWidth: 1)
                )
                .padding()
                .keyboardType(isBinaryToDecimal ? .decimalPad : .numberPad)

            Button("Convert", action: convert)
                .font(.system(size: 24))
                .bold()
                .frame(width: UIScreen.main.bounds.width / 1.3, height: UIScreen.main.bounds.height / 28, alignment: .center)
                .padding()
                .foregroundColor(.white)
                .background(.orange)
                .clipShape(RoundedRectangle(cornerRadius: 27))
                .padding()

            Text(isBinaryToDecimal ? "Binary Result:" : "Decimal Result:")
                .font(.system(size: 20))
                .bold()

            Text(output)
                .font(.system(size: 28))
                .bold()
                .padding()

            Spacer()
        }
        .onChange(of: isBinaryToDecimal) { _ in
            input = ""
            output = ""
        }
        .padding()
    }

    private func convert() {
        if isBinaryToDecimal {
            if let decimalValue = Int(input) {
                output = String(decimalValue, radix: 2)
            } else {
                output = "Invalid Input"
            }
        } else {
            if let binaryValue = Int(input, radix: 2) {
                output = String(binaryValue)
            } else {
                output = "Invalid Input"
            }
        }
    }
}

この記事は役に立ちましたか?

はい
いいえ
貴重なフィードバックありがとうございます!