There appear to be some typos in the code snippet that you posted.
I believe it should look like this:
@IBAction func speakButtonClicked(_ sender: NSButton) {
if let contents = textView.string, !contents.isEmpty {
speechSynthesizer.startSpeaking(contents)
} else {
speechSynthesizer.startSpeaking("The document is empty.")
}
}
Note in particular that there is no space character after the exclamation mark.
Although I also see some extra space characters in other locations, I don’t know if they make a difference or not. Nevertheless, I would think it would be better to get in the habit of writing your code to more closely resemble that of the book.
Finally, note the difference in the line that contains the else statement.
OK, I think the issue is that your “Build Settings” for the project are for Swift 4 (which became available with Xcode 9). Check this by choosing the project name (the top line) in the Xcode Project Navigator column) and choosing the “Build Settings” tab in the main part of the window. Under “Swift Compiler - Language” it probably shows Swift 4.0 as the Swift Language Version.
The book is written for Swift 3. There apparently is enough difference between Swift 3 and Swift 4 to cause this error when you are building the book’s Swift 3 code under Swift 4.
I don’t know how to fix the code to make it build successfully under Swift 4. However, if you change the “Build Settings” to Swift 3, I think your error will disappear.
try this since in swift 4 textview.string doesn’t return optional
// print ("The speak button was clicked")
let contents = textView.string
if(!contents.isEmpty){
speechSynthesizer.startSpeaking(contents)
}else{
speechSynthesizer.startSpeaking("Do not hvae contents")
}
Perhaps try:
contents: String = textView.text
// not a ‘,’ doesn’t associate conditional binding to initialization of contents ?
if contents.isEmpty{…}else{…}