skip to Main Content

Greeting everyone. I just started my Swiftui journey.

I am trying to get a piece of string from a string variable to display as Text() in Swiftui. In my previous languages I would do something like var subVal = val[1] but it seem this method does not work here.

Is there a way to work around this problem?

//I want the "r" value which is the second element of val 
var val = "orange"
@State var newVal = val[1]

.....
Text("(newVal)"

2

Answers


  1. Chosen as BEST ANSWER

    There are many possible ways that you can extract a substring from a string either to get a Character or a new String by using .prefix, .suffix, .index, etc.

    var val = "orange"
    
    //using prefix, you will receive a string back
    var newVal = val.prefix(2) //"or"
    
    //using suffix, you will receive a string back
    var newVal = val.suffix(2) //"ge"
    

    for your case, you can either use the given solution by @workingdog support Ukraine or create a custom extension for reuse

    struct ContentView: View {
    @State var val = "orange"
    var body: some View {
        //you can do String[index] directly
        //the return value is Character, so you need to cast to String
        Text(String(val[1])) //"r"
    }
    }
    
    //reusable extension
    extension StringProtocol {
    subscript(offset: Int) -> Character {
        self[index(startIndex, offsetBy: offset)]
    }
    } 
    

  2. you should read the basics at: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html especially the section on Strings and Characters in Swift at: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html and also do the tutorial at: https://developer.apple.com/tutorials/swiftui/

    Without knowing the basics you will not go very far in coding your app.

    struct ContentView: View {
        var val = "orange"
        @State var newVal = ""
        
        var body: some View {
            Text(newVal)
                .onAppear {
                    let index = val.index(val.startIndex, offsetBy: 1)
                    newVal = String(val[index])
                }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search