So I'm following a tutorial form Lynda.com for making a iOS app with Swift and when I plug this line of code in, it's throwing me errors:
guard let text:String = addressBar.text else
The error I get is:
Consecutive statements on line must be separated by ';'
Once I have Xcode fix it, these are the errors I get:
Expected expression.
Use of unresolved identifier 'guard'.
Expression resolves to an unused function.
Braced block of statements is an unused closure.
I'm really new to Xcode and Swift so any help would be awesome! Thanks!
Because you using outdated xcode and swift language. Latest version is xcode 7 and swift 2.
https://developer.apple.com/xcode/
May be you are using a wrong version of Xcode(version 7.0)
Try it too:
Be certain you are using guard statement in the right conditions. E.g:
class AddressBar {
var text: String? = ""
}
var addressBar = AddressBar()
addressBar.text = nil
//addressBar.text = "text"
func test() {
guard let _text: String = addressBar.text else {
print("Nothing")
return
}
print("I reach this point")
}
test()
Related
Let's say, I have a function which takes a closure as its last parameter, so it can be shortened to something like this:
let reminder = reminders.first { (reminder) -> Bool in
return reminder.mealIdentifier == mealIdentifier
}
Awesome! Now let's say I want to put this in a guard statement, like this:
guard let reminder = reminders.first { (reminder) -> Bool in
return reminder.mealIdentifier == mealIdentifier
} else {
continue
}
The moment I do this, the compiler starts screaming. The fix is to use no trailing closure short syntax when calling the function, but it's cumbersome as the default auto-completion by Xcode doesn't have an option to NOT do trailing closures short syntaxes when your last parameter is a closure:
guard let reminder = reminders.first(where: { (reminder) -> Bool in
return reminder.mealIdentifier == mealIdentifier
}) else {
continue
}
Is there anything I'm missing here? Or is there a way to somehow have Xcode do autocompletion without the shortened syntax?
Or is there a way to somehow have Xcode do autocompletion without the shortened syntax?
Xcode is quite smart. It chooses the non-trailing closure version if you do the auto completion in a control flow statement that needs a {. For example, if I type:
guard let a = reminders.first
The auto complete shows:
If I choose the highlighted option, I get:
guard let a = reminders.first(where: <#T##(String) throws -> Bool#>)
If I then press enter, I get:
guard let a = reminders.first(where: { (<#String#>) -> Bool in
<#code#>
})
It doesn't turn it into a trailing closure, as long as you autocomplete within a guard/if statement.
I have a very simple func in Xcode playgrounds which works when I run it. But when i try to run the same code in CoderPad it gives me the following error Solution.swift:18:1: warning: result of call to 'isPalindrome(word:)' is unused
isPalindrome(word:"racecar")
Here is the code
import Foundation
func isPalindrome(word: String) -> Bool{
var oddCharacters: Set<Character> = []
for char in word {
if oddCharacters.contains(char){
oddCharacters.remove(char)
}else{
oddCharacters.insert(char)
}
}
return oddCharacters.count <= 1
}
isPalindrome(word:"racecar")
I really do not understand why this is happening.
Try this:
import Foundation
func isPalindrome(word: String) -> Bool{
var oddCharacters: Set<Character> = []
for char in word {
if oddCharacters.contains(char){
oddCharacters.remove(char)
}else{
oddCharacters.insert(char)
}
}
return oddCharacters.count <= 1
}
print(isPalindrome(word:"racecar"))
all you had to do was print it, hope this helped
That means, that the "left-hand-side" result of the call to your function isPalindrome(word: "racecar") is unused ("wasted").
It seems that for a debugging, testing, try-out environment like a Playground it's just okay to find out the result of this call (true) without storing it inside a variable. However, when doing that in other development environments, the compiler will be complaining about that. I can give you four options that would prevent the error from being thrown, just to give you a better idea of why the compiler is complaining:
If you want to use it in your further code below, just store the result and change your calling line to let isPalindrome = isPalindrome(word: "racecar"). But if you don't use it, the compiler will give you a warning again saying that you're never using your isPalindrome variable... --> Option 2
If you don't need the result, you can also just say: _ = isPalindrome(word: "racecar"). That will explicitly tell the compiler "bro, it's okay if the result is just ignored". It wouldn't make much sense for this function, though.
You can add the #discardableResult keyword prior to your function declaration, so it would say: #discardableResult func isPalindrome(word: String) -> Bool { ... That would kinda just silence your thrown error and like option 2 just tell the compiler that it's okay to just ignore the result of this function.
Just use the result in any way like:
if isPalindrome(word: "racecar") {
// do something
} else {
// do something else
}
// or
print("racecar is a palindrome: \(isPalindrome(word: "racecar")")
and everything will just be fine. I hope that helps you!
I am a little confused about a conversion error.
I migrated my project form Swift 2.3 to Swift 3.0
func updateCelsiusLabel() {
if let value = celsiusValue {
//This was the original code (that worked but is) failing after migration
//due to: Argument labels do not match any available overloads
celsiusLabel.text = numberFormatter.string(from: NSNumber(value))
//This is my code trying to fix this issue and the project is now compiling
//and everything is fine
celsiusLabel.text = numberFormatter.string(from: value as NSNumber)
}
else { celsiusLabel.text = "???"
}
}
At first I thought that in Swift 3.0 the cast Type(value) was now forbidden, but I checked and I get absolutely no compiler warning. Can somebody tell me what the problem with NSNumber(value) is?
As far as I understand value as NSNumber and NSNumber(value) should be the same thing.
In Swift 3, NSNumber(value) won't work. Let's say that your value is an Int. In that case, you'd need NSNUmber(value: yourIntValue). In Swift 3, you must have the name of the first (and in this case the only) parameter in the function call. So, your usage of
value as NSNumber
works, but
NSNumber(value: yourNumberValue)
works too.
First of all I have taken some assumption here, I have assumed that -
numberFormatter = NSNumberFormatter() // Now it has been renamed to NumberFormatter
celsiusLabel.text I am taking text as optional string just for example you can use label.text for same.
After the above assumption please see below code which will work in Swift 3 -
var celsiusValue:Double?
var numberFormatter = NumberFormatter()
var text:String?
func updateCelsiusLabel() {
if let value = celsiusValue {
//This was the original code (that worked but is) failing after migration due to: Argument labels do not match any available overloads
text = numberFormatter.string(from: NSNumber(value: value))!
}
else {
text = "???"
}
}
Hope it help feel free to leave comment in case you have any doubt.
I am trying to make my first app and I am stuck. I don't know how to rewrite this piece of code from an earlier version of Swift in Swift 2.
func rowCheck(value value:Int) -> (location :String,pattern :String)?{
let acceptableFinds = ["101","110","011"]
var findFunc = [checkGornjiR,checkSrednjiR,checkDonjiR,checkLevuK,checkSrednjuK,checkDesnuK,checkLevuD,checkDesnuD]
for algorithm in findFunc{
let algorithmResults = algorithm(value:value)
if find(acceptableFinds,algorithmResults.pattern) { // Error on this line
return algorithmResults
}
}
return nil
In "if" line I am getting error:
"Optional type 'C.index?' cannot be used as a boolean; test for '!=nil' instead
A bit of help would be nice! Thanks!
you van use contains which return Bool value like this:
if acceptableFinds.contains(algorithmResults.pattern) {
I was asked to migrate a rather large app to Swift 2. The compiler keeps throwing segmentation fault: 11 errors for one function, present in different modules of the app's logic (only difference being variables used):
func loadMoreContent() {
if let collection = self.ratingsCollection where collection.identifier != 0,
let totalEntries = collection.totalEntries,
let objects = self.ratings?.count where objects < totalEntries {
self.ratingsCollection = nil
collection.nextPage().onSuccess { (value) in
if let collection = value as? Collection<Rating> {
self.ratingsCollection = collection
} else {
self.ratingsCollection = Collection<Rating>(identifier: 0)
}
}.onFailure { error in
self.ratingsCollection = Collection<Rating>(identifier: 0)
}
}
}
Here are the errors themselves:
1. While type-checking 'loadMoreContent' at (path redacted).swift:46:3
2. While type-checking expression at [(path redacted).swift:54:9 - line:64:9]
RangeText="collection.nextPage().onSuccess { (value) in
if let collection = value as? Collection<Rating> {
self.ratingsCollection = collection
} else {
self.ratingsCollection = Collection<Rating>(identifier: 0)
}
}.onFailure { error in
self.ratingsCollection = Collection<Rating>(identifier: 0)
}"
3. While loading members for declaration 0x7fdda42ea2b0 at <invalid loc>
4. While deserializing 'producer' (FuncDecl #340)
Does anyone have any idea what can be wrong with this function at first glance? I should add it compiles with no changes in Xcode 6 / Swift 1.2.
This is a hair pulling error especially common in XCode7.
Occasionally the usual XCode stupid bug protocol (clean, XCode Restart, clean, build) fixes it. However, often it is due to one or more offending lines of code. This doesn't necessarily mean there is a bug in the code, either!
So, before restarting, it is sometimes useful to undo recent changes sequentially and trying to build as you go along. If any of your dependencies or frameworks have been updated since your last successful build, these could be a likely candidate.
There are a couple things that seem to produce this error fairly regularly. So please add to this list concisely if you can isolate specific issues that CONSISTENTLY cause errors for you:
1) String concatenation using the plus operator in calls to methods that use autoclosures (found in calls to XCGLogger):
public func myFunc(#autoclosure closure: () -> String?){
// do something
}
someInstance.myFunc("Hi " + nameStr + "!")
2) failure to call super.init() from subclass especially when super class is using a default initializer (you haven't explicitly created your own init)
3) Accidentally using a single equals sign to test for equality (using = instead of == ) especially in complex statement such as in this answer.