What does `outlined init with copy of protocol` mean? - swift

I wrote very simple piece of code in Swift:
protocol MultiplyByTwoProtocol {
func multiply() -> Int
}
class MultiplyByTwoClass: MultiplyByTwoProtocol {
private let n: Int
init(n: Int) { self.n = n }
func multiply() -> Int { return 2 * n }
}
class DynamicDispatchSwift {
private let items: [MultiplyByTwoProtocol]
init(n: Int) {
self.items = Array<Int>.generate(size: n).map(MultiplyByTwoClass.init)
}
func run() {
items.forEach { input in
_ = input.multiply()
}
}
}
(btw generate method for Array just creates an array of random Ints)
Then, I run that code in Instruments and I got following results:
As you can see, almost half of the time takes entry called outlined init with copy of MultiplyByTwoProtocol. Does anyone know what it is?
Thanks for your help.

I just ran into outlined init with copy of ... as the top of a stack trace for crashes coming from an app built with release configuration. I found that turning off the compiler optimization settings would prevent the crash. Ultimately I also found an equivalent syntax for the code the stack trace pointed to, that the optimizer was having problems with, that did not cause crashes and was able to turn optimization back on.
In my case the line of code causing the issue was accessing a static constant inside a for loop. Assigning that same static constant to nothing just prior to the loop fixed the crash, as in this example:
let _ = Foo.fooConstant // This line fixed the crash
for index in 0..<values.count {
let someBar = Bar(foo: .fooConstant)
...
}

Related

Attempting to convert UnsafeMutableRawPointer back into a recognizable type

TL;DR I'm attempting to convert UnsafeMutableRawPointer into some UnsafePointer<T>.
I've developed a Minimal Reproducible Example of my program (Here's a snippet)
var foo: Int = 100
var bar: String = "hello"
func unsafe(_ mutable: (UnsafeMutableRawPointer...) -> ()) {
mutable(&foo, &bar)
}
unsafe { (mutable: UnsafeMutableRawPointer...) in
for m in mutable {
print(UnsafePointer<Int>(.init(m)).pointee)
}
}
The goal is to print this...
100
"hello"
Instead, here is what was printed...
100
478560413032
Finally, if I try and replace...
print(UnsafePointer<Int>(.init(m)).pointee)
with...
print(UnsafePointer<String>(.init(m)).pointee)
I also receive a crash. (If this could be handled with try that would be great. But it is not a throwing method.)
I really wish this was possible, but unfortunately this also crashes:
print(UnsafePointer<Any>(.init(m)).pointee)

Swift function can be called only once

What is the simplest way to write a piece of code that can be executed only once?
I know a way but has a problem.
first, I write a Boolean variable that has negative value but can be set to positive and cannot change after that
var hasTheFunctionCalled : Bool = false {
didSet{
hasTheFunctionCalled = true
}
}
and then write the function and the code inside it:
func theFunction(){
if !hasTheFunctionCalled{
//do the thing
}
hasTheFunctionCalled = true
}
but the problem is that the variable can be changed from somewhere else in the scope and this solution doesn't really look so simple and concrete.
A simple solution is to take advantage of lazy variables in the following way:
// Declare your "once-only" closure like this
private lazy var myFunction: Void = {
// Do something once
}()
...
// Then to execute it, just call
_ = myFunction
This ensures that the code inside the myFunction closure is only executed the first time that the program runs _ = myFunction
Edit: Another approach is to use so called "dispatch once tokens". This comes from Objective-C and was available in Swift until Swift 3. It is still possible to make it work, however you will need to add a little bit of custom code. You can find more information on this post -> dispatch_once after the Swift 3 GCD API changes
Edit2: Should be _ = myFunction and not _ = myFunction(), as JohnMontgomery pointed out.
You might use a static bool inside a struct nested into the function itself doing so:
func theFunction(){
struct Holder { static var called = false }
if !Holder.called {
Holder.called = true
//do the thing
}
}
One possible technique is to put the code into the initializer of a static type property, which is guaranteed to be lazily initialized only once (even when accessed across multiple threads simultaneously):
func theFunction() {
struct Once {
static let once = Once()
init() {
print("This should be executed only once during the lifetime of the program")
}
}
_ = Once.once
}
(Compare Singleton in the "Using Swift with Cocoa and Objective-C" reference.)
Example:
print("Call #1")
theFunction()
print("Call #2")
theFunction()
print("Done")
Output:
Call #1
This should be executed only once during the lifetime of the program
Call #2
Done
You can do smth like:
class Once {
var already: Bool = false
func run(#noescape block: () -> Void) {
guard !already else { return }
block()
already = true
}
}
and than use it like
class ViewController: UIViewController {
let once = Once()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
once.run {
cameraMan.setup()
}
}
}
ref: https://dev.to/onmyway133/how-to-run-action-once-in-swift-3k7o
Depending on what you are doing inside your method : you may check if the end result has already been accomplished :
e.g. if you instantiate a class, check if it is different from nil
You can also use UserDefaults, and the knowledge that the default UserDefault Bool is false:
if !UserDefaults.standard.bool(forKey: "ExecuteOnce") {
func()
UserDefaults.standard.set(true, forKey: "ExecuteOnce")
}
This code will execute exactly once.

Fail to imply _Reflectable protocol

I am reading MirrorType at nshipster,and trying to adopt it's code to Swift 2.1. Everything works fine until when I tried to custom the _MirrorTypewith :
extension WWDCSession : _Reflectable {
func _getMirror() -> _MirrorType {
return WWDCSessionMirror(self)
}
}
An error occured :
error: Playground execution aborted: Execution was interrupted,
reason: EXC_BAD_ACCESS (code=2, address=0x7fff58273e87).
And I found out it's because the init method in WWDCSessionMirror was being called infinite times.
struct WWDCSessionMirror: _MirrorType {
private let _value: WWDCSession
init(_ value: WWDCSession) {
_value = value
}
var value: Any { return _value }
var valueType: Any.Type { return WWDCSession.self }
var objectIdentifier: ObjectIdentifier? { return nil }
var disposition: _MirrorDisposition { return .Struct }
var count: Int { return 4 }
subscript(index: Int) -> (String, _MirrorType) {
switch index {
case 0:
return ("number", _reflect(_value.number))
case 1:
return ("title", _reflect(_value.title))
case 2:
return ("track", _reflect(_value.track))
case 3:
return ("summary", _reflect(_value.summary))
default:
fatalError("Index out of range")
}
}
var summary: String {
return "WWDCSession \(_value.number) [\(_value.track.rawValue)]: \(_value.title)"
}
var quickLookObject: PlaygroundQuickLook? {
print(summary)
return .Text(summary)
}
}
I want to ask why it happened , and how to fix it?
_Reflectable and _MirrorType are not the droids you're looking for.
They are legacy types, which have been superseded by CustomReflectable (among others). The 2015 WWDC session about LLDB goes into some detail about this (disclaimer: I am the speaker of that part of that session, so conflict of interests all around :-)
But, anyway, the issue you're running into is because of this line:
_value = value
Since you're typing this line in your playground, that tells the playground logic to capture for display ("log" in playground parlance) the thing you're assigning. To do so, the playground uses the Mirror attached to that type. So, we go off and create one, which causes us to run
_value = value
again, which tells the playground logic to log value, which then means we create a Mirror, ...
You should first of all check if you can adopt Mirror and CustomReflectable instead of _MirrorType and if using those APIs fixes your problem. If it doesn't a possible workaround is to put the reflection support code in an auxiliary source file which will cause the playground logic to not log things inside of it.

What is the shortest way to run same code n times in Swift?

I have a code that I need to run exactly n times in Swift. What is the shortest possible syntax for that?
I am currently using the for loop but it is a lot of typing.
for i in 0..<n { /* do something */ }
Is there a shorter/nicer way for running same code n times in Swift?
Speaking of syntax, you might define your own shortest syntax:
extension Int {
func times(_ f: () -> ()) {
if self > 0 {
for _ in 0..<self {
f()
}
}
}
func times(_ f: #autoclosure () -> ()) {
if self > 0 {
for _ in 0..<self {
f()
}
}
}
}
var s = "a"
3.times {
s.append(Character("b"))
}
s // "abbb"
var d = 3.0
5.times(d += 1.0)
d // 8.0
Sticking with a for loop - you could extend Int to conform to SequenceType to be able to write:
for i in 5 { /* Repeated five times */ }
To make Int conform to SequenceType you'll could do the following:
extension Int : SequenceType {
public func generate() -> RangeGenerator<Int> {
return (0..<self).generate()
}
}
You have several ways of doing that:
Using for loops:
for i in 1...n { `/*code*/` }
for i = 0 ; i < n ; i++ { `/*code*/` }
for i in n { `/*code*/` }
using while loops:
var i = 0
while (i < n) {
`/*code*/`
` i++`
}
var i = 0
repeat {
` /*code*/`
`i++`
} while(i <= n)
for _ in 1...5 {
//action will be taken 5 times.
}
you could use functional programming on a range instead of a loop, for shorter and "nicer" syntax for example
(0..<n).forEach{print("Index: \($0)")}
Other answers mention defining your own syntax for that. So - that can be fine for a tiny personal project, or as a learning experience. But defining your own syntax for something so trivial and basic in a large project would be maintenance and readability hell.
You could do something like this:
10⨉{ print("loop") }
Using a custom operator and an extension on Int:
infix operator ⨉ // multiplication sign, not lowercase 'x'
extension Int {
static func ⨉( count:Int, block: () ->Void ) {
(0..<count).forEach { _ in block() }
}
}
ABakerSmith's answer updated for Swift 4:
extension Int: Sequence {
public func makeIterator() -> CountableRange<Int>.Iterator {
return (0..<self).makeIterator()
}
}
Use:
for i in 5 {
//Performed 5 times
}
Shorter and (I think) clearer:
for i in 1...n { } // note: this will fail if n < 1
or
for i in n { }
In Swift, what you have is the shortest syntax for performing a loop operation.
Swift provides two kinds of loop that perform a set of statements a
certain number of times:
The for-in loop performs a set of statements for each item in a
sequence.
The for loop performs a set of statements until a specific
condition is met.
If you want to run it infinite times, well try using a while.
There are a lot of answers here, highlighting just how creative you can be, with Swift.
I needed an array so I did this
extension Int {
func of<T>(iteration: (Int) -> T) -> [T] {
var collection = [T]()
for i in 0..<self {
collection.append(iteration(i))
}
return collection
}
}
fun strings() -> [String] {
return 4.of { "\($0) teletubby" }
}
for-loops are a common way to repeat code. Here is an example of using a for-loop to hide six outlets, versus writing the same code for six outlets. Plus if you make another outlet all you have to do is add it to the array.
let array = [outLet0, outlet1, outlet2, outLet3, outLet4, outLet5]
for outlet in array {
outlet.hidden = true
}
Versus writing it like this:
outlet0.hidden = true
outlet1.hidden = true
outlet2.hidden = true
outlet3.hidden = true
outlet4.hidden = true
outlet5.hidden = true
ONLY 5 CHARACTERS (not including n or code)
r(){}
If you're just testing things and need a REALLY short line, try this. Emphasis on using this for testing, not in production, because no one will know what is going on without documentation.
define this somewhere globally
func r(_ n : UInt, _ c: #escaping () -> Void) { for _ in 0..<n { c() } }
call this when you want to run it
r(5) { /*code*/ }
Swift is so awesome, just write your own function or extension and you got it ;) 100 of options there, everyone can do it its own way just look at those answers here.
Or better, write it as you already do, as is common when apps are build in team, as everyone would do it differently anyway and all projects need those extension to be written again or own libs to have and maintain just for stupid thing, that you can write just by some standard way, as you already did with your for loop.
The only loop shorter than that is an infinite while loop:
while (true) {
}
But you would still have to increase a counter and check it in the loop to break the loop, and in the end it wouldn't be shorter.

Swift - access to Dictionary of a singleton causes EXC_BAD_ACCESS

I have an app managing a simple stocks portfolio. Amongst other things, it keeps a record of the required exchange rates in a dictionary, like so:
[ EURUSD=X : 1.267548 ]
This disctionary is a Dictionary property of a singleton called CurrencyRateStore.
When updating the stocks quotations, it checks for an updated exchange rate and updates the dictionary with the following code:
CurrencyRateStore.sharedStore()[symbol] = fetchedRate.doubleValue
That calls:
subscript(index: String) -> Double? {
get {
return dictionary[index]
}
set {
// FIXME: crashes when getting out of the app (Home button) and then relaunching it
dictionary[index] = newValue!
println("CurrencyRateStore - updated rate for \(index) : \(newValue!)")
}
}
The first time the app is started, it works fine.
But if I quit the app (with the Home button) and then relaunch it, the currency rates are updated again, but this time, I get a EXC_BAD_ACCESS at the line
dictionary[index] = newValue!
Here is a screenshot:
[EDIT] Here is the thread in the debug navigator:
I tried to update the dictionary without a subscript, like so:
CurrencyRateStore.sharedStore().dictionary[symbol] = fetchedRate.doubleValue
but without more success. Same if I use the function updateValue:forKey:
I didn't have the issue in Objective-C.
Thanks for your help !
[EDIT] Here is the whole class CurrencyRateStore:
class CurrencyRateStore {
// MARK: Singleton
class func sharedStore() -> CurrencyRateStore! {
struct Static {
static var instance: CurrencyRateStore?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = CurrencyRateStore()
}
return Static.instance!
}
// MARK: Properties
/** Dictionary of currency rates used by the portfolio, presented like [ EURUSD=X : 1.3624 ] */
var dictionary = [String : Double]()
/** Returns a sorted array of all the keys on the currency rates dictionary */
var allKeys: [String] {
var keysArray = Array(dictionary.keys)
keysArray.sort {$0 < $1}
return keysArray
}
init() {
if let currencyRateDictionary: AnyObject = NSKeyedUnarchiver.unarchiveObjectWithFile(currencyRateArchivePath) {
dictionary = currencyRateDictionary as [String : Double]
}
}
subscript(index: String) -> Double? {
get {
return dictionary[index]
}
set {
// FIXME: crashes when getting out of the app (Home button) and then relaunching it
// (ApplicationWillEnterForeground triggers updateStocks)
dictionary[index] = newValue!
println("CurrencyRateStore - updated rate for \(index) : \(newValue!)")
}
}
func deleteRateForKey(key: String) {
dictionary.removeValueForKey(key)
}
/** Removes all currency rates from the Currency rate store */
func deleteAllRates()
{
dictionary.removeAll()
}
// MARK: Archive items in CurrencyRateStore
var currencyRateArchivePath: String { // Archive path
var documentDirectories: Array = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
// Get the only document directory from that list
let documentDirectory: AnyObject = documentDirectories.first!
return documentDirectory.stringByAppendingPathComponent("currencyRates.archive")
}
func saveChanges()-> Bool
{
// return success or failure
return NSKeyedArchiver.archiveRootObject(dictionary, toFile: currencyRateArchivePath)
}
}
This looks to me like a concurrency issue. Swift dictionaries aren't thread safe, and using them from a singleton can lead to multiple reader/writer issues.
Edit: I am pretty sure this is the real answer, based on the given source/debugging dump. To correct what I wrote, specifically MUTABLE dictionaries and arrays (as well as NSMutableDictionary and NSMutableArray) aren't thread safe, and problems arise when using them within Singletons that are accessed from multiple threads, and that appears to be what the sample source code is doing, or enabling other parts of the code to do.
I don't have an Apple link discussing Swift collection class thread safety, but I"m pretty sure common knowledge. But the following tutorial on Grand Central Dispatch discusses the problem in depth and how to solve it using GCD.
http://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1
The error, and the line itself:
dictionary[index] = newValue!
makes me think the problem is newValue being nil - and the error is caused by the forced unwrapping.
I would suggest to set a breakpoint and check its value, or otherwise print it before adding to the dict.
Moreover, it wouldn't be a bad idea to protect that statement with an optional binding:
if let value = newValue {
dictionary[index] = value
}
because if the value type is optional, it can be nil.
So in the end, I contacted Apple Technical Support.
They couldn't reproduce the issue.
I thought that maybe I don't need to save the currency rates, because during the quotes update, the function will check which currency rates it needs anyway, and repopulate the dictionary as needed.
So I deactivated the methods i created to save the CurrencyRateStore and to reload it again with NSKeyedUnarchiver.
Apparently, the crash is gone!