swift2 interview questions
Top swift2 frequently asked interview questions
I'm trying to use Swift 2's new @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?
Source: (StackOverflow)
Let's say I want to split a string by an empty space. This code snippet works fine in Swift 1.x. It does not work in Swift 2 in Xcode 7 Beta 1.
var str = "Hello Bob"
var foo = split(str) {$0 == " "}
I get the following compiler error:
Cannot invoke 'split' with an argument list of type '(String, (_) -> _)
Anyone know how to call this correctly?
Updated: Added a note that this was for the Xcode 7 beta 1.
Source: (StackOverflow)
So I can do this:
var stringNumb: NSString = "1357"
var someNumb: CInt = stringNumb.intValue
But I can't find the way to do it w/ a String
. I'd like to do something like:
var stringNumb: String = "1357"
var someNumb: Int = Int(stringNumb)
This doesn't work either:
var someNumbAlt: Int = myString.integerValue
Source: (StackOverflow)
I have an app I'm trying to submit to Apple. I've already validated it. I'm using Xcode 7 and Swift 2. When I try to submit to Apple, I get the following error:
ERROR ITMS-90474: "Bundle Invalid. iPad Multitasking support requires there orientations:
'UIInterfaceOrientationPortrait,UIIinterfaceOrientationPortraitUpsideDown,UIInterfaceOrientationLandscapeLeft,UIInterfaceOrientationLandscapeRight'. Found 'UIInterfaceOrientationPortrait' in bundle.
What do I do? Do I make some images with the names they ask for?
Source: (StackOverflow)
Just downloaded Xcode 7 Beta, and this error appeared on enumerate
keyword.
for (index, string) in enumerate(mySwiftStringArray)
{
}
Can anyone help me overcome this ?
Also, seems like count()
is no longer working for counting length of String
.
let stringLength = count(myString)
On above line, compiler says :
'count' is unavailable: access the 'count' property on the collection.
Has Apple has released any programming guide for Swift 2.0 ?
Source: (StackOverflow)
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 can be the problem?

Source: (StackOverflow)
This code in XCode 6 does not have error but in XCode 7 (Swift 2) this error has occurred :
Method does not override any method from its superclass
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
}
When remove override
word this error occurred :
Method 'touchesBegan(:withEvent:)' with Objective-C selector 'touchesBegan:withEvent:' conflicts with method 'touchesBegan(:withEvent:)' from superclass 'UIResponder' with the same Objective-C selector
Source: (StackOverflow)
The following URL opens on iOS 8.3 and lower, but it does not work and iOS 9
let instagramURL = NSURL(string: "instagram://app")
Why won't the URL open?
Source: (StackOverflow)
I am getting the following error when I am running my code in Xcode7 with Swift2, after presenting a view controller through a push segue:
_BSMachError: (os/kern) invalid capability (20)
_BSMachError: (os/kern) invalid name (15)
The other SO articles had no resolution, does anyone know about this issue?
Source: (StackOverflow)
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)
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 "|" cannot be applied to two UIUserNotificationType operands
. Please help me.
Source: (StackOverflow)
Swift 2 introduces the guard
keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates an submitTapped function:
func submitTapped() {
guard username.text.characters.count > 0 else {
return
}
print("All good")
}
I am wondering if using guard
is any different than doing it the old fashioned way, using an if
condition. Does it give benefits, which you could not get by using a simple check?
Source: (StackOverflow)
When I try to check for an internet connection on my iPhone by using Swift 2 in xCode I get a bunch of errors. Can anyone help me to fix this?
The code:
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
}
The errors with the code:

If it is unreadable, error 1 says:
'Int' is not convertible to 'SCNetworkReachabilityFlags'
Error 2 & 3:
Could not find an overload for 'init' that accepts the supplied arguments
Source: (StackOverflow)
I am trying to get the difference between the current date as NSDate()
and a date from a PHP time();
call for example: NSDate(timeIntervalSinceReferenceDate: 1417147270)
. How do I go about getting the difference in time between the two dates. I'd like to have a function that compares the two dates and if(seconds > 60)
then it returns minutes, if(minutes > 60)
return hours and if(hours > 24)
return days and so on.
How should I go about this?
EDIT: The current accepted answer has done exactly what I've wanted to do. I recommend it for easy usage for getting the time between two dates in the form that that PHP time()
function uses. If you aren't particularly familiar with PHP, that's the time in seconds from January 1st, 1970. This is beneficial for a backend in PHP. If perhaps you're using a backend like NodeJS you might want to consider some of the other options you'll find below.
Source: (StackOverflow)
In Swift 2.0 NSError
conforms to the ErrorType
protocol.
For a customly defined error, we can specify the associating object(s) for some cases, like below.
enum LifeError: ErrorType {
case BeBorn
case LostJob(job: String)
case GetCaughtByWife(wife: String)
...
}
We can comfortably do the following:
do {
try haveAffairWith(otherPerson)
} catch LifeError.GetCaughtByWife(let wife) {
...
}
However if we want it to pass into other places as an NSError
, it loses its associating object information.
println("\(LifeError.GetCaughtByWife("Name") as NSError)")
prints:
Error Domain=... Code=1 "The operation couldn't be completed". (... error 1)
and its userInfo
is nil
.
Where is my wife
associated with the ErrorType
?
Source: (StackOverflow)