question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I'm trying to add an endpoint to an existing application that sends Server Sent Events. There often may be no event for ~5 minutes. I'm hoping to configure that endpoint to not cut off my server even when the response has not been completed in ~1min, but all other endpoints to timeout if the server fails to respond. Is...
Here is my suggestion for HAProxy and SSE: you have plenty of custom timeout options in HAProxy, and there is 2 interesting options for you. The timeout tunnel specifies timeout for tunnel connection - used for Websockets, SSE or CONNECT. Bypass both server and client timeout. The timeout client handles the situation w...
HAProxy
21,419,859
10
I want to use haproxy as a proxy and load balancer for thousands of backends. So a request needs to be proxied to the correct backend depending on hostname and then load balanced within the backend. I am using haproxy-1.5dev21. The config file looks like this : frontend public bind :80 mode http acl host1 hdr_reg...
Some shortcomings were removed from the config file after expert input, and I list them here in case anyone else may find it useful. Use hdr(Host) instead of hdr_reg(). This vastly improves the time consumed to evaluate the ACLs. Even better, avoid acl and use the inline evaluation e.g. use_backend host1 if { req.fhd...
HAProxy
22,025,412
10
I am trying to achieve this: http://front-end --> http://back-end/app-1 http://front-end/app-2 --> http://back-end/app-2-another-path So that requests will be handled this way: http://front-end/do-this --> http://back-end/app-1/do-this http://front-end/app-2/do-that --> http://back-end/app-2-another-path/d...
You can achieve this "http://front-end/app-2/do-that --> http://back-end/app-2-another-path/do-that" with the following configuration: frontend http #match url ending with /xxxxx/do-that acl do-that path_end -i /app-2/do-that use_backend server1 if do-that backend server1 reqirep ^([^\ :]*)\ /app-2/(.*...
HAProxy
22,219,479
10
I am currently refactoring a haproxy configuration that we use on our production servers to forward TCP traffic from a central server. The goal is to get everything working with docker containers to help with deployment reliability. Everything has gone well so far, but now I have a couple of "listen" proxies using "mo...
If you are using a TCP mode proxy, you have to specify option tcplog in your frontend's definition. This enables tcp mode logging. There's extensive documentation about this in the haproxy manual, for example here for haproxy 1.5: http://cbonte.github.io/haproxy-dconv/configuration-1.5.html#8.2.2
HAProxy
22,391,876
10
I am using HAProxy listening on 80 to send requests to a node server (port:3000) or php server (4000); I also have CSF installed which have ports 3000 and 80 available. It works okay when I browse a page at http://example.com/forum/1/page.php, but sometimes when I accidentally enter example.com/forum/1 (no trailing sl...
Since /forum/1 is a valid physical directory you get redirected to /forum/1/ due to this setting: DirectorySlash On which is used by a module called mod_dir that adds a trailing slash after directories if it is missing. You can of course turn this flag off by using: DirectorySlash Off but be aware of security implica...
HAProxy
30,594,199
10
Consider the following HAProxy Config: frontend front default_backend default backend default balance roundrobin http-response set-header X-RGN us-east-1 server app-1a app.us-east-1a.example.com:443 ssl verify none check server app-1c app.us-east-1c.example.com:443 ssl verify no...
Assuming HAProxy 1.5 or later: http-response set-header X-Server %s
HAProxy
43,105,840
10
I need to integrate several web applications on-premise and off-site under a common internally hosted URL. The on-premise applications are in the same data center as the haproxy, but the off-site applications can only be reached via a http proxy because the server on which haproxy is running has no direct Internet acce...
How about to use delegate ( http://delegate.org/documents/ ) for this, just as an idea. haproxy -> delegate -f -vv -P127.0.0.1:8081 PROXY=<your-proxy> http://delegate9.org/delegate/Manual.shtml?PROXY I know it's not that elegant but it could work. I have tested this setup with a local squid and this curl call echo 'GET...
HAProxy
47,605,766
10
Is it possible to split configuration arguments (in haproxy.cfg) onto multiple lines? Example Current frontend https-in bind :443 ssl strict-sni crt </path/to/cert1.pem> crt </path/to/cert2.pem> crt </path/to/cert3.pem> ... Ideal frontend https-in bind :443 ssl strict-sni crt </path/to/cert1.pem> ...
You can't do multiline syntax in the haproxy.cfg. Take a look at the file format documentation: https://cbonte.github.io/haproxy-dconv/1.8/configuration.html#2.1 Update: Thanks to the comment from Venky I see that there is also the option to use crt-list which does provide an option for multi line pem file references....
HAProxy
53,713,425
10
I have some Lua code, which I use in my openresty nginx.conf file. This Lua code contains such lines: ... local secret = os.getenv("PATH") assert(secret ~= nil, "Environment variable PATH not set") ... Just for testing reasons I tried to check if PATH variable is set and for some reason the assert statement does not p...
You need to tell nginx to make environment variables available. From the docs for the env directive: "By default, nginx removes all environment variables inherited from its parent process except the TZ variable. This directive allows preserving some of the inherited variables, changing their values, or creating new env...
OpenResty
41,800,071
23
I have a question regarding NGINX rate limiting. Is it possible to do rate limiting based on the decoded value of JWT token? I cannot find any information like this in the docs. Or even if there is a way of doing rate limiting by creating pure custom variable (using LuaJIT) which will be assigned with a value from my d...
As you may know that rate limit is applied through unique ip address for best result you should use unique jwt value or token to rate limit. You can follow any of these 3 methods Method You can directly use jwt token in limit_req_zone. http { ... limit_req_zone $http_authorization zone=req_zone:10m rate=5r/s;...
OpenResty
64,263,895
12
I'm pretty new to C++ so I tend to design with a lot of Java-isms while I'm learning. Anyway, in Java, if I had class with a 'search' method that would return an object T from a Collection< T > that matched a specific parameter, I would return that object and if the object was not found in the collection, I would retur...
In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference: Attr *getAttribute(const string& attribute_name) const { //search collection //if found at i return &attributes[i]; //if not found return nullptr; } Other...
Sentinel
2,639,255
101
While reading Eric Niebler's range proposal, I've come across the term sentinel as replacement for the end iterator. I'm having a difficult time understanding the benefits of sentinel over an end iterator. Could someone provide a clear example of what sentintel brings to the table that cannot be done with standard iter...
Sentinel simply allows the end iterator to have a different type. The allowed operations on a past-the-end iterator are limited, but this is not reflected in its type. It is not ok to * a .end() iterator, but the compiler will let you. A sentinel does not have unary dereference, or ++, among other things. It is gener...
Sentinel
32,900,557
24
We're currently using Redis 2.8.4 and StackExchange.Redis (and loving it) but don't have any sort of protection against hardware failures etc at the moment. I'm trying to get the solution working whereby we have master/slaves and sentinel monitoring but can't quite get there and I'm unable to find any real pointers aft...
I was able to spend some time last week with the Linux guys testing scenarios and working on the C# side of this implementation and am using the following approach: Read the sentinel addresses from config and create a ConnectionMultiplexer to connect to them Subscribe to the +switch-master channel Ask each sentinel se...
Sentinel
25,385,075
12
I have attempted everything recommended by the following error message: (error) DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you ...
https://www.reddit.com/r/redis/comments/3zv85m/new_security_feature_redis_protected_mode/ As you know we got several problems from unprotected Redis instances exposed to the internet. I covered the reason why a restrictive binding to 127.0.0.1 by default may be an usability concern and, even worse, may not fix the prob...
Sentinel
43,107,552
12
Ok, I feel like I'm missing some crucial piece of information. Locally I have 1 master and 1 slave redis server running on different ports http://redis.io/topics/sentinel I also have 3 sentinels and they all appear to be aware of each other and working as expected. Now I have a big of java code pointing to 127.0.0.1:6...
You have to subscribe to sentinel messages on one of their pubsub channels. You can see at the link that you posted that the sentinel will publish out messages like +odown <instance details> -- The specified instance is now in Objectively Down state. -odown <instance details> -- The specified instance is no longer in ...
Sentinel
15,437,334
10
I've googled but not been able to find out what the swift equivalent to respondsToSelector: is. This is the only thing I could find (Swift alternative to respondsToSelector:) but isn't too relevant in my case as its checking the existence of the delegate, I don't have a delegate I just want to check if a new API exists...
As mentioned, in Swift most of the time you can achieve what you need with the ? optional unwrapper operator. This allows you to call a method on an object if and only if the object exists (not nil) and the method is implemented. In the case where you still need respondsToSelector:, it is still there as part of the NSO...
Swift
24,167,791
217
I am starting to learn Swift, and have been following the very good Stanford University video lectures on YouTube. Here is a link if you are interested or it helps (although it isn't required to understand my problem): Developing iOS 8 Apps with Swift - 2. More Xcode and Swift, MVC While following the lectures I got to...
I myself am also taking the Standford course and I got stuck here for a long time too, but after some searching, I found something from here: Xcode release notes and it mentioned something below: Swift 1.2 is strict about checking type-based overloading of @objc methods and initializers, something not supported by ...
Swift
29,457,720
216
I have a (somewhat?) basic question regarding time conversions in Swift. I have an integer that I would like converted into Hours / Minutes / Seconds. Example: Int = 27005 would give me: 7 Hours 30 Minutes 5 Seconds I know how to do this in PHP, but alas, swift isn't PHP.
Define func secondsToHoursMinutesSeconds(_ seconds: Int) -> (Int, Int, Int) { return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60) } Use > secondsToHoursMinutesSeconds(27005) (7,30,5) or let (h,m,s) = secondsToHoursMinutesSeconds(27005) The above function makes use of Swift tuples to return thre...
Swift
26,794,703
216
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?
For me none of the previous solutions worked. We discovered that there is a flag ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES (in earlier versions: "Embedded Content Contains Swift Code") in the Build Settings that needs to be set to YES. It was NO by default!
Swift
24,002,836
216
Is it possible to use the range operator ... and ..< with if statement. Maye something like this: let statusCode = 204 if statusCode in 200 ..< 299 { NSLog("Success") }
You can use the "pattern-match" operator ~=: if 200 ... 299 ~= statusCode { print("success") } Or a switch-statement with an expression pattern (which uses the pattern-match operator internally): switch statusCode { case 200 ... 299: print("success") default: print("failure") } Note that ..< denotes a ran...
Swift
24,893,110
215
How to concatenate string in Swift? In Objective-C we do like NSString *string = @"Swift"; NSString *resultStr = [string stringByAppendingString:@" is a new Programming Language"]; or NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string]; But I want to do this in Swift-language.
You can concatenate strings a number of ways: let a = "Hello" let b = "World" let first = a + ", " + b let second = "\(a), \(b)" You could also do: var c = "Hello" c += ", World" I'm sure there are more ways too. Bit of description let creates a constant. (sort of like an NSString). You can't change its value once y...
Swift
24,034,174
214
is there any way to get absolute value from an integer? for example -8 to 8 I already tried to use UInt() assuming it will convert the Int to unsigned value but it didn't work.
The standard abs() function works great here: let c = -8 print(abs(c)) // 8
Swift
24,159,627
213
Suppose I have an array and I want to pick one element at random. What would be the simplest way to do this? The obvious way would be array[random index]. But perhaps there is something like ruby's array.sample? Or if not could such a method be created by using an extension?
Swift 4.2 and above The new recommended approach is a built-in method on the Collection protocol: randomElement(). It returns an optional to avoid the empty case I assumed against previously. let array = ["Frodo", "Samwise", "Merry", "Pippin"] print(array.randomElement()!) // Using ! knowing I have array.count > 0 If ...
Swift
24,003,191
213
How can I convert a String "Hello" to an Array ["H","e","l","l","o"] in Swift? In Objective-C I have used this: NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]]; for (int i=0; i < [myString length]; i++) { NSString *ichar = [NSString stringWithFormat:@"%c", [myString charact...
It is even easier in Swift: let string : String = "Hello 🐶🐮 🇩🇪" let characters = Array(string) println(characters) // [H, e, l, l, o, , 🐶, 🐮, , 🇩🇪] This uses the facts that an Array can be created from a SequenceType, and String conforms to the SequenceType protocol, and its sequence generator enumerates th...
Swift
25,921,204
212
In my app I have a function that makes an NSRURLSession and sends out an NSURLRequest using sesh.dataTaskWithRequest(req, completionHandler: {(data, response, error) In the completion block for this task, I need to do some computation that adds a UIImage to the calling viewcontroller. I have a func called func display...
Modern versions of Swift use DispatchQueue.main.async to dispatch to the main thread: DispatchQueue.main.async { // your code here } To dispatch after on the main queue, use: DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // your code here } Older versions of Swift used: dispatch_async(dispatch_get_main...
Swift
24,985,716
212
Now I would like to migrate my ObjC framework to Swift and I got the following error: include of non-modular header inside framework module 'SOGraphDB' The references is to a header file which just define a protocol and I use this header file in some classes to use this protocol. Is seems related to the module feature...
Is your header public? Select the header file in the project explorer. Then in the section on the right in xcode, you'll notice there is a dropdown next to the target. Change that from "project" to "public". This worked for me.
Swift
24,103,169
212
I am beginning to learn swift by following the iBook-The Swift Programming Language on Swift provided by Apple. The book says to create an empty dictionary one should use [:] same as while declaring array as []: I declared an empty array as follows : let emptyArr = [] // or String[]() But on declaring empty dictionary...
var emptyDictionary = [String: String]() var populatedDictionary = ["key1": "value1", "key2": "value2"] Note: if you're planning to change the contents of the dictionary over time then declare it as a variable (var). You can declare an empty dictionary as a constant (let) but it would be pointless if you have the i...
Swift
24,033,393
212
Given the following enum: enum Audience { case Public case Friends case Private } How do I get the string "Public" from the audience constant below? let audience = Audience.Public
The idiomatic interface for 'getting a String' is to use the CustomStringConvertible interface and access the description getter. You could specify the 'raw type' as String but the use of description hides the 'raw type' implementation; avoids string comparisons in switch/case and allows for internationalization, if y...
Swift
24,701,075
210
in iOS6 I noticed the new Container View but am not quite sure how to access it's controller from the containing view. Scenario: I want to access the labels in Alert view controller from the view controller that houses the container view. There's a segue between them, can I use that?
Yes, you can use the segue to get access the child view controller (and its view and subviews). Give the segue an identifier (such as alertview_embed), using the Attributes inspector in Storyboard. Then have the parent view controller (the one housing the container view) implement a method like this: - (void) prepareFo...
Swift
13,279,105
210
From Apple book "One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference." Can anyone help me understand what that means? To me, classes and structs seem to be the same.
Here's an example with a class. Note how when the name is changed, the instance referenced by both variables is updated. Bob is now Sue, everywhere that Bob was ever referenced. class SomeClass { var name: String init(name: String) { self.name = name } } var aClass = SomeClass(name: "Bob") var bCla...
Swift
24,217,586
209
After updating to the latest version of Xcode at the moment (version 10.0) the project is unable to build because it found some errors regarding some "Command CompileSwift failed with a nonzero exit code" error. How do I solve this errors? They appear in most of the Pods (I use CocoaPods) I use inside my project. I hav...
For me, just cleaning project works using ShiftCommandK & OptionShiftCommandK.
Swift
52,387,452
208
This is my setup: I have an UIScrollView with leading,top, trialing edge set to 0. Inside this I add an UIStackView with this constraints: stackView.centerYAnchor.constraintEqualToAnchor(selectedContactsScrollView.centerYAnchor).active = true stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView....
When isLayoutMarginsRelativeArrangement property is true, the stack view will layout its arranged views relative to its layout margins. stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) stackView.isLayoutMarginsRelativeArrangement = true But it affects all arranged views inside to the stac...
Swift
32,551,890
207
I have a dictionary containing UIColor objects hashed by an enum value, ColorScheme: var colorsForColorScheme: [ColorScheme : UIColor] = ... I would like to be able to extract an array of all the colors (the values) contained by this dictionary. I thought I could use the values property, as is used when iterating over...
As of Swift 2.0, Dictionary’s values property now returns a LazyMapCollection instead of a LazyBidirectionalCollection. The Array type knows how to initialise itself using this abstract collection type: let colors = Array(colorsForColorSchemes.values) Swift's type inference already knows that these values are UIColor ...
Swift
26,988,167
207
I'm trying to make a calculator of growth rate (Double) that will round the result to the nearest Integer and recalculate from there, as such: let firstUsers = 10.0 let growth = 0.1 var users = firstUsers var week = 0 while users < 14 { println("week \(week) has \(users) users") users += users * growth we...
There is a round available in the Foundation library (it's actually in Darwin, but Foundation imports Darwin and most of the time you'll want to use Foundation instead of using Darwin directly). import Foundation users = round(users) Running your code in a playground and then calling: print(round(users)) Outputs: 1...
Swift
26,350,977
207
In Swift 2.0, Apple introduced a new way to handle errors (do-try-catch). And few days ago in Beta 6 an even newer keyword was introduced (try?). Also, knew that I can use try!. What's the difference between the 3 keywords, and when to use each?
Updated for Swift 5.1 Assume the following throwing function: enum ThrowableError: Error { case badError(howBad: Int) } func doSomething(everythingIsFine: Bool = false) throws -> String { if everythingIsFine { return "Everything is ok" } else { throw ThrowableError.badError(howBad: 4) } } try ...
Swift
32,390,611
206
Is there a way to get the index of the array in map or reduce in Swift? I'm looking for something like each_with_index in Ruby. func lunhCheck(number : String) -> Bool { var odd = true; return reverse(number).map { String($0).toInt()! }.reduce(0) { odd = !odd return $0 + (odd ? ($1 == 9 ? 9 : ($...
You can use enumerate to convert a sequence (Array, String, etc.) to a sequence of tuples with an integer counter and and element paired together. That is: let numbers = [7, 8, 9, 10] let indexAndNum: [String] = numbers.enumerate().map { (index, element) in return "\(index): \(element)" } print(indexAndNum) // ["0:...
Swift
28,012,205
206
So I have converted an NSURL to a String. So if I println it looks like file:///Users/... etc. Later I want this back as an NSURL so I try and convert it back as seen below, but I lose two of the forward slashes that appear in the string version above, that in turn breaks the code as the url is invalid. Why is my conve...
In Swift 5, Swift 4 and Swift 3 To convert String to URL: URL(string: String) or, URL.init(string: "yourURLString") And to convert URL to String: URL.absoluteString The one below converts the 'contents' of the url to string String(contentsOf: URL)
Swift
27,062,454
206
I'd like to map a function on all keys in the dictionary. I was hoping something like the following would work, but filter cannot be applied to dictionary directly. What's the cleanest way of achieving this? In this example, I'm trying to increment each value by 1. However this is incidental for the example - the main ...
Swift 4+ Good news! Swift 4 includes a mapValues(_:) method which constructs a copy of a dictionary with the same keys, but different values. It also includes a filter(_:) overload which returns a Dictionary, and init(uniqueKeysWithValues:) and init(_:uniquingKeysWith:) initializers to create a Dictionary from an arbit...
Swift
24,116,271
206
I would like a for in loop to send off a bunch of network requests to firebase, then pass the data to a new view controller once the the method finishes executing. Here is my code: var datesArray = [String: AnyObject]() for key in locationsArray { let ref = Firebase(url: "http://myfirebase.com/" + "\(key.0)...
You can use dispatch groups to fire an asynchronous callback when all your requests finish. Here's an example using dispatch groups to execute a callback asynchronously when multiple networking requests have all finished. override func viewDidLoad() { super.viewDidLoad() let myGroup = DispatchGroup() for ...
Swift
35,906,568
205
I have been reading about Optionals in Swift, and I have seen examples where if let is used to check if an Optional holds a value, and in case it does – do something with the unwrapped value. However, I have seen that in Swift 2.0 the keyword guard let is used mostly. I wonder whether if let has been removed from Swift...
if let and guard let serve similar, but distinct purposes. The "else" case of guard must exit the current scope. Generally that means it must call return or abort the program. guard is used to provide early return without requiring nesting of the rest of the function. if let nests its scope, and does not require anythi...
Swift
32,256,834
205
I'm trying to learn how to use UICollectionView. The documentation is a little hard to understand and the tutorials that I found were either in Objective C or long complicated projects. When I was learning how to use UITableView, We ❤ Swift's How to make a simple tableview with iOS 8 and Swift had a very basic setup an...
This project has been tested with Xcode 10 and Swift 4.2. Create a new project It can be just a Single View App. Add the code Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in th...
Swift
31,735,228
205
I'm really confused with regards to how we create an empty array in Swift. Could you please show me the different ways we have to create an empty array with some detail?
Here you go: var yourArray = [String]() The above also works for other types and not just strings. It's just an example. Adding Values to It I presume you'll eventually want to add a value to it! yourArray.append("String Value") Or let someString = "You can also pass a string variable, like this!" yourArray.append(so...
Swift
30,430,550
204
I'm using Xcode 8.0 beta 4. In previous version, UIViewController have method to set the status bar style public func preferredStatusBarStyle() -> UIStatusBarStyle However, I found it changed to a "Get ONLY varaiable" in Swift 3. public var preferredStatusBarStyle: UIStatusBarStyle { get } How can provide the style...
[UPDATED] For Xcode 10+ & Swift 4.2+ This is the preferred method for iOS 7 and higher In your application's Info.plist, set View controller-based status bar appearance to YES. Override preferredStatusBarStyle (Apple docs) in each of your view controllers. For example: override var preferredStatusBarStyle: UIStatusBar...
Swift
38,740,648
203
I have the following class: class ReportView: NSView { var categoriesPerPage = [[Int]]() var numPages: Int = { return categoriesPerPage.count } } Compilation fails with the message: Instance member 'categoriesPerPage' cannot be used on type 'ReportView' What does this mean?
Sometimes Xcode when overrides methods adds class func instead of just func. Then in static method you can't see instance properties. It is very easy to overlook it. That was my case.
Swift
32,351,343
203
It's possible to add extensions to existing Swift object types using extensions, as described in the language specification. As a result, it's possible to create extensions such as: extension String { var utf8data:NSData { return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! ...
Most examples I have seen mimic the Objective-C approach. The example extension above would be: String+UTF8Data.swift The advantages are that the naming convention makes it easy to understand that it is an extension, and which Class is being extended. The problem with using Extensions.swift or even StringExtensions.swi...
Swift
26,319,660
203
I want to leave a bit of space at the beginning of a UITextField, just like here: Add lefthand margin to UITextField But I don't know how to do that with Swift.
This is what I am using right now: Swift 4.2, 5 class TextField: UITextField { let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) override open func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: padding) } override open func placeholderRect(forBounds bou...
Swift
25,367,502
203
I have an Objective-C project in Xcode 8 Beta 3. Since updating, whenever I try to build I receive the following error: “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift vers...
If you are using CocoaPods and want it to be fixed automatically every time you are doing a pod install, then you can add these lines to the end of your Podfile: post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_...
Swift
38,446,097
202
I'm programming an app in swift and when I run the test app on the iPhone simulator everything works, but then I try to swipe right, which is a gesture that I added for it to go to the next Page(View Controller Two) it crashes and shows this error report in the console log. 2014-10-18 12:07:34.400 soundtest[17081:81892...
CMYR - "his could also happen if you've wired up a button to an IBAction that doesn't exist anymore (or has been renamed)" If you're running into this problem make sure that you go to Main.storyboard, RIGHT click on the yellow box icon (view controller) at the top of the phone outline and DELETE the outlet(s) with yell...
Swift
26,442,414
200
I am familiar with switch statements in Swift, but wondering how to replace this piece of code with a switch: if someVar < 0 { // do something } else if someVar == 0 { // do something else } else if someVar > 0 { // etc }
Here's one approach. Assuming someVar is an Int or other Comparable, you can optionally assign the operand to a new variable. This lets you scope it however you want using the where keyword: var someVar = 3 switch someVar { case let x where x < 0: print("x is \(x)") case let x where x == 0: print("x is \(x)") ...
Swift
31,656,642
199
I'm going through the iOS tutorial from Apple developer page. It seems to me that protocol and interface almost have the same functionality. Are there any differences between the two? the different usage in the project? Updated Yes, I did read the link above and I'm still not sure what the differences and usage betw...
Essentially protocols are very similar to Java interfaces except for: Swift protocols can also specify properties that must be implemented (i.e. fields) Swift protocols need to deal with value/reference through the use of the mutating keyword (because protocols can be implemented by structures, enumerations or classes...
Swift
30,859,334
199
Arrays in Swift support the += operator to add the contents of one Array to another. Is there an easy way to do that for a dictionary? eg: var dict1 = ["a" : "foo"] var dict2 = ["b" : "bar"] var combinedDict = ... (some way of combining dict1 & dict2 without looping)
You can define += operator for Dictionary, e.g., func += <K, V> (left: inout [K:V], right: [K:V]) { for (k, v) in right { left[k] = v } }
Swift
24,051,904
199
Does Swift have something like _.findWhere in Underscore.js? I have an array of structs of type T and would like to check if array contains a struct object whose name property is equal to Foo. Tried to use find() and filter() but they only work with primitive types, e.g. String or Int. Throws an error about not conform...
SWIFT 5 Check if the element exists if array.contains(where: {$0.name == "foo"}) { // it exists, do something } else { //item could not be found } Get the element if let foo = array.first(where: {$0.name == "foo"}) { // do something with foo } else { // item could not be found } Get the element and its of...
Swift
28,727,845
197
Finally now with Beta 5 we can programmatically pop to a parent View. However, there are several places in my app where a view has a "Save" button that concludes a several step process and returns to the beginning. In UIKit, I use popToRootViewController(), but I have been unable to figure out a way to do the same in ...
iOS 16 Update: NavigationPath was added to make this easier. Use with the new NavigationStack that also fixes a lot of bugs. Setting the view modifier isDetailLink to false on a NavigationLink is the key to getting pop-to-root to work. isDetailLink is true by default and is adaptive to the containing View. On iPad land...
Swift
57,334,455
196
I want to convert the string "2014-07-15 06:55:14.198000+00:00" to an NSDate in Swift.
try this: let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = /* find out and place date format from * http://userguide.icu-project.org/formatparse/datetime */ let date = dateFormatter.dateFromString(/* your_date_string */) For further query, check ...
Swift
24,777,496
196
Getting this error in Swift 2.0. Binary operator '|' cannot be applied to two UIViewAutoresizing operands Here is the code: let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568)) addSubview(view) view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight Any idea what...
The OptionSetType got an updated syntax for Swift 2.x and another update for Swift 3.x Swift 3.x view.autoresizingMask = [.flexibleWidth, .flexibleHeight] Swift 2.x view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
Swift
30,867,325
195
I haven't read too much into Swift but one thing I noticed is that there are no exceptions. So how do they do error handling in Swift? Has anyone found anything related to error-handling?
Swift 2 & 3 Things have changed a bit in Swift 2, as there is a new error-handling mechanism, that is somewhat more similar to exceptions but different in detail. 1. Indicating error possibility If function/method wants to indicate that it may throw an error, it should contain throws keyword like this func summonDefau...
Swift
24,010,569
195
I am trying to register my application for local notifications this way: UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil)) In Xcode 7 and Swift 2.0 - I get error Binary Operator "|" cann...
In Swift 2, many types that you would typically do this for have been updated to conform to the OptionSetType protocol. This allows for array like syntax for usage, and In your case, you can use the following. let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil) UIApplication.sharedApp...
Swift
30,761,996
194
I give it a try to understand new error handling thing in swift 2. Here is what I did: I first declared an error enum: enum SandwichError: Error { case NotMe case DoItYourself } And then I declared a method that throws an error (not an exception folks. It is an error.). Here is that method: func makeMeSandwich...
There are two important points to the Swift 2 error handling model: exhaustiveness and resiliency. Together, they boil down to your do/catch statement needing to catch every possible error, not just the ones you know you can throw. Notice that you don't declare what types of errors a function can throw, only whether it...
Swift
30,720,497
194
I need to capture multiple groups of the same pattern. Suppose, I have the following string: HELLO,THERE,WORLD And I've written the following pattern ^(?:([A-Z]+),?)+$ What I want it to do is to capture every single word, so that Group 1 is : "HELLO", Group 2 is "THERE" and Group 3 is "WORLD". What my regex is actual...
With one group in the pattern, you can only get one exact result in that group. If your capture group gets repeated by the pattern (you used the + quantifier on the surrounding non-capturing group), only the last value that matches it gets stored. You have to use your language's regex implementation functions to find a...
Swift
37,003,623
192
The background text in the status bar is still black. How do I change the color to white? // io8, swift, Xcode 6.0.1 override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = UIColor.blackColor() self.navigationController?.navigationBar.titleTextAttributes = ...
In AppDelegate.swift, in application(_:didFinishLaunchingWithOptions:) I put the following: UINavigationBar.appearance().barTintColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0) UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().titleTextAttributes = [NS...
Swift
26,008,536
192
In Objective C, one could do the following to check for strings: if ([myString isEqualToString:@""]) { NSLog(@"myString IS empty!"); } else { NSLog(@"myString IS NOT empty, it is: %@", myString); } How does one detect empty strings in Swift?
There is now the built in ability to detect empty string with .isEmpty: if emptyString.isEmpty { print("Nothing to see here") } Apple Pre-release documentation: "Strings and Characters".
Swift
24,133,157
192
I'm currently working on a iOS app developed in Swift and I need to store some user-created content on the device but I can't seem to find a simple and quick way to store/receive the users content on the device. Could someone explain how to store and access local storage? The idea is to store the data when the user ex...
The simplest solution for storing a few strings or common types is UserDefaults. The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs. UserDefaults lets us store objects against a key of our choice, It's a good idea to store these k...
Swift
28,628,225
191
How can we measure the time elapsed for running a function in Swift? I am trying to display the elapsed time like this: "Elapsed time is .05 seconds". Saw that in Java, we can use System.nanoTime(), are there any equivalent methods available in Swift to accomplish this? Please have a look at the sample program: func is...
Update With Swift 5.7, everything below becomes obsolete. Swift 5.7 introduces the concept of a Clock which has a function designed to do exactly what is required here. There are two concrete examples of a Clock provided: ContinuousClock and SuspendingClock. The former keeps ticking when the system is suspending and th...
Swift
24,755,558
191
I have a framework (in this instance it's RxSwift) which I've compiled using Xcode 11.0 into the traditional RxSwift.framework style package This imported fine into Xcode 11.0 and also 11.1 never had any problems with it Today, upon Apple's release of Xcode 11.2, I upgraded, and I am presented with the error: Module co...
OK, Turns out if you watch the WWDC video, they explain it: https://developer.apple.com/videos/play/wwdc2019/416/ You need to set the Build Settings > Build Options > Build Libraries for Distribution option to Yes in your framework's build settings, otherwise the swift compiler doesn't generate the neccessary .swiftint...
Swift
58,654,714
190
How do you import CommonCrypto in a Swift framework for iOS? I understand how to use CommonCrypto in a Swift app: You add #import <CommonCrypto/CommonCrypto.h> to the bridging header. However, Swift frameworks don't support bridging headers. The documentation says: You can import external frameworks that have a pure ...
Something a little simpler and more robust is to create an Aggregate target called "CommonCryptoModuleMap" with a Run Script phase to generate the module map automatically and with the correct Xcode/SDK path: The Run Script phase should contain this bash: # This if-statement means we'll only run the main script if th...
Swift
25,248,598
190
How can I simply scan barcodes on iPhone and/or iPad?
We produced the 'Barcodes' application for the iPhone. It can decode QR Codes. The source code is available from the zxing project; specifically, you want to take a look at the iPhone client and the partial C++ port of the core library. The port is a little old, from circa the 0.9 release of the Java code, but should s...
Swift
838,724
190
I have a protocol: enum DataFetchResult { case success(data: Data) case failure } protocol DataServiceType { func fetchData(location: String, completion: (DataFetchResult) -> (Void)) func cachedData(location: String) -> Data? } With an example implementation: /// An implementation of DataServiceTy...
This is due to a change in the default behaviour for parameters of function type. Prior to Swift 3 (specifically the build that ships with Xcode 8 beta 6), they would default to being escaping – you would have to mark them @noescape in order to prevent them from being stored or captured, which guarantees they won't out...
Swift
38,990,882
189
How do you play a video with AV Kit Player View Controller in Swift? override func viewDidLoad() { super.viewDidLoad() let videoURLWithPath = "http://****/5.m3u8" let videoURL = NSURL(string: videoURLWithPath) playerViewController = AVPlayerViewController() dispatch_async(dispat...
SwiftUI import SwiftUI import AVKit struct ContentView: View { var body: some View { let videoURL = URL(string: "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_5MB.mp4") let player = AVPlayer(url: videoURL!) VideoPlayer(player: player) } } Swift 3.x - ...
Swift
25,932,570
189
I'm working in swift on Xcode and by default it creates a test file that references XCTest. When I set the target membership to my main project it causes this error Cannot load underlying module for XCTest If this target membership is not set the tests runs properly and everything works fine.
Double check that the file in question is not in the main target but instead only the test target. Only the test target will have that framework to import.
Swift
29,965,397
188
I want to programmatically create a UIImage filled by a solid color. Does anyone have an idea of how to do this in Swift?
Another nice solution, Swift 3.0 public extension UIImage { convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect...
Swift
26,542,035
187
In Swift, is there any way to check if an index exists in an array without a fatal error being thrown? I was hoping I could do something like this: let arr: [String] = ["foo", "bar"] let str: String? = arr[1] if let str2 = arr[2] as String? { // this wouldn't run println(str2) } else { // this would be run ...
An elegant way in Swift: let isIndexValid = array.indices.contains(index)
Swift
25,976,909
187
I have Encoded text(NSString) using NSData Class new API which is Added in iOS7. using this - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding; here is my code NSString *base64EncodedString = [[myText dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0]; NSLog(@"%@", base64EncodedString);...
Swift 3+ let plainString = "foo" Encoding let plainData = plainString.data(using: .utf8) let base64String = plainData?.base64EncodedString() print(base64String!) // Zm9v Decoding if let decodedData = Data(base64Encoded: base64String!), let decodedString = String(data: decodedData, encoding: .utf8) { print(decode...
Swift
19,088,231
187
I have this code to display a list of custom rows. struct ContentView : View { var body: some View { VStack(alignment: .leading) { List(1...10) {_ in CustomRow() } } } } However, I want to remove the line on each row. I tried not using List and instead us...
iOS 15: This year Apple introduced a new modifier .listRowSeparator that can be used to style the separators. you can pass .hidden to hide it: List { ForEach(items, id:\.self) { Text("Row \($0)") .listRowSeparator(.hidden) } } iOS 14: you may consider using a LazyVStack inside a ScrollVie...
Swift
56,553,672
186
I tried to change the UIStackView background from clear to white in Storyboard inspector, but when simulating, the background color of the stack view still has a clear color. How can I change the background color of a UIStackView?
You can't do this – UIStackView is a non-drawing view, meaning that drawRect() is never called and its background color is ignored. If you desperately want a background color, consider placing the stack view inside another UIView and giving that view a background color. Reference from HERE. EDIT: You can add a ...
Swift
34,868,344
186
I have a problem with Swift class. I have a swift file for UITableViewController class and UITableViewCell class. My problem is the UITableViewCell class, and outlets. This class has an error Class "HomeCell" has no initializers, and I don't understand this problem. Thanks for your responses. import Foundation import U...
You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase. @IBOutlet var imgBook: UIImageView! @IBOutlet var titleBook: UILabel! @IBOutlet var pageBook: UILabel! Read this doc, they explain it al...
Swift
27,797,351
186
Unlike Objective-C, Swift has no preprocessor, so is there still a way to manually deprecate members of a class? I am looking for something similar to this: -(id)method __deprecated;
You can use the Available tag, for example : @available(*, deprecated) func myFunc() { // ... } Where * is the platform (iOS, iOSApplicationExtension, macOS, watchOS, tvOS, * for all, etc.). You can also specify the version of the platform from which it was introduced, deprecated, obsoleted, renamed, and a messag...
Swift
25,405,133
186
I am currently opening the link in my app in a WebView, but I'm looking for an option to open the link in Safari instead.
It's not "baked in to Swift", but you can use standard UIKit methods to do it. Take a look at UIApplication's openUrl(_:) (deprecated) and open(_:options:completionHandler:). Swift 4 + Swift 5 (iOS 10 and above) guard let url = URL(string: "https://stackoverflow.com") else { return } UIApplication.shared.open(url) Swi...
Swift
25,945,324
185
Here is my Objective-C code which I'm using to load a nib for my customised UIView: -(id)init{ NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil]; return [subviewArray objectAtIndex:0]; } What is the equivalent code in Swift?
My contribution: extension UIView { class func fromNib<T: UIView>() -> T { return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T } } Then call it like this: let myCustomView: CustomView = UIView.fromNib() ..or even: let myCustomView: CustomView = .from...
Swift
24,857,986
185
Before swift I would define a set of schemes for alpha, beta, and distribution builds. Each of these schemes would have a set of macros that were defined to gate certain behaviors at the project level. The simplest example is the DEBUG=1 macro that is defined by default for all Xcode projects in the default scheme fo...
In Swift you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per Apple docs. Here's an example: #if DEBUG let a = 2 #else let a = 3 #endif Now, you must set the "DEBUG" symbol elsewhere, though. Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" ...
Swift
24,111,854
184
I have a View Controller in which my value is 0 (label) and when I open that View Controller from another ViewController I have set viewDidAppear to set value 20 on label. It works fine but when I close my app and than again I open my app but the value doesn't change because viewDidLoad, viewDidAppear and viewWillAppe...
Curious about the exact sequence of events, I instrumented an app as follows: (@Zohaib, you can use the NSNotificationCenter code below to answer your question). // AppDelegate.m - (void)applicationWillEnterForeground:(UIApplication *)application { NSLog(@"app will enter foreground"); } - (void)applicationDidBec...
Swift
15,864,364
183
Given: typealias Action = () -> () var action: Action = { } func doStuff(stuff: String, completion: @escaping Action) { print(stuff) action = completion completion() } func doStuffAgain() { print("again") action() } doStuff(stuff: "do stuff") { print("swift 3!") } doStuffAgain() Is there ...
from: swift-users mailing list Basically, @escaping is valid only on closures in function parameter position. The noescape-by-default rule only applies to these closures at function parameter position, otherwise they are escaping. Aggregates, such as enums with associated values (e.g. Optional), tuples, structs, etc...
Swift
39,618,803
182
I started my search by wanting to know how I could share to other apps in iOS. I discovered that two important ways are UIActivityViewController UIDocumentInteractionController These and other methods are compared in this SO answer. Often when I am learning a new concept I like to see a basic example to get me star...
UIActivityViewController Example Project Set up your storyboard with two buttons and hook them up to your view controller (see code below). Add an image to your Assets.xcassets. I called mine "lion". Code import UIKit class ViewController: UIViewController { // share text @IBAction func shareTextButton(_...
Swift
35,931,946
182
After I installed Xcode 7 beta and convert my swift code to Swift 2, I got some issue with the code that I can't figure out. I know Swift 2 is new so I search and figure out since there is nothing about it, I should write a question. Here is the error: Call can throw, but it is not marked with 'try' and the error is n...
You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so: func deleteAccountDetail() { let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManaged...
Swift
30,737,262
182
I'm trying to ultimately have an NSMutableURLRequest with a valid HTTPBody, but I can't seem to get my string data (coming from a UITextField) into a usable NSData object. I've seen this method for going the other way: NSString(data data: NSData!, encoding encoding: UInt) But I can't seem to find any documentation for...
In Swift 3 let data = string.data(using: .utf8) In Swift 2 (or if you already have a NSString instance) let data = string.dataUsingEncoding(NSUTF8StringEncoding) In Swift 1 (or if you have a swift String): let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding) Also note that data is an Optional<...
Swift
24,039,868
182
I was just curious as to how I would approach this. If I had a function, and I wanted something to happen when it was fully executed, how would I add this into the function? Thanks
Say you have a download function to download a file from network, and want to be notified when download task has finished. typealias CompletionHandler = (success:Bool) -> Void func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) { // download code. let flag = true // true if download suc...
Swift
30,401,439
181
I'm trying to convert some of my Obj-C class to Swift. And some other Obj-C classes still using enum in that converted class. I searched In the Pre-Release Docs and couldn't find it or maybe I missed it. Is there a way to use Swift enum in Obj-C Class? Or a link to the doc of this issue? This is how I declared my enum ...
As of Swift version 1.2 (Xcode 6.3) you can. Simply prefix the enum declaration with @objc @objc enum Bear: Int { case Black, Grizzly, Polar } Shamelessly taken from the Swift Blog Note: This would not work for String enums or enums with associated values. Your enum will need to be Int-bound In Objective-C this...
Swift
24,139,320
181
In The Swift Programming Language, it says: Functions can also take a variable number of arguments, collecting them into an array. func sumOf(numbers: Int...) -> Int { ... } When I call such a function with a comma-separated list of numbers (`sumOf(1, 2, 3, 4), they are made available as an array inside th...
Splatting is not in the language yet, as confirmed by the devs. [SR-128] Pass array to variadic function Workaround for now is to use an overload or wait if you cannot add overloads.
Swift
24,024,376
181
Can someone explain to me what is the exact difference between modal and push segue? I know that when we use push the segue gets added to a stack, so when we keep using push it keeps occupying memory? Can someone please show me how these two are implemented? Modal segues can be created by simply ctrl-click and draggi...
A push Segue is adding another VC to the navigation stack. This assumes that VC that originates the push is part of the same navigation controller that the VC that is being added to the stack belongs to. Memory management is not an issue with navigation controllers and a deep stack. As long as you are taking care of...
Swift
9,392,744
181
Swift's Encodable/Decodable protocols, released with Swift 4, make JSON (de)serialization quite pleasant. However, I have not yet found a way to have fine-grained control over which properties should be encoded and which should get decoded. I have noticed that excluding the property from the accompanying CodingKeys enu...
The list of keys to encode/decode is controlled by a type called CodingKeys (note the s at the end). The compiler can synthesize this for you but can always override that. Let's say you want to exclude the property nickname from both encoding and decoding: struct Person: Codable { var firstName: String var last...
Swift
44,655,562
180
Swift 4 added the new Codable protocol. When I use JSONDecoder it seems to require all the non-optional properties of my Codable class to have keys in the JSON or it throws an error. Making every property of my class optional seems like an unnecessary hassle since what I really want is to use the value in the json or a...
You can implement the init(from decoder: Decoder) method in your type instead of using the default implementation: class MyCodable: Codable { var name: String = "Default Appleseed" required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if l...
Swift
44,575,293
180
There are two overloads for dequeueReusableCellWithIdentifier and I'm trying to determine when should I use one vs the other? The apple docs regarding the forIndexPath function states, "This method uses the index path to perform additional configuration based on the cell’s position in the table view." I'm not sure how...
The most important difference is that the forIndexPath: version asserts (crashes) if you didn't register a class or nib for the identifier. The older (non-forIndexPath:) version returns nil in that case. You register a class for an identifier by sending registerClass:forCellReuseIdentifier: to the table view. You reg...
Swift
25,826,383
179
I have a type in my module: import Cocoa class ColoredDotView : NSView { ... } It is used in a number of different classes with no issue: class EditSubjectPopoverController : NSObject { @IBOutlet internal var subjectColorDotView : ColoredDotView! ... } But for some reason, when I use it in one specific c...
For me, I encountered this error when my test target did not have some swift files that my app build target had in compile sources. It was very confusing because the 'undeclared type' was being used in so many other places with no problem, and the error seemed vague. So solution there was of course to add the file c...
Swift
25,437,891
179
In Objective-C, one can add a description method to their class to aid in debugging: @implementation MyClass - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo]; } @end Then in the debugger, you can do: po fooClass <MyClass: 0x12938004, foo = "bar"> What is...
To implement this on a Swift type you must implement the CustomStringConvertible protocol and then also implement a string property called description. For example: class MyClass: CustomStringConvertible { let foo = 42 var description: String { return "<\(type(of: self)): foo = \(foo)>" } } print(...
Swift
24,108,634
179
If so, are there any key differences that weren't otherwise present when using key-value observation in Objective-C?
You can use KVO in Swift, but only for dynamic properties of NSObject subclass. Consider that you wanted to observe the bar property of a Foo class. In Swift 4, specify bar as dynamic property in your NSObject subclass: class Foo: NSObject { @objc dynamic var bar = 0 } You can then register to observe changes to t...
Swift
24,092,285
179
What I want to implement: class func getSomeObject() -> [SomeObject]? { let objects = Realm().objects(SomeObject) return objects.count > 0 ? objects : nil } How can I return object as [SomeObject] instead if Results?
Weird, the answer is very straightforward. Here is how I do it: let array = Array(results) // la fin
Swift
31,100,011
178
I'm trying to use Swift's @testable declaration to expose my classes to the test target. However I'm getting this compiler error: Intervals is the module that contains the classes I'm trying to expose. How do I get rid of this error?
In your main target you need to set the Enable Testability build option to Yes. As per the comment by @earnshavian below, this should only be used on debug builds as per apple release notes: "The Enable Testability build setting should be used only in your Debug configuration, because it prohibits optimizations that de...
Swift
30,787,674
178
How do I return 3 separate data values of the same type(Int) from a function in swift? I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible? I think I just don't understand the syntax for returning multipl...
Return a tuple: func getTime() -> (Int, Int, Int) { ... return ( hour, minute, second) } Then it's invoked as: let (hour, minute, second) = getTime() or: let time = getTime() println("hour: \(time.0)")
Swift
27,531,195
178
Let's say I have Customer data type which contains a metadata property that can contains any JSON dictionary in the customer object struct Customer { let id: String let email: String let metadata: [String: Any] } { "object": "customer", "id": "4yq6txdpfadhbaqnwp3", "email": "john.doe@example.com", "me...
With some inspiration from this gist I found, I wrote some extensions for UnkeyedDecodingContainer and KeyedDecodingContainer. You can find a link to my gist here. By using this code you can now decode any Array<Any> or Dictionary<String, Any> with the familiar syntax: let dictionary: [String: Any] = try container.deco...
Swift
44,603,248
177
I have been using DispatchQueue.main.async for a long time to perform UI related operations.

 Swift provides both DispatchQueue.main.async and DispatchQueue.main.sync, and both are performed on the main queue.

 Can anyone tell me the difference between them? 

When should I use each?

 DispatchQueue.main.async { ...
Why Concurrency? As soon as you add heavy tasks to your app like data loading it slows your UI work down or even freezes it. Concurrency lets you perform 2 or more tasks “simultaneously”. The disadvantage of this approach is that thread safety which is not always as easy to control. F.e. when different tasks want to ac...
Swift
44,324,595
177
I have this: class Movies { Name:String Date:Int } and an array of [Movies]. How do I sort the array alphabetically by name? I've tried: movieArr = movieArr.sorted{ $0 < $1 } and movieArr = sorted(movieArr) but that doesn't work because I'm not accessing the name attribute of Movies.
In the closure you pass to sort, compare the properties you want to sort by. Like this: movieArr.sorted { $0.name < $1.name } or the following in the cases that you want to bypass cases: movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() } Sidenote: Typically only types start with an uppercase letter; I'd ...
Swift
26,719,744
177