Search code examples
swifttrim

Swift optional string splitting into array problem


I have a function that takes second from my controller and introInterval from network service. But my codes does not split string that coming from API. But if i put dummy data, it works. I dont know why. Where is the problem ? Both of them works with same string. My aim is to catch up same data with test variable. You can see outputs of them in print lines.

func getCurrentPlayerTimeAndIntroDuration(second: String, introInterval: String?) {
    if let introInterval = introInterval {

        print(introInterval) //output: "01:38 - 5:00"

        let test = "01:38 - 5:00".trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "-")
        let introIntervalArray = introInterval.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "-")
        
        print("test \(test)") //output: ["01:38", "5:00"] correct
        print("introIntervalArray \(introIntervalArray)") //output introIntervalArray ["01:38–02:13"] wrong

    }
}

Solution

  • I believe you're using the wrong character to separate the string. If you compare the - (Non-ASCII) character from your example //output introIntervalArray ["01:38–02:13"] wrong you will see the is different than the one you are using to split the string - (ASCII).

    This code:

    let test = "01:38–02:13".trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "–")
    

    Outputs:

    ["01:38", "02:13"]