Mobile App Dev 2022W: Tutorial 2

From Soma-notes
Revision as of 05:28, 19 January 2022 by Soma (talk | contribs) (Created page with "==Code== <syntaxhighlight lang="swift" line> // // ContentView.swift for textanalyzer-1 // // Created by Anil Somayaji on 2022-01-19. // import SwiftUI struct ContentView...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Code

//
//  ContentView.swift for textanalyzer-1
//
//  Created by Anil Somayaji on 2022-01-19.
//

import SwiftUI

struct ContentView: View {
    @State private var t = ""
    @State private var analysisMode = "Count"
    var body: some View {
        VStack{
            Text("Text Analyzer").bold().padding()
            TextField("Enter Text", text: $t).padding()
            Text(analysisMode + ": " + analysis[analysisMode]!(t)).padding()
            ModeMenu(analysisMode: $analysisMode)
        }
    }
}

struct ModeMenu: View {
    @Binding var analysisMode: String

    var body: some View {
        let availModes = [String](analysis.keys)

        Menu("Analysis menu") {
            ForEach(availModes, id: \.self) {
                mode in
                Button(mode, action: {
                    analysisMode = mode;
                })
            }
        }

    }
}

func countUpper(_ s: String) -> String {
    var count = 0;
    let upperCase: Set<Character> =
    ["A","B","C","D","E","F","G","H","I","J","K","L","M",
     "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    
    for c in s {
        if (upperCase.contains(c)) {
            count += 1;
        }
    }
    
    return String(count);
}

let analysis: [String: (String) -> String] = [
    "Count": {s in return String(s.count)},
    "Upper Case": countUpper
]

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}