2

I am on app on SWIFT 3, I display a sentence on the screen and record the voice of the user to see if it match.

I want to extract each word of the sentence to compare each word separately.

I use the code :

let StringToLearn = word?.text
let StringToLearnArr = StringToLearn?.characters.split{$0 == " "}.map(String.init)
print("StringToLearn: \(StringToLearn)")
print("StringToLearnArr: \(StringToLearnArr)")


print("StringRecorded: \(StringRecorded)")
let StringRecordedArr = StringRecorded.characters.split(whereSeparator: {$0 == " "})
print("StringRecordedArr: \(StringRecordedArr)")

info : let StringRecorded is equal to (Siri Speech API) :

(result?.bestTranscription.formattedString)!

the console give me :

StringToLearn: Optional("My name is Florian")
StringToLearnArr: Optional(["My", "name", "is", "Florian"])
StringRecorded: My name is
StringRecordedArr: [Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: Optional(0x0000000174030d11), _countAndFlags: 4611686018427387906, _owner: Optional(My name is))), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: Optional(0x0000000174030d14), _countAndFlags: 4611686018427387908, _owner: Optional(My name is))), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: Optional(0x0000000174030d19), _countAndFlags: 4611686018427387906, _owner: Optional(My name is)))]

How can I have the same result for StringRecordedArr to compare each item the two arrays ?

Thank you very much.

2 Answers 2

2

Instead of splitting the character-view, you can use the simple components(separatedBy:) API.

Here's a sample that would look better and work:

if let toLearn = word?.text, 
   let recorded = result?.bestTranscription.formattedString  {

    let wordsToLearn = toLearn.components(separatedBy: " ")

    let recordedWords = recorded.components(separatedBy: " ")
}

Note: nonoptionals are better than forced unwraps and optionals.

Sign up to request clarification or add additional context in comments.

Comments

2

What you want to end up with is an array of strings, so instead of the character version use the String version: .components(separatedBy: " ") :

    print("StringRecorded: \(StringRecorded)")
    let StringRecordedArr = StringRecorded.components(separatedBy: " ")
    print("StringRecordedArr: \(StringRecordedArr)")

1 Comment

Thx you for that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.