EzDevInfo.com

swift

An annotation-based Java library for creating Thrift serializable types and services.

iOS 8 UITableView separator inset 0 not working

I have an app where the UITableView's separator inset is set to custom values - Right 0, Left 0. This works perfectly in iOS 7.x, however in iOS 8.0 I see that the separator inset is set to the default of 15 on the right. Even though in the xib files it set to 0, it still shows up incorrectly.

How do I remove the UITableViewCell separator margins?


Source: (StackOverflow)

Transport Security has Blocked a cleartext HTTP

What setting do i need to put in my info.plist to enable http mode as per the error message:

Transport security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.


Source: (StackOverflow)

Advertisements

How can I create a UIColor from a hex string?

How can I create a UIColor from a hexadecimal string format, such as #00FF00?


Source: (StackOverflow)

swift for loop: for index, element in array?

Is there a function that I can use to iterate over an array with a for having both index and element, like python's enumerate?

for index, element in enumerate(list):
    ...

Source: (StackOverflow)

Easy way to see saved NSUserDefaults?

Is there a way to see what's been saved to NSUserDefaults directly? I'd like to see if my data saved correctly.


Source: (StackOverflow)

dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib

I get this error after adding a Swift class to an old Xcode project.

dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib

How can I make the project run again?


Source: (StackOverflow)

Get the length of a String

How do you get the length of a String? For example I have a variable defined like:

var test1: String = "Scott"

However I can't seem to find a length method on the string.


Source: (StackOverflow)

Set padding for UITextField with UITextBorderStyleNone

I wanted to use a custom background for my UITextFields. This works fine except for the fact that I have to use UITextBorderStyleNone to make it look pretty. This forces the text to stick to the left without any padding.

Can I set a padding manually so that it looks similar to UITextBorderStyleRoundedRect except for using my custom background image?


Source: (StackOverflow)

dispatch_once singleton model in swift

I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:

class var sharedInstance:TPScopeManager {
    get {
        struct Static {
            static var instance : TPScopeManager? = nil
        }

        if !Static.instance {
            Static.instance = TPScopeManager()
        }

        return Static.instance!
    }
}

Wrapping the singleton instance in the Static struct should allow a single instance that doesn't collide with singleton instances without complex naming schemings, and should make things fairly private. Obviously though, this model isn't thread safe, so I tried to add dispatch_once to the whole thing:

class var sharedInstance:TPScopeManager {
    get {
        struct Static {
            static var instance : TPScopeManager? = nil
            static var token : dispatch_once_t = 0
        }

        dispatch_once(Static.token) { Static.instance = TPScopeManager() }

        return Static.instance!
    }
}

But I get a compiler error on the dispatch_once line:

Cannot convert the expression's type 'Void' to type '()'

I've tried several different variants of the syntax, but they all seem to have the same results:

dispatch_once(Static.token, { Static.instance = TPScopeManager() })

Anybody know what the proper usage of dispatch_once is using swift? I initially thought the problem was with the block due to the () in the error message, but the more I look at it the more I think it may be a matter of getting the dispatch_once_t correctly defined.


Source: (StackOverflow)

@selector() in Swift?

I'm trying to create an NSTimer in Swift but I'm having some trouble.

NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)

test() is a function in the same class.


I get an error in the editor: Could not find an overload for 'init' that accepts the supplied arguments

When I change selector: test() to selector: nil the error disappears.

I've tried:

  • selector: test()
  • selector: test
  • selector: Selector(test())

But nothing works and I can't find a solution in the references.


Source: (StackOverflow)

Error-Handling in Swift-Language

I haven't read too much into Swift but one thing that i noticed is there are no exceptions. So how do they do error handling in swift? Has anyone found anything to error-handling?


Source: (StackOverflow)

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

This crash has been a blocking issue, basically I used following steps to reproduce the issue:

  • Create a Cocoa Touch Framework project
  • Add a swift file and a class Dog
  • Build framework for device
  • Create a Single View application in Swift
  • Import framework into app project
  • Instantiate swift class from the framework in ViewController
  • Build and run app on device

The app immediate crashed upon launching, here is console log:

dyld: Library not loaded: @rpath/FrameworkTest03.framework/FrameworkTest03
  Referenced from: /var/mobile/Applications/FA6BAAC8-1AAD-49B4-8326-F30F66458CB6/FrameworkTest03App.app/FrameworkTest03App
  Reason: image not found

I have tried to build on iOS 7.1 and 8.0 devices, they both have the same crash. However I can build app and run on simulator fine. Also I am aware that I can change the framework to from Required to Optional in Link Binary With Libraries, but it did not completely resolve the problem, the app crashed when I create an instance of Dog. The behavior is different on device and simulator, I suspect that we can't distribute framework for device using beta version of Xcode. Can anyone shed light on this?


Source: (StackOverflow)

How to call Objective C code from Swift

In the new Swift language from Apple, how does one call Objective-C code?

Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst building new classes in swift?

The Reasoning

Objective-C is a platform-independent language, whereas Swift is platform-dependent. Writing non-platform-dependent code (business logic libraries) in swift would thus not be wise. However writing platform-dependent code in it (interface related for example) would be perfectly fine. Not to say it would be a good idea, however it is definitely an interest


Source: (StackOverflow)

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?

For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will run on it.


Source: (StackOverflow)

Swift performance: sorting arrays

I was implementing an algorithm in Swift and noticed that the performance was very poor. After digging deeper I realised that one of the bottlenecks was something as simple as sorting arrays. The relevant part is here:

let n = 1000000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
    x[i] = random()
}
// start clock here
let y = sort(x)
// stop clock here

In C++, a similar operation takes 0.06 s on my computer.

In Python it takes 0.6 s (no tricks, just y = sorted(x) for a list of integers).

In Swift it takes 6 s if I compile it with the following command:

xcrun swift -O3 -sdk `xcrun --show-sdk-path --sdk macosx`

And it takes as much as 88 s if I compile it with the following command:

xcrun swift -O0 -sdk `xcrun --show-sdk-path --sdk macosx`

Timings in Xcode with "Release" vs. "Debug" builds are similar.

What is wrong here? I could understand some performance loss in comparison with C++, but not a 10-fold slowdown in comparison with pure Python.


Edit: mweathers noticed that changing -O3 to -Ofast makes this code run almost as fast as the C++ version! However, -Ofast changes the semantics of the language a lot — in my testing, it disabled the checks for integer overflows and array indexing overflows. For example, with -Ofast the following Swift code runs silently without crashing (and prints out some garbage):

let n = 10000000
println(n*n*n*n*n)
let x = Int[](count: n, repeatedValue: 10)
println(x[n])

So -Ofast is not what we want; the whole point of Swift is that we have the safety nets in place. Of course the safety nets have some impact on the performance, but they should not make the programs 100 times slower. Remember that Java already checks for array bounds, and in typical cases the slowdown is by a factor much less than 2. And in Clang and GCC we have got -ftrapv for checking (signed) integer overflows, and it is not that slow, either.

Hence the question: how can we get a reasonable performance in Swift without losing the safety nets?


Edit 2: I did some more benchmarking, with very simple loops along the lines of

for i in 0..n {
    x[i] = x[i] ^ 12345678
}

(Here the xor operation is there just so that I can more easily find the relevant loop in the assembly code. I tried to pick an operation that is easy to spot but also "harmless" in the sense that it should not require any checks related to integer overflows.)

Again, there was a huge difference in the performance between -O3 and -Ofast. So I had a look at the assembly code:

  • With -Ofast I get pretty much what I would expect. The relevant part is a loop with 5 machine language instructions.

  • With -O3 I get something that was beyond my wildest imagination. The inner loop spans 88 lines of assembly code. I did not try to understand all of it, but the most suspicious parts are 13 invocations of "callq _swift_retain" and another 13 invocations of "callq _swift_release". That is, 26 subroutine calls in the inner loop!


Edit 3: In comments, Ferruccio asked for benchmarks that are fair in the sense that they do not rely on built-in functions (e.g. sort). I think the following program is a fairly good example:

let n = 10000
let x = Int[](count: n, repeatedValue: 1)
for i in 0..n {
    for j in 0..n {
        x[i] = x[j]
    }
}

There is no arithmetic, so we do not need to worry about integer overflows. The only thing that we do is just lots of array references. And the results are here—Swift -O3 loses by factor almost 500 in comparison with -Ofast:

  • C++ -O3: 0.05 s
  • C++ -O0: 0.4 s
  • Java: 0.2 s
  • Python with PyPy: 0.5 s
  • Python: 12 s
  • Swift -Ofast: 0.05 s
  • Swift -O3: 23 s
  • Swift -O0: 443 s

(If you are concerned that the compiler might optimise out the pointless loops entirely, you can change it to e.g. x[i] ^= x[j], and add a print statement that outputs x[0]. This does not change anything; the timings will be very similar.)

And yes, here the Python implementation was a stupid pure Python implementation with a list of ints and nested for loops. It should be much slower than unoptimised Swift. Something seems to be seriously broken with Swift and array indexing.


Edit 4: These issues (as well as some other performance issues) seems to have been fixed in Xcode 6 beta 5.

For sorting, I now have the following timings:

  • clang++ -O3: 0.06 s
  • swiftc -Ofast: 0.1 s
  • swiftc -O: 0.1 s
  • swiftc: 4 s

For nested loops:

  • clang++ -O3: 0.06 s
  • swiftc -Ofast: 0.3 s
  • swiftc -O: 0.4 s
  • swiftc: 540 s

It seems that there is no reason anymore to use the unsafe -Ofast (a.k.a. -Ounchecked); plain -O produces equally good code.


Source: (StackOverflow)