What Is the Swift 3 Equivalent of Nsurl.Urlbyappendingpathcomponent()

What is the equivalent to `thing = this() || that` in Swift 3?

There's no exact equivalent in Swift, as:

  • No other types than Bool cannot be converted to Bool

  • You cannot write a function returning Bool or Int

(In most languages is a little bit exaggerated, you cannot write such thing in Java, C# or many other strongly-typed languages.)

The most similar thing in Swift is nil-coalescing operator -- ??.

Assume this() returns Int? (aka Optional<Int>), and that() returns Int (non-Optional):

func this() -> Int? {
//...
if someCondition() {
return intValue
} else {
return nil
}
}

func that() -> Int {
//...
return anotherIntValue
}

And use nil-coalescing operator like this:

let result = this() ?? that()

In this assignment, if this() returns non-nil value, then that() is not evaluated, and that non-nil value is assigned to result. When this() returns nil, that() is evaluated and the value is assigned to result.

stringByAppendingPathComponent is unavailable

It looks like the method stringByAppendingPathComponent is removed in Swift 2.0, so what the error message suggests is to use:

let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("instagram.igo")

Update:

URLByAppendingPathComponent() has been replaced by appendingPathComponent() so instead do:

let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("instagram.igo")

How to append something like ?id=1 to a NSMutableURLRequest

The problem is that the question mark in ?timeFrame=n14 is treated as part of the URL's
path and therefore HTML-escaped as %3F. This should work:

let baseUrl = NSURL(string: "http://www.football-data.org")!
let url = NSURL(string: "soccerseasons/" + "\(league.id)" + "/fixtures?timeFrame=n14", relativeToURL:baseUrl)!
let request = NSMutableURLRequest(URL: url)

Alternatively, use NSURLComponents, which lets you build an URL successively from individual components (error checking omitted for brevity):

let urlComponents = NSURLComponents(string: "http://www.football-data.org")!
urlComponents.path = "/soccerseasons/" + "\(league.id)" + "/fixtures"
urlComponents.query = "timeFrame=n14"

let url = urlComponents.URL!
let request = NSMutableURLRequest(URL: url)

Update for Swift 3:

var urlComponents = URLComponents(string: "http://www.football-data.org")!
urlComponents.path = "/soccerseasons/" + "\(league.id)" + "/fixtures"
urlComponents.query = "timeFrame=n14"

let url = urlComponents.url!
var request = URLRequest(url: url)

What is the equivalent to `thing = this() || that` in Swift 3?

There's no exact equivalent in Swift, as:

  • No other types than Bool cannot be converted to Bool

  • You cannot write a function returning Bool or Int

(In most languages is a little bit exaggerated, you cannot write such thing in Java, C# or many other strongly-typed languages.)

The most similar thing in Swift is nil-coalescing operator -- ??.

Assume this() returns Int? (aka Optional<Int>), and that() returns Int (non-Optional):

func this() -> Int? {
//...
if someCondition() {
return intValue
} else {
return nil
}
}

func that() -> Int {
//...
return anotherIntValue
}

And use nil-coalescing operator like this:

let result = this() ?? that()

In this assignment, if this() returns non-nil value, then that() is not evaluated, and that non-nil value is assigned to result. When this() returns nil, that() is evaluated and the value is assigned to result.

URLByAppendingPathComponent with archiveRootObject not working correctly?

Nowadays, the best API to use for this is NSFileManager. You should also use NSURL path method instead of String(). I would recommend this:

if let docDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first,
let filePath = docDir.URLByAppendingPathComponent("savedObject.data").filePathURL?.path
{
// ...Write to the path
}

More on String(x):

I've copied the String initializer's definition below. You can see that it tries several different string representations and is mostly for debugging purposes — in the case of NSURL and many other NSObject subclasses, it calls the Obj-C description method. You should not rely on the result of description. Instead you should use whatever situation-specific methods are available, like path in this case.

extension String {
/// Initialize `self` with the textual representation of `instance`.
///
/// * If `T` conforms to `Streamable`, the result is obtained by
/// calling `instance.writeTo(s)` on an empty string s.
/// * Otherwise, if `T` conforms to `CustomStringConvertible`, the
/// result is `instance`'s `description`
/// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`,
/// the result is `instance`'s `debugDescription`
/// * Otherwise, an unspecified result is supplied automatically by
/// the Swift standard library.
///
/// - SeeAlso: `String.init<T>(reflecting: T)`
public init<T>(_ instance: T)
...

How to migrate Alamofire router class to Swift 3?

EDITED for Alamofire 4.0.0 release (updated URLRequestConvertible protocol with throwing capabilities):

A lot has changed in Swift 3 and you should first really read up on all the changes, maybe starting at http://swift.org. Here's the fixed code:

enum Router: URLRequestConvertible {
static let baseURLString = "http://example.com"
static var OAuthToken: String?

case createUser([String: AnyObject])
case readUser(String)
case updateUser(String, [String: AnyObject])
case destroyUser(String)

var method: Alamofire.HTTPMethod {
switch self {
case .createUser:
return .post
case .readUser:
return .get
case .updateUser:
return .put
case .destroyUser:
return .delete
}
}

var path: String {
switch self {
case .createUser:
return "/users"
case .readUser(let username):
return "/users/\(username)"
case .updateUser(let username, _):
return "/users/\(username)"
case .destroyUser(let username):
return "/users/\(username)"
}
}

func asURLRequest() throws -> URLRequest {
let url = URL(string: Router.baseURLString)!
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue

if let token = Router.OAuthToken {
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}

switch self {
case .createUser(let parameters):
return try Alamofire.JSONEncoding.default.encode(urlRequest, with: parameters)
case .updateUser(_, let parameters):
return try Alamofire.URLEncoding.default.encode(urlRequest, with: parameters)
default:
return urlRequest
}
}
}

The main changes for Swift 3 are :

  • enum cases are now lowercase and you should adopt it too.
  • Variable names now start with lowercase, even if it's an abbreviation like "URL". That why the protocol requires var urlRequest and not var URLRequest (and it would conflict with the next point)
  • Bye-bye NS prefix in many places. NSURLRequest and NSMutableURLRequest are now URLRequest, NSURL is URL, etc.
  • How you name your functions and parameters is now a lot less redundant and more natural. See for example how URLByAppendingPathComponent has changed.

And as for Alamofire v4 :

  • There's a new ParameterEncoding protocol to encoding parameters yourself is different but more versatile
  • MANY other changes which have no impact here but you sure have to read about them too.

And final word of advice : avoid migrating to unreleased versions of a programming language or API if it's time-sensitive. Swift 3 won't budge much but Alamofire still might! For example the ParameterEncoding protocol is only two days old! (EDIT: and indeed it changed since, now in its final version above)

Cheers

why am I not getting the correct URL path in swift OSX

The Swift equivalent is

let formatter : DateFormatter = {
let df = DateFormatter()
df.dateFormat = "YYYYMMDDHHmmss"
return df
}()

let homeDir = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("xyz")

let date = formatter.string(from: Date())
let file = homeDir.appendingPathComponent("xyz-" + date).appendingPathExtension("m4a")

If you want to use the ~ syntax you have to bridge the string to NSString because expandingTildeInPath is not available in Swift String

let homeDir = URL(fileURLWithPath:("~/xyz/" as NSString).expandingTildeInPath).appendingPathComponent("xyz")


Related Topics



Leave a reply



Submit