Questions tagged [swift-guard]
8 questions
10
votes
2 answers
Swift guard with self
I am doing the weak strong dance in swift this way:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { [weak self] in
guard let `self` = self else {
return
}
self.doSomething(1)
})
Before this, I was using…

Infinite Possibilities
- 7,415
- 13
- 55
- 118
5
votes
2 answers
Is there a shorthand for guard return in swift?
Is there is a way to have guard automatically return without needing to actually write it out every single time, e.g:
guard let url = self.webView.url else { return }
guard let componentDict = URLComponents(string: url.absoluteString)?.dict else {…

Geuis
- 41,122
- 56
- 157
- 219
2
votes
1 answer
Guard condition provokes compiler error that talks about closure
Consider this code:
class Foo {
var a: Int
var b: Int
init(a: Int, b: String?) throws {
self.a = a
guard self.a > 0 else {
throw "Too little a!"
}
self.b = self.a
}
}
extension String:…

Raphael
- 9,779
- 5
- 63
- 94
1
vote
1 answer
Initializer for conditional binding must have Optional type, not '[Key : Value?]'
I'm trying to translate javascript to swift. This is the javascript method:
export function serializeProperty(
properties: Map,
): Array<[Key, JsonValue | null]> {
const data = Array.from(properties.entries());
…

userNew
- 11
- 3
1
vote
1 answer
How to tell which block guard exits out of?
When guard fails the condition, they exit the closure. However, what confuses me what is considered to be a block the guard exits out of?
For example, if I have the following:
func doThing() {
while ... {
for ... {
if ... {
guard…

TruMan1
- 33,665
- 59
- 184
- 335
0
votes
3 answers
After guard let url the value still needs to be unwrapped
In a singleton class I am trying the following code with 3 URLs stored in a dictionary:
class DownloadManager {
static let instance = DownloadManager()
let urls = [
"en" : URL(string: "https://wordsbyfarber.com/ws/top"),
…

Alexander Farber
- 21,519
- 75
- 241
- 416
0
votes
1 answer
Early return from a function which has a return type of [String] in Swift 3
I have a function which returns an Array of String if some conditions are met. But I want to have the early return functionality in my function. Something like this:
func fetchPerson() -> [String] {
guard let appDelegate =…

nayem
- 7,285
- 1
- 33
- 51
0
votes
1 answer
Condition after variable binding in guard swift compilation issue
I am using the nice guard statement from Swift 3.0 (in Xcode 8.0) and have the following function:
func parse(suffix s: String) throws -> Instruction {
guard let count = Int(s) where count >= 0 else {
throw InstructionParsingError(message:…

jolivier
- 7,380
- 3
- 29
- 47