Reputation: 1235
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.
Upvotes: 2
Views: 7586
Reputation: 5911
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.
Upvotes: 2
Reputation: 16347
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)")
Upvotes: 2