How to "Strongify" Optional Self Using Guard in Swift 2.0

How to strongify optional self using guard in Swift 2.0

You can shadow self; you just need backticks to indicate that "you know what you're doing". For example:

foo.doSomethingAsyncWithBar(bar) { [weak self] result in
guard let `self` = self else { return }
self.receivedResult(result)
}

Or, in your example:

2> import Foundation
3> class Foo {
4. func guardOptSelf() -> () throws -> Void {
5. return { [weak self] in
6. guard let `self` = self else { throw NSError(domain: "I was destroyed!", code: 1, userInfo: nil) }
7. self.doSomethingNonOptionalSelf()
8. }
9. }
10. }

How to achieve same behavior as with strongify in Swift?

While the other answers work, another option is to use backticks. Doing so does away with having to define strongSelf and allows using self without having to unwrap optional self.

let c: () -> Void = {
[weak self] in
guard let `self` = self else {
throw NSError(domain: "self was destroyed", code: 1, userInfo: nil)
}
self.doSomethingNonOptionalSelf()
}

What is the meaning of following swift code?

First you are creating a block that will be executed asynchronously

DispatchQueue.global(qos: .userInitiated).async

Then inside the block the code checks if self, the object that is calling this function, is still allocated

guard let self = self else {
return
}

We need to check this because self is declared as weak inside the block to avoid a retain cycle (Swift closures causing strong retain cycle with self) and can be deallocated before the block is executed. That line of code checks if self is != nil, and assign it to self, otherwise it returns.

Cannot convert value of type 'ViewController?' to expected argument type '_OptionalNilComparisonType'

Update to Xcode 10 and Swift 4.2. That is the earliest version of Swift where the expression

guard let self = self else { return }

is legal.

If you can’t do that, use some other variable name on the left side of the equal sign. For example:

guard let strongself = self else { return }

Does declaring a variable as optional incurs any additional cost in swift?

Assuming you don't want to reset your struct's name to nil ever, initialize the variables with the values you want them to have. It simplifies the code and expresses the idea of default values.

struct TestStruct {
var name = "Sandeep"
var age = 26

func printInfo(){
print(self.name + "\(self.age)")
}
}

How to play audio file in back ground mode using swift 2.0?

hmm yes i added these lines

  do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do
{
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
self.becomeFirstResponder()
print("AVAudioSession is Active")
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
catch let error as NSError
{
print(error.localizedDescription)
}

in didFinishLaunchingWithOptions and applicationDidEnterBackground

these lines had added UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()

but i can't hear sound in back ground ?

How to initialize CBCentralManager in Swift when a self reference is necessary

There is no way to use self in an init method prior to initializing every non-lazy property that has no default value and is not optional (which have a default value of nil).

If you always initialize centralManager in init, and you have no code that will potentially make it nil, I would say that the CBCentralManager! declaration is a good choice. That is one of the main purposes of the implicitly unwrapped optional type.

Here is the excerpt from the documentation about implicitly unwrapped optionals:

Sometimes it is clear from a program’s structure that an optional will
always have a value, after that value is first set. In these cases, it
is useful to remove the need to check and unwrap the optional’s value
every time it is accessed, because it can be safely assumed to have a
value all of the time.

These kinds of optionals are defined as implicitly unwrapped
optionals. You write an implicitly unwrapped optional by placing an
exclamation mark (String!) rather than a question mark (String?) after
the type that you want to make optional.

If the program logic does potentially allow for it to be nil at some point when it might be used. Then a normal optional type is the appropriate choice.

One other possible option would be for you to declare your centralManager property as a lazy property. If you do this it won't be created until you access it, but you will be able to reference self and make it non-optional. When you need it to be created will govern if you use this option or not.

lazy var centralManager: CBCentralManager = { [unowned self] () -> CBCentralManager in
CBCentralManager.init(delegate: self, queue: nil, options: [:])
}()

Convert array to JSON string in swift

As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.

As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.

Instead just do the array->data->string parts:

Swift 3/4

let array = [ "one", "two" ]

func json(from object:Any) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}

print("\(json(from:array as Any))")

Original Answer

let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

although you should probably not use forced unwrapping, it gives you the right starting point.



Related Topics



Leave a reply



Submit