UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Swift storyboard to swiftui

Forums > SwiftUI

I have an app that was done using swift storyboard. I'm redoing it using swiftui and add additional features. Basically, what the app does is it converts and interprets each character of a string from a textfield and displays the conversion of each character as it is being typed.

I have a separate text for each vowel conversion count, one for consonant conversion count, and another one for total of both.

It looks like this: Vowel Consonant Total 2 6 8

So when a user types, each character being typed will have a display of the combination above plus an interpretation of this combination as another text display.

My challenge is my function involves the textfield value as the main variable. I can get one function to manipulate the input data in the body of the content view. But I need to recalculate it again based on the new result.

I tried creating a dictionary to represent each character/string with an Int so I can add the digits. Is there a way to use this dictionary of String/Character, Int as the key value so I can refer to it and convert it to its value.

For example when a user types a, it will show 1 0 1 because a has a value of 1 and it's a vowel and there's only one a. And 101 will have its own interpretation of what that means in a form of a text.

Is there a better way of doing this? I thought swiftUI makes your app easier to code and shortens the process.

If anyone here thinks this isn't possible, I'd love to know so I can just stick with just using swift. I just like swiftUI but for what I want it to do in this case, I can't seem to make it work which is unfortunate.

Any advise would be very much appreciated.

3      

  1. I think this is along the lines of what you are looking for.
  2. I'm a hack, I think it'll do what you're looking for (with edits in the change text function). Others may come up with better ways to do any item in here.
  3. If you are looking to show both items (what I call textInput and textOutput, just get rid of the ZStacks)
struct ContentView: View {
    @State private var outputShowing = false
    @State private var textInput = ""
    @State private var textOutput = ""

    @State var characterCount = 0

    var body: some View {

        // Goal is to style both the TextField, and the RoundedRectangle the same, so the user doesn't know
        // the difference.  When they click on the textfield, it toggles the Text, which shows what they type
        // only you can edit what comes out when they type keys.  I didn't make these the same look, due to
        // time constraints.

        ZStack {

            TextField("This", text: $textInput, onCommit: {
                self.outputShowing.toggle()
                self.textInput = self.textOutput
            })
            .onReceive(textInput.publisher.collect()) {
                if $0.count > self.characterCount {
                    let newCharacter = $0.last
                    if newCharacter != nil {
                        self.changeText(newLetter: newCharacter!)
                        self.characterCount += 1
                    }
                }
            }
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .onTapGesture {
                    self.outputShowing.toggle()
                }

            .frame(width: 375, height: 50)

            if outputShowing {
                ZStack {
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(Color.black)
                        .background(Color.white)
                        .frame(width: 375, height: 50)
                    Text(textOutput)
                }
            }
        }
    }

    func changeText(newLetter: Character) {
        // Gets one character from the keyboard, do with it what you like.
        // Test takes one character you type, and prints it twice.
        // Hit return to save it as the textfield.

        textOutput = textOutput + String(newLetter) + String (newLetter)
    }
}

3      

Hi Sally, have a look at the below code to see if it suits your needs -

var body: some View {
        VStack(spacing: 20) {
            TextField("Word", text: $word)
            .padding()
                .overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).stroke()
            )

            Text(vowelsAndConsonants(word: word))
                .frame(width: 200, height: 50)
                .background(Color.yellow)
        }
  }

This is just a basic view with a textfield to enter text and a Text View to display the converted text. Unless you need your counts split into 3 text views you can just do it in one like above. If you need the 3 different text views then it would have to be reworked.

Below this view, or somewhere, place the following function -

func vowelsAndConsonants(word: String) -> String {
        let temp = word.lowercased()
        var vowels = 0
        var consanants = 0
        let vos = "aeiou"
        let cons = "bcdfghjklmnpqrstvwxyz"

        for vowel in vos {
            vowels += temp.filter { $0 == vowel }.count
        }

        for consanant in cons {
            consanants += temp.filter { $0 == consanant }.count
        }

        return "\(vowels)\(consanants)\(vowels+consanants)"
    }

This function will be passed the word that is being typed by the user. It will count the number of vowels and consants in the word and then pass them back as a string using string interpolation together with their total.

I know this only addresses the initial problem i cant help with the interpretation of the totals e.g. 1 0 1 to another string without knowing how you want it converted. If you could let me know or post some code to help a little more with this.

Hope this helps,

Dave

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Hi Sally,

Hopefully this answers your question and points you in the right direction but try the following to simplify what you are doing and to head towards achieving what you need -

func deriveVowels(string: String) -> String {
    let vos = ["a":1,"e":5,"i":9,"o":6,"u":3]

    let b = string.compactMap {
        vos[String($0)]
    }

    return String(b.reduce(0, +))
}

So you can use a simple dictionary of the vowels as the keys and their individual values. Just declare it in your function like above. Use the compactMap function on the string passed into the deriveVowels function. The compactMap func will return all non-nil results. What this means if vos[String($0)] (and all we are doing is using each character from the name as the key value to look for) doesn't exist, then it wont return it. At the end you will have an array of Int with the value for each vowel in the vos array.

Then you just use the reduce function with the parameters 0 and + which is saying basically 0 is the starting point and for each value in the Int array i want to add it to 0. At the end you will end up with the total of the values in the int array. Just convert it to String and return it.

This will reduce your code a bit and hopefully it meets your needs. You will have to sort of do the same for the deriveConsants function etc but hopefully this points you in the right direction. Have to let you do some of the work. You could even reduce the above even more by doing the following -

func deriveVowels(string: String) -> String {
    let vos = ["a":1,"e":5,"i":9,"o":6,"u":3]
    return String(string.compactMap { vos[String($0)] }.reduce(0, +))
}

but.. this obviously reduces readability and if your working with a lot of code it might be confusing but ill leave it up to you. I hope this all helps Sally. Dont hesitate to ask anything more. This is one solution and there may be others.

Dave

3      

Just an update and a lil more help the following will be the deriveConstants function (I forgot to the add the .lowercased() on the vowels func but its on the below one) -

private func deriveConsonants(string: String) -> String {
    let cos = [ "j": 1, "s": 1, "b" : 2, "k": 2, "t": 2, "c" : 3, "l": 3, "d" : 4, "m": 4, "v": 4, "n": 5, "w": 5, "f" : 6, "x": 6, "g" : 7, "p": 7, "y": 7, "h" : 8, "q": 8, "z": 8, "r": 9, " ": 0]

    let b = string.lowercased().compactMap {
        cos[String($0)]
    }

    return String(b.reduce(0, +))
}

Dave

3      

To access the deriveVowels function etc you could just create a helper class with static functions like so -

class HelperFunctions {
    public static func deriveConsonants(string: String) -> String {
        let cos = [ "j": 1, "s": 1, "b" : 2, "k": 2, "t": 2, "c" : 3, "l": 3, "d" : 4, "m": 4, "v": 4, "n": 5, "w": 5, "f" : 6, "x": 6, "g" : 7, "p": 7, "y": 7, "h" : 8, "q": 8, "z": 8, "r": 9, " ": 0]

        let b = string.lowercased().compactMap {
            cos[String($0)]
        }

        return String(b.reduce(0, +))
    }

    public static func deriveVowels2(string: String) -> String {
        let vos = ["a":1,"e":5,"i":9,"o":6,"u":3]
        //let a = Array(string)
        let b = string.compactMap {
            vos[String($0)]
        }
        return String(b.reduce(0, +))
    }
}

That way you can call it anywhere within your project like so -

Text(HelperFunctions.deriveVowels2(string: profile.name)) // From your view

// OR from your Profile class like this

consonantsVibration.key = HelperFunctions.deriveConsonants(string: "")

Again there are probably other ways but it may suit what you want.

Dave

3      

Thank you, thank you, thank you so much Dave! I just read this and I'm excited to try it out now. I will let you know how it goes :)

4      

No probs Sally, here to help out. Let me know how you go

3      

Hi Dave,

You are amazing! Thank you once again. I have added new functions to display the raw VCT as the third hstack and underneath to display the interpolation of these three results and reduced to a single digit. I created a keypair value to display the interpretation of VCT but it's not displaying correctly. I have the code below. Is there another way to access a returned variable to create another function? Thank you.


struct ContentView: View {
    @EnvironmentObject var profile: Profile

    var body: some View {
        VStack {
            VStack(spacing: 20) {
                    VStack {
                        Text("Align Your Name With The Higher Vibration")
                        TextField("Enter a Name", text: $profile.name)
                        .padding()
                        .overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).stroke()
                        )
                    }
                HStack {
                    Text(deriveVowels(string: profile.name))
                    Text(deriveConsonants(string: profile.name))
                    Text(deriveRawVCT(string: profile.name))
                }
            }
            Text(deriveNameVibration(string: profile.name))

        }
        }  

 func deriveVowels(string: String) -> String {
        let vos = ["a":1,"e":5,"i":9,"o":6,"u":3]

    let b = string.lowercased().compactMap {
            vos[String($0)]
        }

        return String(b.reduce(0, +))
    }
    private func deriveConsonants(string: String) -> String {
        let cos = [ "j": 1, "s": 1, "b" : 2, "k": 2, "t": 2, "c" : 3, "l": 3, "d" : 4, "m": 4, "v": 4, "n": 5, "w": 5, "f" : 6, "x": 6, "g" : 7, "p": 7, "y": 7, "h" : 8, "q": 8, "z": 8, "r": 9, " ": 0]

        let b = string.lowercased().compactMap {
            cos[String($0)]
        }

        return String(b.reduce(0, +))
    }
    func deriveRawVCT(string: String) -> String {
     let input = profile.name.lowercased()
      let vos = ["a":1,"e":5,"i":9,"o":6,"u":3]
      let cos = [ "j": 1, "s": 1, "b" : 2, "k": 2, "t": 2, "c" : 3, "l": 3, "d" : 4, "m": 4, "v": 4, "n": 5, "w": 5, "f" : 6, "x": 6, "g" : 7, "p": 7, "y": 7, "h" : 8, "q": 8, "z": 8, "r": 9, " ": 0]
     let vowelsTotal = input.compactMap { vos[String($0)] }.reduce(0, +)
        let consonantsTotal = input.compactMap { cos[String($0)] }.reduce(0, +)
     let VCT = String(vowelsTotal + consonantsTotal)
     return VCT
     }
    func deriveNameVibration(string: String) -> String {
        let input = profile.name.lowercased()
        let vos = ["a":1,"e":5,"i":9,"o":6,"u":3]
        let cos = [ "j": 1, "s": 1, "b" : 2, "k": 2, "t": 2, "c" : 3, "l": 3, "d" : 4, "m": 4, "v": 4, "n": 5, "w": 5, "f" : 6, "x": 6, "g" : 7, "p": 7, "y": 7, "h" : 8, "q": 8, "z": 8, "r": 9, " ": 0]
        let V = input.compactMap { vos[String($0)] }.reduce(0, +) % 9
        let C = input.compactMap { cos[String($0)] }.reduce(0, +) % 9
        let rawTotal = (V + C)
        let T = rawTotal % 9
        let VCT = "\(V)\(C)\(T)"
        let interpretation = [
     "022":"This offers a spiritual partnership that can be hard to manage as it doesn't hold a space for self. This is sincere connection to God, source, spirit and can act as a gateway to be the ultimate chameleon in conversation."........ 
     //the rest of the interpretation not pasted
      ]
        let vctInt = VCT.compactMap {
            interpretation[String($0)]
        }
         return String("\(VCT)\(vctInt)")

    }

}

3      

Hi Sally

From what i can see when you run a compactMap on the constant VCT in the deriveNameVibration this is why you might be getting the wrong result. Correct me if I am wrong, but it appears you are attempt to match the VCT string with a key in your interpretation dictionary? If this is the case using compact map on VCT wont work. What the compactMap is doing is iterating through each character in VCT. It is then taking that character and seeing if it matches a key in your interpretation dictionary.

For example... Lets say we had a profile name which ends up with a VCT of "022". From what i can gather it should match against the key "022" in your interpretation dictionary and display the associated text. What will happen is that compactMap will grab "0" first and try and match it with a key and so on. So where you have the following code -

let vctInt = VCT.compactMap {
                interpretation[String($0)]
            }

You want to replace it with this -

guard let vctInt = interpretation[VCT] else { return "No interpretation" }

To access keys values in a dictionary in Swift you simply just access it with 'dictName[key]'. The result returned is an optional because that key may not exist in the dictionary hence why i have used a guard let to safely unwrap and return a default value. So the entire function should look like the following -

func deriveNameVibration(string: String) -> String {
        if var V = Int(deriveVowels(string: string)), var C = Int(deriveConsonants(string: string)) {
            V %= 9; C %= 9
            let rawTotal = V + C
            let T = rawTotal % 9
            let VCT = "\(V)\(C)\(T)"
            let interpretation = [
                "022":"This offers a spiritual partnership that can be hard to manage as it doesn't hold a space for self. This is sincere connection to God, source, spirit and can act as a gateway to be the ultimate chameleon in conversation."
                //the rest of the interpretation not pasted
            ]

            guard let vctInt = interpretation[VCT] else { return "No interpretation" }

            return String("\(VCT)\(vctInt)")
        }
        return "0"
    }

You will notice that the entire function looks a bit different to yours. I have refactored it a little. Its up to you if you choose to do so but this is my reasoning -

  1. The constants vos and cos are used in 4 functions so what I would do is take them out and just declare them outside any struct or class. By themselves. That way you can then access them in any function and they are only declared & initialised once.

  2. In all 4 functions you are getting the total number of vowels or consanants or both. Because you have dedicated functions for those ie deriveVowels & deriveConsanants, we can reuse those functions. I will paste code below so you can see what i mean. So with some refactoring we have the following functions -

func deriveVowels(string: String) -> String {
        let b = string.lowercased().compactMap {
            vos[String($0)]
        }

        return String(b.reduce(0, +))
    }

    private func deriveConsonants(string: String) -> String {
        let b = string.lowercased().compactMap {
            cos[String($0)]
        }

        return String(b.reduce(0, +))
    }

    // In this function i have used a guard let to get the totals for vowels and consants by using the above declared functions.
    // Because those functions return a String we have had to cast the result to an Int. This returns an optional which is why a guard 
    // let has been used to safely do this.
    func deriveRawVCT(string: String) -> String {
        guard let vowelsTotal = Int(deriveVowels(string: string)), let consonantsTotal = Int(deriveConsonants(string: string)) else {
            return "0"
        }

        let VCT = String(vowelsTotal + consonantsTotal)
        return VCT
    }

    // In this function i have used a 'if var' to get the totals for vowels and consants by using the above declared functions.
    // Again because those functions return a String we have had to cast the result to an Int. 
    // The reason for the 'if var' is so we can do the modulus operation within the body to modify the result 
    func deriveNameVibration(string: String) -> String {
        if var V = Int(deriveVowels(string: string)), var C = Int(deriveConsonants(string: string)) {
            V %= 9; C %= 9
            let rawTotal = V + C
            let T = rawTotal % 9
            let VCT = "\(V)\(C)\(T)"
            let interpretation = [
                "022":"This offers a spiritual partnership that can be hard to manage as it doesn't hold a space for self. This is sincere connection to God, source, spirit and can act as a gateway to be the ultimate chameleon in conversation."
                //the rest of the interpretation not pasted
            ]

            guard let vctInt = interpretation[VCT] else { return "No interpretation" }

            return String("\(VCT)\(vctInt)")
        }
        return "0"
    }

Hopefully this does the trick Sally and hope it all makes sense.

Dave

3      

I was trying it out but the second row was giving a 0 result for the VCT. I realized I forgot to add if V > 9 then V = V % 9

I tried to edit the shortcut you gave me so I can add the if statement and I know this might be really simple but I can't seem to put it together properly.

 func deriveVCT(string: String) -> String {
        if let V = Int(deriveVowels(string: string)), let C = Int(deriveConsonants(string: string)) {

        if V > 9 { let V = V % 9

        if C > 9 { let C = C % 9
        let VCT = (V + C)

            }
            return String("\(V)\(C)\(VCT)")
            }
        }
    }

May I offer you a numerology session? I'd love to offer you something as a token of my appreciation.

3      

Hey Sally,

Because you are using a 'if let' you wont be able to change the values of V or C inside that body because they are let constants. If you change the 'if let' to an 'if var' you should be good to go. Like the following -

func deriveVCT(string: String) -> String {
        if var V = Int(deriveVowels(string: string)), var C = Int(deriveConsonants(string: string)) {

        if V > 9 { V %= 9 } // Just using compound assignment operator here. Its like saying V = V % 9
        if C > 9 { C %= 9 }

        let VCT = String(V + C) // I think you left this out in your above snippet

        return String("\(V)\(C)\(VCT)")

        }

        return "Default string value here in case the 'if var' falls through" // Make sure you have this after the 'if var' body. If the above cant convert the return values to Int then this will be returned
}

Hopefull that works. I think you may have got a bit lost with your curly braces with the if statements for checking if V and C are greater than 9.

Wow Sally I really do appreciate the offer but I am happy helping out. I think as programmers we are constantly evolving and learning. It never stops. One of the most valuable tools is helping others because i feel we tend to learn ourselves whilst doing so. I have learnt a lot helping you and others and that in itself is rewarding enough for me :)

Dave

3      

Yes I actually figured it out before you replied and I was just confused with the curly braces and separator. I'm glad you're learning too and I believe that's what makes you a master.

I'm not sure why it's still adding up 1 and 8 as 0 as if it's still being calculated with modulus

3      

Oh im by no means a master Sally. Im flattered though, thankyou.

One thing i find that helps me is to add print statements to your code in areas where your expecting certain results. That way you can follow what is happening and find where the calculation is incorrect.

Give that a go and see what happens

Dave

3      

Sorry I made a mistake with my arithmetic equation. I was able to fix it in case you'd like to see :) I'll go ahead and do the fun part now and finish up my app. If I get stuck, I hope it's ok to ask for help. Thank you thank you thank you Dave. I'm impressed with how short you were able to convert my long swift file to this swiftUI version. The help you give to people will come back to you sevenfolds.

func deriveVCT(string: String) -> String {
            if var V = Int(deriveVowels(string: string)), var C = Int(deriveConsonants(string: string)) {
            if V > 9 { V = (1 + ((V-1) % 9)) }
            if C > 9 { C = (1 + ((C-1) % 9)) }

            var T = V + C
            if T > 9 { T = (1 + ((T-1) % 9)) }

            return String("\(V)\(C)\(T)")

            }

4      

Hey Sally

Good to hear its sorted :) Please let me know how it goes. It was my pleasure helping and thankyou for the kind words. And by all means if you get stuck i will be more than willing to help.

Might i suggest to have a look at Paul's book Swift Coding challenges. There are a lot of challenges that are helpful there that will help you with future coding problems :)

Dave

4      

Thank you. Yes I will do them for sure. I also love watching Paul's videos on youtube. I love supporting other people as well. I will pay it forward.

3      

I've added rating to interpretation. How do I convert return expression of type 'Interpretation' to return type 'String'?

struct Interpretation: Codable {
    var interpretation: String
    var balanced: Balanced
    var love: Int
    var wealth: Int

    enum CodingKeys: String,CodingKey {
        case interpretation
        case balanced
        case love
        case wealth
    }
 func deriveNameVibration(string: String) -> String {
        if var V = Int(deriveVowels(string: string)), var C = Int(deriveConsonants(string: string)) {
            if V > 9 { V = (1 + ((V-1) % 9)) }
            if C > 9 { C = (1 + ((C-1) % 9)) }
            var T = V + C
            if T > 9 { T = (1 + ((T-1) % 9)) }
            let VCT = "\(V)\(C)\(T)"
            let interpretationDictionary: [String : Interpretation] = [
                "000" : Interpretation (interpretation: "The infinite void of the universe. This is an extremely rare combination and usually only shows up when someone does not have a middle name. This is a direct connection to holy and divine and represents a mature soul.", balanced: Balanced.No, love: 0, wealth: 0),
                "011" : Interpretation (interpretation: "The Number 1 represents Leadership, Independence, and Self Awareness. On the positive side, they add up to become leaders and champions, but on the negative side they can be self serving at the cost of others.", balanced: Balanced.No, love: 0, wealth: 0)
                //the rest of the code
                ]
                     guard let vctInt = interpretationDictionary[VCT] else { return "No interpretation" }

            return vctInt
        }
        return "0"
    }

I have this separate loverating file from my previous swift app file with the code below but not sure where the best place to put in swiftui

open class LoveRatingView: UIView {

    // MARK: Properties

    /// Array of empty image views
    private var emptyImage: UIImage!

    private var ratingImageView: UIImageView!

    /// Array of full image views
    private var positiveImages: [UIImage] = []

    /// Array of empty image views
    private var negativeImages: [UIImage] = []

    /// Sets the empty and full image view content mode.
    open var imageContentMode: UIView.ContentMode = UIView.ContentMode.scaleAspectFit

    /// Set the current rating.
    var rating: Double = 0 {
        didSet {
            if rating != oldValue {
                refresh()
            }
        }
    }

    required override public init(frame: CGRect) {
        super.init(frame: frame)

        initImageViews()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        initImageViews()
    }

    // MARK: Helper methods
    private func initImageViews() {
        guard  positiveImages.isEmpty else {
            return
        }

        // Add new image views
        for i in 0..<5 {
            let positiveImage = getPostiveImage(num: i + 1 )
            positiveImages.append(positiveImage)
        }

        for i in 0..<5 {
            let negativeImage = getNegativeImage(num: i + 1 )
            negativeImages.append(negativeImage)
        }

        emptyImage = getEmptyImage()
        ratingImageView = UIImageView(frame: self.frame)
        ratingImageView.contentMode = imageContentMode
        ratingImageView.image = emptyImage
        addSubview(ratingImageView)
    }

    func getPostiveImage(num: Int) -> UIImage {
        let positiveImage = UIImage(named: "Heart \(num).png")
        return positiveImage!
    }

    func getNegativeImage(num: Int) -> UIImage {
        let negativeImage = UIImage(named: "Broken Heart \(num).png")
        return negativeImage!
    }

    func getEmptyImage() -> UIImage {
        let emptyImage = UIImage(named: "emptyrating.png")
        return emptyImage!
    }

    // Refresh hides or shows full images
    private func refresh() {

        if rating > 0 {
            var index = Int(abs(rating) - 1)
            if index > 4 {
                index = 4
            }
            ratingImageView.image = positiveImages[index]
            ratingImageView.layer.mask = nil
            ratingImageView.isHidden = false
        } else if rating < 0 {
            var index = Int(abs(rating)-1)
            if index > 4 {
                index = 4
            }
            ratingImageView.image = negativeImages[index]
            ratingImageView.layer.mask = nil
            ratingImageView.isHidden = false
        } else {
            ratingImageView.image = emptyImage
            ratingImageView.layer.mask = nil;
            ratingImageView.isHidden = true
        }
        ratingImageView.layoutSubviews()
    }
}

3      

Hey Sally

In regards to returning your string, instead of -

return vctInt

just add the following -

return vctInt.interpretation

As this is the property of type String that you need access to.

In regards to your open class... Because it is of Type UIView im not sure you would be able to use it in SwiftUI unless you tweak it a little and make it conform to UIViewRepresentable.

There would be a bit involved in getting that done. You will also run into some issues using UImages etc in SwiftUI as well. Have a look at Pauls 100 days of SwiftUI course and in there, there is a project... I think its InstaFilter where he talks about using UIImages in SwiftUI.

Can i ask though, what did you use that class for in your original project?

Dave

3      

Thank you Dave. I was thinking since we were able to show the "vct" with the interpretation, and all that's left was to show two images for each vct.

I have this function below. So far I can get one image

 private func updateInterpretation(string: String) -> String {
            let VCT = deriveVCT(string: string)
    let interpretationDictionary: [String : String] = [
    "628" : "Heart 2", //("Green Dollar 5") I want to add another image here as well
    "933" : "Broken Heart 5"]
    let symbolVCT = interpretationDictionary[VCT] ?? ""
return String(symbolVCT)
}

3      

Hi Sally,

You can do the following -

// This is your current code in your function
let interpretationDictionary: [String : String] = [
    "628" : "Heart 2", //("Green Dollar 5") I want to add another image here as well
    "933" : "Broken Heart 5"]

// You can change it to this
let interpretationDictionary: [String : [String]] = [
    "628" : ["Heart 2", "Other image"] //("Green Dollar 5") I want to add another image here as well
    "933" : ["Broken Heart 5", "Other image"]]

All you are doing is changed your [String : String] dictionary to a [String : [String]] dictionary. So each key/value pair is a String key with a String array value. To access each image in your array value in your dictionary you just do the following -

private func updateInterpretation(string: String) -> (String, String) { // Update return type to be 2 Strings
    let VCT = deriveVCT(string: string)
    let interpretationDictionary: [String : [String]] = [
    "628" : ["Heart 2", "Other Image"],
    "933" : ["Broken Heart 5", "Other image"]]

    // Because accessing dictionary key value returns optional safely unwrap
    guard let interpretation = interpretationDictionary[VCT] else { return ("No image found", "No image found") }

   // If we get to here then we have safely unwrapped the dictionary key value and we just return it
   return (interpretation[0], interpretation[1]) // returning names of both images
}

Hope this is okay

Dave

3      

Thank you Dave! You're the best. :)

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.