Swift 2.0 - `nil` or `0` enum arguments
Options are now specified as a set, so just pass an empty set: options: []
.
How to pass empty value when enum is expected in swift
UIViewAnimationOptions conforms to the OptionSetType protocol so you should give an array of the options you want and if you don't want any you can give an empty array.
UIView.animateWithDuration(1,
delay: 0,
usingSpringWithDamping: 0.4,
initialSpringVelocity: 0.4,
options: [],
animations: {
}) { finished in
}
How to pass multiple enum values as a function parameter
Edit: In Swift 3.0:
let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
Edit: This is how you would use the options enum in Swift 2.0:
let options: NSStringDrawingOptions = [.UsesLineFragmentOrigin, .UsesFontLeading]
Edit: The issue has been resolved in iOS 8.3 SDK Beta 1 (12F5027d):
Modified
NSStringDrawingOptions
[struct]
- From:
enum NSStringDrawingOptions : Int
- To:
struct NSStringDrawingOptions : RawOptionSetType
You can now write:
let options : NSStringDrawingOptions = .UsesLineFragmentOrigin | .UsesFontLeading
After some research and and @Anton Tcholakov's "comment":
If you're targeting OS X 10.10, this is as simple way to do it:
let size = CGSize(width: 280, height: Int.max)
let options : NSStringDrawingOptions = .UsesLineFragmentOrigin | .UsesFontLeading
let boundingRect = string.bridgeToObjectiveC().boundingRectWithSize(size, options: options, attributes: attributes, context: nil)However, in iOS 8 SDK (in the current seed), there's a bug, where
NSStringDrawingOptions
is ported to Swift asenum : Int
, instead ofstruct : RawOptionSet
. You should send a bug report to Apple describing this serious problem.
Enum initialized with a non-existent rawValue does not fail and return nil
I filed a bug with Apple and this is the reply I received:
"Engineering has determined that this issue behaves as intended based on the following information:
Because C enums may have values added in future releases, or even have "private case" values used by the framework that are not included in the headers, there's no way to check whether a value provided in Swift is actually valid or invalid. Therefore,
init(rawValue:)
is obliged to produce a value just as a C cast would. There are discussions in the Swift Open Source project on how to improve this situation in later versions of Swift, but the initializer for MKMapType still won't return nil."
Thanks to Apple Engineering for this explanation.
How to declare variable and enum declaration in one line?
Even if you could do it, those are not the same at all. enum
is an object type, like class
. In your first example, panDirection
is an instance of the Direction enum. In your second example, if it could compile and run, panDirection
would end up as the enum itself (the type, not an instance of the type) — which is not at all what you want.
Thus, what you are trying to do is to declare a type in the middle of a line. You can't do that. The rules for where you can declare a type are very clear and very strict.
Note, however, that you can declare a type within another type, or even purely locally, e.g. within a function's code. Thus, for example, you can declare the type temporarily as a way of passing data around inside a function. Nutty but legal:
func myCoolFunction(up:Bool) {
enum Direction : String {
case Up
case Down
}
let dir : Direction = (up ? .Up : .Down)
print("user wants \(dir)")
}
Swift: testing against optional value in switch case
Optional is just a enum
like this:
enum Optional<T> : Reflectable, NilLiteralConvertible {
case none
case some(T)
// ...
}
So you can match them as usual "Associated Values" matching patterns:
let someValue = 5
let someOptional: Int? = nil
switch someOptional {
case .some(someValue):
println("the value is \(someValue)")
case .some(let val):
println("the value is \(val)")
default:
println("nil")
}
If you want match from someValue
, using guard expression:
switch someValue {
case let val where val == someOptional:
println(someValue)
default:
break
}
And for Swift > 2.0
switch someValue {
case let val where val == someOptional:
print("matched")
default:
print("didn't match; default")
}
How would I expose this function, that takes an enum as a parameter, to objc?
You can fix your @objc
error from this link.
But you still face the problem for passing value to the parameter.
You can use the subclass of the UIButton.
Here is the demo
Custom Button Class
class CustomButton: UIButton {
var networkAction: NetworkAction = .post
}
Target Method
@objc func networkCall(sender: CustomButton) {
switch sender.networkAction {
case .post:
print("Posting")
case .get:
print("Getting")
case .delete:
print("Deleting")
case .update:
print("Updating")
}
}
Usage
let postButton = CustomButton()
postButton.networkAction = .post
postButton.addTarget(self, action: #selector(networkCall(sender:)), for: .touchUpInside)
Another approach you can use the tag.
enum NetworkAction: Int {
case post = 0
case get = 1
case delete = 2
case update = 3
}
@objc func networkCall(sender: UIButton) {
switch NetworkAction(rawValue: sender.tag) {
case .post:
print("Posting")
case .get:
print("Getting")
case .delete:
print("Deleting")
case .update:
print("Updating")
case .none:
print("none")
}
}
let postButton = UIButton()
postButton.tag = 0
postButton.addTarget(self, action: #selector(networkCall(sender:)), for: .touchUpInside)
from iOS14
You can simply use the addAction
instead of the target.
button.addAction(UIAction(handler: { [weak self] action in
self?.networkCall(sender: .post)
}), for: .touchUpInside)
Declare enum Router Alamofire swift 2.0
You should add a
var URLRequest: NSURLRequest {...}
to the enum, which generates & returns the NSURLRequest
from your other components like path
or method
EXAMPLE:
var URLRequest: NSURLRequest {
let URL = NSURL(string: baseURLString)!
let mutableURLRequest = path != nil ? NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path!)) : NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = method.rawValue
if let authorizationHeader = authorizationHeader { mutableURLRequest.setValue(authorizationHeader, forHTTPHeaderField: "Authorization") }
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(mutableURLRequest, parameters: [ "foo": "bar" ]).0
}
How to pass no options to NSJSONSerialization.JSONObjectWithData in Swift
In swift 2 you should use the empty array []
to indicate no options
:
NSJSONSerialization.JSONObjectWithData(data, options: [])
Related Topics
Best Practice for Swift Methods That Can Return or Error
Why Should Not Directly Extend Uiview or Uiviewcontroller
Non-Strong References Not Working in Playground
Transform a Swift Sequence in to Adjacent Pairs
How to Retrieve a Random Object from Firebase Using a Sequential Id
Apply Vertical Alpha Gradient to Uitableview
Are the #If Debug Statements Really Needed for Previews in Swiftui to Remove It in a Release Build
Uicollectionview Compositionallayout Not Calling Uiscrolldelegate
Converting Swift Array to Cfarray in Xcode 8 (Swift 3)
How to Use List Type with Codable? (Realmswift)
How to Test Whether Generic Variable Is of Type Anyobject
Know When an Iteration Over Array with Async Method Is Finished
I Won't Be Able to Return a Value with Alamofire in Swift
Implicit Return in a Closure Causing an Error
How to Split an Int to Its Individual Digits
Writing Data to an Nsoutputstream in Swift 3
How to Copy a Struct and Modify One of Its Properties at the Same Time