I use PagingMenuController 2.0.0 in my project using swift3.
I have a problem when I write following codes.
These codes are copied from README of PagingMenuController.
An error "Argument labels '(options:)' do not match any available overloads" occurs in the last line.
struct MenuItem1: MenuItemViewCustomizable {}
struct MenuItem2: MenuItemViewCustomizable {}
struct MenuOptions: MenuViewCustomizable {
var itemsOptions: [MenuItemViewCustomizable] {
return [MenuItem1(), MenuItem2()]
}
}
struct PagingMenuOptions: PagingMenuControllerCustomizable {
var componentType: ComponentType {
return .all(menuOptions: MenuOptions(), pagingControllers: [UIViewController(), UIViewController()])
}
}
let options = PagingMenuOptions()
let pagingMenuController = PagingMenuController(options: options)
Related
I've defined an enum and made it conform to Value like so:
enum Name: Int {
//cases
}
extension Name: Value {
static var declaredDatatype: String {
return Int.declaredDatatype
}
static func fromDatatypeValue(_ intValue: Int) -> Name {
return Name(rawValue: intValue)!
}
var datatypeValue: Int {
return self.rawValue
}
}
Unfortunately I get the follow exception:
fatal error: unexpectedly found nil while unwrapping an Optional value
It happens in this function:
public func get<V: Value>(_ column: Expression<V>) -> V {
return get(Expression<V?>(column))!
}
The function in my enum extension is not called so I think this is a more general bug in SQLite.swift, but it only happens with my custom type.
Im using Xcode 8.3.3 and SQLite.swift ec7b589.
after upgrading to new version of Xcode/swift i am getting error "Ambiguous use of subscript before was work well but now i am getting this error
my code for search in my data
#IBAction func searchB(sender: UITextField) {
dataSecond = []
if sender.text == "" {
search = false
self.reload()
} else {
for i in data {
if (i["name"] as! String!).lowercaseString.findInString(sender.text!) { //Here is the error in this if condition
dataSecond.addObject(i)
}
}
search = true
self.reload()
}
Swift 2.2 is rather strict about types, much more strict than the previous versions. What was implicit before has now to be explicit.
Use safe unwrapping and downcasting and it should work:
if let senderText = sender.text {
for i in data {
if let name = i["name"] as? String {
if name.lowercaseString.findInString(senderText) {
dataSecond.addObject(i)
}
}
}
}
I've defined a protocol with a protocol extension to simplify working with NSError.
protocol NSErrorConvertible: RawRepresentable {
var domain: String { get }
var localizedDescription: String { get }
}
extension NSErrorConvertible where RawValue == Int {
func generateError(parameters parameters: [String] = []) -> NSError {
let error = self.generateError(format: self.localizedDescription, parameters: parameters)
return error
}
func generateError(format format: String, parameters: [String] = []) -> NSError {
let description = String(format: format, arguments: parameters) // <-- BREAK
let error = NSError(domain: self.domain, code: self.rawValue, localizedDescription: description)
return error
}
}
extension NSError {
convenience init(domain: String, code: Int, localizedDescription: String) {
let userInfo = [NSLocalizedDescriptionKey : localizedDescription]
self.init(domain: domain, code: code, userInfo: userInfo)
}
}
Here's how the protocol is used:
enum DefaultEngineErrors: Int, NSErrorConvertible {
case ImagesNotSupported
case FooDoesNotHaveABar
case NilBar
var domain: String { return "DefaultEngineErrors" }
var localizedDescription: String {
switch self {
case .ImagesNotSupported: return "%s: Images are not supported."
case .FooDoesNotHaveABar: return "%s: Foo does not have a bar."
case .NilBar: return "%s: The bar is nil."
}
}
}
And here is how the protocol extension methods are called:
let error = DefaultEngineErrors.FooDoesNotHaveABar.generateError(parameters: ["\(foo.id)"])
When this code is run, the debugger breaks on the line that builds the description in the second generateError extension function and the following message is displayed in the debugger console:
fatal error: can't unsafeBitCast between types of different sizes
Note that if I replace the call to String(format:) with just format, everything works fine.
Q: What is wrong with what I've done here?
In addition to this, I can't examine the parameters in the protocol extension. The following message is displayed when I try:
(lldb) po format
error: <EXPR>:1:1: error: non-nominal type '$__lldb_context' (aka 'Self') cannot be extended
extension $__lldb_context {
^ ~~~~~~~~~~~~~~~
<EXPR>:15:5: error: value of type 'DefaultEngineErrors' has no member '$__lldb_wrapped_expr_54'
$__lldb_injected_self.$__lldb_wrapped_expr_54(
^~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
Swift string Array is not compatible with CVarArgType... or [CVarArgType]
try using.
extension NSErrorConvertible where RawValue == Int {
func generateError(format format: String) -> NSError {
let error = NSError(domain: self.domain, code: self.rawValue, localizedDescription: format)
return error
}
func generateError(args : CVarArgType...) -> NSError {
let returnString = NSString(format: self.localizedDescription, arguments: getVaList(args)) as String
// let returnString = withVaList(args) {
// NSString(format: self.localizedDescription, arguments: $0)
// } as String
let error = generateError(format: returnString)
return error
}
}
enum DefaultEngineErrors: Int, NSErrorConvertible {
case ImagesNotSupported
case FooDoesNotHaveABar
case FooWithMultiPar
case NilBar
var domain: String { return "DefaultEngineErrors" }
var localizedDescription: String {
switch self {
case .ImagesNotSupported: return "%#: Images are not supported."
case .FooDoesNotHaveABar: return "%#: Foo does not have a bar."
case .FooWithMultiPar: return "%#:%# Foo does not have a bar."
case .NilBar: return "%#: The bar is nil."
}
}
}
print(DefaultEngineErrors.FooDoesNotHaveABar.generateError("test"))
print(DefaultEngineErrors.FooWithMultiPar.generateError("test1","test2"))
Check this
How to test wether a function in Swift 2.0 throws or not? How to assert that the correct ErrorType is thrown?
EDIT: Updated the code for Swift 4.1 (still valid with Swift 5.2)
Here's the latest Swift version of Fyodor Volchyok's answer who used XCTAssertThrowsError:
enum MyError: Error {
case someExpectedError
case someUnexpectedError
}
func functionThatThrows() throws {
throw MyError.someExpectedError
}
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.someExpectedError)
}
}
If your Error enum has associated values, you can either have your Error enum conform to Equatable, or use the if case statement:
enum MyError: Error, Equatable {
case someExpectedError
case someUnexpectedError
case associatedValueError(value: Int)
}
func functionThatThrows() throws {
throw MyError.associatedValueError(value: 10)
}
// Equatable pattern: simplest solution if you have a simple associated value that can be tested inside 1 XCTAssertEqual
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.associatedValueError(value: 10))
}
}
// if case pattern: useful if you have one or more associated values more or less complex (struct, classes...)
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
guard case MyError.associatedValueError(let value) = error else {
return XCTFail()
}
XCTAssertEqual(value, 10)
// if you have several values or if they require more complex tests, you can do it here
}
}
At least of Xcode 7.3 (maybe earlier) you could use built-in XCTAssertThrowsError():
XCTAssertThrowsError(try methodThatThrows())
If nothing is thrown during test you'll see something like this:
If you want to check if thrown error is of some concrete type, you could use errorHandler parameter of XCTAssertThrowsError():
enum Error: ErrorType {
case SomeExpectedError
case SomeUnexpectedError
}
func functionThatThrows() throws {
throw Error.SomeExpectedError
}
XCTAssertThrowsError(try functionThatThrows(), "some message") { (error) in
XCTAssertEqual(error as? Error, Error.SomeExpectedError)
}
Given the following functions and declarations:
enum SomeError: ErrorType {
case FifthError
case FirstError
}
func throwingFunction(x: Int) throws {
switch x {
case 1:
throw SomeError.FirstError
case 5:
throw SomeError.FifthError
default:
return
}
}
This function will throw a FifthError if 5 is given to the function and FirstError if 1 is given.
To test, that a function successfully runs the unit test could look as follows:
func testNotError() {
guard let _ = try? throwingFunction(2) else {
XCTFail("Error thrown")
return
}
}
The let _ may also be replaced by any other name, so you can further test the output.
To assert that a function throws, no matter what ErrorType the unit test could look like this:
func testError() {
if let _ = try? throwingFunction(5) {
XCTFail("No error thrown")
return
}
}
If you want to test for a specific ErrorType it's done with a do-catch-statement. This is not the best way compared to other languages.
You have to make sure that you...
return in the catch for the correct ErrorType
XCTFail() and return for all other catch
XCTFail() if no catch is executed
Given this requirements a test case could look like this:
func testFifthError() {
do {
try throwingFunction(5)
} catch SomeError.FifthError {
return
} catch {
XCTFail("Wrong error thrown")
return
}
XCTFail("No error thrown")
}
Swift 4.1 Error throwing Test for associated values
enum ParseError: Error, Equatable {
case unexpectedArgument(String)
}
func testWithNoSchemaButWithOneArgument() {
XCTAssertThrowsError(try Args(withSchema: "", andArguments: ["-x"])) { error in
XCTAssertEqual(error as? ParseError, ParseError.unexpectedArgument("Argument(s) -x unexpected."))
}
}
You can use this function:
func XCTAssertThrowsError<T, E: Error & Equatable>(
_ expression: #autoclosure () throws -> T,
error: E,
in file: StaticString = #file,
line: UInt = #line
) {
var thrownError: Error?
XCTAssertThrowsError(
try expression(),
file: file,
line: line) {
thrownError = $0
}
XCTAssertTrue(
thrownError is E,
"Unexpected error type: \(type(of: thrownError))",
file: file,
line: line
)
XCTAssertEqual(
thrownError as? E,
error,
file: file,
line: line
)
}
Example:
XCTAssertThrowsError(try funcThatThrowsSpecificError(), error: SpecificErrorEnum.someError)
Looking for a Swift equivalent of Cocoa's description, I found the following protocols in Swift: Printable and DebugPrintable.
What's the difference between these two protocols and when should I use each one?
Here is an example class
class Foo: Printable, DebugPrintable {
var description: String {
return "Foo"
}
var debugDescription: String {
return "debug Foo"
}
}
This is how to use it.
println(Foo())
debugPrintln(Foo())
Here is the output with no surprises:
Foo
debug Foo
I didn't try this in a Playground. It works in an actual project.
The answer above was for Swift 1. It was correct at the time.
Update for Swift 2.
println and debugPrintln are gone and the protocols have been renamed.
class Foo: CustomStringConvertible, CustomDebugStringConvertible {
var description: String {
return "Foo"
}
var debugDescription: String {
return "debug Foo"
}
}
print(Foo())
debugPrint(Foo())
In Xcode 6 Beta (Version 6.2 (6C101)) I find that both println and debugPrintln use description if-and-only-if the class descends from NSObject. I don't see that either uses debugDescription at all but when run in a Playground debugPrintln outputs only to the Console and doesn't appear in the playground itself.
import Foundation
class Tdesc: NSObject, Printable, DebugPrintable {
override var description: String {return "A description"}
override var debugDescription: String {return "A debugDescription"}
}
class Xdesc: Printable, DebugPrintable {
var description: String {return "A description"}
var debugDescription: String {return "A debugDescription"}
}
let t = Tdesc()
let x = Xdesc()
t.description
let z: String = "x\(t)"
println(t) // Displays "A description" in the Playground and Console
debugPrintln(t) // Displays nothing in the Playground but "A description" in the Console
x.description
let y: String = "x\(x)"
println(x) // Displays "__lldb_expr_405.Xdesc" in the Playground and Console
debugPrintln(x)
I believe the main difference is the property that's used to print. Printable has description and DebugPrintable has debugDescription:
https://stackoverflow.com/a/24254220/887210
https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/Printable.html#//apple_ref/doc/uid/TP40014608-CH11-SW1
Edit:
Apparently print() and println() don't work properly with Printable and DebugPrintable:
struct TestPrintable : Printable {
var description: String { return "Testing Printable" }
}
struct TestDebugPrintable : DebugPrintable {
var debugDescription: String { return "Testing DebugPrintable" }
}
println(TestPrintable()) // -> "__lldb_expr_42.TestPrintable"
println(TestDebugPrintable()) // -> "__lldb_expr_42.TestDebugPrintable"
More information about this:
http://vperi.com/2014/06/04/textual-representation-for-classes-in-swift/