import UIKit
class ViewController: UIViewController {
@IBOutlet weak var ortalamaLabel: UILabel!
@IBOutlet weak var firstSectionCredit: UITextField!
@IBOutlet weak var firstSectionGrade: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
var firstNumberGrade:Double = 0 //These are my grade variables.
var secondNumberGrade:Double = 0
var sonuc1:Double = 0
@IBAction func calculate(_ sender: Any) {
let ilkKredi = Double(firstSectionCredit.text!)
if let ilkNot = firstSectionGrade.text {
if ilkNot == "AA" {
firstNumberGrade = 4.0
}
if ilkNot == "BA" {
firstNumberGrade = 3.5
}
if ilkNot == "BB" {
firstNumberGrade = 3.0
}
if ilkNot == "CB" {
firstNumberGrade = 2.5
}
if ilkNot == "CC" {
firstNumberGrade = 2.0
}
if ilkNot == "DC" {
firstNumberGrade = 1.5
}
if ilkNot == "DD" {
firstNumberGrade = 1.0
}
if ilkNot == "FF" {
firstNumberGrade = 0
}
sonuc1 = firstNumberGrade * ilkKredi!
//I want to do these process for 8 section.I don want to rewrite all these codes.
I want to make university grade calculator.But it takes too much time and I repeated so much codes.I have 8 section 8 grades and 8 section credits.How can I use easy function to do that.I am beginner in Swift
CodePudding user response:
You may use Enums
.
enum Grade: String {
case AA, BA, BB, CB, CC, DC, DD, FF
var gradeValue: Double {
switch self {
case AA:
return 4.0
case BA:
return 3.5
case BB:
return 3.0
..and so on
}
}
}
if let text = firstSectionGrade.text, let textilkNot = Grade(rawValue: text) {
firstNumberGrade = textilkNot.gradeValue
}
CodePudding user response:
You can condense in an enum
all the related code
enum SectionGrade: String{
case AA
case BA
case BB
case CB
case CC
case DC
case DD
case FF
var grade: Double{
switch self {
case .AA:
return 4.0
case .BA:
return 3.5
case .BB:
return 3.0
case .CB:
return 2.5
case .CC:
return 2.0
case .DC:
return 1.5
case .DD:
return 1.0
case .FF:
return 0
}
}
func sonuc( _ ilkKredi : Double) -> Double{
grade * ilkKredi
}
}
Then just change your if let
if let ilkNot = firstSectionGrade.text, let sectionGrade = SectionGrade(rawValue: ilkNot), let ilkKredi = ilkKredi {
sonuc = sectionGrade.sonuc(ilkKredi)
} else{
// Do something if firstSectionGrade.text == nil or
// if ilkNot's value does not exist in SectionGrade or
// ilkKredi is nil
}