repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
apstrand/loggy
LoggyTools/Constants.swift
1
1081
// // Settings.swift // Loggy // // Created by Peter Strand on 2017-06-30. // Copyright © 2017 Peter Strand. All rights reserved. // import Foundation public struct SettingName { public static let Suite = "group.se.nena.loggy" public static let PowerSave = "power_save" public static let AutoWaypoint = "auto_waypoint" public static let SpeedUnit = "speed_unit" public static let AltitudeUnit = "altitude_unit" public static let LocationUnit = "location_unit" public static let BearingUnit = "bearing_unit" public static let TrackingEnabled = "tracking_enabled" public static let AutoSaveGen = "auto_save_gen" } public enum AppCommand : String { case StartTracking = "action?startTracking" case StopTracking = "action?stopTracking" case StoreWaypoint = "action?storeWaypoint" } public struct AppUrl { public static let AppUrl = "loggy://" public static func app(cmd : AppCommand) -> URL { guard let url = URL(string:AppUrl + cmd.rawValue) else { fatalError("Failed to create appurl for command: \"\(cmd)\"") } return url } }
mit
atelierclockwork/PodsVSCarthage
PodsVSCarthage/PodsVSCarthageTests/PodsVSCarthageTests.swift
1
439
// // PodsVSCarthageTests.swift // PodsVSCarthageTests // // Created by Michael Skiba on 4/27/15. // Copyright (c) 2015 Atelier Clockwork. All rights reserved. // import UIKit import XCTest import PodsVSCarthage class PodsVSCarthageTests: XCTestCase { func testExample() { // This is an example of a functional test case. XCTAssert(ExternalDetail.publicDetail == "Detail", "Details properly Passed") } }
mit
adamastern/decked
Source/Decorated.swift
1
1040
// // Decorated.swift // pinch // // Created by Adam Stern on 19/04/2016. // Copyright © 2016 TurboPython. All rights reserved. // import UIKit @objc public enum DecorationQueue: Int { case Top case Bottom } public protocol Decorated: class { var decorations: [Decoration]? {get} func addDecoration(decoration: Decoration, atPosition position: DecorationPosition) func addDecoration(decoration: Decoration, atPosition position: DecorationPosition, insets: UIEdgeInsets) func removeDecoration(decoration: Decoration) func removeDecorationAtPosition(position: DecorationPosition) func queueDecoration(decoration: ManagedDecoration, inQueue queue: DecorationQueue, insets: UIEdgeInsets) -> DecorationManager func queueDecoration(decoration: ManagedDecoration, inQueue queue: DecorationQueue, insets: UIEdgeInsets, dismissAfter: NSTimeInterval) -> DecorationManager func dismissDecoration(decoration: ManagedDecoration) func layoutDecorations() }
mit
aryaxt/ScrollPager
ScrollPager/ViewController.swift
1
1543
// // ViewController.swift // ScrollPager // // Created by Aryan Ghassemi on 2/22/15. // Copyright (c) 2015 Aryan Ghassemi. All rights reserved. // import UIKit class ViewController: UIViewController, ScrollPagerDelegate { @IBOutlet var scrollPager: ScrollPager! @IBOutlet var secondScrollPager: ScrollPager! override func viewDidLoad() { super.viewDidLoad() let firstView = UILabel() firstView.backgroundColor = UIColor.white firstView.text = "first View" firstView.textAlignment = .center let secondView = UILabel() secondView.backgroundColor = UIColor.white secondView.text = "second view" secondView.textAlignment = .center let thirdView = UILabel() thirdView.backgroundColor = UIColor.white thirdView.text = "third view" thirdView.textAlignment = .center let fourthView = UILabel() fourthView.backgroundColor = UIColor.white fourthView.text = "fourth view" fourthView.textAlignment = .center scrollPager.delegate = self scrollPager.addSegmentsWithTitlesAndViews(segments: [ ("Home", firstView), ("Public Feed", secondView), ("Profile", thirdView), ("One More", fourthView) ]) secondScrollPager.addSegmentsWithImages(segmentImages: [ UIImage(named: "envelope")!, UIImage(named: "home")!, UIImage(named: "like")!, UIImage(named: "message")!, UIImage(named: "notes")! ]) } // MARK: - ScrollPagerDelegate - func scrollPager(scrollPager: ScrollPager, changedIndex: Int) { print("scrollPager index changed: \(changedIndex)") } }
mit
Hukuma23/CS193p
Assignment_1/Calculator/CalculatorBrain.swift
1
4500
// // CalculatorBrain.swift // Calculator // // Created by Nikita Litvinov on 12/15/2016. // Copyright © 2016 Nikita Litvinov. All rights reserved. // import Foundation class CalculatorBrain{ private var accumulator = 0.0 private var descriptionAccumulator = "" var isPartialResult : Bool { return pending != nil } private var pending: PendingBinaryOperationInfo? var result: Double { return accumulator } var strAccumulator : String { return String(accumulator) } var description : String { if let pend = pending { return pend.descriptionOperation(pend.descriptionOperand, pend.descriptionOperand != descriptionAccumulator ? descriptionAccumulator : "") } else { return descriptionAccumulator } } func clear() { accumulator = 0 descriptionAccumulator = "" pending = nil } func setOperand(_ operand: Double) { accumulator = operand descriptionAccumulator = formatter.string(from: NSNumber(value: accumulator)) ?? "" } private var operations : [String: Operation] = [ "π": Operation.Constant(M_PI), "e": Operation.Constant(M_E), "±": Operation.UnaryOperation({ -$0 }, {"±(" + $0 + ")"}), "√": Operation.UnaryOperation(sqrt, {"√(" + $0 + ")"}), "cos": Operation.UnaryOperation(cos, {"cos(" + $0 + ")"}), "sin": Operation.UnaryOperation(sin, {"sin(" + $0 + ")"}), "log": Operation.UnaryOperation(log10, {"log(" + $0 + ")"}), "x⁻¹": Operation.UnaryOperation({1 / $0}, {"(" + $0 + ")⁻¹"}), "x²": Operation.UnaryOperation({$0 * $0}, {"(" + $0 + ")²"}), "×": Operation.BinaryOperation({$0 * $1}, {$0 + " × " + $1}), "÷": Operation.BinaryOperation({$0 / $1}, {$0 + " ÷ " + $1}), "+": Operation.BinaryOperation({$0 + $1}, {$0 + " + " + $1}), "−": Operation.BinaryOperation({$0 - $1}, {$0 + " − " + $1}), "=": Operation.Equals, "C": Operation.Clear ] enum Operation{ case Constant(Double) case UnaryOperation((Double) -> Double, (String) -> String) case BinaryOperation((Double, Double) -> Double, (String, String) -> String) case Equals case Clear } func performOperation(_ symbol: String){ if let operation = operations[symbol]{ switch operation { case .Constant(let value): descriptionAccumulator = symbol accumulator = value case .UnaryOperation(let function, let descriptionFunction): if pending != nil { descriptionAccumulator = String(accumulator) } descriptionAccumulator = descriptionFunction(descriptionAccumulator) accumulator = function(accumulator) case .BinaryOperation(let function, let descriptionFunction): executeBinaryOperation() if descriptionAccumulator == "" { descriptionAccumulator = String(accumulator) } pending = PendingBinaryOperationInfo(binaryOperation: function, firstOperand: accumulator, descriptionOperand: descriptionAccumulator, descriptionOperation: descriptionFunction) case .Equals: executeBinaryOperation() case .Clear: clear() } } } private func executeBinaryOperation() { if pending != nil { accumulator = pending!.binaryOperation(pending!.firstOperand, accumulator) descriptionAccumulator = pending!.descriptionOperation(pending!.descriptionOperand, descriptionAccumulator) pending = nil } } private struct PendingBinaryOperationInfo { var binaryOperation: (Double, Double) -> Double var firstOperand: Double var descriptionOperand : String var descriptionOperation : (String, String) -> String } private let formatter : NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 6 formatter.minimumFractionDigits = 0 formatter.notANumberSymbol = "Error" formatter.groupingSeparator = " " formatter.locale = Locale.current return formatter }() }
apache-2.0
gabek/GitYourFeedback
Example/Pods/GRMustache.swift/Sources/ZipFilter.swift
2
3130
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation let ZipFilter = VariadicFilter { (boxes) in // Turn collection arguments into iterators. Iterators can be iterated // all together, and this is what we need. // // Other kinds of arguments generate an error. var zippedIterators: [AnyIterator<MustacheBox>] = [] for box in boxes { if box.isEmpty { // Missing collection does not provide anything } else if let array = box.arrayValue { // Array zippedIterators.append(AnyIterator(array.makeIterator())) } else { // Error throw MustacheError(kind: .renderError, message: "Non-enumerable argument in zip filter: `\(box.value)`") } } // Build an array of custom render functions var renderFunctions: [RenderFunction] = [] while true { // Extract from all iterators the boxes that should enter the rendering // context at each iteration. // // Given the [1,2,3], [a,b,c] input collections, those boxes would be // [1,a] then [2,b] and finally [3,c]. var zippedBoxes: [MustacheBox] = [] for iterator in zippedIterators { var iterator = iterator if let box = iterator.next() { zippedBoxes.append(box) } } // All iterators have been enumerated: stop if zippedBoxes.isEmpty { break; } // Build a render function which extends the rendering context with // zipped boxes before rendering the tag. let renderFunction: RenderFunction = { (info) -> Rendering in var context = zippedBoxes.reduce(info.context) { (context, box) in context.extendedContext(box) } return try info.tag.render(context) } renderFunctions.append(renderFunction) } return renderFunctions }
mit
Josscii/iOS-Demos
iPhoneXAdaptationDemo/iPhoneXAdaptationDemo/AppDelegate.swift
1
2181
// // AppDelegate.swift // iPhoneXAdaptationDemo // // Created by josscii on 2018/4/2. // Copyright © 2018年 josscii. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
peferron/algo
EPI/Linked Lists/Implement even-odd merge/swift/test.swift
1
1150
import Darwin func nodes(_ count: Int) -> [Node] { let nodes = (0..<count).map { _ in Node() } for i in 0..<count - 1 { nodes[i].next = nodes[i + 1] } return nodes } ({ let n = nodes(1) n[0].merge() guard n[0].next === nil else { print("Failed test with 1 nodes") exit(1) } })() ({ let n = nodes(2) n[0].merge() guard n[0].next === n[1] && n[1].next == nil else { print("Failed test with 2 nodes") exit(1) } })() ({ let n = nodes(3) n[0].merge() guard n[0].next === n[2] && n[2].next === n[1] && n[1].next == nil else { print("Failed test with 3 nodes") exit(1) } })() ({ let n = nodes(4) n[0].merge() guard n[0].next === n[2] && n[2].next === n[1] && n[1].next === n[3] && n[3].next == nil else { print("Failed test with 4 nodes") exit(1) } })() ({ let n = nodes(5) n[0].merge() guard n[0].next === n[2] && n[2].next === n[4] && n[4].next === n[1] && n[1].next === n[3] && n[3].next == nil else { print("Failed test with 5 nodes") exit(1) } })()
mit
0416354917/FeedMeIOS
MeTableViewController.swift
1
4476
// // MeTableViewController.swift // FeedMeIOS // // Created by Jun Chen on 11/04/2016. // Copyright © 2016 FeedMe. All rights reserved. // import UIKit class MeTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.setBackground(self) self.setBar(self) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewDidAppear(animated: Bool) { if FeedMe.Variable.userInLoginState == false { let nextViewController = self.storyboard!.instantiateViewControllerWithIdentifier("sign_in_up") self.presentViewController(nextViewController, animated: true, completion: nil) } else { self.tableView.reloadData() } } // override func viewWillAppear(animated: Bool) { // if FeedMe.Variable.userInLoginState == false { // let nextViewController = self.storyboard!.instantiateViewControllerWithIdentifier("sign_in_up") // self.presentViewController(nextViewController, animated: true, completion: nil) // } // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return 1 default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "MeTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MeTableViewCell // Configure the cell... if FeedMe.user == nil { cell.itemLabel.text = "" return cell } NSLog("user: %@", FeedMe.user!.toJsonString(.None)) switch indexPath.section { case 0: cell.itemLabel.text = FeedMe.user!.getEmail() case 1: cell.itemLabel.text = "Settings" default: cell.itemLabel.text = "" } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
bsd-3-clause
mobistix/ios-charts
Charts/Classes/Renderers/TimelineHorizontalAxisRenderer.swift
1
4619
// // TimelineHorizontalAxisRenderer.swift // RoadCheck // // Created by Rares Zehan on 03/04/16. // Copyright © 2016 Realine. All rights reserved. // import Foundation let hourInSeconds: Double = 3600 let dayInHours: Int = 24 public class TimelineHorizontalAxisRenderer: ChartYAxisRendererHorizontalBarChart { public var showExtended = false public var topTitleFormatter: ExtendedTitleNumberFormatter? public override func computeAxisValues(min: Double, max: Double) { let range = max - min guard let yAxis = yAxis else { return } let yMin = Date(timeIntervalSince1970: min) _ = Date(timeIntervalSince1970: max) let hoursCount = Int(range / hourInSeconds) if hoursCount == 0 { return } let modItemsCount = hoursCount / yAxis.labelCount var hoursInterval = modItemsCount < 1 ? 1 : modItemsCount if viewPortHandler.scaleX < 3 { hoursInterval = dayInHours } var dateComponents = Calendar.utcCalendar().dateComponents([.year, .month, .day, .hour, .minute], from: yMin) if dateComponents.minute != 0 { dateComponents.minute = 0 dateComponents.hour = hoursInterval } if hoursInterval == dayInHours { dateComponents.minute = 0 dateComponents.hour = 0 } let firstHourModulus = Calendar.utcCalendar().date(from: dateComponents)! yAxis.entries = [Double]() for i in 0 ..< 48 { let entry = firstHourModulus.timeIntervalSince1970 + Double(i) * Double(hoursInterval) * hourInSeconds if entry > max { break } yAxis.entries += [entry] } } /// draws the y-labels on the specified x-position public override func drawYLabels(context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { guard let yAxis = yAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let scaleX = viewPortHandler.scaleX var prevDay = -1 for i in 0 ..< yAxis.entryCount { let timelineNumberFormatter = yAxis.valueFormatter as! TimelineNumberFormatter timelineNumberFormatter.formatterType = scaleX < 3 && showExtended ? .WeekFormatterType : .DayFormatterType let text = timelineNumberFormatter.string(from: yAxis.entries[i] as NSNumber ) ChartUtils.drawText(context: context, text: text!, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) if (scaleX > 3 && showExtended) { let currentDate = Date(timeIntervalSince1970: yAxis.entries[i]).localDate() var dayComps = Calendar.utcCalendar().dateComponents([Calendar.Component.day], from: currentDate) dayComps.timeZone = TimeZone.utcTimeZone() let day = dayComps.day if day != prevDay { prevDay = day! ChartUtils.drawText(context: context, text: text!, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } } if showExtended && topTitleFormatter != nil { let titleFont = UIFont(name: "HelveticaNeue", size: 18.0) topTitleFormatter!.formatterType = scaleX < 3 ? .WeekFormatterType : .DayFormatterType let millis = yAxis.entries[yAxis.entries.count / 2] as NSNumber let formattedDate = topTitleFormatter?.string(from: millis) ChartUtils.drawText(context: context, text: "\(formattedDate!)", point: CGPoint(x: viewPortHandler.chartWidth / 2, y: fixedPosition - 40), align: .center, attributes: [NSFontAttributeName: titleFont!, NSForegroundColorAttributeName: UIColor.black]) } } }
apache-2.0
jigneshsheth/Datastructures
DataStructure/DataStructure/RetailMeNot/FreeShippingThresold.swift
1
2598
// // FreeShippingThresold.swift // DataStructure // // Created by Jigs Sheth on 3/30/16. // Copyright © 2016 jigneshsheth.com. All rights reserved. // import Foundation /** Question Given a list of prices on a website, find the two distinct item prices you need to have the lowest shopping cart total Variations You can start with free shipping at $25 and items of $5, $8, $15, $22. that meets a free shipping requirement. There is an n^2 solution that's obvious. n log n that's more efficient. n if you assume all prices are below the free shipping requirement. For the O( n ) solution, add the restriction that all items in the catalog are below the free shipping amount and that there are a huge number of them. One variation is to say that you can have as many items in the cart as you want to reach the free shipping total. */ /** Optimal solution O(n log n) because of the sort in the middle: - parameter productPrices: - parameter freeShippingAmt: Thresold for the free shipping - returns: touple of 2 values */ public func calculateFreeShipping(productPrices:[Int],freeShippingAmt:Int) -> (Int,Int) { var minFreeShippingDelta = freeShippingAmt var index1 = 0 var index2 = productPrices.count - 1 var result:(Int,Int) = (-1,-1) // Below statement do O(log n) let _productPrices = productPrices.sorted() // Below statement do O(n) so total complexity of the method is O(n log n) while index1 < index2 { let price1 = _productPrices[index1] let price2 = _productPrices[index2] let delta = price1 + price2 - freeShippingAmt if delta > 0 && delta < minFreeShippingDelta { minFreeShippingDelta = delta result = (price1,price2) } if delta < 0 { index1 += 1 }else { index2 -= 1 } } return result } public func calculateFreeShippingOptimal(productPrices:[Int],freeShippingAmt:Int) -> (Int,Int) { var minFreeShippingDelta = freeShippingAmt var index1 = 0 var index2 = productPrices.count - 1 var result:(Int,Int) = (-1,-1) // Below statement do O(log n) let _productPrices = productPrices.sorted() // Below statement do O(n) so total complexity of the method is O(n log n) while index1 < index2 { let price1 = _productPrices[index1] let price2 = _productPrices[index2] let delta = price1 + price2 - freeShippingAmt if delta > 0 && delta < minFreeShippingDelta { minFreeShippingDelta = delta result = (price1,price2) } if delta < 0 { index1 += 1 }else { index2 -= 1 } } return result }
mit
SonnyBrooks/ProjectEulerSwift
ProjectEulerSwift/Problem29.swift
1
1133
// // Problem29.swift // ProjectEulerSwift // // Created by Andrew Budziszek on 1/23/17. // Copyright © 2017 Andrew Budziszek. All rights reserved. // // /* Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? */ import Foundation func p29() -> String { return "This problem has been done in Python due to max integer restraints. See Problem29.py" } private func distinctPowers() -> Int { var hit:[Int] = [] for i in 2...100{ for j in 2...100{ let currentPow = Int(pow(Double(i), Double(j))) if !hit.contains(currentPow) { hit.append(currentPow) } } } return hit.count }
mit
wordpress-mobile/WordPress-Aztec-iOS
AztecTests/TextKit/TextViewTests.swift
2
84241
import XCTest @testable import Aztec import MobileCoreServices class TextViewTests: XCTestCase { struct Constants { static let sampleText0 = "Lorem ipsum sarasum naradum taradum insumun" static let sampleText1 = " patronum sitanum elanum zoipancoiamum." } let attachmentDelegate = TextViewStubAttachmentDelegate() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: - TextView construction func createTextViewWithContent() -> TextView { let paragraph = "Lorem ipsum dolar sit amet.\n" let richTextView = Aztec.TextView(defaultFont: UIFont.systemFont(ofSize: 14), defaultMissingImage: UIImage()) richTextView.textAttachmentDelegate = attachmentDelegate let attributes = [NSAttributedString.Key.paragraphStyle : NSParagraphStyle()] let templateString = NSMutableAttributedString(string: paragraph, attributes: attributes) let attrStr = NSMutableAttributedString() attrStr.append(templateString) attrStr.append(templateString) attrStr.append(templateString) richTextView.attributedText = attrStr return richTextView } // MARK: - Configuration func testTextViewReferencesStorage() { let textView = Aztec.TextView(defaultFont: UIFont.systemFont(ofSize: 14), defaultMissingImage: UIImage()) textView.text = "Foo" XCTAssert(textView.text == "Foo") XCTAssert(textView.text == textView.textStorage.string) XCTAssert(textView.attributedText == textView.textStorage) textView.attributedText = NSAttributedString(string: "Bar") XCTAssert(textView.text == "Bar") XCTAssert(textView.text == textView.textStorage.string) XCTAssert(textView.attributedText == textView.textStorage) XCTAssert(textView.textStorage == textView.layoutManager.textStorage) XCTAssert(textView.textStorage == textView.textContainer.layoutManager!.textStorage) XCTAssert(textView.textStorage.isKind(of: TextStorage.self)) } // MARK: - Test Index Wrangling func testMaxIndex() { let textView = Aztec.TextView(defaultFont: UIFont.systemFont(ofSize: 14), defaultMissingImage: UIImage()) textView.text = "foo" let count = textView.text!.count let maxIndex = count - 1 // Test upper and lower bounds XCTAssert(maxIndex == textView.maxIndex(100)) XCTAssert(0 == textView.maxIndex(0)) } func testAdjustedIndex() { let textView = Aztec.TextView(defaultFont: UIFont.systemFont(ofSize: 14), defaultMissingImage: UIImage()) textView.text = "foobarbaz" let count = textView.text!.count let maxIndex = count - 1 // Test upper and lower bounds. // Remember that an adjusted character index should be one less than // the NSRange.location. XCTAssert(maxIndex - 1 == textView.adjustedIndex(100)) XCTAssert(0 == textView.adjustedIndex(0)) XCTAssert(0 == textView.adjustedIndex(1)) XCTAssert(1 == textView.adjustedIndex(2)) } // MARK: - Retrieve Format Identifiers func testFormattingIdentifiersSpanningRange() { let textView = TextViewStub(withHTML: "foo<b>bar</b>baz") let range = NSRange(location: 3, length: 3) let identifiers = textView.formattingIdentifiersSpanningRange(range) XCTAssert(identifiers.count == 1) XCTAssert(identifiers.contains(.bold)) } func testFormattingIdentifiersAtIndex() { let textView = TextViewStub(withHTML: "foo<b>bar</b>baz") var identifiers = textView.formattingIdentifiersAtIndex(4) XCTAssert(identifiers.count == 1) XCTAssert(identifiers.contains(.bold)) identifiers = textView.formattingIdentifiersAtIndex(5) XCTAssert(identifiers.count == 1) XCTAssert(identifiers.contains(.bold)) identifiers = textView.formattingIdentifiersAtIndex(6) XCTAssert(identifiers.count == 1) XCTAssert(identifiers.contains(.bold)) identifiers = textView.formattingIdentifiersAtIndex(0) XCTAssert(identifiers.count == 0) identifiers = textView.formattingIdentifiersAtIndex(3) XCTAssert(identifiers.count == 0) identifiers = textView.formattingIdentifiersAtIndex(7) XCTAssert(identifiers.count == 0) } // MARK: - Toggle Attributes func testToggleBold() { let textView = TextViewStub(withHTML: "foo<b>bar</b>baz") let range = NSRange(location: 3, length: 3) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.bold)) textView.toggleBold(range: range) XCTAssert(!textView.formattingIdentifiersSpanningRange(range).contains(.bold)) textView.toggleBold(range: range) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.bold)) } func testToggleItalic() { let textView = TextViewStub(withHTML: "foo<i>bar</i>baz") let range = NSRange(location: 3, length: 3) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.italic)) textView.toggleItalic(range: range) XCTAssert(!textView.formattingIdentifiersSpanningRange(range).contains(.italic)) textView.toggleItalic(range: range) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.italic)) } func testToggleUnderline() { let textView = TextViewStub(withHTML: "foo<u>bar</u>baz") let range = NSRange(location: 3, length: 3) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.underline)) textView.toggleUnderline(range: range) XCTAssert(!textView.formattingIdentifiersSpanningRange(range).contains(.underline)) textView.toggleUnderline(range: range) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.underline)) } func testToggleStrike() { let textView = TextViewStub(withHTML: "foo<strike>bar</strike>baz") let range = NSRange(location: 3, length: 3) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.strikethrough)) textView.toggleStrikethrough(range: range) XCTAssert(!textView.formattingIdentifiersSpanningRange(range).contains(.strikethrough)) textView.toggleStrikethrough(range: range) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.strikethrough)) } func testToggleBlockquote() { let textView = createTextViewWithContent() let length = textView.text.count let range = NSRange(location: 0, length: length) textView.toggleBlockquote(range: range) XCTAssert(textView.formattingIdentifiersAtIndex(1).contains(.blockquote)) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.blockquote)) textView.toggleBlockquote(range: range) XCTAssert(!textView.formattingIdentifiersAtIndex(1).contains(.blockquote)) XCTAssert(!textView.formattingIdentifiersSpanningRange(range).contains(.blockquote)) } func testToggleOrderedList() { let textView = createTextViewWithContent() let length = textView.text.count let range = NSRange(location: 0, length: length) textView.toggleOrderedList(range: range) XCTAssert(textView.formattingIdentifiersAtIndex(0).contains(.orderedlist)) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.orderedlist)) textView.toggleOrderedList(range: range) XCTAssert(!textView.formattingIdentifiersAtIndex(0).contains(.orderedlist)) XCTAssert(!textView.formattingIdentifiersSpanningRange(range).contains(.orderedlist)) } func testToggleUnorderedList() { let textView = createTextViewWithContent() let length = textView.text.count let range = NSRange(location: 0, length: length) textView.toggleUnorderedList(range: range) XCTAssert(textView.formattingIdentifiersAtIndex(0).contains(.unorderedlist)) XCTAssert(textView.formattingIdentifiersSpanningRange(range).contains(.unorderedlist)) textView.toggleOrderedList(range: range) XCTAssert(!textView.formattingIdentifiersAtIndex(0).contains(.unorderedlist)) XCTAssert(!textView.formattingIdentifiersSpanningRange(range).contains(.unorderedlist)) } /// This test was created to prevent regressions related to this issue: /// https://github.com/wordpress-mobile/WordPress-Aztec-iOS/issues/350 /// func testToggleBlockquoteAndStrikethrough() { let textView = TextViewStub() textView.toggleStrikethrough(range: NSRange.zero) textView.toggleBlockquote(range: NSRange.zero) // The test not crashing would be successful. } // MARK: - Test Attributes Exist func check(textView: TextView, range:NSRange, forIndentifier identifier: FormattingIdentifier) -> Bool { return textView.formattingIdentifiersSpanningRange(range).contains(identifier) } func testBoldSpansRange() { let textView = TextViewStub(withHTML: "foo<b>bar</b>baz") XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 3)).contains(.bold)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 2)).contains(.bold)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 1)).contains(.bold)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 2, length: 3)).contains(.bold)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 4, length: 3)).contains(.bold)) } func testItalicSpansRange() { let textView = TextViewStub(withHTML: "foo<i>bar</i>baz") XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 3)).contains(.italic)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 2)).contains(.italic)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 1)).contains(.italic)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 2, length: 3)).contains(.italic)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 4, length: 3)).contains(.italic)) } func testUnderlineSpansRange() { let textView = TextViewStub(withHTML: "foo<u>bar</u>baz") XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 3)).contains(.underline)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 2)).contains(.underline)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 1)).contains(.underline)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 2, length: 3)).contains(.underline)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 4, length: 3)).contains(.underline)) } func testStrikethroughSpansRange() { let textView = TextViewStub(withHTML: "foo<strike>bar</strike>baz") XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 3)).contains(.strikethrough)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 2)).contains(.strikethrough)) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 3, length: 1)).contains(.strikethrough)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 2, length: 3)).contains(.strikethrough)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 4, length: 3)).contains(.strikethrough)) } func testBlockquoteSpansRange() { let textView = createTextViewWithContent() let range = NSRange(location: 0, length: 1) let length = "Lorem ipsum dolar sit amet.\n".count textView.toggleBlockquote(range: range) XCTAssert(textView.formattingIdentifiersSpanningRange(NSRange(location: 0, length: length)).contains(.blockquote)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 0, length: length + 1)).contains(.blockquote)) XCTAssert(!textView.formattingIdentifiersSpanningRange(NSRange(location: 1, length: length)).contains(.blockquote)) } func testBoldAtIndex() { let textView = TextViewStub(withHTML: "foo<b>bar</b>baz") XCTAssert(textView.formattingIdentifiersAtIndex(4).contains(.bold)) XCTAssert(textView.formattingIdentifiersAtIndex(5).contains(.bold)) XCTAssert(textView.formattingIdentifiersAtIndex(6).contains(.bold)) XCTAssert(!textView.formattingIdentifiersAtIndex(2).contains(.bold)) XCTAssert(!textView.formattingIdentifiersAtIndex(7).contains(.bold)) } func testItalicAtIndex() { let textView = TextViewStub(withHTML: "foo<i>bar</i>baz") XCTAssert(textView.formattingIdentifiersAtIndex(4).contains(.italic)) XCTAssert(textView.formattingIdentifiersAtIndex(5).contains(.italic)) XCTAssert(textView.formattingIdentifiersAtIndex(6).contains(.italic)) XCTAssert(!textView.formattingIdentifiersAtIndex(2).contains(.italic)) XCTAssert(!textView.formattingIdentifiersAtIndex(7).contains(.italic)) } func testUnderlineAtIndex() { let textView = TextViewStub(withHTML: "foo<u>bar</u>baz") XCTAssert(textView.formattingIdentifiersAtIndex(4).contains(.underline)) XCTAssert(textView.formattingIdentifiersAtIndex(5).contains(.underline)) XCTAssert(textView.formattingIdentifiersAtIndex(6).contains(.underline)) XCTAssert(!textView.formattingIdentifiersAtIndex(2).contains(.underline)) XCTAssert(!textView.formattingIdentifiersAtIndex(7).contains(.underline)) } func testStrikethroughAtIndex() { let textView = TextViewStub(withHTML: "foo<strike>bar</strike>baz") XCTAssert(textView.formattingIdentifiersAtIndex(4).contains(.strikethrough)) XCTAssert(textView.formattingIdentifiersAtIndex(5).contains(.strikethrough)) XCTAssert(textView.formattingIdentifiersAtIndex(6).contains(.strikethrough)) XCTAssert(!textView.formattingIdentifiersAtIndex(2).contains(.strikethrough)) XCTAssert(!textView.formattingIdentifiersAtIndex(7).contains(.strikethrough)) } func testBlockquoteAtIndex() { let textView = createTextViewWithContent() let range = NSRange(location: 0, length: 1) XCTAssert(!textView.formattingIdentifiersAtIndex(1).contains(.blockquote)) textView.toggleBlockquote(range: range) XCTAssert(textView.formattingIdentifiersAtIndex(1).contains(.blockquote)) textView.toggleBlockquote(range: range) XCTAssert(!textView.formattingIdentifiersAtIndex(1).contains(.blockquote)) } func testColorAttributeAtPosition() { let textView = TextViewStub(withHTML: "foo<span style=\"color: #FF0000\">bar</span>baz") XCTAssert(textView.attributedText!.attributes(at: 4, effectiveRange: nil).keys.contains(.foregroundColor)) let color = textView.attributedText!.attributes(at: 4, effectiveRange: nil)[.foregroundColor] as! UIColor XCTAssertEqual(color, UIColor(hexString: "#FF0000")) } // MARK: - Adding newlines /// Tests that entering a newline in an empty editor does not crash it. /// /// Added to avoid regressions to the bug reported here: /// https://github.com/wordpress-mobile/WordPress-Aztec-iOS/issues/352 /// func testAddingNewlineOnEmptyEditor() { let textView = TextViewStub(withHTML: "") textView.insertText("\n") } /// Tests that a visual newline is not added at EoF /// func testNewlineNotAddedAtEof() { let textView = TextViewStub(withHTML: "<p>Testing <b>bold</b> newlines</p>") XCTAssertEqual(textView.text, "Testing bold newlines") } /// Tests that the visual newline is shown at the correct position. /// /// Added to avoid regressions to the bug reported here: /// https://github.com/wordpress-mobile/WordPress-Aztec-iOS/issues/387 /// func testNewlineRenderedAtTheCorrectPosition() { let textView = TextViewStub(withHTML: "<p>Testing <b>bold</b> newlines</p>Hey!") XCTAssertEqual(textView.text, "Testing bold newlines\(String(.paragraphSeparator))Hey!") } // MARK: - Deleting newlines /// Tests that deleting a newline works by merging the component around it. /// /// Input: /// - Initial HTML: "<p>Hello</p><p>World!</p>" /// - Deletion range: (loc: 5, len 1) /// /// Output: /// - Final HTML: "<p>HelloWorld!</p>" /// func testDeleteNewline() { let textView = TextViewStub(withHTML: "<p>Hello</p><p>World!</p>") let rangeStart = textView.position(from: textView.beginningOfDocument, offset: 5)! let rangeEnd = textView.position(from: rangeStart, offset: 1)! let range = textView.textRange(from: rangeStart, to: rangeEnd)! textView.replace(range, withText: "") XCTAssertEqual(textView.getHTML(), "<p>HelloWorld!</p>") } /// Tests that deleting a newline works by merging the component around it. /// /// Input: /// - Initial HTML: "Hello<p>World!</p>" /// - Deletion range: (loc: 5, len 1) /// /// Output: /// - Final HTML: "HelloWorld!" /// func testDeleteNewline2() { let textView = TextViewStub(withHTML: "Hello<p>World!</p>") let rangeStart = textView.position(from: textView.beginningOfDocument, offset: 5)! let rangeEnd = textView.position(from: rangeStart, offset: 1)! let range = textView.textRange(from: rangeStart, to: rangeEnd)! textView.replace(range, withText: "") XCTAssertEqual(textView.getHTML(), "<p>HelloWorld!</p>") } /// Tests that deleting a newline works by merging the component around it. /// /// Input: /// - Initial HTML: "<blockquote>Hello</blockquote><p>World!</p>" /// - Deletion range: (loc: 5, len 1) /// /// Output: /// - Final HTML: "<blockquote>HelloWorld!</blockquote>" /// func testDeleteNewline3() { let textView = TextViewStub(withHTML: "<blockquote>Hello</blockquote><p>World!</p>") let rangeStart = textView.position(from: textView.beginningOfDocument, offset: 5)! let rangeEnd = textView.position(from: rangeStart, offset: 1)! let range = textView.textRange(from: rangeStart, to: rangeEnd)! textView.replace(range, withText: "") XCTAssertEqual(textView.getHTML(), "<blockquote>HelloWorld!</blockquote>") } /// Tests that deleting a newline works by merging the component around it. /// /// Input: /// - Initial HTML: "<p>Hello</p>World!" /// - Deletion range: (loc: 5, len 1) /// /// Output: /// - Final HTML: "<p>HelloWorld!</p>" /// func testDeleteNewline4() { let textView = TextViewStub(withHTML: "<p>Hello</p>World!") let rangeStart = textView.position(from: textView.beginningOfDocument, offset: 5)! let rangeEnd = textView.position(from: rangeStart, offset: 1)! let range = textView.textRange(from: rangeStart, to: rangeEnd)! textView.replace(range, withText: "") XCTAssertEqual(textView.getHTML(), "<p>HelloWorld!</p>") } /// Tests that deleting a newline works by merging the component around it. /// /// Input: /// - Initial HTML: "List<ul><li>first</li><li>second</li><li>third</li></ul>" /// - Deletion range: (loc: 4, len 1) /// - Second deletion range: (loc: 9, len: 1) /// - Third deletion range: (loc: 15, len: 1) /// /// Output: /// - Final HTML: "Listfirstsecond" /// func testDeleteNewline5() { let textView = TextViewStub(withHTML: "List<ul><li>first</li><li>second</li><li>third</li></ul>") let rangeStart = textView.position(from: textView.beginningOfDocument, offset: 4)! let rangeEnd = textView.position(from: rangeStart, offset: 1)! let range = textView.textRange(from: rangeStart, to: rangeEnd)! textView.replace(range, withText: "") XCTAssertEqual(textView.getHTML(prettify: false), "<p>Listfirst</p><ul><li>second</li><li>third</li></ul>") let rangeStart2 = textView.position(from: textView.beginningOfDocument, offset: 9)! let rangeEnd2 = textView.position(from: rangeStart2, offset: 1)! let range2 = textView.textRange(from: rangeStart2, to: rangeEnd2)! textView.replace(range2, withText: "") XCTAssertEqual(textView.getHTML(prettify: false), "<p>Listfirstsecond</p><ul><li>third</li></ul>") let rangeStart3 = textView.position(from: textView.beginningOfDocument, offset: 15)! let rangeEnd3 = textView.position(from: rangeStart3, offset: 1)! let range3 = textView.textRange(from: rangeStart3, to: rangeEnd3)! textView.replace(range3, withText: "") XCTAssertEqual(textView.getHTML(prettify: false), "<p>Listfirstsecondthird</p>") } /// Tests that deleting a newline works by merging the component around it. /// /// Input: /// - Initial HTML: "<ol><li>First</li><li>Second</li></ol><ul><li>Third</li><li>Fourth</li></ul>" /// - Deletion range: (loc: 12, len 1) /// /// Output: /// - Final HTML: "<ol><li>First</li><li>Second</li><li>Third</li></ol><ul><li>Fourth</li></u" /// func testDeleteNewline6() { let textView = TextViewStub(withHTML: "<ol><li>First</li><li>Second</li></ol>Ahoi<br>Arr!") let rangeStart = textView.position(from: textView.beginningOfDocument, offset: 12)! let rangeEnd = textView.position(from: rangeStart, offset: 1)! let range = textView.textRange(from: rangeStart, to: rangeEnd)! textView.replace(range, withText: "") XCTAssertEqual(textView.getHTML(prettify: false), "<ol><li>First</li><li>SecondAhoi<br>Arr!</li></ol>") } /// Tests that deleting a newline works at the end of text with paragraph with header before works. /// /// Input: /// - Initial HTML: "<h1>Header</h1><br>" /// - Deletion range: (loc: 5, len 1) /// /// Output: /// - Final HTML: "<h1>Header</h1>" /// func testDeleteNewlineAtEndOfText() { let html = "<h1>Header</h1><br>" let textView = TextViewStub(withHTML: html) let range = NSRange(location: textView.text.count, length:0) textView.selectedRange = range textView.deleteBackward() XCTAssertEqual(textView.getHTML(), "<h1>Header</h1>") } // MARK: - Backspace /// Makes sure that backspacing in the middle of a paragraph doesn't cause any issues with the /// paragraph. /// /// Introduced to avoid regressions with: /// https://github.com/wordpress-mobile/AztecEditor-iOS/issues/457 /// func testBackspaceInMiddleOfParagraph() { let html = "<p>Hello 🌎 there!</p>" let textView = TextViewStub(withHTML: html) let newSelectedRange = NSRange(location: 6, length: 1) textView.selectedRange = textView.text.utf16NSRange(from: newSelectedRange) textView.deleteBackward() textView.deleteBackward() XCTAssertEqual(textView.getHTML(), "<p>Hello there!</p>") } // MARK: - Insert links /// Tests that inserting a link on an empty textView works. Also that it doesn't crash the /// textView (which was the reason why this test was first introduced). /// /// Input: /// - Link URL is: "www.wordpress.com" /// - Link Title: "WordPress.com" /// - Insertion range: (loc: 0, len: 0) /// func testInsertingLinkWorks() { let linkUrl = "www.wordpress.com" let linkTitle = "WordPress.com" let insertionRange = NSRange(location: 0, length: 0) let textView = TextViewStub(withHTML: "") let url = URL(string: linkUrl)! textView.setLink(url, title: linkTitle, inRange: insertionRange) XCTAssertEqual(textView.getHTML(), "<p><a href=\"\(linkUrl)\">\(linkTitle)</a></p>") } /// Tests that inserting a link on the same place twice works properly /// func testSetLinkTwiceInSameRangeWorks() { let linkUrl = "www.wordpress.com" let linkTitle = "WordPress.com" let insertionRange = NSRange(location: 0, length: linkTitle.utf8.count) let textView = TextViewStub(withHTML: linkTitle) let url = URL(string: linkUrl)! textView.setLink(url, inRange: insertionRange) XCTAssertEqual(textView.getHTML(), "<p><a href=\"\(linkUrl)\">\(linkTitle)</a></p>") textView.setLink(url, inRange: insertionRange) XCTAssertEqual(textView.getHTML(), "<p><a href=\"\(linkUrl)\">\(linkTitle)</a></p>") } /// Tests that removing a link on the same place twice works properly /// func testRemoveLinkTwiceInSameRangeWorks() { let linkUrl = "www.wordpress.com" let linkTitle = "WordPress.com" let insertionRange = NSRange(location: 0, length: linkTitle.utf8.count) let textView = TextViewStub(withHTML: linkTitle) let url = URL(string: linkUrl)! textView.setLink(url, inRange: insertionRange) XCTAssertEqual(textView.getHTML(), "<p><a href=\"\(linkUrl)\">\(linkTitle)</a></p>") textView.removeLink(inRange: insertionRange) XCTAssertEqual(textView.getHTML(), "<p>\(linkTitle)</p>") textView.removeLink(inRange: insertionRange) XCTAssertEqual(textView.getHTML(), "<p>\(linkTitle)</p>") } func testParsingOfInvalidLink() { let html = "<p><a href=\"\\http:\\badlink&?\">link</a></p>" let textView = TextViewStub(withHTML: html) XCTAssertEqual(textView.getHTML(), html) } func testParsingOfLinkWithTarget() { let html = "<p><a href=\"http://wordpress.com?\" target=\"_blank\">link</a></p>" let textView = TextViewStub(withHTML: html) let insertionRange = NSRange(location: 0, length: 4) let target = textView.linkTarget(forRange: insertionRange) XCTAssertEqual(textView.getHTML(), html) XCTAssertEqual(target, "_blank") } func testToggleBlockquoteWriteOneCharAndDelete() { let textView = TextViewStub() textView.toggleBlockquote(range: NSRange.zero) textView.insertText("A") textView.deleteBackward() // The test not crashing would be successful. } /// Tests that there is no content loss, when switching to HTML mode, after toggling H1 Style. /// /// Input: /// - "Header" (inserted character by character). /// /// Ref.: https://github.com/wordpress-mobile/WordPress-Aztec-iOS/issues/404 /// func testToggleHeader1DoesNotLooseTheFirstCharacter() { let textView = TextViewStub(withHTML: "") textView.toggleHeader(.h1, range: .zero) textView.insertText("H") textView.insertText("e") textView.insertText("a") textView.insertText("d") textView.insertText("e") textView.insertText("r") XCTAssertEqual(textView.getHTML(), "<h1>Header</h1>") } /// Tests that there is no HTML Corruption when editing text, after toggling H1 and entering two lines of text. /// /// Input: /// - "Header\n12" (Inserted character by character) /// - Delete Backwards event. /// /// Ref. https://github.com/wordpress-mobile/WordPress-Aztec-iOS/issues/407 /// func testDeletingBackwardAfterTogglingHeaderDoesNotTriggerInvalidHTML() { let textView = TextViewStub(withHTML: "") textView.toggleHeader(.h1, range: .zero) textView.insertText("H") textView.insertText("e") textView.insertText("a") textView.insertText("d") textView.insertText("e") textView.insertText("r") textView.insertText("\n") textView.insertText("1") textView.insertText("2") textView.deleteBackward() XCTAssertEqual(textView.getHTML(prettify: false), "<h1>Header</h1><p>1</p>") } /// Tests that Newline Characters inserted at the middle of a H1 String will cause the newline to loose the style. /// /// Input: /// - "Header Header" /// - "\n" inserted in between the two words /// Ref. https://github.com/wordpress-mobile/AztecEditor-iOS/issues/466 /// func testInsertingNewlineAtTheMiddleOfHeaderDoesNotLooseHeaderStyleOnNewline() { let textView = TextViewStub(withHTML: "") textView.toggleHeader(.h1, range: .zero) textView.insertText("Header Header") textView.selectedRange = NSMakeRange("Header".count, 0) textView.insertText("\n") let identifiers = textView.formattingIdentifiersAtIndex(textView.selectedRange.location) XCTAssert(identifiers.contains(.header1)) XCTAssertEqual(textView.getHTML(prettify: false), "<h1>Header</h1><h1> Header</h1>") } // MARK: - Unicode tests /// Tests that applying bold to a string with unicode characters doesn't crash the app. /// /// This test was crashing the app as of 2017/04/18. /// func testBoldWithUnicodeCharacter() { let string = "Hello 🌎!" let textView = TextViewStub(withHTML: string) let swiftRange = NSRange(location: 0, length: string.count) let utf16Range = string.utf16NSRange(from: swiftRange) textView.toggleBold(range: utf16Range) } // MARK: - Lists /// Verifies that a Text List does not get removed, whenever the user presses backspace /// /// Input: /// - Ordered List /// - "First Item" /// - Backspace /// /// Ref. Scenario Mark I on Issue https://github.com/wordpress-mobile/AztecEditor-iOS/pull/425 /// func testListDoesNotGetLostAfterPressingBackspace() { let textView = TextViewStub(withHTML: "") textView.toggleOrderedList(range: .zero) textView.insertText("First Item") textView.deleteBackward() let formatter = TextListFormatter(style: .ordered) let range = textView.storage.rangeOfEntireString let present = formatter.present(in: textView.storage, at: range) XCTAssertTrue(present) } /// Verifies that the List gets nuked whenever the only `\n` present in the document is deleted. /// /// Input: /// - Ordered List /// - Selection of the EOD /// - Backspace /// /// Ref. Scenario Mark II on Issue https://github.com/wordpress-mobile/AztecEditor-iOS/pull/425 /// func testEmptyListGetsNukedWheneverTheOnlyNewlineCharacterInTheDocumentIsNuked() { let textView = TextViewStub(withHTML: "") textView.toggleOrderedList(range: .zero) textView.selectedRange = textView.text.endOfStringNSRange() textView.deleteBackward() XCTAssertFalse(TextListFormatter.listsOfAnyKindPresent(in: textView.typingAttributes)) XCTAssert(textView.storage.length == 0) } /// Verifies that New Line Characters get effectively inserted after a Text List. /// /// Input: /// - Ordered List /// - \n at the end of the document /// /// Ref. Scenario Mark III on Issue https://github.com/wordpress-mobile/AztecEditor-iOS/pull/425 /// func testNewLinesAreInsertedAfterEmptyList() { let textView = TextViewStub(withHTML: "") // Toggle List + Move the selection to the EOD textView.toggleOrderedList(range: .zero) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) // Insert Newline var expectedLength = textView.text.count textView.insertText(String(.lineFeed)) expectedLength += String(.lineFeed).count XCTAssertEqual(textView.text.count, expectedLength) } /// Verifies that New List Items do get their bullet, even when the ending `\n` character was deleted. /// /// Input: /// - Ordered List /// - Text: Constants.sampleText0 /// - Selection of the `\n` at the EOD, and backspace /// - Text: "\n" /// - Text: Constants.sampleText1 /// /// Ref. Scenario Mark IV on Issue https://github.com/wordpress-mobile/AztecEditor-iOS/pull/425 /// func testNewLinesGetBulletStyleEvenAfterDeletingEndOfDocumentNewline() { let newline = String(.lineFeed) let textView = TextViewStub(withHTML: "") textView.toggleOrderedList(range: .zero) textView.insertText(Constants.sampleText0) // Select the end of the document textView.selectedRange = textView.text.endOfStringNSRange() // Delete + Insert Newline textView.deleteBackward() textView.insertText(newline + Constants.sampleText1) // Verify it's still present let secondLineIndex = Constants.sampleText0.count + newline.count let secondLineRange = NSRange(location: secondLineIndex, length: Constants.sampleText1.count) let formatter = TextListFormatter(style: .ordered) let present = formatter.present(in: textView.storage, at: secondLineRange) XCTAssert(present) } /// Verifies that after selecting a newline below a TextList, TextView wil not render (nor carry over) /// the Text List formatting attributes. /// /// Input: /// - Ordered List /// - Selection of the `\n` at the EOD /// /// Ref. Scenario Mark V on Issue https://github.com/wordpress-mobile/AztecEditor-iOS/pull/425 /// func testTypingAttributesLooseTextListWhenSelectingAnEmptyNewlineBelowTextList() { let textView = TextViewStub(withHTML: "") textView.toggleOrderedList(range: .zero) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) XCTAssertFalse(TextListFormatter.listsOfAnyKindPresent(in: textView.typingAttributes)) } /// Verifies that a Text List gets removed, whenever the user types `\n` in an empty line. /// /// Input: /// - Ordered List /// - `\n` on the first line /// /// Ref. Scenario Mark IV on Issue https://github.com/wordpress-mobile/AztecEditor-iOS/pull/425 /// func testListGetsRemovedWhenTypingNewLineOnAnEmptyBullet() { let textView = TextViewStub(withHTML: "") textView.toggleOrderedList(range: .zero) textView.insertText(String(.lineFeed)) let formatter = TextListFormatter(style: .ordered) let attributedText = textView.attributedText! for location in 0 ..< attributedText.length { XCTAssertFalse(formatter.present(in: attributedText, at: location)) } XCTAssertFalse(TextListFormatter.listsOfAnyKindPresent(in: textView.typingAttributes)) } /// Verifies that toggling an Unordered List, when editing an empty document, inserts a Newline. /// /// Input: /// - Unordered List /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/414 /// func testTogglingUnorderedListsOnEmptyDocumentsInsertsNewline() { let textView = TextViewStub(withHTML: "") textView.toggleUnorderedList(range: .zero) XCTAssert(textView.text.isEndOfLine()) } /// Verifies that toggling an Unordered List, when editing the end of a non empty line should /// never insert a newline, but that a newline is inserted for an empty line. /// /// Input: /// - "Something Here" /// - Selection of the end of document /// - Unordered List /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/414 /// func testTogglingUnorderedListsOnNonEmptyDocumentsWhenSelectedRangeIsAtTheEndOfDocumentWillInsertNewline() { let textView = TextViewStub(withHTML: Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.toggleUnorderedList(range: .zero) XCTAssertEqual(textView.text, Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.insertText(Constants.sampleText1) textView.insertText(String(.lineFeed)) XCTAssertEqual(textView.text, Constants.sampleText0 + Constants.sampleText1 + String(.lineFeed) + String(.lineFeed) ) } /// Verifies that toggling an Ordered List, when editing an empty document, inserts a Newline. /// /// Input: /// - Ordered List /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/414 /// func testTogglingOrderedListsOnEmptyDocumentsInsertsNewline() { let textView = TextViewStub(withHTML: "") textView.toggleOrderedList(range: .zero) XCTAssert(textView.text.isEndOfLine()) } /// Verifies that toggling an Ordered List, when editing the end of a non empty document, inserts a Newline. /// /// Input: /// - "Something Here" /// - Selection of the end of document /// - Ordered List /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/414 /// func testTogglingOrderedListsOnNonEmptyDocumentsWhenSelectedRangeIsAtTheEndOfDocumentWillInsertNewline() { let textView = TextViewStub(withHTML: Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.toggleOrderedList(range: .zero) XCTAssertEqual(textView.text, Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.insertText(Constants.sampleText1) textView.insertText(String(.lineFeed)) let expected = Constants.sampleText0 + Constants.sampleText1 + String(.lineFeed) + String(.lineFeed) XCTAssertEqual(textView.text, expected) } /// When deleting the newline between lines 1 and 2 in the following example: /// Line 1: <empty> /// Line 2: <empty> (with list style) /// Line 3: <empty> /// /// Aztec tends to naturally maintain the list style alive, due to the newline between line 2 and /// 3, since line 1 has no paragraph style once its closing newline is removed. /// /// This test makes sure that removing the newline between line 1 and 2, also removes the list /// style in line 2. /// func testDeleteNewlineRemovesListStyleIfPreceededByAnEmptyLine() { let textView = TextViewStub() textView.insertText(String(.lineFeed)) textView.toggleUnorderedList(range: textView.selectedRange) textView.deleteBackward() XCTAssertFalse(TextListFormatter.listsOfAnyKindPresent(in: textView.typingAttributes)) } /// When the caret is positioned at both EoF and EoL, inserting a line separator (in most /// editors by pressing shift + enter) must not remove the list style. /// /// This test is to avoid regressions on: /// https://github.com/wordpress-mobile/AztecEditor-iOS/issues/594 /// func testShiftEnterAtEndOfListAndEndOfFile() { let textView = TextViewStub() textView.insertText("First line") textView.toggleUnorderedList(range: textView.selectedRange) textView.insertText(String(.lineSeparator)) let unorderedListFormatter = TextListFormatter(style: .unordered) XCTAssertTrue(unorderedListFormatter.present(in: textView.storage, at: 0)) XCTAssertTrue(unorderedListFormatter.present(in: textView.storage, at: textView.selectedRange)) } /// This test makes sure that lists are ended when the user presses ENTER twice. /// /// Related issue: /// https://github.com/wordpress-mobile/AztecEditor-iOS/issues/1012 /// func testDoubleNewlineEndsList() { let textView = TextViewStub() let firstLine = "First Line" let secondLine = "Second Line" textView.insertText(firstLine) textView.toggleUnorderedList(range: textView.selectedRange) textView.insertText(String(.paragraphSeparator)) textView.insertText(String(.paragraphSeparator)) textView.insertText(secondLine) let firstLineParagraphStyle = textView.storage.attributes(at: 0, effectiveRange: nil).paragraphStyle() let secondLineParagraphStyle = textView.storage.attributes(at: firstLine.count + 1, effectiveRange: nil).paragraphStyle() XCTAssertTrue(firstLineParagraphStyle.properties.contains(where: { (property) -> Bool in return property is TextList || property is HTMLLi })) XCTAssertFalse(secondLineParagraphStyle.properties.contains(where: { (property) -> Bool in return property is TextList || property is HTMLLi })) } // MARK: - Blockquotes /// Verifies that a Blockquote does not get removed whenever the user presses backspace /// /// Input: /// - Blockquote /// - Text: Constants.sampleText0 /// - Backspace /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testBlockquoteDoesNotGetLostAfterPressingBackspace() { let textView = TextViewStub(withHTML: "") textView.toggleBlockquote(range: .zero) textView.insertText(Constants.sampleText0) textView.deleteBackward() let formatter = BlockquoteFormatter() let range = textView.storage.rangeOfEntireString XCTAssertTrue(formatter.present(in: textView.storage, at: range)) } /// Verifies that the Blockquote gets nuked whenever the only `\n` present in the document is deleted. /// /// Input: /// - Blockquote /// - Selection of the EOD /// - Backspace /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testEmptyBlockquoteGetsNukedWheneverTheOnlyNewlineCharacterInTheDocumentIsNuked() { let textView = TextViewStub(withHTML: "") textView.toggleBlockquote(range: .zero) textView.selectedRange = textView.text.endOfStringNSRange() textView.deleteBackward() let formatter = BlockquoteFormatter() XCTAssertFalse(formatter.present(in: textView.typingAttributes)) XCTAssert(textView.storage.length == 0) } /// Verifies that New Line Characters get effectively inserted after a Blockquote. /// /// Input: /// - Blockquote /// - \n at the end of the document /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testNewLinesAreInsertedAfterEmptyBlockquote() { let newline = String(.lineFeed) let textView = TextViewStub(withHTML: "") textView.toggleBlockquote(range: .zero) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) var expectedLength = textView.text.count textView.insertText(newline) expectedLength += newline.count XCTAssertEqual(textView.text.count, expectedLength) } /// Verifies that New Blockquote Lines do get their style, even when the ending `\n` character was deleted. /// /// Input: /// - Blockquote /// - Text: Constants.sampleText0 /// - Selection of the `\n` at the EOD, and backspace /// - Text: "\n" /// - Text: Constants.sampleText1 /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testNewLinesGetBlockquoteStyleEvenAfterDeletingEndOfDocumentNewline() { let newline = String(.lineFeed) let textView = TextViewStub(withHTML: "") textView.toggleBlockquote(range: .zero) textView.insertText(Constants.sampleText0) textView.selectedRange = textView.text.endOfStringNSRange() // Delete + Insert Newline textView.deleteBackward() textView.insertText(newline) textView.insertText(Constants.sampleText1) // Verify it's still present let secondLineIndex = Constants.sampleText0.count + newline.count let secondLineRange = NSRange(location: secondLineIndex, length: Constants.sampleText1.count) let formatter = BlockquoteFormatter() let present = formatter.present(in: textView.storage, at: secondLineRange) XCTAssert(present) } /// Verifies that after selecting a newline below a Blockquote, TextView wil not render (nor carry over) /// the Blockquote formatting attributes. /// /// Input: /// - Blockquote /// - Selection of the `\n` at the EOD /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testTypingAttributesLooseBlockquoteWhenSelectingAnEmptyNewlineBelowBlockquote() { let textView = TextViewStub(withHTML: "") textView.toggleBlockquote(range: .zero) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) XCTAssertFalse(BlockquoteFormatter().present(in: textView.typingAttributes)) } /// Verifies that Blockquotes get removed whenever the user types `\n` in an empty line. /// /// Input: /// - Ordered List /// - `\n` on the first line /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testBlockquoteGetsRemovedWhenTypingNewLineOnAnEmptyBlockquoteLine() { let textView = TextViewStub(withHTML: "") textView.toggleBlockquote(range: .zero) textView.insertText(String(.lineFeed)) let formatter = BlockquoteFormatter() let attributedText = textView.attributedText! for location in 0 ..< attributedText.length { XCTAssertFalse(formatter.present(in: attributedText, at: location)) } XCTAssertFalse(formatter.present(in: textView.typingAttributes)) } /// Verifies that toggling a Blockquote, when editing an empty document, inserts a Newline. /// /// Input: /// - Blockquote /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testTogglingBlockquoteOnEmptyDocumentsInsertsNewline() { let textView = TextViewStub(withHTML: "") textView.toggleBlockquote(range: .zero) XCTAssertEqual(textView.text, String(.paragraphSeparator)) } /// Verifies that toggling a Blockquote, when editing the end of a non empty document, inserts a Newline. /// /// Input: /// - Text: Constants.sampleText0 /// - Selection of the end of document /// - Blockquote /// - Backspace /// - Text: Constants.sampleText1 /// - Text: newline /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/422 /// func testTogglingBlockquoteOnNonEmptyDocumentsWhenSelectedRangeIsAtTheEndOfDocumentWillInsertNewline() { let textView = TextViewStub(withHTML: Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.toggleBlockquote(range: .zero) XCTAssertEqual(textView.text, Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.insertText(Constants.sampleText1) textView.insertText(String(.lineFeed)) XCTAssertEqual(textView.text, Constants.sampleText0 + Constants.sampleText1 + String(.lineFeed) + String(.lineFeed)) } /// Verifies that toggling a Blockquote paragraph in the middle of paragraph does not crash system. /// func testTogglingBlockquoteOnMiddleOfRangeDoesNotCrash() { let initialQuote = """ <blockquote><strong>Quote One</strong></blockquote> <blockquote><strong>Quote Two</strong></blockquote> <blockquote><strong>Quote Three</strong></blockquote> """ let textView = TextViewStub(withHTML: initialQuote) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.toggleBlockquote(range: NSRange(location: 11, length: 0)) XCTAssertEqual(textView.text, "Quote One" + String(.paragraphSeparator)+"Quote Two"+String(.lineFeed)+"Quote Three") } // MARK: - Pre /// Verifies that a Pre does not get removed whenever the user presses backspace /// /// Input: /// - Pre /// - Text: Constants.sampleText0 /// - Backspace /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testPreDoesNotGetLostAfterPressingBackspace() { let textView = TextViewStub(withHTML: "") textView.togglePre(range: .zero) textView.insertText(Constants.sampleText0) textView.deleteBackward() let formatter = PreFormatter() let range = textView.storage.rangeOfEntireString XCTAssertTrue(formatter.present(in: textView.storage, at: range)) } /// Verifies that the Pre Style gets nuked whenever the only `\n` present in the document is deleted. /// /// Input: /// - Pre /// - Selection of the EOD /// - Backspace /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testEmptyPreGetsNukedWheneverTheOnlyNewlineCharacterInTheDocumentIsNuked() { let textView = TextViewStub(withHTML: "") textView.togglePre(range: .zero) textView.selectedRange = textView.text.endOfStringNSRange() textView.deleteBackward() let formatter = PreFormatter() XCTAssertFalse(formatter.present(in: textView.typingAttributes)) XCTAssert(textView.storage.length == 0) } /// Verifies that New Line Characters get effectively inserted after a Pre. /// /// Input: /// - Pre /// - \n at the end of the document /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testNewLinesAreInsertedAfterEmptyPre() { let newline = String(.lineFeed) let textView = TextViewStub(withHTML: "") textView.togglePre(range: .zero) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) var expectedLength = textView.text.count textView.insertText(newline) expectedLength += newline.count XCTAssertEqual(textView.text.count, expectedLength) } /// Verifies that New Pre Lines do get their style, even when the ending `\n` character was deleted. /// /// Input: /// - Blockquote /// - Text: Constants.sampleText0 /// - Selection of the `\n` at the EOD, and backspace /// - Text: "\n" /// - Text: Constants.sampleText1 /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testNewLinesGetPreStyleEvenAfterDeletingEndOfDocumentNewline() { let newline = String(.lineFeed) let textView = TextViewStub(withHTML: "") textView.togglePre(range: .zero) textView.insertText(Constants.sampleText0) textView.selectedRange = textView.text.endOfStringNSRange() // Delete + Insert Newline textView.deleteBackward() textView.insertText(newline) textView.insertText(Constants.sampleText1) // Verify it's still present let secondLineIndex = Constants.sampleText0.count + newline.count let secondLineRange = NSRange(location: secondLineIndex, length: Constants.sampleText1.count) let formatter = PreFormatter() let present = formatter.present(in: textView.storage, at: secondLineRange) XCTAssert(present) } /// Verifies that after selecting a newline below a Pre, TextView wil not render (nor carry over) /// the Pre formatting attributes. /// /// Input: /// - Pre /// - Selection of the `\n` at the EOD /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testTypingAttributesLoosePreWhenSelectingAnEmptyNewlineBelowPre() { let textView = TextViewStub(withHTML: "") textView.togglePre(range: .zero) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) XCTAssertFalse(PreFormatter().present(in: textView.typingAttributes)) } /// Verifies that Pre get removed whenever the user types `\n` in an empty line. /// /// Input: /// - Pre /// - `\n` on the first line /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testPreGetsRemovedWhenTypingNewLineOnAnEmptyPreLine() { let textView = TextViewStub(withHTML: "") textView.togglePre(range: .zero) textView.insertText(String(.lineFeed)) let formatter = PreFormatter() let attributedText = textView.attributedText! for location in 0 ..< attributedText.length { XCTAssertFalse(formatter.present(in: attributedText, at: location)) } XCTAssertFalse(formatter.present(in: textView.typingAttributes)) } /// Verifies that toggling a Pre, when editing an empty document, inserts a Newline. /// /// Input: /// - Pre /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testTogglingPreOnEmptyDocumentsInsertsNewline() { let textView = TextViewStub(withHTML: "") textView.togglePre(range: .zero) XCTAssertEqual(textView.text, String(.paragraphSeparator)) } /// Verifies that toggling a Pre, when editing the end of a non empty document, inserts a Newline. /// /// Input: /// - Text: Constants.sampleText0 /// - Selection of the end of document /// - Blockquote /// - Backspace /// - Text: Constants.sampleText1 /// - Text: newline /// /// Ref. Issue https://github.com/wordpress-mobile/AztecEditor-iOS/issues/420 /// func testTogglingPreOnNonEmptyDocumentsWhenSelectedRangeIsAtTheEndOfDocumentWillInsertNewline() { let textView = TextViewStub(withHTML: Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.togglePre(range: .zero) XCTAssertEqual(textView.text, Constants.sampleText0) textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) textView.insertText(Constants.sampleText1) textView.insertText(String(.lineFeed)) XCTAssertEqual(textView.text, Constants.sampleText0 + Constants.sampleText1 + String(.lineFeed) + String(.lineFeed)) } // MARK: - Media: Images func testPasteImage() { let sourceTextView = TextViewStub(withHTML: "<em>This is an image </em>") let targetTextView = TextViewStub(withHTML: "<strong>Pasted: </strong>") let videoInsertionRange = NSRange(location: sourceTextView.text.count, length: 0) let _ = sourceTextView.replaceWithImage(at: videoInsertionRange, sourceURL: URL(string: "image.jpg")!, placeHolderImage: nil) sourceTextView.selectedRange = NSRange(location: 0, length: sourceTextView.text.count) sourceTextView.copy(nil) targetTextView.selectedRange = NSRange(location: targetTextView.text.count, length: 0) targetTextView.paste(nil) XCTAssertEqual(targetTextView.getHTML(), "<p><strong>Pasted: </strong><em>This is an image <img src=\"image.jpg\"></em></p>") } func testPasteImageWithoutFormatting() { let sourceTextView = TextViewStub(withHTML: "<em>This is an image </em>") let targetTextView = TextViewStub(withHTML: "<strong>Pasted: </strong>") let videoInsertionRange = NSRange(location: sourceTextView.text.count, length: 0) let _ = sourceTextView.replaceWithImage(at: videoInsertionRange, sourceURL: URL(string: "image.jpg")!, placeHolderImage: nil) sourceTextView.selectedRange = NSRange(location: 0, length: sourceTextView.text.count) sourceTextView.copy(nil) targetTextView.selectedRange = NSRange(location: targetTextView.text.count, length: 0) targetTextView.pasteWithoutFormatting(nil) XCTAssertEqual(targetTextView.getHTML(), "<p><strong>Pasted: This is an image <img src=\"image.jpg\"></strong></p>") } // MARK: - Media: Video func testInsertVideo() { let textView = TextViewStub() let _ = textView.replaceWithVideo(at: NSRange(location:0, length:0), sourceURL: URL(string: "video.mp4")!, posterURL: URL(string: "video.jpg"), placeHolderImage: nil) XCTAssertEqual(textView.getHTML(), "<p><video src=\"video.mp4\" poster=\"video.jpg\"></video></p>") } func testPasteVideo() { let sourceTextView = TextViewStub(withHTML: "<em>This is a video </em>") let targetTextView = TextViewStub(withHTML: "<strong>Pasted: </strong>") let videoInsertionRange = NSRange(location: sourceTextView.text.count, length: 0) let _ = sourceTextView.replaceWithVideo(at: videoInsertionRange, sourceURL: URL(string: "video.mp4")!, posterURL: URL(string: "video.jpg"), placeHolderImage: nil) sourceTextView.selectedRange = NSRange(location: 0, length: sourceTextView.text.count) sourceTextView.copy(nil) targetTextView.selectedRange = NSRange(location: targetTextView.text.count, length: 0) targetTextView.paste(nil) XCTAssertEqual(targetTextView.getHTML(), "<p><strong>Pasted: </strong><em>This is a video <video src=\"video.mp4\" poster=\"video.jpg\"></video></em></p>") } func testPasteVideoWithoutFormatting() { let sourceTextView = TextViewStub(withHTML: "<em>This is a video </em>") let targetTextView = TextViewStub(withHTML: "<strong>Pasted: </strong>") let videoInsertionRange = NSRange(location: sourceTextView.text.count, length: 0) let _ = sourceTextView.replaceWithVideo(at: videoInsertionRange, sourceURL: URL(string: "video.mp4")!, posterURL: URL(string: "video.jpg"), placeHolderImage: nil) sourceTextView.selectedRange = NSRange(location: 0, length: sourceTextView.text.count) sourceTextView.copy(nil) targetTextView.selectedRange = NSRange(location: targetTextView.text.count, length: 0) targetTextView.pasteWithoutFormatting(nil) XCTAssertEqual(targetTextView.getHTML(), "<p><strong>Pasted: This is a video <video src=\"video.mp4\" poster=\"video.jpg\"></video></strong></p>") } /// Verifies that any edition performed on VideoAttachment's srcURL attribute is properly serialized back, /// during the HTML generation step. /// func testEditingVideoAttachmentAttributesCausesAttributesToProperlySerializeBack() { let textView = TextViewStub(withHTML: "<video src=\"video.mp4\" poster=\"video.jpg\" alt=\"The video\"></video>") guard let videoAttachment = textView.storage.mediaAttachments.first! as? VideoAttachment else { fatalError() } videoAttachment.updateURL(URL(string:"newVideo.mp4")!) textView.refresh(videoAttachment) XCTAssertEqual(textView.getHTML(), "<p><video src=\"newVideo.mp4\" poster=\"video.jpg\" alt=\"The video\"></video></p>") } func testParseVideoWithExtraAttributes() { let videoHTML = "<video src=\"newVideo.mp4\" poster=\"video.jpg\" data-wpvideopress=\"videopress\"></video>" let textView = TextViewStub(withHTML: videoHTML) XCTAssertEqual(textView.getHTML(), "<p><video src=\"newVideo.mp4\" poster=\"video.jpg\" data-wpvideopress=\"videopress\"></video></p>") guard let attachment = textView.storage.mediaAttachments.first as? VideoAttachment else { XCTFail("An video attachment should be present") return } XCTAssertEqual(attachment.extraAttributes["data-wpvideopress"], .string("videopress"), "Property should be available") attachment.extraAttributes["data-wpvideopress"] = .string("ABCDE") XCTAssertEqual(textView.getHTML(), "<p><video src=\"newVideo.mp4\" poster=\"video.jpg\" data-wpvideopress=\"ABCDE\"></video></p>") } func testParseVideoWithSourceElements() { let videoHTML = "<video poster=\"video.jpg\"><source src=\"newVideo.mp4\"></video>" let textView = TextViewStub(withHTML: videoHTML) XCTAssertEqual(textView.getHTML(), "<p><video poster=\"video.jpg\"><source src=\"newVideo.mp4\"></video></p>") guard let attachment = textView.storage.mediaAttachments.first as? VideoAttachment else { XCTFail("An video attachment should be present") return } XCTAssertEqual(attachment.sources.count, 1, "One source should be available") XCTAssertEqual(attachment.sources[0].src, "newVideo.mp4", "Video source should match") XCTAssertEqual(attachment.mediaURL, URL(string:"newVideo.mp4"), "Video source should match") } // MARK: - Comments /// This test check if the insertion of a Comment Attachment works correctly and the expected tag gets inserted /// func testInsertComment() { let textView = TextViewStub() textView.replace(.zero, withComment: "more") let html = textView.getHTML() XCTAssertEqual(html, "<p><!--more--></p>") } /// This test check if the insertion of a Comment Attachment works correctly and the expected tag gets inserted /// func testInsertCommentAttachmentDoNotCrashTheEditorWhenCalledSequentially() { let textView = TextViewStub() textView.replace(.zero, withComment: "more") textView.replace(.zero, withComment: "some other comment should go here") let html = textView.getHTML() XCTAssertEqual(html, "<p><!--some other comment should go here--><!--more--></p>") } // MARK: - HR /// This test check if the insertion of an horizontal ruler works correctly and the hr tag is inserted /// func testReplaceRangeWithHorizontalRuler() { let textView = TextViewStub() textView.replaceWithHorizontalRuler(at: .zero) let html = textView.getHTML(prettify: false) XCTAssertEqual(html, "<p><hr></p>") } /// This test check if the insertion of antwo horizontal ruler works correctly and the hr tag(s) are inserted /// func testReplaceRangeWithHorizontalRulerGeneratesExpectedHTMLWhenExecutedSequentially() { let textView = TextViewStub() textView.replaceWithHorizontalRuler(at: .zero) textView.replaceWithHorizontalRuler(at: .zero) let html = textView.getHTML(prettify: false) XCTAssertEqual(html, "<p><hr><hr></p>") } /// This test check if the insertion of an horizontal ruler over an image attachment works correctly and the hr tag is inserted /// func testReplaceRangeWithHorizontalRulerRulerOverImage() { let textView = TextViewStub() textView.replaceWithImage(at: .zero, sourceURL: URL(string:"https://wordpress.com")!, placeHolderImage: nil) textView.replaceWithHorizontalRuler(at: NSRange(location: 0, length:1)) let html = textView.getHTML(prettify: false) XCTAssertEqual(html, "<p><hr></p>") } func testReplaceRangeWithAttachmentDontDisableDefaultParagraph() { let textView = TextViewStub() textView.replaceWithImage(at: .zero, sourceURL: URL(string:"https://wordpress.com")!, placeHolderImage: nil) let html = textView.getHTML() XCTAssertEqual(html, "<p><img src=\"https://wordpress.com\"></p>") textView.selectedRange = NSRange(location: NSAttributedString.lengthOfTextAttachment, length: 1) guard let font = textView.typingAttributes[.font] as? UIFont else { XCTFail("Font should be set") return } XCTAssertEqual(font, textView.defaultFont) } func testInsertEmojiKeepsDefaultFont() { let font = UIFont(name:"HelveticaNeue", size: 14)! let textView = TextViewStub(font: font) textView.insertText("😘") let currentTypingFont = textView.typingAttributes[.font] as! UIFont XCTAssertEqual(currentTypingFont.fontDescriptor, font.fontDescriptor, "Font should be set to default") } func testRemovalOfAttachment() { let textView = TextViewStub() let attachment = textView.replaceWithImage(at: .zero, sourceURL: URL(string:"https://wordpress.com")!, placeHolderImage: nil) var html = textView.getHTML() XCTAssertEqual(html, "<p><img src=\"https://wordpress.com\"></p>") textView.remove(attachmentID: attachment.identifier) html = textView.getHTML() XCTAssertEqual(html, "") } /// This method test the parsing of img tag that contains attributes thar are not directly supported by Image attachments /// It also tests if changes on those attributes is correctly reflected on the generated HTML /// func testParseImageWithExtraAttributes() { let html = "<img src=\"image.jpg\" class=\"alignnone\" alt=\"Alt\" title=\"Title\">" let textView = TextViewStub(withHTML: html) XCTAssertEqual(textView.getHTML(), "<p><img src=\"image.jpg\" class=\"alignnone\" alt=\"Alt\" title=\"Title\"></p>") guard let attachment = textView.storage.mediaAttachments.first as? ImageAttachment else { XCTFail("An video attachment should be present") return } XCTAssertEqual(attachment.extraAttributes["alt"], .string("Alt"), "Alt Property should be available") XCTAssertEqual(attachment.extraAttributes["title"], .string("Title"), "Title Property should be available") attachment.extraAttributes["alt"] = .string("Changed Alt") attachment.extraAttributes["class"] = .string("wp-image-169") XCTAssertEqual(textView.getHTML(), "<p><img src=\"image.jpg\" class=\"alignnone wp-image-169\" alt=\"Changed Alt\" title=\"Title\"></p>") } // MARK: - Bugfixing /// This test verifies that the H1 Header does not get lost during the Rich <> Raw transitioning. /// func testToggleHtmlWithTwoEmptyLineBreaksDoesNotLooseHeaderStyle() { let pristineHTML = "<br><br><h1>Header</h1>" let textView = TextViewStub(withHTML: pristineHTML) let generatedHTML = textView.getHTML(prettify: false) XCTAssertEqual(generatedHTML, "<p><br><br></p><h1>Header</h1>") } /// This test verifies that the H1 Header does not get lost, in the scenario in which the H1 is contained /// within the second line of text (and thus, would be expected to get rendered below!). /// func testToggleHtmlWithTwoLineBreaksAndInlineHeaderDoesNotLooseHeaderStyle() { let pristineHTML = "<br>1<br>2<h1>Heder</h1>" let textView = TextViewStub(withHTML: pristineHTML) let generatedHTML = textView.getHTML(prettify: false) XCTAssertEqual(generatedHTML, "<p><br>1<br>2</p><h1>Heder</h1>") } /// This test verifies that img class attributes are not duplicated /// func testParseImageDoesntDuplicateExtraAttributes() { let html = "<img src=\"image.jpg\" class=\"alignnone wp-image-test\" title=\"Title\" alt=\"Alt\">" let textView = TextViewStub(withHTML: html) let generatedHTML = textView.getHTML() XCTAssertEqual(generatedHTML, "<p>\(html)</p>") } /// This test verifies that copying the Sample HTML Document does not trigger a crash. /// Ref. Issue #626: NSKeyedArchiver Crash /// func testCopyDoesNotCauseAztecToCrash() { let textView = TextViewStub(withSampleHTML: true) textView.selectedRange = textView.storage.rangeOfEntireString textView.copy(nil) } /// This test verifies that cutting the Sample HTML Document does not trigger a crash. /// Ref. Issue #626: NSKeyedArchiver Crash /// func testCutDoesNotCauseAztecToCrash() { let textView = TextViewStub(withSampleHTML: true) textView.selectedRange = textView.storage.rangeOfEntireString textView.cut(nil) } /// This test verifies that trying to store data in an empty pasteboard /// doesn't cause Aztec to crash. /// func testWritingIntoAnEmptyPasteboardDoesNotCauseAztecToCrash() { let pasteboard = UIPasteboard.general pasteboard.items.removeAll() let data = "Foo".data(using: .utf8)! let textView = TextViewStub(withSampleHTML: true) textView.storeInPasteboard(encoded: data, pasteboard: pasteboard) XCTAssertEqual(pasteboard.items.count, 1) } /// This test verifies that Japanese Characters do not get hexa encoded anymore, since we actually support UTF8! /// Ref. Issue #632: Stop encoding non-latin characters /// func testJapaneseCharactersWillNotGetEscaped() { let pristineJapanese = "国ドぼゆ九会以つまにの市賛済ツ聞数ナシ私35奨9企め全談ヱマヨワ全竹スレフヨ積済イナ続害ホテ" + "ソト聞長津装げ。16北夢みは殻容ク洋意能緯ざた投記ぐだもみ学徳局みそイし済更離ラレミネ展至察畑しのわぴ。航リむは" + "素希ホソ元不サト国十リ産望イげ地年ニヲネ将広ぴん器学サナチ者一か新米だしず災9識じざい総台男みのちフ。" let textView = TextViewStub(withHTML: pristineJapanese) XCTAssertEqual(textView.getHTML(), "<p>\(pristineJapanese)</p>") } /// This test verifies that Nested Text Lists are 'Grouped Together', and not simply appended at the end of /// the Properties collection. For instance, a 'broken' behavior would produce the following HTML: /// /// <ol><li><blockquote><ol><li><ol><li>First Item</li></ol></li></ol></blockquote></li></ol> /// /// Ref. Issue #633: Hitting Tab causes the bullet to indent, but the blockquote is not moving /// func testNestedTextListsAreProperlyGroupedTogether() { let textView = TextViewStub(withHTML: "") textView.toggleOrderedList(range: .zero) textView.toggleBlockquote(range: .zero) textView.insertText("First Item") // Simulate TAB Event let command = textView.keyCommands?.first { command in return command.input == String(.tab) && command.modifierFlags.isEmpty } guard let tab = command else { XCTFail() return } // Insert Two Nested Levels textView.handleTab(command: tab) textView.handleTab(command: tab) // Verify! let expected = "<ol><li><ol><li><ol><li><blockquote>First Item</blockquote></li></ol></li></ol></li></ol>" XCTAssertEqual(textView.getHTML(prettify: false), expected) } /// This test verifies that the `deleteBackward` call does not result in loosing the Typing Attributes. /// Precisely, we'll ensure that the Italics style isn't lost after hitting backspace, and retyping the /// deleted character. /// /// Ref. Issue #749: Loosing Style after hitting Backspace /// func testDeleteBackwardsDoesNotEndUpLoosingItalicsStyle() { let textView = TextViewStub(withHTML: "") textView.toggleBoldface(self) textView.insertText("First Line") textView.insertText("\n") textView.toggleItalics(self) textView.insertText("Second") let expectedHTML = textView.getHTML() textView.deleteBackward() textView.insertText("d") XCTAssertEqual(textView.getHTML(), expectedHTML) } /// This test verifies that the *ACTUAL* Typing Attributes are retrieved whenever requested from within /// UITextView's `onDidChange` delegate callback. /// /// We're doing this because of (multiple) iOS 11 bugs in which Typing Attributes get lost. /// /// Ref. Issue #748: Format Bar: Active Style gets de-higlighted /// func testActiveStyleDoesNotGetLostWheneverOnDidChangeDelegateMethodIsCalled() { let textView = TextViewStub(withHTML: "") let delegate = TextViewStubDelegate() textView.delegate = delegate textView.toggleBoldface(self) textView.insertText("Bold") textView.insertText("\n") textView.toggleItalics(self) delegate.onDidChange = { let identifiers = textView.formattingIdentifiersForTypingAttributes() XCTAssert(identifiers.contains(.bold)) XCTAssert(identifiers.contains(.italic)) } textView.insertText("Italics") } /// This test verifies that H1 Style doesn't turn rogue, and come back after editing a line of text that /// never had H1 style, to begin with!. /// /// Ref. Issue #747: Zombie H1 Style /// func testHeaderStyleDoesNotComeBackFromNonExistanceWheneverDeleteBackwardResultsInEmptyParagraph() { let textView = TextViewStub(withHTML: "") textView.toggleHeader(.h1, range: textView.selectedRange) textView.insertText("Header") textView.insertText("\n") textView.insertText("One Two") textView.insertText("\n") textView.insertText("T") textView.deleteBackward() textView.insertText("Three") let expected = "<h1>Header</h1><p>One Two</p><p>Three</p>" XCTAssertEqual(textView.getHTML(prettify: false), expected) } /// This test verifies that H1 Style doesn't turn rogue (Scenario #2), and come back after editing a line /// of text that never had H1 style, to begin with!. /// /// Ref. Issue #747: Zombie H1 Style /// func testHeaderStyleDoesNotComeBackFromNonExistanceWheneverDeleteBackwardResultsInEmptyParagraphBeforeHeaderStyle() { let textView = TextViewStub(withHTML: "") textView.toggleHeader(.h1, range: textView.selectedRange) textView.insertText("Header") textView.insertText("\n") textView.insertText("1") textView.deleteBackward() textView.insertText("1") let expected = "<h1>Header</h1><p>1</p>" XCTAssertEqual(textView.getHTML(prettify: false), expected) } /// This test verifies that attributes on media attachment are being removed properly. /// of text that never had H1 style, to begin with!. /// func testAttributesOnMediaAttachmentsAreRemoved() { let textView = TextViewStub(withHTML: "<img src=\"http://placeholder\" data-wp_upload_id=\"ABCDE\" >") guard let attachment = textView.storage.mediaAttachments.first else { XCTFail("There must be an attachment") return } guard let attributedValue = attachment.extraAttributes["data-wp_upload_id"] else { XCTFail("There must be an attribute with the name data-wp_upload_i") return } XCTAssertEqual(attributedValue, .string("ABCDE")) // Remove attribute attachment.extraAttributes["data-wp_upload_id"] = nil let html = textView.getHTML() XCTAssertEqual(html, "<p><img src=\"http://placeholder\"></p>" ) } /// This test makes sure that if an `<hr>` was in the original HTML, it will still get output after our processing. func testHRPeristsAfterAztec() { let textView = TextViewStub(withHTML: "<h1>Header</h1><p>test<hr></p>") let html = textView.getHTML(prettify: false) XCTAssertEqual(html, "<h1>Header</h1><p>test</p><p><hr></p>") } /// This test makes sure that if an auto replacement is made with smaller text, for example an emoji, things work correctly func testAutoCompletionReplacementHackWhenUsingEmoji() { let textView = TextViewStub(withHTML: "Love") let uiTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.endOfDocument)! textView.replace(uiTextRange, withText: "😘") let html = textView.getHTML() XCTAssertEqual(html, "<p>😘</p>") } func testMultipleFigureCaptionAreProperlyParsed() { let originalHTML = """ <figure><img src=\"a.png\" class=\"alignnone\"><figcaption>caption a</figcaption></figure><figure><img src=\"b.png\" class=\"alignnone\"><figcaption>caption b</figcaption></figure> """ let textView = TextViewStub(withHTML: originalHTML) XCTAssertEqual(textView.getHTML(prettify: false), originalHTML) } func testPasteOfURLsWithoutSelectedRange() { let textView = TextViewStub(withHTML: "") let pasteboard = UIPasteboard.general let url = URL(string: "http://wordpress.com")! pasteboard.setValue(url, forPasteboardType: String(kUTTypeURL)) textView.paste(nil) let html = "<p><a href=\"http://wordpress.com\">http://wordpress.com</a></p>" XCTAssertEqual(textView.getHTML(prettify: false), html) } func testPasteOfURLsWithSelectedRange() { let textView = TextViewStub(withHTML: "WordPress") let pasteboard = UIPasteboard.general let url = URL(string: "http://wordpress.com")! pasteboard.setValue(url, forPasteboardType: String(kUTTypeURL)) textView.selectedRange = NSRange(location: 0, length: 9) textView.paste(nil) let html = "<p><a href=\"http://wordpress.com\">WordPress</a></p>" XCTAssertEqual(textView.getHTML(prettify: false), html) } // MARK: - Non-breaking spaces. func testNonBreakingSpacesAreProperlyEncoded() { let textView = TextViewStub(withHTML: "WordPress") let html = "<p>&nbsp;&nbsp;</p><p>&nbsp;<br>&nbsp;</p>" let expected = "<p>&nbsp;&nbsp;</p><p>&nbsp;<br>&nbsp;</p>" textView.setHTML(html) let output = textView.getHTML(prettify: false) XCTAssertEqual(output, expected) } /// This test makes sure that if an empty list is in the original HTML, it will still get output after our processing. func testEmptyListsPersistsAfterAztec() { let textView = TextViewStub(withHTML: "<ul><li></li></ul>") let html = textView.getHTML(prettify: false) XCTAssertEqual(html, "<ul><li></li></ul>") } func testNestedLists() { let textView = TextViewStub(withHTML: "WordPress") let html = "<ul><li>Hello</li><li>world<ul><li>Inner</li><li>Inner<ul><li>Inner2</li><li>Inner2</li></ul></li></ul></li></ul>" let expected = "<ul><li>Hello</li><li>world<ul><li>Inner</li><li>Inner<ul><li>Inner2</li><li>Inner2</li></ul></li></ul></li></ul>" textView.setHTML(html) let output = textView.getHTML(prettify: false) XCTAssertEqual(output, expected) } // MARK: - Copy/Paste tests func testCopyAndPasteToPlainText() { let sourceTextView = TextViewStub(withHTML: "This is text with attributes: <strong>bold</strong>") sourceTextView.selectedRange = NSRange(location: 0, length: sourceTextView.text.count) sourceTextView.copy(nil) XCTAssertEqual(UIPasteboard.general.string, "This is text with attributes: bold") } func testCopyHTML() { let sourceTextView = TextViewStub(withHTML: "<p>This is text with attributes: <strong>bold</strong> and <italic>italic</italic></p>") sourceTextView.selectedRange = NSRange(location: 0, length: sourceTextView.text.count) sourceTextView.copy(nil) XCTAssertEqual(UIPasteboard.general.html(), "<p>This is text with attributes: <strong>bold</strong> and <italic>italic</italic></p>") } func testCutHTML() { let sourceTextView = TextViewStub(withHTML: "<p>This is text with attributes: <strong>bold</strong> and <italic>italic</italic></p>") sourceTextView.selectedRange = NSRange(location: 0, length: sourceTextView.text.count) sourceTextView.cut(nil) XCTAssertEqual(UIPasteboard.general.html(), "<p>This is text with attributes: <strong>bold</strong> and <italic>italic</italic></p>") } func testCopyPartialHTML() { let sourceTextView = TextViewStub(withHTML: "<p><strong>bold</strong> and <italic>italic</italic></p>") sourceTextView.selectedRange = NSRange(location: 0, length: 3) sourceTextView.copy(nil) XCTAssertEqual(UIPasteboard.general.html(), "<p><strong>bol</strong></p>") } /// Check if pasting attributed text without color, the color is set to default color func testPasteAttributedText() { let sourceAttributedText = NSAttributedString(string: "Hello world") var pasteItems = [String:Any]() pasteItems[kUTTypePlainText as String] = try! sourceAttributedText.data(from: sourceAttributedText.rangeOfEntireString, documentAttributes: [.documentType: DocumentType.plain]) UIPasteboard.general.setItems([pasteItems], options: [:]) let textView = TextViewStub(withHTML: "") textView.textColor = UIColor.red textView.paste(nil) let attributedString = textView.attributedText! let attributes = attributedString.attributes(at: 0, effectiveRange: nil) if let colorSet = attributes[.foregroundColor] as? UIColor { XCTAssertEqual(colorSet, UIColor.red) } XCTAssertEqual(textView.text, "Hello world") } /// Check that deleting all text resets the typying attributes to the default attributes func testDeleteAllTextSetTypyingAttributesToDefault() { let textView = TextViewStub(withHTML: "<p style=\"color:0xFF0000\">Hello world</p>") textView.defaultTextColor = UIColor.green textView.selectedRange = textView.attributedText!.rangeOfEntireString textView.deleteBackward() let attributes = textView.typingAttributes XCTAssertEqual(attributes[.foregroundColor] as! UIColor,UIColor.green) } func testLinksWithMultipleCharactersNonLatinDontBreak() { let textView = TextViewStub(withHTML: "<p><a href=\"www.worpdress.com\">WordPress 워드 프레스</a></p>") let html = textView.getHTML() XCTAssertEqual(html, "<p><a href=\"www.worpdress.com\">WordPress 워드 프레스</a></p>") textView.setHTML("<p><a href=\"www.worpdress.com\">WordPress</a><a href=\"www.jetpack.com\">워드 프레스</a></p>") let htmlTwoLinks = textView.getHTML() XCTAssertEqual(htmlTwoLinks, "<p><a href=\"www.worpdress.com\">WordPress</a><a href=\"www.jetpack.com\">워드 프레스</a></p>") } }
gpl-2.0
perpetio/JSQMessagesViewController
SwiftExample/SwiftExampleTests/ChatViewControllerTests.swift
3
10167
// // ViewControllertTests.swift // SwiftExample // // Created by Gianni Carlo on 5/30/16. // Copyright © 2016 MacMeDan. All rights reserved. // import UIKit import XCTest import JSQMessagesViewController @testable import SwiftExample class ChatViewControllerTests: XCTestCase { let changeSetting = NSUserDefaults.standardUserDefaults().setBool let chatViewController = ChatViewController() override func setUp() { super.setUp() let chatViewController = ChatViewController() chatViewController.messages = makeNormalConversation() // This ensures that ViewDidLoad() has been called let _ = chatViewController.view } override func tearDown() { super.tearDown() changeSetting(false, forKey: Setting.removeAvatar.rawValue) changeSetting(false, forKey: Setting.removeSenderDisplayName.rawValue) changeSetting(false, forKey: Setting.removeBubbleTails.rawValue) } func testSendButtonAction() { let _ = chatViewController.view let button = self.chatViewController.inputToolbar.sendButtonOnRight ? self.chatViewController.inputToolbar.contentView!.rightBarButtonItem! : self.chatViewController.inputToolbar.contentView!.leftBarButtonItem! let text = "Testing text" let senderId = self.chatViewController.senderId() let senderDisplayName = self.chatViewController.senderDisplayName() let date = NSDate() let originalCount = self.chatViewController.messages.count self.chatViewController.didPressSendButton(button, withMessageText: text, senderId: senderId, senderDisplayName: senderDisplayName, date: date) let newCount = self.chatViewController.messages.count XCTAssert(newCount == (originalCount + 1)) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage.senderId == senderId) XCTAssert(newMessage.senderDisplayName == senderDisplayName) XCTAssert(newMessage.date == date) XCTAssert(newMessage.text == text) } func testSendImage() { let senderId = self.chatViewController.senderId() let senderDisplayName = self.chatViewController.senderDisplayName() let photoItem = JSQPhotoMediaItem(image: UIImage(named: "goldengate")) self.chatViewController.addMedia(photoItem) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage.senderId == senderId) XCTAssert(newMessage.senderDisplayName == senderDisplayName) XCTAssert(newMessage.media is JSQPhotoMediaItem) } func testSendLocation() { let senderId = self.chatViewController.senderId() let senderDisplayName = self.chatViewController.senderDisplayName() let locationItem = self.chatViewController.buildLocationItem() self.chatViewController.addMedia(locationItem) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage.senderId == senderId) XCTAssert(newMessage.senderDisplayName == senderDisplayName) XCTAssert(newMessage.media is JSQLocationMediaItem) } func testSendVideo() { let senderId = self.chatViewController.senderId() let senderDisplayName = self.chatViewController.senderDisplayName() let videoItem = self.chatViewController.buildVideoItem() self.chatViewController.addMedia(videoItem) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage.senderId == senderId) XCTAssert(newMessage.senderDisplayName == senderDisplayName) XCTAssert(newMessage.media is JSQVideoMediaItem) } func testSendAudio() { let senderId = self.chatViewController.senderId() let senderDisplayName = self.chatViewController.senderDisplayName() let audioItem = self.chatViewController.buildAudioItem() self.chatViewController.addMedia(audioItem) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage.senderId == senderId) XCTAssert(newMessage.senderDisplayName == senderDisplayName) XCTAssert(newMessage.media is JSQAudioMediaItem) } /** * Test when the messages array is empty, it should add a new incoming text message * Test when the messages array last message is a text message, it should add a new incoming text message */ func testSimulatedIncomingTextMessage() { self.chatViewController.messages = [] let _ = chatViewController.view self.chatViewController.collectionView!.reloadData() // trigger action let rightBarButton = self.chatViewController.navigationItem.rightBarButtonItem! rightBarButton.target!.performSelector(rightBarButton.action, withObject: rightBarButton) let lastMessage = self.chatViewController.messages.last! XCTAssert(!lastMessage.isMediaMessage) XCTAssert(lastMessage.senderId != self.chatViewController.senderId()) XCTAssert(lastMessage.senderDisplayName != self.chatViewController.senderDisplayName()) // triger action rightBarButton.target!.performSelector(rightBarButton.action, withObject: rightBarButton) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage != lastMessage) XCTAssert(!newMessage.isMediaMessage) XCTAssert(newMessage.senderId != self.chatViewController.senderId()) XCTAssert(newMessage.senderDisplayName != self.chatViewController.senderDisplayName()) } /** * Simulate that last message is an image and test message received functionality */ func testSimulatedIncomingImage() { // add image let photoItem = JSQPhotoMediaItem(image: UIImage(named: "goldengate")) self.chatViewController.addMedia(photoItem) let _ = chatViewController.view let lastMessage = self.chatViewController.messages.last! // trigger action let rightBarButton = self.chatViewController.navigationItem.rightBarButtonItem! rightBarButton.target!.performSelector(rightBarButton.action, withObject: rightBarButton) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage != lastMessage) XCTAssert(newMessage.media is JSQPhotoMediaItem) XCTAssert(newMessage.senderId != self.chatViewController.senderId()) XCTAssert(newMessage.senderDisplayName != self.chatViewController.senderDisplayName()) } /** * Simulate that last message is a location and test message received functionality */ func testSimulatedIncomingLocation() { // add location let locationItem = self.chatViewController.buildLocationItem() self.chatViewController.addMedia(locationItem) let _ = chatViewController.view let lastMessage = self.chatViewController.messages.last! // trigger action let rightBarButton = self.chatViewController.navigationItem.rightBarButtonItem! rightBarButton.target!.performSelector(rightBarButton.action, withObject: rightBarButton) let newMessage = self.chatViewController.messages.last! XCTAssert(newMessage != lastMessage) XCTAssert(newMessage.media is JSQLocationMediaItem) XCTAssert(newMessage.senderId != self.chatViewController.senderId()) XCTAssert(newMessage.senderDisplayName != self.chatViewController.senderDisplayName()) } func testRemoveAvatarSetting() { changeSetting(true, forKey: Setting.removeAvatar.rawValue) let _ = chatViewController.view XCTAssertEqual(chatViewController.collectionView?.collectionViewLayout.incomingAvatarViewSize, .zero, "Incoming Avatar should be hidden") XCTAssertEqual(chatViewController.collectionView?.collectionViewLayout.outgoingAvatarViewSize, .zero, "Outgoing Avatar should be hidden") } func testSenderDisplayNameDefaultSetting() { changeSetting(false, forKey: Setting.removeSenderDisplayName.rawValue) let _ = chatViewController.view let button = self.chatViewController.inputToolbar.sendButtonOnRight ? self.chatViewController.inputToolbar.contentView!.rightBarButtonItem! : self.chatViewController.inputToolbar.contentView!.leftBarButtonItem! self.chatViewController.didPressSendButton(button, withMessageText: "Testing Text", senderId: chatViewController.senderId(), senderDisplayName: chatViewController.senderDisplayName(), date: NSDate()) let senderDisplayName = chatViewController.collectionView(self.chatViewController.collectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath: NSIndexPath(forItem: self.chatViewController.messages.count - 1, inSection: 0)) XCTAssertNotNil(senderDisplayName, "Sender Display should not be nil") } func testRemoveSenderDisplayNameSetting() { changeSetting(true, forKey: Setting.removeSenderDisplayName.rawValue) let _ = chatViewController.view let button = self.chatViewController.inputToolbar.sendButtonOnRight ? self.chatViewController.inputToolbar.contentView!.rightBarButtonItem! : self.chatViewController.inputToolbar.contentView!.leftBarButtonItem! self.chatViewController.didPressSendButton(button, withMessageText: "Testing Text", senderId: chatViewController.senderId(), senderDisplayName: chatViewController.senderDisplayName(), date: NSDate()) XCTAssertNil(chatViewController.collectionView(self.chatViewController.collectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath: NSIndexPath(forItem: self.chatViewController.messages.count - 1, inSection: 0)), "Sender Display should be nil") } }
mit
dinhcong/ALCameraViewController
ALCameraViewController/ViewController/ConfirmViewController.swift
1
8397
// // ALConfirmViewController.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/30. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import Photos internal class ConfirmViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var scrollView: UIScrollView! let imageView = UIImageView() @IBOutlet weak var cropOverlay: CropOverlay! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var confirmButton: UIButton! @IBOutlet weak var centeringView: UIView! @IBOutlet weak var spinner: UIActivityIndicatorView! var allowsCropping: Bool = false var verticalPadding: CGFloat = 30 var horizontalPadding: CGFloat = 30 var onComplete: ALCameraViewCompletion? var asset: PHAsset! internal init(asset: PHAsset, allowsCropping: Bool) { self.allowsCropping = allowsCropping self.asset = asset super.init(nibName: "ConfirmViewController", bundle: CameraGlobals.shared.bundle) commonInit() } internal required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func commonInit() { if UIScreen.mainScreen().bounds.width <= 320 { horizontalPadding = 15 } } internal override func prefersStatusBarHidden() -> Bool { return true } internal override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return UIStatusBarAnimation.Slide } internal override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() scrollView.addSubview(imageView) scrollView.delegate = self scrollView.maximumZoomScale = 1 cropOverlay.hidden = true guard let asset = asset else { return } spinner.startAnimating() SingleImageFetcher() .setAsset(asset) .setTargetSize(largestPhotoSize()) .onSuccess { image in self.configureWithImage(image) self.spinner.stopAnimating() } .onFailure { error in self.spinner.stopAnimating() } .fetch() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let scale = calculateMinimumScale(view.frame.size) let frame = allowsCropping ? cropOverlay.frame : view.bounds scrollView.contentInset = calculateScrollViewInsets(frame) scrollView.minimumZoomScale = scale scrollView.zoomScale = scale centerScrollViewContents() centerImageViewOnRotate() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) let scale = calculateMinimumScale(size) var frame = view.bounds if allowsCropping { frame = cropOverlay.frame let centeringFrame = centeringView.frame var origin: CGPoint if size.width > size.height { // landscape let offset = (size.width - centeringFrame.height) let expectedX = (centeringFrame.height/2 - frame.height/2) + offset origin = CGPoint(x: expectedX, y: frame.origin.x) } else { let expectedY = (centeringFrame.width/2 - frame.width/2) origin = CGPoint(x: frame.origin.y, y: expectedY) } frame.origin = origin } else { frame.size = size } coordinator.animateAlongsideTransition({ context in self.scrollView.contentInset = self.calculateScrollViewInsets(frame) self.scrollView.minimumZoomScale = scale self.scrollView.zoomScale = scale self.centerScrollViewContents() self.centerImageViewOnRotate() }, completion: nil) } private func configureWithImage(image: UIImage) { if allowsCropping { cropOverlay.hidden = false } else { cropOverlay.hidden = true } buttonActions() imageView.image = image imageView.sizeToFit() view.setNeedsLayout() } private func calculateMinimumScale(size: CGSize) -> CGFloat { var _size = size if allowsCropping { _size = cropOverlay.frame.size } guard let image = imageView.image else { return 1 } let scaleWidth = _size.width / image.size.width let scaleHeight = _size.height / image.size.height var scale: CGFloat if allowsCropping { scale = max(scaleWidth, scaleHeight) } else { scale = min(scaleWidth, scaleHeight) } return scale } private func calculateScrollViewInsets(frame: CGRect) -> UIEdgeInsets { let bottom = view.frame.height - (frame.origin.y + frame.height) let right = view.frame.width - (frame.origin.x + frame.width) let insets = UIEdgeInsets(top: frame.origin.y, left: frame.origin.x, bottom: bottom, right: right) return insets } private func centerImageViewOnRotate() { if allowsCropping { let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size let scrollInsets = scrollView.contentInset let imageSize = imageView.frame.size var contentOffset = CGPoint(x: -scrollInsets.left, y: -scrollInsets.top) contentOffset.x -= (size.width - imageSize.width) / 2 contentOffset.y -= (size.height - imageSize.height) / 2 scrollView.contentOffset = contentOffset } } private func centerScrollViewContents() { let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size let imageSize = imageView.frame.size var imageOrigin = CGPoint.zero if imageSize.width < size.width { imageOrigin.x = (size.width - imageSize.width) / 2 } if imageSize.height < size.height { imageOrigin.y = (size.height - imageSize.height) / 2 } imageView.frame.origin = imageOrigin } private func buttonActions() { confirmButton.addTarget(self, action: "confirmPhoto", forControlEvents: UIControlEvents.TouchUpInside) cancelButton.addTarget(self, action: "cancel", forControlEvents: UIControlEvents.TouchUpInside) } internal func cancel() { onComplete?(nil) } internal func confirmPhoto() { imageView.hidden = true spinner.startAnimating() let fetcher = SingleImageFetcher() .onSuccess { image in self.onComplete?(image) self.spinner.stopAnimating() } .onFailure { error in self.spinner.stopAnimating() } .setAsset(asset) if allowsCropping { var cropRect = cropOverlay.frame cropRect.origin.x += scrollView.contentOffset.x cropRect.origin.y += scrollView.contentOffset.y let normalizedX = cropRect.origin.x / imageView.frame.width let normalizedY = cropRect.origin.y / imageView.frame.height let normalizedWidth = cropRect.width / imageView.frame.width let normalizedHeight = cropRect.height / imageView.frame.height let rect = normalizedRect(CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight), orientation: imageView.image!.imageOrientation) fetcher.setCropRect(rect) } fetcher.fetch() } internal func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } internal func scrollViewDidZoom(scrollView: UIScrollView) { centerScrollViewContents() } }
mit
CloudThunderStorm/Gogether
iOS application/GogetherUITests/GogetherUITests.swift
1
1152
// // GogetherUITests.swift // GogetherUITests // // import XCTest class GogetherUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
apache-2.0
omise/omise-ios
OmiseSDK/FPXBankChooserViewController.swift
1
4557
import UIKit import os @objc(OMSFPXBankChooserViewController) class FPXBankChooserViewController: AdaptableDynamicTableViewController<Capability.Backend.Bank>, PaymentSourceChooser, PaymentChooserUI { var email: String? var flowSession: PaymentCreatorFlowSession? private let defaultImage: String = "FPX/unknown" private let message = NSLocalizedString( "fpx.bank-chooser.no-banks-available.text", bundle: .module, value: "Cannot retrieve list of banks.\nPlease try again later.", comment: "A descriptive text telling the user when there's no banks available" ) override var showingValues: [Capability.Backend.Bank] { didSet { os_log("FPX Bank Chooser: Showing options - %{private}@", log: uiLogObject, type: .info, showingValues.map { $0.name }.joined(separator: ", ")) } } @IBInspectable var preferredPrimaryColor: UIColor? { didSet { applyPrimaryColor() } } @IBInspectable var preferredSecondaryColor: UIColor? { didSet { applySecondaryColor() } } override func viewDidLoad() { super.viewDidLoad() applyPrimaryColor() applySecondaryColor() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) if showingValues.isEmpty { displayEmptyMessage() } else { restore() } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if let cell = cell as? PaymentOptionTableViewCell { cell.separatorView.backgroundColor = currentSecondaryColor } let bank = showingValues[indexPath.row] cell.accessoryView?.tintColor = currentSecondaryColor cell.textLabel?.text = bank.name cell.imageView?.image = bankImage(bank: bank.code) cell.textLabel?.textColor = currentPrimaryColor if !bank.isActive { disableCell(cell: cell) } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) else { return } let selectedBank = element(forUIIndexPath: indexPath) let paymentInformation = PaymentInformation.FPX(bank: selectedBank.code, email: email) tableView.deselectRow(at: indexPath, animated: true) os_log("FPX Banking Chooser: %{private}@ was selected", log: uiLogObject, type: .info, selectedBank.name) let oldAccessoryView = cell.accessoryView let loadingIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray) loadingIndicator.color = currentSecondaryColor cell.accessoryView = loadingIndicator loadingIndicator.startAnimating() view.isUserInteractionEnabled = false flowSession?.requestCreateSource(.fpx(paymentInformation)) { _ in cell.accessoryView = oldAccessoryView self.view.isUserInteractionEnabled = true } } private func applyPrimaryColor() { guard isViewLoaded else { return } } private func applySecondaryColor() { } private func bankImage(bank: String) -> UIImage? { if let image = UIImage(named: "FPX/" + bank, in: .module, compatibleWith: nil) { return image } else { return UIImage(named: defaultImage, in: .module, compatibleWith: nil) } } private func disableCell(cell: UITableViewCell) { cell.selectionStyle = UITableViewCell.SelectionStyle.none cell.contentView.alpha = 0.5 cell.isUserInteractionEnabled = false } private func displayEmptyMessage() { let label = UILabel( frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height) ) label.text = message label.textColor = currentPrimaryColor label.numberOfLines = 0 label.textAlignment = .center label.sizeToFit() tableView.backgroundView = label tableView.separatorStyle = .none } private func restore() { tableView.backgroundView = nil tableView.separatorStyle = .singleLine } }
mit
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/ConversationMessageActionController.swift
1
7076
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireDataModel import WireCommonComponents final class ConversationMessageActionController { enum Context: Int { case content, collection } let message: ZMConversationMessage let context: Context weak var responder: MessageActionResponder? weak var view: UIView! init(responder: MessageActionResponder?, message: ZMConversationMessage, context: Context, view: UIView) { self.responder = responder self.message = message self.context = context self.view = view } // MARK: - List of Actions private var allPerformableMessageAction: [MessageAction] { return MessageAction.allCases .filter(canPerformAction) } func allMessageMenuElements() -> [UIAction] { weak var responder = self.responder weak var message = self.message unowned let targetView: UIView = self.view return allPerformableMessageAction.compactMap { messageAction in guard let title = messageAction.title else { return nil } let handler: UIActionHandler = { _ in responder?.perform(action: messageAction, for: message, view: targetView) } return UIAction(title: title, image: messageAction.systemIcon(), handler: handler) } } // MARK: - UI menu static var allMessageActions: [UIMenuItem] { return MessageAction.allCases.compactMap { guard let selector = $0.selector, let title = $0.title else { return nil } return UIMenuItem(title: title, action: selector) } } func canPerformAction(action: MessageAction) -> Bool { switch action { case .copy: return message.canBeCopied case .digitallySign: return message.canBeDigitallySigned case .reply: return message.canBeQuoted case .openDetails: return message.areMessageDetailsAvailable case .edit: return message.canBeEdited case .delete: return message.canBeDeleted case .save: return message.canBeSaved case .cancel: return message.canCancelDownload case .download: return message.canBeDownloaded case .forward: return message.canBeForwarded case .like: return message.canBeLiked && !message.liked case .unlike: return message.canBeLiked && message.liked case .resend: return message.canBeResent case .showInConversation: return context == .collection case .sketchDraw, .sketchEmoji: return message.isImage case .present, .openQuote, .resetSession: return false } } func canPerformAction(_ selector: Selector) -> Bool { guard let action = MessageAction.allCases.first(where: { $0.selector == selector }) else { return false } return canPerformAction(action: action) } func makeAccessibilityActions() -> [UIAccessibilityCustomAction] { return ConversationMessageActionController.allMessageActions .filter { self.canPerformAction($0.action) } .map { menuItem in UIAccessibilityCustomAction(name: menuItem.title, target: self, selector: menuItem.action) } } @available(iOS, introduced: 9.0, deprecated: 13.0, message: "UIViewControllerPreviewing is deprecated. Please use UIContextMenuInteraction.") var previewActionItems: [UIPreviewAction] { return allPerformableMessageAction.compactMap { messageAction in guard let title = messageAction.title else { return nil } return UIPreviewAction(title: title, style: .default) { [weak self] _, _ in self?.perform(action: messageAction) } } } // MARK: - Single Tap Action func performSingleTapAction() { guard let singleTapAction = singleTapAction else { return } perform(action: singleTapAction) } var singleTapAction: MessageAction? { if message.isImage, message.imageMessageData?.isDownloaded == true { return .present } else if message.isFile, !message.isAudio, let transferState = message.fileMessageData?.transferState { switch transferState { case .uploaded: return .present default: return nil } } return nil } // MARK: - Double Tap Action func performDoubleTapAction() { guard let doubleTapAction = doubleTapAction else { return } perform(action: doubleTapAction) } var doubleTapAction: MessageAction? { return message.canBeLiked ? .like : nil } // MARK: - Handler private func perform(action: MessageAction) { responder?.perform(action: action, for: message, view: view) } @objc func digitallySignMessage() { perform(action: .digitallySign) } @objc func copyMessage() { perform(action: .copy) } @objc func editMessage() { perform(action: .edit) } @objc func quoteMessage() { perform(action: .reply) } @objc func openMessageDetails() { perform(action: .openDetails) } @objc func cancelDownloadingMessage() { perform(action: .cancel) } @objc func downloadMessage() { perform(action: .download) } @objc func saveMessage() { perform(action: .save) } @objc func forwardMessage() { perform(action: .forward) } @objc func likeMessage() { perform(action: .like) } @objc func unlikeMessage() { perform(action: .like) } @objc func deleteMessage() { perform(action: .delete) } @objc func resendMessage() { perform(action: .resend) } @objc func revealMessage() { perform(action: .showInConversation) } }
gpl-3.0
sforteln/GridOverlay
GridOverlay/GridOverlay/ViewController.swift
1
515
// // ViewController.swift // GridOverlay // // Created by Simon Fortelny on 5/13/15. // Copyright (c) 2015 Simon Fortelny. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
michaelvu812/MVFetchedResultsController
MVFetchedResultsController/ViewController.swift
1
1140
// // ViewController.swift // MVFetchedResultsController // // Created by Michael on 1/7/14. // Copyright (c) 2014 Michael Vu. All rights reserved. // import UIKit class ViewController: MVFetchedResultsController { var canInsert = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.sortDescriptor = NSSortDescriptor(key: "name", ascending: true) self.entityName = "Entity" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? { let entity = self.fetchedResultsController.objectAtIndexPath(indexPath) as Entity super.tableView(tableView, cellForRowAtIndexPath: indexPath) let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil) let text = entity.name cell.textLabel.text = text return cell } }
mit
nab0y4enko/PrettyKeyboardHelper
PrettyKeyboardHelper/UIScrollView+PrettyKeyboardHelper.swift
1
1460
// // UIScrollView+PrettyKeyboardHelper.swift // PrettyKeyboardHelper // // Created by Oleksii Naboichenko on 12/7/16. // Copyright © 2016 Oleksii Naboichenko. All rights reserved. // import UIKit public extension UIScrollView { final func updateBottomInset(with keyboardInfo: PrettyKeyboardInfo, defaultBottomInset: CGFloat = 0.0, safeAreaInsets: UIEdgeInsets? = nil, completion: ((Bool) -> Swift.Void)? = nil) { var bottomContentInset = keyboardInfo.estimatedKeyboardHeight + defaultBottomInset if let bottomSafeAreaInset = safeAreaInsets?.bottom, keyboardInfo.keyboardState == .willBeShown { bottomContentInset -= bottomSafeAreaInset } UIView.animate( withDuration: keyboardInfo.duration, delay: 0, options: keyboardInfo.animationOptions, animations: { [weak self] in guard let self = self else { return } var contentInset = self.contentInset contentInset.bottom = bottomContentInset self.contentInset = contentInset var verticalScrollIndicatorInsets = self.verticalScrollIndicatorInsets verticalScrollIndicatorInsets.bottom = bottomContentInset self.verticalScrollIndicatorInsets = verticalScrollIndicatorInsets }, completion: completion ) } }
mit
mkrd/Swift-Big-Integer
Package.swift
1
488
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "BigNumber", products: [ .library( name: "BigNumber", targets: ["BigNumber"]), ], dependencies: [], targets: [ .target( name: "BigNumber", dependencies: [], path: "Sources"), .testTarget( name: "BigNumberTests", dependencies: ["BigNumber"], path: "Tests"), ] )
mit
greycats/Greycats.swift
Greycats/Camera.swift
1
4321
import AVFoundation import GreycatsCore import GreycatsGraphics import UIKit open class Camera { var session: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! var stillCameraOutput: AVCaptureStillImageOutput! public init() { session = AVCaptureSession() stillCameraOutput = AVCaptureStillImageOutput() session.sessionPreset = AVCaptureSession.Preset.photo previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill if let input = backCameraInput() { if session.canAddInput(input) { session.addInput(input) } } if session.canAddOutput(stillCameraOutput) { session.addOutput(stillCameraOutput) } } fileprivate func backCameraDevice() -> AVCaptureDevice? { let availableCameraDevices = AVCaptureDevice.devices(for: AVMediaType.video) for device in availableCameraDevices { if device.position == .back { return device } } return nil } open func containerDidUpdate(_ container: UIView) { if previewLayer.superlayer == nil { container.layer.addSublayer(previewLayer) } UIView.setAnimationsEnabled(false) previewLayer.frame = container.bounds UIView.setAnimationsEnabled(true) } open func start() { foreground { self.checkPermission {[weak self] in self?.session.startRunning() } } } open func capture(_ next: @escaping (UIImage?) -> Void) { if let connection = stillCameraOutput.connection(with: AVMediaType.video) { if connection.isVideoOrientationSupported { connection.videoOrientation = .portrait } if !connection.isEnabled || !connection.isActive { next(nil) return } stillCameraOutput.captureStillImageAsynchronously(from: connection) { [weak self] buffer, _ in self?.stop() if let buffer = buffer { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) let image = UIImage(data: imageData!)?.fixedOrientation() foreground { next(image) } } else { next(nil) } } } else { next(nil) } } open func stop() { session.stopRunning() } open func toggleFlash() -> AVCaptureDevice.FlashMode? { if let device = backCameraDevice() { do { try device.lockForConfiguration() if device.flashMode == .off { device.flashMode = .on } else { device.flashMode = .off } device.unlockForConfiguration() } catch { } return device.flashMode } return nil } fileprivate func backCameraInput() -> AVCaptureDeviceInput? { if let device = backCameraDevice() { return try? AVCaptureDeviceInput(device: device) } return nil } fileprivate func checkPermission(_ next: @escaping () -> Void) { let authorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) switch authorizationStatus { case .notDetermined: // permission dialog not yet presented, request authorization AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in if granted { foreground { next() } } else { // user denied, nothing much to do } } case .authorized: next() case .denied, .restricted: // the user explicitly denied camera usage or is not allowed to access the camera devices return @unknown default: return } } }
mit
isnine/HutHelper-Open
HutHelper/SwiftApp/Third/FWPopupView/FWMenuView.swift
1
21181
// // FWMenuView.swift // FWPopupView // // Created by xfg on 2018/5/19. // Copyright © 2018年 xfg. All rights reserved. // 仿QQ、微信菜单 /** ************************************************ github地址:https://github.com/choiceyou/FWPopupView bug反馈、交流群:670698309 *************************************************** */ import Foundation import UIKit class FWMenuViewTableViewCell: UITableViewCell { var iconImgView: UIImageView! var titleLabel: UILabel! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = UIColor.clear self.iconImgView = UIImageView() self.iconImgView.contentMode = .center self.iconImgView.backgroundColor = UIColor.clear self.contentView.addSubview(self.iconImgView) self.titleLabel = UILabel() self.titleLabel.backgroundColor = UIColor.clear self.contentView.addSubview(self.titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupContent(title: String?, image: UIImage?, property: FWMenuViewProperty) { self.selectionStyle = property.selectionStyle if image != nil { self.iconImgView.isHidden = false self.iconImgView.image = image self.iconImgView.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(property.letfRigthMargin) make.centerY.equalToSuperview() make.size.equalTo(image!.size) } } else { self.iconImgView.isHidden = true } if title != nil { self.titleLabel.textAlignment = property.textAlignment let attributedString = NSAttributedString(string: title!, attributes: property.titleTextAttributes) self.titleLabel.attributedText = attributedString self.titleLabel.snp.makeConstraints { (make) in if image != nil { make.left.equalTo(self.iconImgView.snp.right).offset(property.commponentMargin) } else { make.left.equalToSuperview().offset(property.letfRigthMargin) } make.right.equalToSuperview().offset(-property.letfRigthMargin) make.top.equalToSuperview().offset(property.topBottomMargin) make.bottom.equalToSuperview().offset(-property.topBottomMargin) } } } } open class FWMenuView: FWPopupView, UITableViewDelegate, UITableViewDataSource { /// 外部传入的标题数组 @objc public var itemTitleArray: [String]? { didSet { self.setNeedsLayout() self.setNeedsDisplay() } } /// 外部传入的图片数组 @objc public var itemImageArray: [UIImage]? { didSet { self.setNeedsLayout() self.setNeedsDisplay() } } /// 当前选中下标 private var selectedIndex: Int = 0 /// 最大的那一项的size private var maxItemSize: CGSize = CGSize.zero /// 保存点击回调 private var popupItemClickedBlock: FWPopupItemClickedBlock? /// 有箭头时:当前layer的mask private var maskLayer: CAShapeLayer? /// 有箭头时:当前layer的border private var borderLayer: CAShapeLayer? private lazy var tableView: UITableView = { let tableView = UITableView() tableView.register(FWMenuViewTableViewCell.self, forCellReuseIdentifier: "cellId") tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = UIColor.clear self.addSubview(tableView) return tableView }() /// 类初始化方法1 /// /// - Parameters: /// - itemTitles: 标题 /// - itemBlock: 点击回调 /// - Returns: self @objc open class func menu(itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil) -> FWMenuView { return self.menu(itemTitles: itemTitles, itemImageNames: nil, itemBlock: itemBlock, property: nil) } /// 类初始化方法2 /// /// - Parameters: /// - itemTitles: 标题 /// - itemBlock: 点击回调 /// - property: 可设置参数 /// - Returns: self @objc open class func menu(itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil, property: FWMenuViewProperty?) -> FWMenuView { return self.menu(itemTitles: itemTitles, itemImageNames: nil, itemBlock: itemBlock, property: property) } /// 类初始化方法3 /// /// - Parameters: /// - itemTitles: 标题 /// - itemImageNames: 图片 /// - itemBlock: 点击回调 /// - property: 可设置参数 /// - Returns: self @objc open class func menu(itemTitles: [String]?, itemImageNames: [UIImage]?, itemBlock: FWPopupItemClickedBlock? = nil, property: FWMenuViewProperty?) -> FWMenuView { let popupMenu = FWMenuView() popupMenu.setupUI(itemTitles: itemTitles, itemImageNames: itemImageNames, itemBlock: itemBlock, property: property) return popupMenu } public override init(frame: CGRect) { super.init(frame: frame) self.vProperty = FWMenuViewProperty() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 刷新当前视图及数据 @objc open func refreshData() { self.setupFrame(property: self.vProperty as! FWMenuViewProperty) self.tableView.reloadData() } } extension FWMenuView { private func setupUI(itemTitles: [String]?, itemImageNames: [UIImage]?, itemBlock: FWPopupItemClickedBlock? = nil, property: FWMenuViewProperty?) { if itemTitles == nil && itemImageNames == nil { return } if property != nil { self.vProperty = property! } else { self.vProperty = FWMenuViewProperty() } self.clipsToBounds = true self.itemTitleArray = itemTitles self.itemImageArray = itemImageNames self.popupItemClickedBlock = itemBlock let property = self.vProperty as! FWMenuViewProperty self.tableView.separatorInset = property.separatorInset self.tableView.layoutMargins = property.separatorInset self.tableView.separatorColor = property.separatorColor self.tableView.bounces = property.bounces self.maxItemSize = self.measureMaxSize() self.setupFrame(property: property) var tableViewY: CGFloat = 0 if property.popupArrowStyle == .none { self.layer.cornerRadius = self.vProperty.cornerRadius self.layer.borderColor = self.vProperty.splitColor.cgColor self.layer.borderWidth = self.vProperty.splitWidth } else { tableViewY = property.popupArrowSize.height } // 箭头方向 var isUpArrow = true switch property.popupCustomAlignment { case .bottomLeft, .bottomRight, .bottomCenter: isUpArrow = false break default: isUpArrow = true break } // 用来隐藏多余的线条,不想自定义线条 let footerViewHeight: CGFloat = 1 let footerView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: footerViewHeight)) footerView.backgroundColor = UIColor.clear self.tableView.tableFooterView = footerView self.tableView.snp.remakeConstraints { (make) in make.top.equalToSuperview().offset(isUpArrow ? tableViewY : 0) make.left.right.equalToSuperview() make.bottom.equalToSuperview().offset(-((isUpArrow ? 0 : tableViewY ) - footerViewHeight)) } } private func setupFrame(property: FWMenuViewProperty) { var tableViewY: CGFloat = 0 switch property.popupArrowStyle { case .none: tableViewY = 0 break case .round, .triangle: tableViewY = property.popupArrowSize.height break } var tmpMaxHeight: CGFloat = 0.0 if self.superview != nil { tmpMaxHeight = self.vProperty.popupViewMaxHeightRate * self.superview!.frame.size.height } else { tmpMaxHeight = self.vProperty.popupViewMaxHeightRate * UIScreen.main.bounds.height } var selfSize: CGSize = CGSize.zero if property.popupViewSize.width > 0 && property.popupViewSize.height > 0 { selfSize = property.popupViewSize } else if self.vProperty.popupViewMaxHeightRate > 0 && self.maxItemSize.height * CGFloat(self.itemsCount()) > tmpMaxHeight { selfSize = CGSize(width: self.maxItemSize.width, height: tmpMaxHeight) } else { selfSize = CGSize(width: self.maxItemSize.width, height: self.maxItemSize.height * CGFloat(self.itemsCount())) } selfSize.height += tableViewY self.frame = CGRect(x: 0, y: tableViewY, width: selfSize.width, height: selfSize.height) self.finalSize = selfSize self.setupMaskLayer(property: property) } private func setupMaskLayer(property: FWMenuViewProperty) { // 绘制箭头 if property.popupArrowStyle != .none { if self.maskLayer != nil { self.layer.mask = nil self.maskLayer?.removeFromSuperlayer() self.maskLayer = nil } if self.borderLayer != nil { self.borderLayer?.removeFromSuperlayer() self.borderLayer = nil } // 圆角值 let cornerRadius = property.cornerRadius /// 箭头的尺寸 let arrowSize = property.popupArrowSize if property.popupArrowVertexScaleX > 1 { property.popupArrowVertexScaleX = 1 } else if property.popupArrowVertexScaleX < 0 { property.popupArrowVertexScaleX = 0 } // 箭头方向 var isUpArrow = true switch property.popupCustomAlignment { case .bottomLeft, .bottomRight, .bottomCenter: isUpArrow = false break default: isUpArrow = true break } // 弹窗箭头顶点坐标 let arrowPoint = CGPoint(x: (self.frame.width - arrowSize.width - cornerRadius * 2) * property.popupArrowVertexScaleX + arrowSize.width/2 + cornerRadius, y: isUpArrow ? 0 : self.frame.height) // 顶部Y值 let maskTop = isUpArrow ? arrowSize.height : 0 // 底部Y值 let maskBottom = isUpArrow ? self.frame.height : self.frame.height - arrowSize.height // 开始画贝塞尔曲线 let maskPath = UIBezierPath() // 左上圆角 maskPath.move(to: CGPoint(x: 0, y: cornerRadius + maskTop)) maskPath.addArc(withCenter: CGPoint(x: cornerRadius, y: cornerRadius + maskTop), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 180), endAngle: self.degreesToRadians(angle: 270), clockwise: true) // 箭头向上时的箭头位置 if isUpArrow { maskPath.addLine(to: CGPoint(x: arrowPoint.x - arrowSize.width/2, y: arrowSize.height)) if property.popupArrowStyle == .triangle { // 菱角箭头 maskPath.addLine(to: arrowPoint) maskPath.addLine(to: CGPoint(x: arrowPoint.x + arrowSize.width/2, y: arrowSize.height)) } else { // 圆角箭头 maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x - property.popupArrowCornerRadius, y: property.popupArrowCornerRadius), controlPoint: CGPoint(x: arrowPoint.x - arrowSize.width/2 + property.popupArrowBottomCornerRadius, y: arrowSize.height)) maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x + property.popupArrowCornerRadius, y: property.popupArrowCornerRadius), controlPoint: arrowPoint) maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x + arrowSize.width/2, y: arrowSize.height), controlPoint: CGPoint(x: arrowPoint.x + arrowSize.width/2 - property.popupArrowBottomCornerRadius, y: arrowSize.height)) } } // 右上圆角 maskPath.addLine(to: CGPoint(x: self.frame.width - cornerRadius, y: maskTop)) maskPath.addArc(withCenter: CGPoint(x: self.frame.width - cornerRadius, y: maskTop + cornerRadius), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 270), endAngle: self.degreesToRadians(angle: 0), clockwise: true) // 右下圆角 maskPath.addLine(to: CGPoint(x: self.frame.width, y: maskBottom - cornerRadius)) maskPath.addArc(withCenter: CGPoint(x: self.frame.width - cornerRadius, y: maskBottom - cornerRadius), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 0), endAngle: self.degreesToRadians(angle: 90), clockwise: true) // 箭头向下时的箭头位置 if !isUpArrow { maskPath.addLine(to: CGPoint(x: arrowPoint.x + arrowSize.width/2, y: self.frame.height - arrowSize.height)) if property.popupArrowStyle == .triangle { // 菱角箭头 maskPath.addLine(to: arrowPoint) maskPath.addLine(to: CGPoint(x: arrowPoint.x - arrowSize.width/2, y: self.frame.height - arrowSize.height)) } else { // 圆角箭头 maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x + property.popupArrowCornerRadius, y: self.frame.height - property.popupArrowCornerRadius), controlPoint: CGPoint(x: arrowPoint.x + arrowSize.width/2 - property.popupArrowBottomCornerRadius, y: self.frame.height - arrowSize.height)) maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x - property.popupArrowCornerRadius, y: self.frame.height - property.popupArrowCornerRadius), controlPoint: arrowPoint) maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x - arrowSize.width/2, y: self.frame.height - arrowSize.height), controlPoint: CGPoint(x: arrowPoint.x - arrowSize.width/2 + property.popupArrowBottomCornerRadius, y: self.frame.height - arrowSize.height)) } } // 左下圆角 maskPath.addLine(to: CGPoint(x: cornerRadius, y: maskBottom)) maskPath.addArc(withCenter: CGPoint(x: cornerRadius, y: maskBottom - cornerRadius), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 90), endAngle: self.degreesToRadians(angle: 180), clockwise: true) maskPath.close() // 截取圆角和箭头 self.maskLayer = CAShapeLayer() self.maskLayer?.frame = self.bounds self.maskLayer?.path = maskPath.cgPath self.layer.mask = self.maskLayer // 边框 self.borderLayer = CAShapeLayer() self.borderLayer?.frame = self.bounds self.borderLayer?.path = maskPath.cgPath self.borderLayer?.lineWidth = 1 self.borderLayer?.fillColor = UIColor.clear.cgColor self.borderLayer?.strokeColor = property.splitColor.cgColor self.layer.addSublayer(self.borderLayer!) } } } extension FWMenuView { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.itemsCount() } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.maxItemSize.height } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! FWMenuViewTableViewCell cell.setupContent(title: (self.itemTitleArray != nil) ? self.itemTitleArray![indexPath.row] : nil, image: (self.itemImageArray != nil) ? self.itemImageArray![indexPath.row] : nil, property: self.vProperty as! FWMenuViewProperty) return cell } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.hide() if self.popupItemClickedBlock != nil { self.popupItemClickedBlock!(self, indexPath.row, (self.itemTitleArray != nil) ? self.itemTitleArray![indexPath.row] : nil) } } } extension FWMenuView { /// 计算控件的最大宽度、高度 /// /// - Returns: CGSize fileprivate func measureMaxSize() -> CGSize { if self.itemTitleArray == nil && self.itemImageArray == nil { return CGSize.zero } let property = self.vProperty as! FWMenuViewProperty var titleSize = CGSize.zero var imageSize = CGSize.zero var totalMaxSize = CGSize.zero let titleAttrs = property.titleTextAttributes if self.itemTitleArray != nil { var tmpSize = CGSize.zero var index = 0 for title: String in self.itemTitleArray! { titleSize = (title as NSString).size(withAttributes: titleAttrs) if self.itemImageArray != nil && self.itemImageArray!.count == self.itemTitleArray!.count { let image = self.itemImageArray![index] imageSize = image.size } tmpSize = CGSize(width: titleSize.width + imageSize.width, height: titleSize.height + imageSize.height) totalMaxSize.width = max(totalMaxSize.width, tmpSize.width) totalMaxSize.height = max(totalMaxSize.height, tmpSize.height) index += 1 } } else if self.itemTitleArray == nil && self.itemImageArray != nil { for image: UIImage in self.itemImageArray! { imageSize = image.size totalMaxSize.width = max(totalMaxSize.width, imageSize.width) totalMaxSize.height = max(totalMaxSize.height, imageSize.height) } } totalMaxSize.width += property.letfRigthMargin * 2 if self.itemTitleArray != nil && self.itemImageArray != nil { totalMaxSize.width += property.commponentMargin } totalMaxSize.height += property.topBottomMargin * 2 var width = min(ceil(totalMaxSize.width), property.popupViewMaxWidth) width = max(width, property.popupViewMinWidth) totalMaxSize.width = width if property.popupViewItemHeight > 0 { totalMaxSize.height = property.popupViewItemHeight } else { totalMaxSize.height = ceil(totalMaxSize.height) } return totalMaxSize } /// 计算总计行数 /// /// - Returns: 行数 fileprivate func itemsCount() -> Int { if self.itemTitleArray != nil { return self.itemTitleArray!.count } else if self.itemImageArray != nil { return self.itemImageArray!.count } else { return 0 } } /// 角度转换 /// /// - Parameter angle: 传入的角度值 /// - Returns: CGFloat fileprivate func degreesToRadians(angle: CGFloat) -> CGFloat { return angle * CGFloat(Double.pi) / 180 } } /// FWMenuView的相关属性,请注意其父类中还有很多公共属性 open class FWMenuViewProperty: FWPopupViewProperty { /// 弹窗大小,如果没有设置,将按照统一的计算方式 @objc public var popupViewSize = CGSize.zero /// 指定行高优先级 > 自动计算的优先级 @objc public var popupViewItemHeight: CGFloat = 0 /// 未选中时按钮字体属性 @objc public var titleTextAttributes: [NSAttributedString.Key: Any]! /// 文字位置 @objc public var textAlignment: NSTextAlignment = .left /// 内容位置 @objc public var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment = .left /// 选中风格 @objc public var selectionStyle: UITableViewCell.SelectionStyle = .none /// 分割线颜色 @objc public var separatorColor: UIColor = kPV_RGBA(r: 231, g: 231, b: 231, a: 1) /// 分割线偏移量 @objc public var separatorInset: UIEdgeInsets = UIEdgeInsets.zero /// 是否开启tableview回弹效果 @objc public var bounces: Bool = false /// 弹窗的最大宽度 @objc open var popupViewMaxWidth: CGFloat = UIScreen.main.bounds.width * 0.6 /// 弹窗的最小宽度 @objc open var popupViewMinWidth: CGFloat = 20 public override func reSetParams() { super.reSetParams() self.titleTextAttributes = [NSAttributedString.Key.foregroundColor: self.itemNormalColor, NSAttributedString.Key.backgroundColor: UIColor.clear, NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.buttonFontSize)] self.letfRigthMargin = 20 self.popupViewMaxHeightRate = 0.7 } }
lgpl-2.1
ejeklint/hello-server
Sources/App/Routes.swift
1
584
import Vapor extension Droplet { func setupRoutes() throws { get("hello") { req in var json = JSON() try json.set("hello", "world") return json } get("plaintext") { req in return "Hello, wöörld!" } // response to requests to /info domain // with a description of the request get("info") { req in return req.description } get("description") { req in return req.description } try resource("posts", PostController.self) } }
mit
therealbnut/swift
benchmark/single-source/Walsh.swift
5
2354
//===--- Walsh.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils import Darwin func IsPowerOfTwo(_ x: Int) -> Bool { return (x & (x - 1)) == 0 } // Fast Walsh Hadamard Transform func WalshTransform(_ data: inout [Double]) { assert(IsPowerOfTwo(data.count), "Not a power of two") var temp = [Double](repeating: 0, count: data.count) var ret = WalshImpl(&data, &temp, 0, data.count) for i in 0..<data.count { data[i] = ret[i] } } func Scale(_ data: inout [Double], _ scalar : Double) { for i in 0..<data.count { data[i] = data[i] * scalar } } func InverseWalshTransform(_ data: inout [Double]) { WalshTransform(&data) Scale(&data, Double(1)/Double(data.count)) } func WalshImpl(_ data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] { if (size == 1) { return data } let stride = size/2 for i in 0..<stride { temp[start + i] = data[start + i + stride] + data[start + i] temp[start + i + stride] = data[start + i] - data[start + i + stride] } _ = WalshImpl(&temp, &data, start, stride) return WalshImpl(&temp, &data, start + stride, stride) } func checkCorrectness() { var In : [Double] = [1,0,1,0,0,1,1,0] var Out : [Double] = [4,2,0,-2,0,2,0,2] var data : [Double] = In WalshTransform(&data) var mid = data InverseWalshTransform(&data) for i in 0..<In.count { // Check encode. CheckResults(abs(data[i] - In[i]) < 0.0001, "Incorrect results in Walsh.") // Check decode. CheckResults(abs(mid[i] - Out[i]) < 0.0001, "Incorrect results in Walsh.") } } @inline(never) public func run_Walsh(_ N: Int) { checkCorrectness() // Generate data. var data2 : [Double] = [] for i in 0..<1024 { data2.append(Double(sin(Float(i)))) } // Transform back and forth. for _ in 1...10*N { WalshTransform(&data2) InverseWalshTransform(&data2) } }
apache-2.0
ytakzk/Fusuma
Example/FusumaExample/ViewController.swift
1
4106
// // ViewController.swift // Fusuma // // Created by ytakzk on 01/31/2016. // Copyright (c) 2016 ytakzk. All rights reserved. // import UIKit class ViewController: UIViewController, FusumaDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var showButton: UIButton! @IBOutlet weak var fileUrlLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() showButton.layer.cornerRadius = 2.0 fileUrlLabel.text = "" } @IBAction func showButtonPressed(_ sender: AnyObject) { // Show Fusuma let fusuma = FusumaViewController() fusuma.delegate = self fusuma.cropHeightRatio = 1.0 fusuma.allowMultipleSelection = false fusuma.availableModes = [.library, .video, .camera] fusuma.photoSelectionLimit = 4 fusumaSavesImage = true present(fusuma, animated: true, completion: nil) } // MARK: FusumaDelegate Protocol func fusumaImageSelected(_ image: UIImage, source: FusumaMode) { switch source { case .camera: print("Image captured from Camera") case .library: print("Image selected from Camera Roll") default: print("Image selected") } imageView.image = image } func fusumaMultipleImageSelected(_ images: [UIImage], source: FusumaMode) { print("Number of selection images: \(images.count)") var count: Double = 0 for image in images { DispatchQueue.main.asyncAfter(deadline: .now() + (3.0 * count)) { self.imageView.image = image print("w: \(image.size.width) - h: \(image.size.height)") } count += 1 } } func fusumaImageSelected(_ image: UIImage, source: FusumaMode, metaData: ImageMetadata) { print("Image mediatype: \(metaData.mediaType)") print("Source image size: \(metaData.pixelWidth)x\(metaData.pixelHeight)") print("Creation date: \(String(describing: metaData.creationDate))") print("Modification date: \(String(describing: metaData.modificationDate))") print("Video duration: \(metaData.duration)") print("Is favourite: \(metaData.isFavourite)") print("Is hidden: \(metaData.isHidden)") print("Location: \(String(describing: metaData.location))") } func fusumaVideoCompleted(withFileURL fileURL: URL) { print("video completed and output to file: \(fileURL)") self.fileUrlLabel.text = "file output to: \(fileURL.absoluteString)" } func fusumaDismissedWithImage(_ image: UIImage, source: FusumaMode) { switch source { case .camera: print("Called just after dismissed FusumaViewController using Camera") case .library: print("Called just after dismissed FusumaViewController using Camera Roll") default: print("Called just after dismissed FusumaViewController") } } func fusumaCameraRollUnauthorized() { print("Camera roll unauthorized") let alert = UIAlertController(title: "Access Requested", message: "Saving image needs to access your photo album", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Settings", style: .default) { (action) -> Void in if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.openURL(url) } }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in }) guard let vc = UIApplication.shared.delegate?.window??.rootViewController, let presented = vc.presentedViewController else { return } presented.present(alert, animated: true, completion: nil) } func fusumaClosed() { print("Called when the FusumaViewController disappeared") } func fusumaWillClosed() { print("Called when the close button is pressed") } }
mit
jokechat/swift3-novel
swift_novels/Pods/SnapKit/Source/Constraint.swift
15
11168
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public class Constraint { internal let sourceLocation: (String, UInt) internal let label: String? private let from: ConstraintItem private let to: ConstraintItem private let relation: ConstraintRelation private let multiplier: ConstraintMultiplierTarget private var constant: ConstraintConstantTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } private var priority: ConstraintPriorityTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } private var layoutConstraints: [LayoutConstraint] // MARK: Initialization internal init(from: ConstraintItem, to: ConstraintItem, relation: ConstraintRelation, sourceLocation: (String, UInt), label: String?, multiplier: ConstraintMultiplierTarget, constant: ConstraintConstantTarget, priority: ConstraintPriorityTarget) { self.from = from self.to = to self.relation = relation self.sourceLocation = sourceLocation self.label = label self.multiplier = multiplier self.constant = constant self.priority = priority self.layoutConstraints = [] // get attributes let layoutFromAttributes = self.from.attributes.layoutAttributes let layoutToAttributes = self.to.attributes.layoutAttributes // get layout from let layoutFrom: ConstraintView = self.from.view! // get relation let layoutRelation = self.relation.layoutRelation for layoutFromAttribute in layoutFromAttributes { // get layout to attribute let layoutToAttribute: NSLayoutAttribute #if os(iOS) || os(tvOS) if layoutToAttributes.count > 0 { if self.from.attributes == .edges && self.to.attributes == .margins { switch layoutFromAttribute { case .left: layoutToAttribute = .leftMargin case .right: layoutToAttribute = .rightMargin case .top: layoutToAttribute = .topMargin case .bottom: layoutToAttribute = .bottomMargin default: fatalError() } } else if self.from.attributes == .margins && self.to.attributes == .edges { switch layoutFromAttribute { case .leftMargin: layoutToAttribute = .left case .rightMargin: layoutToAttribute = .right case .topMargin: layoutToAttribute = .top case .bottomMargin: layoutToAttribute = .bottom default: fatalError() } } else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else { layoutToAttribute = layoutToAttributes[0] } } else { layoutToAttribute = layoutFromAttribute } #else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else if layoutToAttributes.count > 0 { layoutToAttribute = layoutToAttributes[0] } else { layoutToAttribute = layoutFromAttribute } #endif // get layout constant let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) // get layout to var layoutTo: AnyObject? = self.to.target // use superview if possible if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { layoutTo = layoutFrom.superview } // create layout constraint let layoutConstraint = LayoutConstraint( item: layoutFrom, attribute: layoutFromAttribute, relatedBy: layoutRelation, toItem: layoutTo, attribute: layoutToAttribute, multiplier: self.multiplier.constraintMultiplierTargetValue, constant: layoutConstant ) // set label layoutConstraint.label = self.label // set priority layoutConstraint.priority = self.priority.constraintPriorityTargetValue // set constraint layoutConstraint.constraint = self // append self.layoutConstraints.append(layoutConstraint) } } // MARK: Public @available(*, deprecated:3.0, message:"Use activate().") public func install() { self.activate() } @available(*, deprecated:3.0, message:"Use deactivate().") public func uninstall() { self.deactivate() } public func activate() { self.activateIfNeeded() } public func deactivate() { self.deactivateIfNeeded() } @discardableResult public func update(offset: ConstraintOffsetTarget) -> Constraint { self.constant = offset.constraintOffsetTargetValue return self } @discardableResult public func update(inset: ConstraintInsetTarget) -> Constraint { self.constant = inset.constraintInsetTargetValue return self } @discardableResult public func update(priority: ConstraintPriorityTarget) -> Constraint { self.priority = priority.constraintPriorityTargetValue return self } @available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.") public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) } @available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.") public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) } @available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityRequired() -> Void {} @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } // MARK: Internal internal func updateConstantAndPriorityIfNeeded() { for layoutConstraint in self.layoutConstraints { let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) layoutConstraint.priority = self.priority.constraintPriorityTargetValue } } internal func activateIfNeeded(updatingExisting: Bool = false) { guard let view = self.from.view else { print("WARNING: SnapKit failed to get from view from constraint. Activate will be a no-op.") return } let layoutConstraints = self.layoutConstraints let existingLayoutConstraints = view.snp.constraints.map({ $0.layoutConstraints }).reduce([]) { $0 + $1 } if updatingExisting { for layoutConstraint in layoutConstraints { let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } guard let updateLayoutConstraint = existingLayoutConstraint else { fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") } let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) } } else { NSLayoutConstraint.activate(layoutConstraints) view.snp.add(constraints: [self]) } } internal func deactivateIfNeeded() { guard let view = self.from.view else { print("WARNING: SnapKit failed to get from view from constraint. Deactivate will be a no-op.") return } let layoutConstraints = self.layoutConstraints NSLayoutConstraint.deactivate(layoutConstraints) view.snp.remove(constraints: [self]) } }
apache-2.0
acchou/RxGmail
Example/RxGmail/Data+Base64URL.swift
1
1990
// Data+Base64URL.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension Data { init?(base64URLEncoded string: String) { let base64Encoded = string .replacingOccurrences(of: "_", with: "/") .replacingOccurrences(of: "-", with: "+") // iOS can't handle base64 encoding without padding. Add manually let padLength = (4 - (base64Encoded.characters.count % 4)) % 4 let base64EncodedWithPadding = base64Encoded + String(repeating: "=", count: padLength) self.init(base64Encoded: base64EncodedWithPadding) } func base64URLEncodedString() -> String { // use URL safe encoding and remove padding return self.base64EncodedString() .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "=", with: "") } }
mit
jiakunyue/DouYuTV
DouYuTV/DouYuTV/Classes/Main/Controller/MainViewController.swift
1
631
// // MainViewController.swift // DouYuTV // // Created by Justin on 2017/1/24. // Copyright © 2017年 jerei. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() addChildVC(storyName: "Home") addChildVC(storyName: "Live") addChildVC(storyName: "Follow") addChildVC(storyName: "Profile") } private func addChildVC(storyName : String) { let vc = UIStoryboard(name: storyName, bundle: nil).instantiateInitialViewController()! addChildViewController(vc) } }
mit
qbalsdon/br.cd
brcd/brcd/AppDelegate.swift
1
2317
// // AppDelegate.swift // brcd // // Created by Quintin Balsdon on 2016/01/10. // Copyright © 2016 Balsdon. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. CoreDataStackManager.sharedInstance.saveContext() } }
mit
caloon/NominatimSwift
Example/Nominatim/AppDelegate.swift
1
2165
// // AppDelegate.swift // Nominatim // // Created by caloon on 12/21/2017. // Copyright (c) 2017 caloon. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
wilzh40/SoundSieve
SwiftSkeleton/LFTPulseAnimation.swift
1
3615
// // LFTPulseAnimation.swift // // Created by Christoffer Tews on 18.12.14. // Copyright (c) 2014 Christoffer Tews. All rights reserved. // // Swift clone of: https://github.com/shu223/PulsingHalo/blob/master/PulsingHalo/PulsingHaloLayer.m import UIKit class LFTPulseAnimation: CALayer { var radius: CGFloat = 200.0 var fromValueForRadius: Float = 0.0 var fromValueForAlpha: Float = 0.45 var keyTimeForHalfOpacity: Float = 0.2 var animationDuration: NSTimeInterval = 3.0 var pulseInterval: NSTimeInterval = 0.0 var useTimingFunction: Bool = true var animationGroup: CAAnimationGroup = CAAnimationGroup() var repetitions: Float = Float.infinity // Need to implement that, because otherwise it can't find // the constructor init(layer:AnyObject!) // Doesn't seem to look in the super class override init!(layer: AnyObject!) { super.init(layer: layer) } init(repeatCount: Float=Float.infinity, radius: CGFloat, position: CGPoint) { super.init() self.contentsScale = UIScreen.mainScreen().scale self.opacity = 0.0 self.backgroundColor = UIColor.whiteColor().CGColor self.radius = radius; self.repetitions = repeatCount; self.position = position dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { self.setupAnimationGroup() self.setPulseRadius(self.radius) if (self.pulseInterval != Double.infinity) { dispatch_async(dispatch_get_main_queue(), { self.addAnimation(self.animationGroup, forKey: "pulse") }) } })} required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setPulseRadius(radius: CGFloat) { self.radius = radius var tempPos = self.position var diameter = self.radius * 2 self.bounds = CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter) self.cornerRadius = self.radius self.position = tempPos } func setupAnimationGroup() { self.animationGroup = CAAnimationGroup() self.animationGroup.duration = self.animationDuration + self.pulseInterval self.animationGroup.repeatCount = self.repetitions self.animationGroup.removedOnCompletion = false if self.useTimingFunction { var defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) self.animationGroup.timingFunction = defaultCurve } self.animationGroup.animations = [createScaleAnimation(), createOpacityAnimation()] } func createScaleAnimation() -> CABasicAnimation { var scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy") scaleAnimation.fromValue = NSNumber(float: self.fromValueForRadius) scaleAnimation.toValue = NSNumber(float: 1.0) scaleAnimation.duration = self.animationDuration return scaleAnimation } func createOpacityAnimation() -> CAKeyframeAnimation { var opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = self.animationDuration opacityAnimation.values = [self.fromValueForAlpha, 0.8, 0] opacityAnimation.keyTimes = [0, self.keyTimeForHalfOpacity, 1] opacityAnimation.removedOnCompletion = false return opacityAnimation } }
mit
getSenic/nuimo-swift-demo-osx
Pods/NuimoSwift/SDK/BLEDiscoveryManager.swift
1
8426
// // BLEDiscoveryManager.swift // Nuimo // // Created by Lars Blumberg on 12/10/15. // Copyright © 2015 Senic. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. import CoreBluetooth /** Allows for easy discovering bluetooth devices. Automatically re-starts discovery if bluetooth was disabled for a previous discovery. */ public class BLEDiscoveryManager: NSObject { public private(set) lazy var centralManager: CBCentralManager = self.discovery.centralManager public weak var delegate: BLEDiscoveryManagerDelegate? private let options: [String : AnyObject] private lazy var discovery: BLEDiscoveryManagerPrivate = BLEDiscoveryManagerPrivate(discovery: self, options: self.options) public init(delegate: BLEDiscoveryManagerDelegate? = nil, options: [String : AnyObject] = [:]) { self.delegate = delegate self.options = options super.init() } /// If detectUnreachableDevices is set to true, it will invalidate devices if they stop advertising. Consumes more energy since `CBCentralManagerScanOptionAllowDuplicatesKey` is set to true. public func startDiscovery(discoverServiceUUIDs: [CBUUID], detectUnreachableDevices: Bool = false) { discovery.startDiscovery(discoverServiceUUIDs, detectUnreachableDevices: detectUnreachableDevices) } public func stopDiscovery() { discovery.stopDiscovery() } internal func invalidateDevice(device: BLEDevice) { discovery.invalidateDevice(device) } } @objc public protocol BLEDiscoveryManagerDelegate: class { func bleDiscoveryManager(discovery: BLEDiscoveryManager, deviceWithPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject]?) -> BLEDevice? func bleDiscoveryManager(discovery: BLEDiscoveryManager, didDiscoverDevice device: BLEDevice) func bleDiscoveryManager(discovery: BLEDiscoveryManager, didRestoreDevice device: BLEDevice) optional func bleDiscoveryManagerDidStartDiscovery(discovery: BLEDiscoveryManager) optional func bleDiscoveryManagerDidStopDiscovery(discovery: BLEDiscoveryManager) } /** Private implementation of BLEDiscoveryManager. Hides implementation of CBCentralManagerDelegate. */ private class BLEDiscoveryManagerPrivate: NSObject, CBCentralManagerDelegate { let discovery: BLEDiscoveryManager let options: [String : AnyObject] lazy var centralManager: CBCentralManager = CBCentralManager(delegate: self, queue: nil, options: self.options) var discoverServiceUUIDs = [CBUUID]() var detectUnreachableDevices = false var shouldStartDiscoveryWhenPowerStateTurnsOn = false var deviceForPeripheral = [CBPeripheral : BLEDevice]() var restoredConnectedPeripherals: [CBPeripheral]? private var isScanning = false init(discovery: BLEDiscoveryManager, options: [String : AnyObject]) { self.discovery = discovery self.options = options super.init() } func startDiscovery(discoverServiceUUIDs: [CBUUID], detectUnreachableDevices: Bool) { self.discoverServiceUUIDs = discoverServiceUUIDs self.detectUnreachableDevices = detectUnreachableDevices self.shouldStartDiscoveryWhenPowerStateTurnsOn = true guard centralManager.state == .PoweredOn else { return } startDiscovery() } private func startDiscovery() { var options = self.options options[CBCentralManagerScanOptionAllowDuplicatesKey] = detectUnreachableDevices centralManager.scanForPeripheralsWithServices(discoverServiceUUIDs, options: options) isScanning = true discovery.delegate?.bleDiscoveryManagerDidStartDiscovery?(discovery) } func stopDiscovery() { shouldStartDiscoveryWhenPowerStateTurnsOn = false guard isScanning else { return } centralManager.stopScan() isScanning = false discovery.delegate?.bleDiscoveryManagerDidStopDiscovery?(discovery) } func invalidateDevice(device: BLEDevice) { device.invalidate() // Remove all peripherals associated with controller (there should be only one) deviceForPeripheral .filter{ $0.1 == device } .forEach { deviceForPeripheral.removeValueForKey($0.0) } // Restart discovery if the device was connected before and if we are not receiving duplicate discovery events for the same peripheral – otherwise we wouldn't detect this invalidated peripheral when it comes back online. iOS and tvOS only report duplicate discovery events if the app is active (i.e. independently from the "allow duplicates" flag) – this said, we don't need to restart the discovery if the app is active and we're already getting duplicate discovery events for the same peripheral #if os(iOS) || os(tvOS) let appIsActive = UIApplication.sharedApplication().applicationState == .Active #else let appIsActive = true #endif if isScanning && device.didInitiateConnection && !(appIsActive && detectUnreachableDevices) { startDiscovery() } } @objc func centralManager(central: CBCentralManager, willRestoreState state: [String : AnyObject]) { //TODO: Should work on OSX as well. http://stackoverflow.com/q/33210078/543875 #if os(iOS) || os(tvOS) restoredConnectedPeripherals = (state[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral])?.filter{ $0.state == .Connected } #endif } @objc func centralManagerDidUpdateState(central: CBCentralManager) { switch central.state { case .PoweredOn: restoredConnectedPeripherals?.forEach{ centralManager(central, didRestorePeripheral: $0) } restoredConnectedPeripherals = nil // When bluetooth turned on and discovery start had already been triggered before, start discovery now shouldStartDiscoveryWhenPowerStateTurnsOn ? startDiscovery() : () default: // Invalidate all connections as bluetooth state is .PoweredOff or below deviceForPeripheral.values.forEach(invalidateDevice) } } @objc func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { // Prevent devices from being discovered multiple times. iOS devices in peripheral role are also discovered multiple times. var device: BLEDevice? if let knownDevice = deviceForPeripheral[peripheral] { if detectUnreachableDevices { device = knownDevice } } else if let discoveredDevice = discovery.delegate?.bleDiscoveryManager(discovery, deviceWithPeripheral: peripheral, advertisementData: advertisementData) { deviceForPeripheral[peripheral] = discoveredDevice discovery.delegate?.bleDiscoveryManager(discovery, didDiscoverDevice: discoveredDevice) device = discoveredDevice } device?.didAdvertise(advertisementData, RSSI: RSSI, willReceiveSuccessiveAdvertisingData: detectUnreachableDevices) } func centralManager(central: CBCentralManager, didRestorePeripheral peripheral: CBPeripheral) { guard let device = discovery.delegate?.bleDiscoveryManager(discovery, deviceWithPeripheral: peripheral, advertisementData: nil) else { return } deviceForPeripheral[peripheral] = device device.didRestore() discovery.delegate?.bleDiscoveryManager(discovery, didRestoreDevice: device) } @objc func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { guard let device = self.deviceForPeripheral[peripheral] else { return } device.didConnect() } @objc func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { guard let device = self.deviceForPeripheral[peripheral] else { return } device.didFailToConnect(error) } @objc func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { guard let device = self.deviceForPeripheral[peripheral] else { return } device.didDisconnect(error) invalidateDevice(device) } }
mit
dooch/mySwiftStarterApp
SwiftWeatherTests/UnitTests/WeatherIconSpec.swift
1
3947
// // Created by Tran Xuan Hoang on 12/4/15. // Copyright © 2015 Jake Lin. All rights reserved. // import Quick import Nimble @testable import SwiftWeather class WeatherIconSpec: QuickSpec { let dayDictionary = [ 200: "\u{f010}", 201: "\u{f010}", 202: "\u{f010}", 210: "\u{f005}", 211: "\u{f005}", 212: "\u{f005}", 221: "\u{f005}", 230: "\u{f010}", 231: "\u{f010}", 232: "\u{f010}", 300: "\u{f00b}", 301: "\u{f00b}", 302: "\u{f008}", 310: "\u{f008}", 311: "\u{f008}", 312: "\u{f008}", 313: "\u{f008}", 314: "\u{f008}", 321: "\u{f00b}", 500: "\u{f00b}", 501: "\u{f008}", 502: "\u{f008}", 503: "\u{f008}", 504: "\u{f008}", 511: "\u{f006}", 520: "\u{f009}", 521: "\u{f009}", 522: "\u{f009}", 531: "\u{f00e}", 600: "\u{f00a}", 601: "\u{f0b2}", 602: "\u{f00a}", 611: "\u{f006}", 612: "\u{f006}", 615: "\u{f006}", 616: "\u{f006}", 620: "\u{f006}", 621: "\u{f00a}", 622: "\u{f00a}", 701: "\u{f009}", 711: "\u{f062}", 721: "\u{f0b6}", 731: "\u{f063}", 741: "\u{f003}", 761: "\u{f063}", 762: "\u{f063}", 781: "\u{f056}", 800: "\u{f00d}", 801: "\u{f000}", 802: "\u{f000}", 803: "\u{f000}", 804: "\u{f00c}", 900: "\u{f056}", 902: "\u{f073}", 903: "\u{f076}", 904: "\u{f072}", 906: "\u{f004}", 957: "\u{f050}" ] let nightDictionary = [ 200: "\u{f02d}", 201: "\u{f02d}", 202: "\u{f02d}", 210: "\u{f025}", 211: "\u{f025}", 212: "\u{f025}", 221: "\u{f025}", 230: "\u{f02d}", 231: "\u{f02d}", 232: "\u{f02d}", 300: "\u{f02b}", 301: "\u{f02b}", 302: "\u{f028}", 310: "\u{f028}", 311: "\u{f028}", 312: "\u{f028}", 313: "\u{f028}", 314: "\u{f028}", 321: "\u{f02b}", 500: "\u{f02b}", 501: "\u{f028}", 502: "\u{f028}", 503: "\u{f028}", 504: "\u{f028}", 511: "\u{f026}", 520: "\u{f029}", 521: "\u{f029}", 522: "\u{f029}", 531: "\u{f02c}", 600: "\u{f02a}", 601: "\u{f0b4}", 602: "\u{f02a}", 611: "\u{f026}", 612: "\u{f026}", 615: "\u{f026}", 616: "\u{f026}", 620: "\u{f026}", 621: "\u{f02a}", 622: "\u{f02a}", 701: "\u{f029}", 711: "\u{f062}", 721: "\u{f0b6}", 731: "\u{f063}", 741: "\u{f04a}", 761: "\u{f063}", 762: "\u{f063}", 781: "\u{f056}", 800: "\u{f02e}", 801: "\u{f022}", 802: "\u{f022}", 803: "\u{f022}", 804: "\u{f086}", 900: "\u{f056}", 902: "\u{f073}", 903: "\u{f076}", 904: "\u{f072}", 906: "\u{f024}", 957: "\u{f050}" ] override func spec() { describe("#init(condition:,iconString:)") { context("day") { context("invalid condition Int") { self.expectWeatherIconWithCondition(999, isDay: true, toHaveIconTextEqualToString: "") } context("valid condition Int") { for (condition, description) in self.dayDictionary { self.expectWeatherIconWithCondition(condition, isDay: true, toHaveIconTextEqualToString: description) } } } context("night") { context("invalid condition Int") { self.expectWeatherIconWithCondition(999, isDay: false, toHaveIconTextEqualToString: "") } context("valid condition Int") { for (condition, description) in self.nightDictionary { self.expectWeatherIconWithCondition(condition, isDay: false, toHaveIconTextEqualToString: description) } } } } } } extension WeatherIconSpec { func expectWeatherIconWithCondition(condition: Int, isDay: Bool, toHaveIconTextEqualToString description: String) { let weatherIcon = WeatherIcon(condition: condition, iconString: isDay ? "day" : "night") expect(weatherIcon.iconText).to(equal(description)) } }
mit
fancymax/12306ForMac
12306ForMac/Model/AutoSubmitParams.swift
1
1544
// // autoSubmitParams.swift // 12306ForMac // // Created by fancymax on 2016/12/13. // Copyright © 2016年 fancy. All rights reserved. // import Foundation struct AutoSubmitParams{ init(with ticket:QueryLeftNewDTO, purposeCode:String,passengerTicket:String,oldPassenger:String) { secretStr = ticket.SecretStr! train_date = ticket.trainDateStr purpose_codes = purposeCode query_from_station_name = ticket.FromStationName! query_to_station_name = ticket.ToStationName! passengerTicketStr = passengerTicket oldPassengerStr = oldPassenger } var secretStr = "" var train_date = "" let tour_flag = "dc" var purpose_codes = "ADULT" var query_from_station_name = "" var query_to_station_name = "" let cancel_flag = "2" let bed_level_order_num = "000000000000000000000000000000" var passengerTicketStr = "" var oldPassengerStr = "" func ToPostParams()->[String:String]{ return [ "secretStr":secretStr, "train_date":train_date,//2015-11-17 "tour_flag":tour_flag, "purpose_codes":purpose_codes, "query_from_station_name":query_from_station_name, "query_to_station_name":query_to_station_name, "cancel_flag":cancel_flag, "bed_level_order_num":bed_level_order_num, "passengerTicketStr":passengerTicketStr, "oldPassengerStr":oldPassengerStr] } }
mit
leleks/TextFieldEffects
TextFieldEffects/TextFieldEffects/IsaoTextField.swift
1
5298
// // IsaoTextField.swift // TextFieldEffects // // Created by Raúl Riera on 29/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit @IBDesignable public class IsaoTextField: TextFieldEffects { @IBInspectable public var inactiveColor: UIColor? { didSet { updateBorder() } } @IBInspectable public var activeColor: UIColor? { didSet { updateBorder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: (active: CGFloat, inactive: CGFloat) = (4, 2) private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) private let borderLayer = CALayer() override func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font) updateBorder() updatePlaceholder() layer.addSublayer(borderLayer) addSubview(placeholderLabel) delegate = self } private func updateBorder() { borderLayer.frame = rectForBorder(frame) borderLayer.backgroundColor = isFirstResponder() ? activeColor?.CGColor : inactiveColor?.CGColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = inactiveColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.7) return smallerFont } private func rectForBorder(bounds: CGRect) -> CGRect { var newRect:CGRect if isFirstResponder() { newRect = CGRect(x: 0, y: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness.active, width: bounds.size.width, height: borderThickness.active) } else { newRect = CGRect(x: 0, y: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness.inactive, width: bounds.size.width, height: borderThickness.inactive) } return newRect } private func layoutPlaceholderInTextRect() { if !text.isEmpty { return } let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } override func animateViewsForTextEntry() { updateBorder() if let activeColor = activeColor { performPlacerholderAnimationWithColor(activeColor) } } override func animateViewsForTextDisplay() { updateBorder() if let inactiveColor = inactiveColor { performPlacerholderAnimationWithColor(inactiveColor) } } private func performPlacerholderAnimationWithColor(color: UIColor) { let yOffset:CGFloat = 4 UIView.animateWithDuration(0.15, animations: { () -> Void in self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, -yOffset) self.placeholderLabel.alpha = 0 }) { (completed) -> Void in self.placeholderLabel.transform = CGAffineTransformIdentity self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, yOffset) UIView.animateWithDuration(0.15, animations: { self.placeholderLabel.textColor = color self.placeholderLabel.transform = CGAffineTransformIdentity self.placeholderLabel.alpha = 1 }) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } }
mit
suragch/MongolAppDevelopment-iOS
Mongol App ComponantsTests/MongolUnicodeRendererTests.swift
1
19699
import XCTest @testable import Mongol_App_Componants class MongolUnicodeRendererTests: XCTestCase { func testUnicodeToGlyphs_emptyString_returnEmptyString() { // Arrange let unicode = "" let expected = "" let renderer = MongolUnicodeRenderer() // Act let result = renderer.unicodeToGlyphs(unicode) // Assert XCTAssertEqual(result, expected) } func testUnicodeToGlyphs_nonMongolString_returnSame() { // Arrange let unicode = "abc" let expected = unicode let renderer = MongolUnicodeRenderer() // Act let result = renderer.unicodeToGlyphs(unicode) // Assert XCTAssertEqual(result, expected) } func testUnicodeToGlyphs_IsolateI_returnGlyph() { // Arrange let unicode = "ᠢ" let expected = "" let renderer = MongolUnicodeRenderer() // Act let result = renderer.unicodeToGlyphs(unicode) // Assert XCTAssertEqual(result, expected) } func testUnicodeToGlyphs_InitialMedialFinalNom_returnGlyph() { // Arrange let unicode = "ᠨᠣᠮ" let expected = "" let renderer = MongolUnicodeRenderer() // Act let result = renderer.unicodeToGlyphs(unicode) // Assert XCTAssertEqual(result, expected) } func testUnicodeToGlyphs_MVS_returnGlyphs() { // Arrange let baina = "ᠪᠠᠢᠨ᠎ᠠ" let minggan = "ᠮᠢᠩᠭ᠎ᠡᠨ" let na = "‍ᠨ᠎ᠡ" let ngqa = "‍ᠩᠬ᠎ᠡ" let ngga = "‍ᠩᠭ᠎ᠡ" let qa = "‍ᠬ᠎ᠡ" let ga = "‍ᠭ᠎ᠡ" let ma = "‍ᠮ᠎ᠡ" let la = "‍ᠯ᠎ᠡ" let ya = "‍ᠶ᠎ᠡ" // y let wa = "‍ᠸ᠎ᠡ" let ia = "‍ᠢ᠎ᠡ" // i let ra = "‍ᠷ᠎ᠡ" let bainaExpected = "" let mingganExpected = "" let naExpected = "" let ngqaExpected = "" let nggaExpected = "" let qaExpected = "" let gaExpected = "" let maExpected = "" let laExpected = "" let yaExpected = "" // y let waExpected = "" let iaExpected = "" // i let raExpected = "" let renderer = MongolUnicodeRenderer() // Assert XCTAssertEqual(renderer.unicodeToGlyphs(baina), bainaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(minggan), mingganExpected) XCTAssertEqual(renderer.unicodeToGlyphs(na), naExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ngqa), ngqaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ngga), nggaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(qa), qaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ga), gaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ma), maExpected) XCTAssertEqual(renderer.unicodeToGlyphs(la), laExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ya), yaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(wa), waExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ia), iaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ra), raExpected) } // TODO: make more tests func testUnicodeToGlyphs_YiRuleNamayi_returnGlyphs() { // Arrange let unicode = "ᠨᠠᠮᠠᠶᠢ" let expected = "" let renderer = MongolUnicodeRenderer() // Act let result = renderer.unicodeToGlyphs(unicode) // Assert XCTAssertEqual(result, expected) // show print("Unicode: \(unicode), Rendered: \(result)") } // Words from "A Study of Traditional Mongolian Script Encodings and Rendering" func testUnicodeToGlyphs_wordList1_returnGlyphs() { // Arrange let biqig = "ᠪᠢᠴᠢᠭ" let egshig_inu = "ᠡᠭᠡᠰᠢᠭ ᠢᠨᠦ" let bujig_i_ben_yugen = "ᠪᠦᠵᠢᠭ ᠢ ᠪᠡᠨ ᠶᠦᠭᠡᠨ" let chirig_mini = "ᠴᠢᠷᠢᠭ ᠮᠠᠨᠢ" let egche = "ᠡᠭᠴᠡ" let hugjim_dur_iyen_degen = "ᠬᠦᠭᠵᠢᠮ ᠳᠦᠷ ᠢᠶᠡᠨ ᠳᠡᠭᠡᠨ" let buridgel_iyen = "ᠪᠦᠷᠢᠳᠭᠡᠯ ᠢᠶᠡᠨ" let sedgil_mini = "ᠰᠡᠳᠬᠢᠯ ᠮᠢᠨᠢ" let uiledburi_du = "ᠦᠢᠯᠠᠳᠪᠦᠷᠢ ᠳᠦ" let jeligudgen_u = "ᠵᠡᠯᠢᠭᠦᠳᠭᠡᠨ ᠦ" let manggal_dur_iyen_dagan = "ᠮᠠᠩᠭᠠᠯ ᠳᠤᠷ ᠢᠶᠠᠨ ᠳᠠᠭᠠᠨ" let dung_i = "ᠳ᠋ᠦᠩ ᠢ" let sodnam_acha_ban_achagan = "ᠰᠣᠳᠨᠠᠮ ᠠᠴᠠ ᠪᠠᠨ ᠠᠴᠠᠭᠠᠨ" let lhagba_luga = "ᡀᠠᠭᠪᠠ ᠯᠤᠭ᠎ᠠ" let cement_tayigan = "ᠼᠧᠮᠧᠨ᠋ᠲ ᠲᠠᠶᠢᠭᠠᠨ" // should't have FVS1 according to Unicode 8.0 draft let chebegmed_luge = "ᠴᠡᠪᠡᠭᠮᠡᠳ ᠯᠦᠭᠡ" let uniye_teyigen = "ᠦᠨᠢᠶ᠎ᠡ ᠲᠡᠶᠢᠭᠡᠨ" let hoyina = "ᠬᠣᠶᠢᠨ᠎ᠠ" let angna = "ᠠᠩᠨ᠎ᠠ" // missing gliph in font let biqigExpected = "" let egshig_inuExpected = " " let bujig_i_ben_yugenExpected = "   " let chirig_miniExpected = " " let egcheExpected = "" let hugjim_dur_iyen_degenExpected = "   " let buridgel_iyenExpected = " " let sedgil_miniExpected = " " let uiledburi_duExpected = " " let jeligudgen_uExpected = " " let manggal_dur_iyen_daganExpected = "   " let dung_iExpected = " " let sodnam_acha_ban_achaganExpected = "   " let lhagba_lugaExpected = " " let cement_tayiganExpected = " " let chebegmed_lugeExpected = " " let uniye_teyigenExpected = " " let hoyinaExpected = "" let angnaExpected = "" let renderer = MongolUnicodeRenderer() // Assert XCTAssertEqual(renderer.unicodeToGlyphs(biqig), biqigExpected) XCTAssertEqual(renderer.unicodeToGlyphs(egshig_inu), egshig_inuExpected) XCTAssertEqual(renderer.unicodeToGlyphs(bujig_i_ben_yugen), bujig_i_ben_yugenExpected) XCTAssertEqual(renderer.unicodeToGlyphs(chirig_mini), chirig_miniExpected) XCTAssertEqual(renderer.unicodeToGlyphs(egche), egcheExpected) XCTAssertEqual(renderer.unicodeToGlyphs(hugjim_dur_iyen_degen), hugjim_dur_iyen_degenExpected) XCTAssertEqual(renderer.unicodeToGlyphs(buridgel_iyen), buridgel_iyenExpected) XCTAssertEqual(renderer.unicodeToGlyphs(sedgil_mini), sedgil_miniExpected) XCTAssertEqual(renderer.unicodeToGlyphs(uiledburi_du), uiledburi_duExpected) XCTAssertEqual(renderer.unicodeToGlyphs(jeligudgen_u), jeligudgen_uExpected) XCTAssertEqual(renderer.unicodeToGlyphs(manggal_dur_iyen_dagan), manggal_dur_iyen_daganExpected) XCTAssertEqual(renderer.unicodeToGlyphs(dung_i), dung_iExpected) XCTAssertEqual(renderer.unicodeToGlyphs(sodnam_acha_ban_achagan), sodnam_acha_ban_achaganExpected) XCTAssertEqual(renderer.unicodeToGlyphs(lhagba_luga), lhagba_lugaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(cement_tayigan), cement_tayiganExpected) XCTAssertEqual(renderer.unicodeToGlyphs(chebegmed_luge), chebegmed_lugeExpected) XCTAssertEqual(renderer.unicodeToGlyphs(uniye_teyigen), uniye_teyigenExpected) XCTAssertEqual(renderer.unicodeToGlyphs(hoyina), hoyinaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(angna), angnaExpected) // show print("Unicode: \(biqig), Rendered: \(renderer.unicodeToGlyphs(biqig))") print("Unicode: \(egshig_inu), Rendered: \(renderer.unicodeToGlyphs(egshig_inu))") print("Unicode: \(bujig_i_ben_yugen), Rendered: \(renderer.unicodeToGlyphs(bujig_i_ben_yugen))") print("Unicode: \(chirig_mini), Rendered: \(renderer.unicodeToGlyphs(chirig_mini))") print("Unicode: \(egche), Rendered: \(renderer.unicodeToGlyphs(egche))") print("Unicode: \(hugjim_dur_iyen_degen), Rendered: \(renderer.unicodeToGlyphs(hugjim_dur_iyen_degen))") print("Unicode: \(buridgel_iyen), Rendered: \(renderer.unicodeToGlyphs(buridgel_iyen))") print("Unicode: \(sedgil_mini), Rendered: \(renderer.unicodeToGlyphs(sedgil_mini))") print("Unicode: \(uiledburi_du), Rendered: \(renderer.unicodeToGlyphs(uiledburi_du))") print("Unicode: \(jeligudgen_u), Rendered: \(renderer.unicodeToGlyphs(jeligudgen_u))") print("Unicode: \(manggal_dur_iyen_dagan), Rendered: \(renderer.unicodeToGlyphs(manggal_dur_iyen_dagan))") print("Unicode: \(dung_i), Rendered: \(renderer.unicodeToGlyphs(dung_i))") print("Unicode: \(sodnam_acha_ban_achagan), Rendered: \(renderer.unicodeToGlyphs(sodnam_acha_ban_achagan))") print("Unicode: \(lhagba_luga), Rendered: \(renderer.unicodeToGlyphs(lhagba_luga))") print("Unicode: \(cement_tayigan), Rendered: \(renderer.unicodeToGlyphs(cement_tayigan))") print("Unicode: \(chebegmed_luge), Rendered: \(renderer.unicodeToGlyphs(chebegmed_luge))") print("Unicode: \(uniye_teyigen), Rendered: \(renderer.unicodeToGlyphs(uniye_teyigen))") print("Unicode: \(hoyina), Rendered: \(renderer.unicodeToGlyphs(hoyina))") print("Unicode: \(angna), Rendered: \(renderer.unicodeToGlyphs(angna))") } // Additional words func testUnicodeToGlyphs_wordList2_returnGlyphs() { // TODO: sort these out into different tests based on rules // Arrange let chingalahu = "ᠴᠢᠩᠭᠠᠯᠠᠬᠤ" let taljiyagsan = "ᠳᠠᠯᠵᠢᠶᠭᠰᠠᠨ" let ilbigchi = "ᠢᠯᠪᠢᠭᠴᠢ" let bichigchi = "ᠪᠢᠴᠢᠭᠴᠢ" let shigshiglehu = "ᠰᠢᠭᠰᠢᠭᠯᠡᠬᠦ" let tiglimsigsen = "ᠳᠢᠭᠯᠢᠮᠰᠢᠭᠰᠡᠨ" let chigiglig = "ᠴᠢᠭᠢᠭᠯᠢᠭ" let gram = "ᠭᠷᠠᠮ" // g+non-vowel words let mingga = "ᠮᠢᠩᠭ᠎ᠠ" let minggan = "ᠮᠢᠩᠭ᠎ᠠᠨ" let naima = "ᠨᠠᠢ᠌ᠮᠠ" let baina = "ᠪᠠᠢᠨ᠎ᠠ" let bayina = "ᠪᠠᠶᠢᠨ᠎ᠠ" let buu = "ᠪᠦᠦ" let huu = "ᠬᠦᠦ" let heuhed = "ᠬᠡᠦᠬᠡᠳ" let angli = "ᠠᠩᠭᠯᠢ" let soyol = "ᠰᠤᠶᠤᠯ" let saihan = "ᠰᠠᠢᠬᠠᠨ" // beautiful let sayihan = "ᠰᠠᠶ᠋ᠢᠬᠠᠨ" // recently let sayi = "ᠰᠠᠶᠢ" // old form - straight Y let sayiHooked = "ᠰᠠᠶ᠋ᠢ" // hooked y let naranGerel = "ᠨᠠᠷᠠᠨᠭᠡᠷᠡᠯ" let cholmonOdo = "ᠴᠣᠯᠮᠣᠨ᠍ᠣ᠋ᠳᠣ" //let sodoBilig = "ᠰᠣᠳᠣᠪᠢᠯᠢᠭ" // TODO: final g unspecified let sodoBilig2 = "ᠰᠣᠳᠣᠪᠢᠯᠢᠭ᠌" // final g is specified let erdeniTana = "ᠡᠷᠳᠡᠨᠢᠲ᠋ᠠᠨ᠎ᠠ" // two-part name, with second medial TA form let engheBold = "ᠡᠩᠬᠡᠪᠣᠯᠣᠳ" let bayanUnder = "ᠪᠠᠶᠠᠨ᠍ᠦ᠌ᠨᠳᠦᠷ" let biburie = "ᠪᠢᠪᠦᠷᠢ᠎ᠡ" // i-e as an alternate to y-e let asiglaju = "ᠠᠰᠢᠭᠯᠠᠵᠤ" // ig let eimu = "ᠡᠢᠮᠣ" let namayi = "ᠨᠠᠮᠠᠶᠢ" let heduin = "ᠬᠡᠳᠦᠢᠨ" let chingalahuExpected = "" let taljiyagsanExpected = "" let ilbigchiExpected = "" let bichigchiExpected = "" let shigshiglehuExpected = "" let tiglimsigsenExpected = "" let chigigligExpected = "" let gramExpected = "" let minggaExpected = "" let mingganExpected = "" let naimaExpected = "" let bainaExpected = "" let bayinaExpected = "" let buuExpected = "" let huuExpected = "" let heuhedExpected = "" let angliExpected = "" let soyolExpected = "" let saihanExpected = "" let sayihanExpected = "" let sayiExpected = "" let sayiHookedExpected = "" let naranGerelExpected = "" let cholmonOdoExpected = "" //let sodoBiligExpected = "" let sodoBilig2Expected = "" let erdeniTanaExpected = "" let engheBoldExpected = "" let bayanUnderExpected = "" let biburieExpected = "" let asiglajuExpected = "" let eimuExpected = "" let namayiExpected = "" let heduinExpected = "" let renderer = MongolUnicodeRenderer() // Assert XCTAssertEqual(renderer.unicodeToGlyphs(chingalahu), chingalahuExpected) XCTAssertEqual(renderer.unicodeToGlyphs(taljiyagsan), taljiyagsanExpected) XCTAssertEqual(renderer.unicodeToGlyphs(ilbigchi), ilbigchiExpected) XCTAssertEqual(renderer.unicodeToGlyphs(bichigchi), bichigchiExpected) XCTAssertEqual(renderer.unicodeToGlyphs(shigshiglehu), shigshiglehuExpected) XCTAssertEqual(renderer.unicodeToGlyphs(tiglimsigsen), tiglimsigsenExpected) XCTAssertEqual(renderer.unicodeToGlyphs(chigiglig), chigigligExpected) XCTAssertEqual(renderer.unicodeToGlyphs(gram), gramExpected) XCTAssertEqual(renderer.unicodeToGlyphs(mingga), minggaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(minggan), mingganExpected) XCTAssertEqual(renderer.unicodeToGlyphs(naima), naimaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(baina), bainaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(bayina), bayinaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(buu), buuExpected) XCTAssertEqual(renderer.unicodeToGlyphs(huu), huuExpected) XCTAssertEqual(renderer.unicodeToGlyphs(heuhed), heuhedExpected) XCTAssertEqual(renderer.unicodeToGlyphs(angli), angliExpected) XCTAssertEqual(renderer.unicodeToGlyphs(soyol), soyolExpected) XCTAssertEqual(renderer.unicodeToGlyphs(saihan), saihanExpected) XCTAssertEqual(renderer.unicodeToGlyphs(sayihan), sayihanExpected) XCTAssertEqual(renderer.unicodeToGlyphs(sayi), sayiExpected) XCTAssertEqual(renderer.unicodeToGlyphs(sayiHooked), sayiHookedExpected) XCTAssertEqual(renderer.unicodeToGlyphs(naranGerel), naranGerelExpected) XCTAssertEqual(renderer.unicodeToGlyphs(cholmonOdo), cholmonOdoExpected) XCTAssertEqual(renderer.unicodeToGlyphs(sodoBilig2), sodoBilig2Expected) XCTAssertEqual(renderer.unicodeToGlyphs(erdeniTana), erdeniTanaExpected) XCTAssertEqual(renderer.unicodeToGlyphs(engheBold), engheBoldExpected) XCTAssertEqual(renderer.unicodeToGlyphs(bayanUnder), bayanUnderExpected) XCTAssertEqual(renderer.unicodeToGlyphs(biburie), biburieExpected) XCTAssertEqual(renderer.unicodeToGlyphs(asiglaju), asiglajuExpected) XCTAssertEqual(renderer.unicodeToGlyphs(eimu), eimuExpected) XCTAssertEqual(renderer.unicodeToGlyphs(namayi), namayiExpected) XCTAssertEqual(renderer.unicodeToGlyphs(heduin), heduinExpected) // show print("Unicode: \(chingalahu), Rendered: \(renderer.unicodeToGlyphs(chingalahu))") print("Unicode: \(taljiyagsan), Rendered: \(renderer.unicodeToGlyphs(taljiyagsan))") print("Unicode: \(ilbigchi), Rendered: \(renderer.unicodeToGlyphs(ilbigchi))") print("Unicode: \(bichigchi), Rendered: \(renderer.unicodeToGlyphs(bichigchi))") print("Unicode: \(shigshiglehu), Rendered: \(renderer.unicodeToGlyphs(shigshiglehu))") print("Unicode: \(tiglimsigsen), Rendered: \(renderer.unicodeToGlyphs(tiglimsigsen))") print("Unicode: \(chigiglig), Rendered: \(renderer.unicodeToGlyphs(chigiglig))") print("Unicode: \(gram), Rendered: \(renderer.unicodeToGlyphs(gram))") print("Unicode: \(mingga), Rendered: \(renderer.unicodeToGlyphs(mingga))") print("Unicode: \(minggan), Rendered: \(renderer.unicodeToGlyphs(minggan))") print("Unicode: \(naima), Rendered: \(renderer.unicodeToGlyphs(naima))") print("Unicode: \(baina), Rendered: \(renderer.unicodeToGlyphs(baina))") print("Unicode: \(bayina), Rendered: \(renderer.unicodeToGlyphs(bayina))") print("Unicode: \(buu), Rendered: \(renderer.unicodeToGlyphs(buu))") print("Unicode: \(huu), Rendered: \(renderer.unicodeToGlyphs(huu))") print("Unicode: \(heuhed), Rendered: \(renderer.unicodeToGlyphs(heuhed))") print("Unicode: \(angli), Rendered: \(renderer.unicodeToGlyphs(angli))") print("Unicode: \(soyol), Rendered: \(renderer.unicodeToGlyphs(soyol))") print("Unicode: \(saihan), Rendered: \(renderer.unicodeToGlyphs(saihan))") print("Unicode: \(sayihan), Rendered: \(renderer.unicodeToGlyphs(sayihan))") print("Unicode: \(sayi), Rendered: \(renderer.unicodeToGlyphs(sayi))") print("Unicode: \(sayiHooked), Rendered: \(renderer.unicodeToGlyphs(sayiHooked))") print("Unicode: \(naranGerel), Rendered: \(renderer.unicodeToGlyphs(naranGerel))") print("Unicode: \(cholmonOdo), Rendered: \(renderer.unicodeToGlyphs(cholmonOdo))") //print("Unicode: \(sodoBilig), Rendered: \(renderer.unicodeToGlyphs(sodoBilig))") print("Unicode: \(sodoBilig2), Rendered: \(renderer.unicodeToGlyphs(sodoBilig2))") print("Unicode: \(erdeniTana), Rendered: \(renderer.unicodeToGlyphs(erdeniTana))") print("Unicode: \(engheBold), Rendered: \(renderer.unicodeToGlyphs(engheBold))") print("Unicode: \(bayanUnder), Rendered: \(renderer.unicodeToGlyphs(bayanUnder))") print("Unicode: \(biburie), Rendered: \(renderer.unicodeToGlyphs(biburie))") print("Unicode: \(asiglaju), Rendered: \(renderer.unicodeToGlyphs(asiglaju))") print("Unicode: \(eimu), Rendered: \(renderer.unicodeToGlyphs(eimu))") print("Unicode: \(namayi), Rendered: \(renderer.unicodeToGlyphs(namayi))") print("Unicode: \(heduin), Rendered: \(renderer.unicodeToGlyphs(heduin))") } }
mit
Tsiems/WirelessNetwork
NetworkSimulation/NetworkSimulation/AppDelegate.swift
1
2234
// // AppDelegate.swift // NetworkSimulation // // Created by Travis Siems on 2/24/17. // Copyright © 2017 Travis Siems. All rights reserved. // // icon made with http://editor.method.ac/ // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
JoeLago/MHGDB-iOS
MHGDB/Screens/Monster/Custom/MonsterStatusesCell.swift
1
1199
// // MIT License // Copyright (c) Gathering Hall Studios // import Foundation class MonsterStatusesCell: GridCell<Monster> { override var model: Monster? { didSet { if let model = model { populate(monster: model) } } } func populate(monster: Monster) { add(imageNames: ["", "Poison", "Sleep", "Paralysis", "Stun", "exhaust", "mount", "jump", "BlastBlight"]) for status in monster.statuses { let values: [Any] = [status.stat.capitalizingFirstLetter(), status.poison, status.sleep, status.paralysis, status.ko, status.exhaust, status.mount, status.jump, status.blast] add(values: values) } } }
mit
velvetroom/columbus
Source/View/CreateSave/VCreateSaveStatusError+Factory.swift
1
6286
import UIKit extension VCreateSaveStatusError { //MARK: private private func factoryTitle() -> NSAttributedString { let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font : UIFont.medium(size:VCreateSaveStatusError.Constants.titleFontSize), NSAttributedStringKey.foregroundColor : UIColor.white] let string:String = String.localizedView(key:"VCreateSaveStatusError_labelTitle") let attributedString:NSAttributedString = NSAttributedString( string:string, attributes:attributes) return attributedString } private func factoryDescr() -> NSAttributedString { let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font : UIFont.regular(size:VCreateSaveStatusError.Constants.descrFontSize), NSAttributedStringKey.foregroundColor : UIColor(white:1, alpha:0.8)] let string:String = String.localizedView(key:"VCreateSaveStatusError_labelDescr") let attributedString:NSAttributedString = NSAttributedString( string:string, attributes:attributes) return attributedString } private func factoryInfo() -> NSAttributedString { let title:NSAttributedString = factoryTitle() let descr:NSAttributedString = factoryDescr() let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(title) mutableString.append(descr) return mutableString } //MARK: internal func factoryViews() { let info:NSAttributedString = factoryInfo() let colourTop:UIColor = UIColor( red:1, green:0.4352941176470589, blue:0.5686274509803924, alpha:1) let viewGradient:VGradient = VGradient.vertical( colourTop:colourTop, colourBottom:UIColor.colourFail) let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.center label.numberOfLines = 0 label.attributedText = info let buttonCancel:UIButton = UIButton() buttonCancel.translatesAutoresizingMaskIntoConstraints = false buttonCancel.setTitleColor( UIColor(white:1, alpha:0.9), for:UIControlState.normal) buttonCancel.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonCancel.setTitle( String.localizedView(key:"VCreateSaveStatusError_buttonCancel"), for:UIControlState.normal) buttonCancel.titleLabel!.font = UIFont.regular( size:VCreateSaveStatusError.Constants.cancelFontSize) buttonCancel.addTarget( self, action:#selector(selectorCancel(sender:)), for:UIControlEvents.touchUpInside) let buttonRetry:UIButton = UIButton() buttonRetry.translatesAutoresizingMaskIntoConstraints = false buttonRetry.setTitleColor( UIColor.white, for:UIControlState.normal) buttonRetry.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonRetry.setTitle( String.localizedView(key:"VCreateSaveStatusError_buttonRetry"), for:UIControlState.normal) buttonRetry.titleLabel!.font = UIFont.bold( size:VCreateSaveStatusError.Constants.retryFontSize) buttonRetry.addTarget( self, action:#selector(selectorRetry(sender:)), for:UIControlEvents.touchUpInside) let image:UIImageView = UIImageView() image.isUserInteractionEnabled = false image.translatesAutoresizingMaskIntoConstraints = false image.clipsToBounds = true image.contentMode = UIViewContentMode.center image.image = #imageLiteral(resourceName: "assetGenericError").withRenderingMode(UIImageRenderingMode.alwaysTemplate) image.tintColor = UIColor.white addSubview(viewGradient) addSubview(label) addSubview(buttonCancel) addSubview(buttonRetry) addSubview(image) NSLayoutConstraint.equals( view:viewGradient, toView:self) NSLayoutConstraint.bottomToBottom( view:label, toView:self, constant:VCreateSaveStatusError.Constants.labelBottom) NSLayoutConstraint.height( view:label, constant:VCreateSaveStatusError.Constants.labelHeight) NSLayoutConstraint.equalsHorizontal( view:label, toView:self) NSLayoutConstraint.topToBottom( view:buttonCancel, toView:buttonRetry) NSLayoutConstraint.height( view:buttonCancel, constant:VCreateSaveStatusError.Constants.buttonHeight) layoutCancelLeft = NSLayoutConstraint.leftToLeft( view:buttonCancel, toView:self) NSLayoutConstraint.width( view:buttonCancel, constant:VCreateSaveStatusError.Constants.buttonWidth) NSLayoutConstraint.topToBottom( view:buttonRetry, toView:label) NSLayoutConstraint.height( view:buttonRetry, constant:VCreateSaveStatusError.Constants.buttonHeight) layoutRetryLeft = NSLayoutConstraint.leftToLeft( view:buttonRetry, toView:self) NSLayoutConstraint.width( view:buttonRetry, constant:VCreateSaveStatusError.Constants.buttonWidth) NSLayoutConstraint.bottomToTop( view:image, toView:label) NSLayoutConstraint.height( view:image, constant:VCreateSaveStatusError.Constants.imageHeight) NSLayoutConstraint.equalsHorizontal( view:image, toView:self) } }
mit
aulas-lab/ads-mobile
swift/Todo/Todo/AppDelegate.swift
1
2132
// // AppDelegate.swift // Todo // // Created by Mobitec on 17/05/16. // Copyright (c) 2016 Unopar. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Managers/DatabaseManager.swift
1
6271
// // DatabaseManager.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 01/09/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift import Realm /** This keys are used to store all servers and database information to each server user is connected to. */ struct ServerPersistKeys { // Server controls static let servers = "kServers" static let selectedIndex = "kSelectedIndex" // Database static let databaseName = "kDatabaseName" // Authentication information static let token = "kAuthToken" static let serverURL = "kAuthServerURL" static let serverVersion = "kAuthServerVersion" static let userId = "kUserId" // Display information static let serverIconURL = "kServerIconURL" static let serverName = "kServerName" // Two-way SSL certificate & password static let sslClientCertificatePath = "kSSLClientCertificatePath" static let sslClientCertificatePassword = "kSSLClientCertificatePassword" } struct DatabaseManager { /** - returns: The selected database index. */ static var selectedIndex: Int { return UserDefaults.group.value(forKey: ServerPersistKeys.selectedIndex) as? Int ?? 0 } /** - returns: All servers stored locally into the app. */ static var servers: [[String: String]]? { return UserDefaults.group.value(forKey: ServerPersistKeys.servers) as? [[String: String]] } /** - parameter index: The database index user wants to select. */ static func selectDatabase(at index: Int) { UserDefaults.group.set(index, forKey: ServerPersistKeys.selectedIndex) } /** - parameter index: The database index that needs to be updated. */ static func updateSSLClientInformation(for index: Int, path: URL, password: String) { guard var servers = self.servers, servers.count > index else { return } // Update SSL Client Certificate information var server = servers[index] server[ServerPersistKeys.sslClientCertificatePath] = path.absoluteString server[ServerPersistKeys.sslClientCertificatePassword] = password servers[index] = server UserDefaults.group.set(servers, forKey: ServerPersistKeys.servers) } /** Remove selected server and select the first one. */ static func removeSelectedDatabase() { removeDatabase(at: selectedIndex) selectDatabase(at: 0) } /** Removes server information at some index. parameter index: The database index user wants to delete. */ static func removeDatabase(at index: Int) { if var servers = self.servers, servers.count > index { servers.remove(at: index) UserDefaults.group.set(servers, forKey: ServerPersistKeys.servers) } } /** This method cleans the servers that doesn't have authentication information. */ static func cleanInvalidDatabases() { let servers = self.servers ?? [] var validServers: [[String: String]] = [] for (index, server) in servers.enumerated() { guard server[ServerPersistKeys.token] != nil, server[ServerPersistKeys.userId] != nil, server[ServerPersistKeys.databaseName] != nil, server[ServerPersistKeys.serverURL] != nil, let realmConfiguration = databaseConfiguration(index: index), (try? Realm(configuration: realmConfiguration)) != nil else { continue } validServers.append(server) } if selectedIndex > validServers.count - 1 { selectDatabase(at: 0) } UserDefaults.group.set(validServers, forKey: ServerPersistKeys.servers) } /** This method will create a new database before user even authenticated into the server. This is used so we can populate the authentication information when user logins. - parameter serverURL: The server URL. */ @discardableResult static func createNewDatabaseInstance(serverURL: String) -> Int { let defaults = UserDefaults.group var servers = self.servers ?? [] servers.append([ ServerPersistKeys.databaseName: "\(String.random()).realm", ServerPersistKeys.serverURL: serverURL ]) let index = servers.count - 1 defaults.set(servers, forKey: ServerPersistKeys.servers) defaults.set(index, forKey: ServerPersistKeys.selectedIndex) return index } /** This method gets the realm associated with this server */ static func databaseInstace(index: Int) -> Realm? { guard let configuration = databaseConfiguration(index: index) else { return nil } return try? Realm(configuration: configuration) } /** This method returns the realm configuration associated with this server */ static func databaseConfiguration(index: Int? = nil) -> Realm.Configuration? { guard let server = AuthManager.selectedServerInformation(index: index), let databaseName = server[ServerPersistKeys.databaseName], let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppGroup.identifier) else { return nil } #if DEBUG Log.debug("Realm path: \(url.appendingPathComponent(databaseName))") #endif return Realm.Configuration( fileURL: url.appendingPathComponent(databaseName), deleteRealmIfMigrationNeeded: true ) } } extension DatabaseManager { /** This method returns an index for the server with this URL if it already exists. - parameter serverUrl: The URL of the server */ static func serverIndexForUrl(_ serverUrl: URL) -> Int? { return servers?.index { guard let url = URL(string: $0[ServerPersistKeys.serverURL] ?? "") else { return false } return url.host == serverUrl.host } } }
mit
creatubbles/ctb-api-swift
CreatubblesAPIClientUnitTests/Spec/User/NewCreatorRequestSpec.swift
1
2834
// // NewCreatorRequestSpec.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Quick import Nimble @testable import CreatubblesAPIClient class NewCreatorRequestSpec: QuickSpec { override func spec() { describe("New creator request") { let name = "TestCreatorName" let displayName = "TestCreatorDisplayName" let birthYear = 2_000 let birthMonth = 10 let countryCode = "PL" let gender = Gender.male var creatorRequest: NewCreatorRequest { return NewCreatorRequest(name: name, displayName: displayName, birthYear: birthYear, birthMonth: birthMonth, countryCode: countryCode, gender: gender) } it("Should have proper endpoint") { let request = creatorRequest expect(request.endpoint) == "creators" } it("Should have proper method") { let request = creatorRequest expect(request.method) == RequestMethod.post } it("Should have proper parameters") { let request = creatorRequest let params = request.parameters expect(params["name"] as? String) == name expect(params["display_name"] as? String) == displayName expect(params["birth_year"] as? Int) == birthYear expect(params["birth_month"] as? Int) == birthMonth expect(params["country"] as? String) == countryCode expect(params["gender"] as? Int) == gender.rawValue } } } }
mit
emilstahl/swift
stdlib/public/core/ArrayBuffer.swift
9
16801
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the class that implements the storage and object management for // Swift Array. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims internal typealias _ArrayBridgeStorage = _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCoreType> public struct _ArrayBuffer<Element> : _ArrayBufferType { /// Create an empty buffer. public init() { _storage = _ArrayBridgeStorage(native: _emptyArrayStorage) } public init(nsArray: _NSArrayCoreType) { _sanityCheck(_isClassOrObjCExistential(Element.self)) _storage = _ArrayBridgeStorage(objC: nsArray) } /// Returns an `_ArrayBuffer<U>` containing the same elements. /// /// - Requires: The elements actually have dynamic type `U`, and `U` /// is a class or `@objc` existential. @warn_unused_result func castToBufferOf<U>(_: U.Type) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) return _ArrayBuffer<U>(storage: _storage) } /// The spare bits that are set when a native array needs deferred /// element type checking. var deferredTypeCheckMask : Int { return 1 } /// Returns an `_ArrayBuffer<U>` containing the same elements, /// deffering checking each element's `U`-ness until it is accessed. /// /// - Requires: `U` is a class or `@objc` existential derived from `Element`. @warn_unused_result func downcastToBufferWithDeferredTypeCheckOf<U>( _: U.Type ) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) // FIXME: can't check that U is derived from Element pending // <rdar://problem/19915280> generic metatype casting doesn't work // _sanityCheck(U.self is Element.Type) return _ArrayBuffer<U>( storage: _ArrayBridgeStorage( native: _native._storage, bits: deferredTypeCheckMask)) } var needsElementTypeCheck: Bool { // NSArray's need an element typecheck when the element type isn't AnyObject return !_isNativeTypeChecked && !(AnyObject.self is Element.Type) } //===--- private --------------------------------------------------------===// internal init(storage: _ArrayBridgeStorage) { _storage = storage } internal var _storage: _ArrayBridgeStorage } extension _ArrayBuffer { /// Adopt the storage of `source`. public init(_ source: NativeBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") _storage = _ArrayBridgeStorage(native: source._storage) } var arrayPropertyIsNative : Bool { return _isNative } /// `true`, if the array is native and does not need a deferred type check. var arrayPropertyIsNativeTypeChecked : Bool { return _isNativeTypeChecked } /// Returns `true` iff this buffer's storage is uniquely-referenced. @warn_unused_result mutating func isUniquelyReferenced() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferenced_native_noSpareBits() } return _storage.isUniquelyReferencedNative() && _isNative } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. @warn_unused_result mutating func isUniquelyReferencedOrPinned() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferencedOrPinned_native_noSpareBits() } return _storage.isUniquelyReferencedOrPinnedNative() && _isNative } /// Convert to an NSArray. /// /// - Precondition: `_isBridgedToObjectiveC(Element.self)`. /// O(1) if the element type is bridged verbatim, O(N) otherwise. @warn_unused_result public func _asCocoaArray() -> _NSArrayCoreType { _sanityCheck( _isBridgedToObjectiveC(Element.self), "Array element type is not bridged to Objective-C") return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns `nil`. @warn_unused_result public mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { if _fastPath(isUniquelyReferenced()) { let b = _native if _fastPath(b.capacity >= minimumCapacity) { return b } } return nil } @warn_unused_result public mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } @warn_unused_result public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @warn_unused_result public func requestNativeBuffer() -> NativeBuffer? { if !_isClassOrObjCExistential(Element.self) { return _native } return _fastPath(_storage.isNative) ? _native : nil } // We have two versions of type check: one that takes a range and the other // checks one element. The reason for this is that the ARC optimizer does not // handle loops atm. and so can get blocked by the presence of a loop (over // the range). This loop is not necessary for a single element access. @inline(never) internal func _typeCheckSlowPath(index: Int) { if _fastPath(_isNative) { let element: AnyObject = castToBufferOf(AnyObject.self)._native[index] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { let ns = _nonNative _precondition( ns.objectAtIndex(index) is Element, "NSArray element failed to match the Swift Array Element type") } } func _typeCheck(subRange: Range<Int>) { if !_isClassOrObjCExistential(Element.self) { return } if _slowPath(needsElementTypeCheck) { // Could be sped up, e.g. by using // enumerateObjectsAtIndexes:options:usingBlock: in the // non-native case. for i in subRange { _typeCheckSlowPath(i) } } } /// Copy the given subRange of this buffer into uninitialized memory /// starting at target. Return a pointer past-the-end of the /// just-initialized memory. @inline(never) // The copy loop blocks retain release matching. public func _uninitializedCopy( subRange: Range<Int>, target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _typeCheck(subRange) if _fastPath(_isNative) { return _native._uninitializedCopy(subRange, target: target) } let nonNative = _nonNative let nsSubRange = SwiftShims._SwiftNSRange( location:subRange.startIndex, length: subRange.endIndex - subRange.startIndex) let buffer = UnsafeMutablePointer<AnyObject>(target) // Copies the references out of the NSArray without retaining them nonNative.getObjects(buffer, range: nsSubRange) // Make another pass to retain the copied objects var result = target for _ in subRange { result.initialize(result.memory) ++result } return result } /// Return a `_SliceBuffer` containing the given `subRange` of values /// from this buffer. public subscript(subRange: Range<Int>) -> _SliceBuffer<Element> { get { _typeCheck(subRange) if _fastPath(_isNative) { return _native[subRange] } // Look for contiguous storage in the NSArray let nonNative = self._nonNative let cocoa = _CocoaArrayWrapper(nonNative) let cocoaStorageBaseAddress = cocoa.contiguousStorage(self.indices) if cocoaStorageBaseAddress != nil { return _SliceBuffer( owner: nonNative, subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress), indices: subRange, hasNativeBuffer: false) } // No contiguous storage found; we must allocate let subRangeCount = subRange.count let result = _ContiguousArrayBuffer<Element>( count: subRangeCount, minimumCapacity: 0) // Tell Cocoa to copy the objects into our storage cocoa.buffer.getObjects( UnsafeMutablePointer(result.firstElementAddress), range: _SwiftNSRange( location: subRange.startIndex, length: subRangeCount)) return _SliceBuffer(result, shiftedToStartIndex: subRange.startIndex) } set { fatalError("not implemented") } } public var _unconditionalMutableSubscriptBaseAddress: UnsafeMutablePointer<Element> { _sanityCheck(_isNative, "must be a native buffer") return _native.firstElementAddress } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. public var firstElementAddress: UnsafeMutablePointer<Element> { if (_fastPath(_isNative)) { return _native.firstElementAddress } return nil } /// The number of elements the buffer stores. public var count: Int { @inline(__always) get { return _fastPath(_isNative) ? _native.count : _nonNative.count } set { _sanityCheck(_isNative, "attempting to update count of Cocoa array") _native.count = newValue } } /// Traps if an inout violation is detected or if the buffer is /// native and the subscript is out of range. /// /// wasNative == _isNative in the absence of inout violations. /// Because the optimizer can hoist the original check it might have /// been invalidated by illegal user code. internal func _checkInoutAndNativeBounds(index: Int, wasNative: Bool) { _precondition( _isNative == wasNative, "inout rules were violated: the array was overwritten") if _fastPath(wasNative) { _native._checkValidSubscript(index) } } // TODO: gyb this /// Traps if an inout violation is detected or if the buffer is /// native and typechecked and the subscript is out of range. /// /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of /// inout violations. Because the optimizer can hoist the original /// check it might have been invalidated by illegal user code. internal func _checkInoutAndNativeTypeCheckedBounds( index: Int, wasNativeTypeChecked: Bool ) { _precondition( _isNativeTypeChecked == wasNativeTypeChecked, "inout rules were violated: the array was overwritten") if _fastPath(wasNativeTypeChecked) { _native._checkValidSubscript(index) } } /// The number of elements the buffer can store without reallocation. public var capacity: Int { return _fastPath(_isNative) ? _native.capacity : _nonNative.count } @inline(__always) @warn_unused_result func getElement(i: Int, wasNativeTypeChecked: Bool) -> Element { if _fastPath(wasNativeTypeChecked) { return _nativeTypeChecked[i] } return unsafeBitCast(_getElementSlowPath(i), Element.self) } @inline(never) @warn_unused_result func _getElementSlowPath(i: Int) -> AnyObject { _sanityCheck( _isClassOrObjCExistential(Element.self), "Only single reference elements can be indexed here.") let element: AnyObject if _isNative { // _checkInoutAndNativeTypeCheckedBounds does no subscript // checking for the native un-typechecked case. Therefore we // have to do it here. _native._checkValidSubscript(i) element = castToBufferOf(AnyObject.self)._native[i] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { // ObjC arrays do their own subscript checking. element = _nonNative.objectAtIndex(i) _precondition( element is Element, "NSArray element failed to match the Swift Array Element type") } return element } /// Get or set the value of the ith element. public subscript(i: Int) -> Element { get { return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked) } nonmutating set { if _fastPath(_isNative) { _native[i] = newValue } else { var refCopy = self refCopy.replace( subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue)) } } } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. public func withUnsafeBufferPointer<R>( @noescape body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { if _fastPath(_isNative) { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } return try ContiguousArray(self).withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Requires: Such contiguous storage exists or the buffer is empty. public mutating func withUnsafeMutableBufferPointer<R>( @noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _sanityCheck( firstElementAddress != nil || count == 0, "Array is bridging an opaque NSArray; can't get a pointer to the elements" ) defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } /// An object that keeps the elements stored in this buffer alive. public var owner: AnyObject { return _fastPath(_isNative) ? _native._storage : _nonNative } /// An object that keeps the elements stored in this buffer alive. /// /// - Requires: This buffer is backed by a `_ContiguousArrayBuffer`. public var nativeOwner: AnyObject { _sanityCheck(_isNative, "Expect a native array") return _native._storage } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. public var identity: UnsafePointer<Void> { if _isNative { return _native.identity } else { return unsafeAddressOf(_nonNative) } } //===--- CollectionType conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Int { return count } //===--- private --------------------------------------------------------===// typealias Storage = _ContiguousArrayStorage<Element> public typealias NativeBuffer = _ContiguousArrayBuffer<Element> var _isNative: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNative } } /// `true`, if the array is native and does not need a deferred type check. var _isNativeTypeChecked: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask) } } /// Our native representation. /// /// - Requires: `_isNative`. var _native: NativeBuffer { return NativeBuffer( _isClassOrObjCExistential(Element.self) ? _storage.nativeInstance : _storage.nativeInstance_noSpareBits) } /// Fast access to the native representation. /// /// - Requires: `_isNativeTypeChecked`. var _nativeTypeChecked: NativeBuffer { return NativeBuffer(_storage.nativeInstance_noSpareBits) } var _nonNative: _NSArrayCoreType { @inline(__always) get { _sanityCheck(_isClassOrObjCExistential(Element.self)) return _storage.objCInstance } } } #endif
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/01765-swift-inflightdiagnostic-highlight.swift
1
507
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol c : C { typealias B : Int = b protocol C { class b: a { class A { return { c() } } } func g: T])) r
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/00866-swift-constraints-constraintgraph-addconstraint.swift
1
476
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck if true { print() { } func g<T.b : U : T] in self.b = c: P { struct c = { c()
apache-2.0
ephread/Instructions
Examples/Example/UI Tests/TransitionExampleTests.swift
1
2288
// Copyright (c) 2018-present Frédéric Maquin <fred@ephread.com> and contributors. // Licensed under the terms of the MIT License. import XCTest class TransitionExampleTests: XCTestCase { #if targetEnvironment(macCatalyst) #else let originalOrientation = XCUIDevice.shared.orientation #endif override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launchWithAnimationsDisabled() #if targetEnvironment(macCatalyst) #else XCUIDevice.shared.orientation = .portrait #endif } override func tearDown() { super.tearDown() #if targetEnvironment(macCatalyst) #else XCUIDevice.shared.orientation = originalOrientation #endif } func testTapThroughCutout() { let app = XCUIApplication() app.tables.staticTexts["Transitioning from code"].tap() let overlay = app.otherElements["AccessibilityIdentifiers.overlayView"] _ = overlay.waitForExistence(timeout: 10) let defaultCoordinates = app.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.1)) defaultCoordinates.tap() defaultCoordinates.tap() // One extra tap, to make sure touch is disabled at this point. defaultCoordinates.tap() let cutoutCoordinates = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) cutoutCoordinates.tap() defaultCoordinates.tap() defaultCoordinates.tap() defaultCoordinates.tap() app.navigationBars["Transition From Code"].buttons["Instructions"].tap() } func testTapThroughOverlay() { let app = XCUIApplication() app.tables.staticTexts["Transitioning from code"].tap() let overlay = app.otherElements["AccessibilityIdentifiers.overlayView"] _ = overlay.waitForExistence(timeout: 10) overlay.tap() let vector = CGVector(dx: 0.8, dy: 0.8) let coordinate = overlay.coordinate(withNormalizedOffset: vector) coordinate.tap() overlay.tap() overlay.tap() if app.navigationBars["Transition From Code"].buttons["Instructions"].isHittable { XCTFail("Back button should not be hittable.") } } }
mit
mmsaddam/TheMovie
Pods/Gloss/Sources/Operators.swift
2
12561
// // Operators.swift // Gloss // // Copyright (c) 2015 Harlan Kellaway // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: - Operator <~~ (Decode) /** Decode custom operator. */ infix operator <~~ { associativity left precedence 150 } /** Convenience operator for decoding JSON to generic value. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ <T>(key: String, json: JSON) -> T? { return Decoder.decode(key)(json) } /** Convenience operator for decoding JSON to Decodable object. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ <T: Decodable>(key: String, json: JSON) -> T? { return Decoder.decodeDecodable(key)(json) } /** Convenience operator for decoding JSON to array of Decodable objects. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ <T: Decodable>(key: String, json: JSON) -> [T]? { return Decoder.decodeDecodableArray(key)(json) } /** Convenience operator for decoding JSON to dictionary of String to Decodable. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ <T: Decodable>(key: String, json: JSON) -> [String : T]? { return Decoder.decodeDecodableDictionary(key)(json) } /** Convenience operator for decoding JSON to dictionary of String to Decodable array. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ <T: Decodable>(key: String, json: JSON) -> [String : [T]]? { return Decoder.decodeDecodableDictionary(key)(json) } /** Convenience operator for decoding JSON to enum value. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ <T: RawRepresentable>(key: String, json: JSON) -> T? { return Decoder.decodeEnum(key)(json) } /** Convenience operator for decoding JSON to array of enum values. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ <T: RawRepresentable>(key: String, json: JSON) -> [T]? { return Decoder.decodeEnumArray(key)(json) } /** Convenience operator for decoding JSON to Int32. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> Int32? { return Decoder.decodeInt32(key)(json) } /** Convenience operator for decoding JSON to Int32 array. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> [Int32]? { return Decoder.decodeInt32Array(key)(json) } /** Convenience operator for decoding JSON to UInt32. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> UInt32? { return Decoder.decodeUInt32(key)(json) } /** Convenience operator for decoding JSON to UInt32 array. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> [UInt32]? { return Decoder.decodeUInt32Array(key)(json) } /** Convenience operator for decoding JSON to Int64. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> Int64? { return Decoder.decodeInt64(key)(json) } /** Convenience operator for decoding JSON to Int64 array. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> [Int64]? { return Decoder.decodeInt64Array(key)(json) } /** Convenience operator for decoding JSON to UInt64. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> UInt64? { return Decoder.decodeUInt64(key)(json) } /** Convenience operator for decoding JSON to UInt64 array. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> [UInt64]? { return Decoder.decodeUInt64Array(key)(json) } /** Convenience operator for decoding JSON to URL. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> NSURL? { return Decoder.decodeURL(key)(json) } /** Convenience operator for decoding JSON to array of URLs. - parameter key: JSON key for value to decode. - parameter json: JSON. - returns: Decoded value when successful, nil otherwise. */ public func <~~ (key: String, json: JSON) -> [NSURL]? { return Decoder.decodeURLArray(key)(json) } // MARK: - Operator ~~> (Encode) /** Encode custom operator. */ infix operator ~~> { associativity left precedence 150 } /** Convenience operator for encoding generic value to JSON */ /** Convenience operator for encoding a generic value to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T>(key: String, property: T?) -> JSON? { return Encoder.encode(key)(property) } /** Convenience operator for encoding an array of generic values to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T>(key: String, property: [T]?) -> JSON? { return Encoder.encodeArray(key)(property) } /** Convenience operator for encoding an Encodable object to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T: Encodable>(key: String, property: T?) -> JSON? { return Encoder.encodeEncodable(key)(property) } /** Convenience operator for encoding an array of Encodable objects to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T: Encodable>(key: String, property: [T]?) -> JSON? { return Encoder.encodeEncodableArray(key)(property) } /** Convenience operator for encoding a dictionary of String to Encodable to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T: Encodable>(key: String, property: [String : T]?) -> JSON? { return Encoder.encodeEncodableDictionary(key)(property) } /** Convenience operator for encoding a dictionary of String to Encodable array to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T: Encodable>(key: String, property: [String : [T]]?) -> JSON? { return Encoder.encodeEncodableDictionary(key)(property) } /** Convenience operator for encoding an enum value to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T: RawRepresentable>(key: String, property: T?) -> JSON? { return Encoder.encodeEnum(key)(property) } /** Convenience operator for encoding an array of enum values to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> <T: RawRepresentable>(key: String, property: [T]?) -> JSON? { return Encoder.encodeEnumArray(key)(property) } /** Convenience operator for encoding an Int32 to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: Int32?) -> JSON? { return Encoder.encodeInt32(key)(property) } /** Convenience operator for encoding an Int32 array to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: [Int32]?) -> JSON? { return Encoder.encodeInt32Array(key)(property) } /** Convenience operator for encoding an UInt32 to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: UInt32?) -> JSON? { return Encoder.encodeUInt32(key)(property) } /** Convenience operator for encoding an UInt32 array to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: [UInt32]?) -> JSON? { return Encoder.encodeUInt32Array(key)(property) } /** Convenience operator for encoding an Int64 to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: Int64?) -> JSON? { return Encoder.encodeInt64(key)(property) } /** Convenience operator for encoding an Int64 array to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: [Int64]?) -> JSON? { return Encoder.encodeInt64Array(key)(property) } /** Convenience operator for encoding an UInt64 to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: UInt64?) -> JSON? { return Encoder.encodeUInt64(key)(property) } /** Convenience operator for encoding an UInt64 array to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: [UInt64]?) -> JSON? { return Encoder.encodeUInt64Array(key)(property) } /** Convenience operator for encoding a URL to JSON. - parameter key: JSON key for value to encode. - parameter property: Object to encode to JSON. - returns: JSON when successful, nil otherwise. */ public func ~~> (key: String, property: NSURL?) -> JSON? { return Encoder.encodeURL(key)(property) }
mit
dshahidehpour/IGListKit
Examples/Examples-tvOS/IGListKitExamples/SectionControllers/LabelSectionController.swift
4
1403
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import IGListKit final class LabelSectionController: IGListSectionController, IGListSectionType { var object: String? func numberOfItems() -> Int { return 1 } func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext!.dequeueReusableCell(of: LabelCell.self, for: self, at: index) as! LabelCell cell.label.text = object return cell } func didUpdate(to object: Any) { self.object = String(describing: object) } func didSelectItem(at index: Int) {} }
bsd-3-clause
machelix/ViewMonitor
Example/ViewMonitorExample/ViewMonitorExample/ViewController.swift
6
417
// // ViewController.swift // ViewMonitorExample // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
noppoMan/aws-sdk-swift
Sources/Soto/Services/S3Outposts/S3Outposts_API.swift
1
5021
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS S3Outposts service. Amazon S3 on Outposts provides access to S3 on Outposts operations. */ public struct S3Outposts: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the S3Outposts client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, service: "s3-outposts", serviceProtocol: .restjson, apiVersion: "2017-07-25", endpoint: endpoint, errorType: S3OutpostsErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// S3 on Outposts access points simplify managing data access at scale for shared datasets in Amazon S3 on Outposts. S3 on Outposts uses endpoints to connect to Outposts buckets so that you can perform actions within your virtual private cloud (VPC). This action creates an endpoint and associates it with the specified Outpost. Related actions include: DeleteEndpoint ListEndpoints public func createEndpoint(_ input: CreateEndpointRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateEndpointResult> { return self.client.execute(operation: "CreateEndpoint", path: "/S3Outposts/CreateEndpoint", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// S3 on Outposts access points simplify managing data access at scale for shared datasets in Amazon S3 on Outposts. S3 on Outposts uses endpoints to connect to Outposts buckets so that you can perform actions within your virtual private cloud (VPC). This action deletes an endpoint. Related actions include: CreateEndpoint ListEndpoints @discardableResult public func deleteEndpoint(_ input: DeleteEndpointRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteEndpoint", path: "/S3Outposts/DeleteEndpoint", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// S3 on Outposts access points simplify managing data access at scale for shared datasets in Amazon S3 on Outposts. S3 on Outposts uses endpoints to connect to Outposts buckets so that you can perform actions within your virtual private cloud (VPC). This action lists endpoints associated with the Outpost. Related actions include: CreateEndpoint DeleteEndpoint public func listEndpoints(_ input: ListEndpointsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListEndpointsResult> { return self.client.execute(operation: "ListEndpoints", path: "/S3Outposts/ListEndpoints", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension S3Outposts { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: S3Outposts, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
apache-2.0
TouchInstinct/LeadKit
Sources/Structures/DrawingOperations/PaddingDrawingOperation.swift
1
2163
// // Copyright (c) 2017 Touch Instinct // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the Software), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import CoreGraphics struct PaddingDrawingOperation: DrawingOperation { private let image: CGImage private let imageSize: CGSize private let padding: CGFloat public init(image: CGImage, imageSize: CGSize, padding: CGFloat) { self.image = image self.imageSize = imageSize self.padding = padding } public var contextSize: CGContextSize { let width = Int(ceil(imageSize.width + padding * 2)) let height = Int(ceil(imageSize.height + padding * 2)) return (width: width, height: height) } public func apply(in context: CGContext) { // Draw the image in the center of the context, leaving a gap around the edges let imageLocation = CGRect(x: padding, y: padding, width: imageSize.width, height: imageSize.height) context.addRect(imageLocation) context.clip() context.draw(image, in: imageLocation) } }
apache-2.0
kasimir-technology/AppReviewTimeMonitor
AppReviewTimeMonitorTests/AppReviewTimeMonitorTests.swift
1
1039
// // AppReviewTimeMonitorTests.swift // AppReviewTimeMonitorTests // // Created by Alexander Kasimir on 26/10/15. // Copyright © 2015 Alexander Kasimir. All rights reserved. // import XCTest @testable import AppReviewTimeMonitor class AppReviewTimeMonitorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
mac-cain13/DocumentStore
DocumentStore/Store/CommitAction.swift
1
537
// // CommitAction.swift // DocumentStore // // Created by Mathijs Kadijk on 07-11-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation extension DocumentStore { /// Action to take when the `ReadWriteTransaction` is completed. /// /// - saveChanges: Save the changes made /// - discardChanges: Discard any changes that have been made public enum CommitAction { /// Save the changes made case saveChanges /// Discard any changes that have been made case discardChanges } }
mit
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/PBMORTBBidRequestTest.swift
1
4725
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import XCTest class PBMORTBBidRequestTest: XCTestCase { func testCombinedProperties() { // PBMORTBBidRequest checkInt(PBMORTBBidRequest(), property: "tmax") // PBMORTBBanner checkInt(PBMORTBBanner(), property: "pos") // PBMORTBVideo checkInt(PBMORTBVideo(), property: "minduration") checkInt(PBMORTBVideo(), property: "maxduration") checkInt(PBMORTBVideo(), property: "w") checkInt(PBMORTBVideo(), property: "h") checkInt(PBMORTBVideo(), property: "startdelay") checkInt(PBMORTBVideo(), property: "minbitrate") checkInt(PBMORTBVideo(), property: "maxbitrate") // PBMORTBPmp checkInt(PBMORTBPmp(), property: "private_auction") // PBMORTBDeal checkInt(PBMORTBDeal(), property: "at") // PBMORTBApp checkInt(PBMORTBApp(), property: "privacypolicy") checkInt(PBMORTBApp(), property: "paid") // PBMORTBDevice checkInt(PBMORTBDevice(), property: "lmt") checkInt(PBMORTBDevice(), property: "devicetype") checkInt(PBMORTBDevice(), property: "h") checkInt(PBMORTBDevice(), property: "w") checkInt(PBMORTBDevice(), property: "ppi") checkDouble(PBMORTBDevice(), property: "pxratio") checkInt(PBMORTBDevice(), property: "js") checkInt(PBMORTBDevice(), property: "geofetch") checkInt(PBMORTBDevice(), property: "connectiontype") // PBMORTBGeo checkDouble(PBMORTBGeo(), property: "lat") checkDouble(PBMORTBGeo(), property: "lon") checkInt(PBMORTBGeo(), property: "type") checkInt(PBMORTBGeo(), property: "accuracy") checkInt(PBMORTBGeo(), property: "lastfix") checkInt(PBMORTBGeo(), property: "utcoffset") // PBMORTBUser checkInt(PBMORTBUser(), property: "yob") } // MARK: Test Function func checkInt(_ object: NSObject, property: String, file: StaticString = #file, line: UInt = #line) { check(object, property: property, testValues: [1, 2], file: file, line: line) } func checkDouble(_ object: NSObject, property: String, file: StaticString = #file, line: UInt = #line) { check(object, property: property, testValues: [1.1, 2.2], file: file, line: line) } func check<T: Comparable>(_ object: NSObject, property: String, typePrefix: String? = nil, testValues: [T], file: StaticString = #file, line: UInt = #line) { // Prepare var typedProperty = property if let type = typePrefix { typedProperty = type + String(property.first!).uppercased() + property.dropFirst() } XCTAssertEqual(testValues.count, 2, file: file, line: line) XCTAssertNotEqual(testValues[0], testValues[1], file: file, line: line) // Check the property existence XCTAssert(object.responds(to: Selector(property)), "There is no property \(property)", file: file, line: line) XCTAssert(object.responds(to: Selector(typedProperty)), "There is no property \(typedProperty)", file: file, line: line) // Default should be nil XCTAssertNil(object.value(forKey: property), file: file, line: line) XCTAssertNil(object.value(forKey: typedProperty), file: file, line: line) let v1 = testValues[0] object.setValue(v1, forKey: property) XCTAssertEqual(object.value(forKey: typedProperty) as! T , v1, file: file, line: line) let v2 = testValues[1] object.setValue(v2, forKey: typedProperty) XCTAssertEqual(object.value(forKey: property) as! T, v2, file: file, line: line) object.setValue(nil, forKey: property) XCTAssertNil(object.value(forKey: property), file: file, line: line) XCTAssertNil(object.value(forKey: typedProperty), file: file, line: line) } }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/12323-swift-diagnosticengine-diagnose.swift
11
249
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func<{ { } let a{ func i{ class b{ protocol B:d struct d<T where g:B{ protocol a
mit
radex/swift-compiler-crashes
crashes-duplicates/05019-swift-sourcemanager-getmessage.swift
11
204
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let end = [Void{ } { class case c,
mit
radex/swift-compiler-crashes
crashes-fuzzing/22359-swift-diagnosticengine-diagnose.swift
11
305
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B { let d{ struct B { let d{ protocol P { let t: String typealias e : e struct c { class A { var d { let d{ protocol P { class A
mit
swish-server/CommandLine
Tests/CommandLineTests/CommandLineTests.swift
1
808
import XCTest @testable import CommandLine class CommandLineTests: XCTestCase { func testRunCommand() { let runExpectation = expectation(description: "Run <ls> to see files in current directory.") let commandLine = CommandLine() let command = "/usr/bin/env" let arguments = [ "ls" ] let result = commandLine.execute(command, with: arguments) switch result { case .output(let output): runExpectation.fulfill() print(output) case .error(let message): print("Error: \(message)") } waitForExpectations(timeout: 1.0) } static var allTests : [(String, (CommandLineTests) -> () throws -> Void)] { return [ ("testRunCommand", testRunCommand), ] } }
apache-2.0
IBM-MIL/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Extensions/UIButtonExtension.swift
1
2055
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation import UIKit extension UIButton{ func setBackgroundColorForState(color: UIColor, forState: UIControlState){ self.setBackgroundImage(UIButton.imageWithColor(color, width: self.frame.size.width, height: self.frame.size.height), forState: forState) } /** Create an image of a given color - parameter color: The color that the image will have - parameter width: Width of the returned image - parameter height: Height of the returned image - returns: An image with the color, height and width */ private class func imageWithColor(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage { let rect = CGRect(x: 0, y: 0, width: width, height: height) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func setKernAttribute(size: CGFloat!){ let states = [UIControlState.Normal, UIControlState.Application, UIControlState.Disabled, UIControlState.Highlighted, UIControlState.Reserved, UIControlState.Selected] for state in states{ let titleColor = self.titleColorForState(state) var attributes : [String: AnyObject] if titleColor != nil { attributes = [NSKernAttributeName: size, NSForegroundColorAttributeName: titleColor!] }else{ attributes = [NSKernAttributeName: size] } let title = self.titleForState(state) if(title != nil){ self.setAttributedTitle(NSAttributedString(string: title!, attributes: attributes), forState: state) } } } }
epl-1.0
davidpaul0880/ChristiansSongs
christiansongs/BMAddTableViewController.swift
1
6766
// // BMAddTableViewController.swift // christiansongs // // Created by jijo on 3/11/15. // Copyright (c) 2015 jeesmon. All rights reserved. // import UIKit import CoreData class BMAddTableViewController: UITableViewController , FolderSelection{ var newBM : Dictionary<String, AnyObject>? var folder : Folder! var editingBookMark : BookMarks? @IBAction func cancelBM(sender: UIBarButtonItem?) { if editingBookMark != nil { self.navigationController?.popViewControllerAnimated(true); }else{ self.dismissViewControllerAnimated(true, completion: nil) } } @IBAction func saveBM(sender: UIBarButtonItem) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContextUserData! let entity1 = NSEntityDescription.entityForName("BookMarks", inManagedObjectContext: managedObjectContext) let newBMTemp = BookMarks(entity: entity1!, insertIntoManagedObjectContext: managedObjectContext) //managedObjectContext.insertObject(newBM!) newBMTemp.createddate = NSDate() newBMTemp.folder = self.folder! newBMTemp.songtitle = newBM!["songtitle"]! as! String newBMTemp.song_id = newBM!["song_id"]! as! NSNumber var error: NSError? do { try managedObjectContext.save() } catch let error1 as NSError { error = error1 } if let err = error { print("\(error)") } else { //("success") } self.cancelBM(nil) } func updatedBM(){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedObjectContext = appDelegate.managedObjectContextUserData! editingBookMark!.folder = self.folder var error: NSError? do { try managedObjectContext.save() } catch let error1 as NSError { error = error1 } if let _ = error { print("\(error)") } else { //("success") } self.cancelBM(nil) } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() if editingBookMark != nil { self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: Selector("updatedBM")) self.navigationItem.title = "Edit Bookmark" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var ident = "CellTitle" if indexPath.section == 1 { ident = "FolderCell" } let cell = tableView.dequeueReusableCellWithIdentifier(ident, forIndexPath: indexPath) if indexPath.section == 0 { if editingBookMark != nil { cell.textLabel?.text = editingBookMark!.songtitle }else{ cell.textLabel?.text = newBM!["songtitle"] as? String } }else{ cell.textLabel?.text = self.folder!.folder_label cell.imageView?.image = UIImage(named: "folder.png") cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. if segue.identifier == "SelectFolder" { let controller = segue.destinationViewController as! FolderSelectionTableViewController controller.delegate = self } } // MARK: protocol FolderSelection func folderSelected(selectedFolder : Folder) { self.folder = selectedFolder self.folder.lastaccessed = NSDate() self.tableView.reloadData() } }
gpl-2.0
madcato/LongPomo
LongPomo/Shared/Util/Date+now.swift
1
328
// // Date+now.swift // LongPomo // // Created by Daniel Vela on 01/03/2018. // Copyright © 2018 Daniel Vela. All rights reserved. // import Foundation /** Date class extension */ extension Date { /** Now - Returns: the current date and time */ static var now: Date { return Date() } }
mit
carlynorama/learningSwift
Playgrounds/SimpleInfoChecking_iOS10.playground/Contents.swift
1
2258
//Array, Dictionary Scratch Pad, Swift Xcode 8 Beta 6 //2016. 08 //carlynorama, license: CC0 //https://www.udemy.com/complete-ios-10-developer-course/ //https://developer.apple.com/reference/swift/dictionary //https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch import UIKit let stringVar:String? = nil stringVar ?? "a default string" // if string var is not nill return stringVar, else return default enum UserProfileError: Error { case UserNotFound case BadPass case NietherSupplied case OneNotSupplied } //SCOPE!!! These must be outside do to be used also by the catches. let enteredUser = "GeorgeJettson" let enteredPassword = "partparty" func checkUser(user: String, withPassword password: String) throws -> String { guard !password.isEmpty && !user.isEmpty else { throw UserProfileError.NietherSupplied } guard !password.isEmpty || !user.isEmpty else { throw UserProfileError.OneNotSupplied } var userVerified = Bool() var passwordVerified = Bool() if user == "GeorgeJettson" { userVerified = true; } else { userVerified = false } //if password == "partyparty" { passwordVerified = true } else { passwordVerified = false } //a >= 0 ? doThis(): doThat() password == "partyparty" ? (passwordVerified = true) : (passwordVerified = false) guard userVerified else { throw UserProfileError.UserNotFound } guard passwordVerified else { throw UserProfileError.BadPass } //let welcomeMessage = return "Welcome \(enteredUser). Please enjoy the show."} do { defer { print("Shutting the door.") } let verificationMessage = try checkUser(user: enteredUser, withPassword: enteredPassword) print(verificationMessage) //other stuff } catch UserProfileError.UserNotFound { print("I don't recognize you.") } catch UserProfileError.BadPass { let message = String(format: "I'm sorry %@ that password was not correct", enteredUser) print(message) } catch UserProfileError.NietherSupplied { print("I'm sorry I didn't hear anything") } catch UserProfileError.OneNotSupplied { print("I'm sorry, could you make sure you entered BOTH a username and password?") } catch { print("Something went wrong!") }
unlicense
jacobwhite/firefox-ios
Client/Frontend/Browser/FindInPageBar.swift
1
7136
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit protocol FindInPageBarDelegate: class { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) func findInPageDidPressClose(_ findInPage: FindInPageBar) } private struct FindInPageUX { static let ButtonColor = UIColor.black static let MatchCountColor = UIColor.lightGray static let MatchCountFont = UIConstants.DefaultChromeFont static let SearchTextColor = UIColor(rgb: 0xe66000) static let SearchTextFont = UIConstants.DefaultChromeFont static let TopBorderColor = UIColor(rgb: 0xEEEEEE) } class FindInPageBar: UIView { weak var delegate: FindInPageBarDelegate? fileprivate let searchText = UITextField() fileprivate let matchCountView = UILabel() fileprivate let previousButton = UIButton() fileprivate let nextButton = UIButton() var currentResult = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } } } var totalResults = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } previousButton.isEnabled = totalResults > 1 nextButton.isEnabled = previousButton.isEnabled } } var text: String? { get { return searchText.text } set { searchText.text = newValue didTextChange(searchText) } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white searchText.addTarget(self, action: #selector(didTextChange), for: .editingChanged) searchText.textColor = FindInPageUX.SearchTextColor searchText.font = FindInPageUX.SearchTextFont searchText.autocapitalizationType = .none searchText.autocorrectionType = .no searchText.inputAssistantItem.leadingBarButtonGroups = [] searchText.inputAssistantItem.trailingBarButtonGroups = [] searchText.enablesReturnKeyAutomatically = true searchText.returnKeyType = .search searchText.accessibilityIdentifier = "FindInPage.searchField" addSubview(searchText) matchCountView.textColor = FindInPageUX.MatchCountColor matchCountView.font = FindInPageUX.MatchCountFont matchCountView.isHidden = true matchCountView.accessibilityIdentifier = "FindInPage.matchCount" addSubview(matchCountView) previousButton.setImage(UIImage(named: "find_previous"), for: []) previousButton.setTitleColor(FindInPageUX.ButtonColor, for: []) previousButton.accessibilityLabel = NSLocalizedString("Previous in-page result", tableName: "FindInPage", comment: "Accessibility label for previous result button in Find in Page Toolbar.") previousButton.addTarget(self, action: #selector(didFindPrevious), for: .touchUpInside) previousButton.accessibilityIdentifier = "FindInPage.find_previous" addSubview(previousButton) nextButton.setImage(UIImage(named: "find_next"), for: []) nextButton.setTitleColor(FindInPageUX.ButtonColor, for: []) nextButton.accessibilityLabel = NSLocalizedString("Next in-page result", tableName: "FindInPage", comment: "Accessibility label for next result button in Find in Page Toolbar.") nextButton.addTarget(self, action: #selector(didFindNext), for: .touchUpInside) nextButton.accessibilityIdentifier = "FindInPage.find_next" addSubview(nextButton) let closeButton = UIButton() closeButton.setImage(UIImage(named: "find_close"), for: []) closeButton.setTitleColor(FindInPageUX.ButtonColor, for: []) closeButton.accessibilityLabel = NSLocalizedString("Done", tableName: "FindInPage", comment: "Done button in Find in Page Toolbar.") closeButton.addTarget(self, action: #selector(didPressClose), for: .touchUpInside) closeButton.accessibilityIdentifier = "FindInPage.close" addSubview(closeButton) let topBorder = UIView() topBorder.backgroundColor = FindInPageUX.TopBorderColor addSubview(topBorder) searchText.snp.makeConstraints { make in make.leading.top.bottom.equalTo(self).inset(UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)) } searchText.setContentHuggingPriority(.defaultLow, for: .horizontal) searchText.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) matchCountView.snp.makeConstraints { make in make.leading.equalTo(searchText.snp.trailing) make.centerY.equalTo(self) } matchCountView.setContentHuggingPriority(.defaultHigh, for: .horizontal) matchCountView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) previousButton.snp.makeConstraints { make in make.leading.equalTo(matchCountView.snp.trailing) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } nextButton.snp.makeConstraints { make in make.leading.equalTo(previousButton.snp.trailing) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } closeButton.snp.makeConstraints { make in make.leading.equalTo(nextButton.snp.trailing) make.size.equalTo(self.snp.height) make.trailing.centerY.equalTo(self) } topBorder.snp.makeConstraints { make in make.height.equalTo(1) make.left.right.top.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @discardableResult override func becomeFirstResponder() -> Bool { searchText.becomeFirstResponder() return super.becomeFirstResponder() } @objc fileprivate func didFindPrevious(_ sender: UIButton) { delegate?.findInPage(self, didFindPreviousWithText: searchText.text ?? "") } @objc fileprivate func didFindNext(_ sender: UIButton) { delegate?.findInPage(self, didFindNextWithText: searchText.text ?? "") } @objc fileprivate func didTextChange(_ sender: UITextField) { matchCountView.isHidden = searchText.text?.trimmingCharacters(in: .whitespaces).isEmpty ?? true delegate?.findInPage(self, didTextChange: searchText.text ?? "") } @objc fileprivate func didPressClose(_ sender: UIButton) { delegate?.findInPageDidPressClose(self) } }
mpl-2.0
AshuMishra/BMSLocationFinder
BMSLocationFinder/BMSLocationFinder/Helper/ENSideMenu.swift
1
10315
// // SideMenu.swift // SwiftSideMenu // // Created by Evgeny on 24.07.14. // Copyright (c) 2014 Evgeny Nazarov. All rights reserved. // import UIKit @objc public protocol ENSideMenuDelegate { optional func sideMenuWillOpen() optional func sideMenuWillClose() optional func sideMenuShouldOpenSideMenu () -> Bool } @objc public protocol ENSideMenuProtocol { var sideMenu : ENSideMenu? { get } func setContentViewController(contentViewController: UIViewController) } public enum ENSideMenuAnimation : Int { case None case Default } public enum ENSideMenuPosition : Int { case Left case Right } public extension UIViewController { public func toggleSideMenuView () { sideMenuController()?.sideMenu?.toggleMenu() } public func hideSideMenuView () { sideMenuController()?.sideMenu?.hideSideMenu() } public func showSideMenuView () { sideMenuController()?.sideMenu?.showSideMenu() } public func sideMenuController () -> ENSideMenuProtocol? { var iteration : UIViewController? = self.parentViewController if (iteration == nil) { return topMostController() } do { if (iteration is ENSideMenuProtocol) { return iteration as? ENSideMenuProtocol } else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) { iteration = iteration!.parentViewController; } else { iteration = nil; } } while (iteration != nil) return iteration as? ENSideMenuProtocol } internal func topMostController () -> ENSideMenuProtocol? { var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController while (topController?.presentedViewController is ENSideMenuProtocol) { topController = topController?.presentedViewController; } return topController as? ENSideMenuProtocol } } public class ENSideMenu : NSObject { public var menuWidth : CGFloat = 160.0 { didSet { needUpdateApperance = true updateFrame() } } private let menuPosition:ENSideMenuPosition = .Left public var bouncingEnabled :Bool = true private let sideMenuContainerView = UIView() private var menuTableViewController : UITableViewController! private var animator : UIDynamicAnimator! private let sourceView : UIView! private var needUpdateApperance : Bool = false public weak var delegate : ENSideMenuDelegate? private var isMenuOpen : Bool = false public init(sourceView: UIView, menuPosition: ENSideMenuPosition) { super.init() self.sourceView = sourceView self.menuPosition = menuPosition self.setupMenuView() animator = UIDynamicAnimator(referenceView:sourceView) // Add right swipe gesture recognizer let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:") rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right sourceView.addGestureRecognizer(rightSwipeGestureRecognizer) // Add left swipe gesture recognizer let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:") leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left if (menuPosition == .Left) { sourceView.addGestureRecognizer(rightSwipeGestureRecognizer) sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer) } else { sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer) sourceView.addGestureRecognizer(leftSwipeGestureRecognizer) } } public convenience init(sourceView: UIView, menuTableViewController: UITableViewController, menuPosition: ENSideMenuPosition) { self.init(sourceView: sourceView, menuPosition: menuPosition) self.menuTableViewController = menuTableViewController self.menuTableViewController.tableView.frame = sideMenuContainerView.bounds self.menuTableViewController.tableView.autoresizingMask = .FlexibleHeight | .FlexibleWidth sideMenuContainerView.addSubview(self.menuTableViewController.tableView) } private func updateFrame() { let menuFrame = CGRectMake( (menuPosition == .Left) ? isMenuOpen ? 0 : -menuWidth-1.0 : isMenuOpen ? sourceView.frame.size.width - menuWidth : sourceView.frame.size.width+1.0, sourceView.frame.origin.y, menuWidth, sourceView.frame.size.height ) sideMenuContainerView.frame = menuFrame } private func setupMenuView() { // Configure side menu container updateFrame() sideMenuContainerView.backgroundColor = UIColor.clearColor() sideMenuContainerView.clipsToBounds = false sideMenuContainerView.layer.masksToBounds = false; sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0); sideMenuContainerView.layer.shadowRadius = 1.0; sideMenuContainerView.layer.shadowOpacity = 0.125; sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath sourceView.addSubview(sideMenuContainerView) if (NSClassFromString("UIVisualEffectView") != nil) { // Add blur view var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView visualEffectView.frame = sideMenuContainerView.bounds visualEffectView.autoresizingMask = .FlexibleHeight | .FlexibleWidth sideMenuContainerView.addSubview(visualEffectView) } else { // TODO: add blur for ios 7 } } private func toggleMenu (shouldOpen: Bool) { if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) { return; } updateSideMenuApperanceIfNeeded() isMenuOpen = shouldOpen if (bouncingEnabled) { animator.removeAllBehaviors() var gravityDirectionX: CGFloat var pushMagnitude: CGFloat var boundaryPointX: CGFloat var boundaryPointY: CGFloat if (menuPosition == .Left) { // Left side menu gravityDirectionX = (shouldOpen) ? 4 : -4 pushMagnitude = (shouldOpen) ? 20 : -20 boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2 boundaryPointY = 20 } else { // Right side menu gravityDirectionX = (shouldOpen) ? -1 : 1 pushMagnitude = (shouldOpen) ? -20 : 20 boundaryPointX = (shouldOpen) ? sourceView.frame.size.width-menuWidth : sourceView.frame.size.width+menuWidth+2 boundaryPointY = -20 } let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView]) gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0) animator.addBehavior(gravityBehavior) let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView]) collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY), toPoint: CGPointMake(boundaryPointX, sourceView.frame.size.height)) animator.addBehavior(collisionBehavior) let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous) pushBehavior.magnitude = pushMagnitude animator.addBehavior(pushBehavior) let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView]) menuViewBehavior.elasticity = 0.25 animator.addBehavior(menuViewBehavior) } else { var destFrame :CGRect if (menuPosition == .Left) { destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, sideMenuContainerView.frame.size.height) } else { destFrame = CGRectMake((shouldOpen) ? sourceView.frame.size.width-menuWidth : sourceView.frame.size.width+2.0, 0, menuWidth, sideMenuContainerView.frame.size.height) } UIView.animateWithDuration(0.4, animations: { () -> Void in self.sideMenuContainerView.frame = destFrame }) } if (shouldOpen) { delegate?.sideMenuWillOpen?() } else { delegate?.sideMenuWillClose?() } } internal func handleGesture(gesture: UISwipeGestureRecognizer) { toggleMenu((self.menuPosition == .Right && gesture.direction == .Left) || (self.menuPosition == .Left && gesture.direction == .Right)) } private func updateSideMenuApperanceIfNeeded () { if (needUpdateApperance) { var frame = sideMenuContainerView.frame frame.size.width = menuWidth sideMenuContainerView.frame = frame sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath needUpdateApperance = false } } public func toggleMenu () { if (isMenuOpen) { toggleMenu(false) } else { updateSideMenuApperanceIfNeeded() toggleMenu(true) } } public func showSideMenu () { if (!isMenuOpen) { toggleMenu(true) } } public func hideSideMenu () { if (isMenuOpen) { toggleMenu(false) } } }
mit
ylovesy/CodeFun
wuzhentao/findDisappeardNumbers.swift
1
460
class Solution { //正负号标记法 func findDisappearedNumbers(_ nums: [Int]) -> [Int] { var tmp = nums; var arr: [Int] = [] for i in 0..<tmp.count { let index = abs(tmp[i]) - 1 if tmp[index] > 0 { tmp[index] *= -1 } } for i in 0..<tmp.count { if tmp[i] > 0 { arr.append(i+1) } } return arr; } }
apache-2.0
victorpimentel/SwiftLint
Source/SwiftLintFramework/Rules/ImplicitReturnRule.swift
2
3187
// // ImplicitReturnRule.swift // SwiftLint // // Created by Marcelo Fabri on 04/30/17. // Copyright © 2017 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct ImplicitReturnRule: ConfigurationProviderRule, CorrectableRule, OptInRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "implicit_return", name: "Implicit Return", description: "Prefer implicit returns in closures.", nonTriggeringExamples: [ "foo.map { $0 + 1 }", "foo.map({ $0 + 1 })", "foo.map { value in value + 1 }", "func foo() -> Int {\n return 0\n}", "if foo {\n return 0\n}", "var foo: Bool { return true }" ], triggeringExamples: [ "foo.map { value in\n ↓return value + 1\n}", "foo.map {\n ↓return $0 + 1\n}" ], corrections: [ "foo.map { value in\n ↓return value + 1\n}": "foo.map { value in\n value + 1\n}", "foo.map {\n ↓return $0 + 1\n}": "foo.map {\n $0 + 1\n}" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(in: file).flatMap { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } public func correct(file: File) -> [Correction] { let violatingRanges = file.ruleEnabled(violatingRanges: self.violationRanges(in: file), for: self) var correctedContents = file.contents var adjustedLocations = [Int]() for violatingRange in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents.replacingCharacters(in: indexRange, with: "") adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } private func violationRanges(in file: File) -> [NSRange] { let pattern = "(?:\\bin|\\{)\\s+(return\\s+)" let contents = file.contents.bridge() return file.matchesAndSyntaxKinds(matching: pattern).flatMap { result, kinds in let range = result.range guard kinds == [.keyword, .keyword] || kinds == [.keyword], let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length), let outerKind = file.structure.kinds(forByteOffset: byteRange.location).last, SwiftExpressionKind(rawValue: outerKind.kind) == .call else { return nil } return result.rangeAt(1) } } }
mit
PedroTrujilloV/TIY-Assignments
37--Resurgence/VenuesMenuQuadrat/VenuesMenuQuadrat/AppDelegate.swift
1
6821
// // AppDelegate.swift // VenuesMenuQuadrat // // Created by Pedro Trujillo on 11/26/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit import CoreData import QuadratTouch @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let client = Client(clientID: "OA5RPW0Y4AHZ0EPBIMXRNOSJQGAM0IFCKY11KEBGWIUK4L2A", clientSecret: "WK3N22CGBLPEM3B5OKELM2JNI4ISXOGAIAAKLVLYZ0QVXP3D", redirectURL: "testapp123://foursquare") var configuration = Configuration(client:client) configuration.mode = "foursquare" // or "swarm" configuration.shouldControllNetworkActivityIndicator = true Session.setupSharedSessionWithConfiguration(configuration) return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return Session.sharedSession().handleURL(url) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.tiy.VenuesMenuQuadrat" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("VenuesMenuQuadrat", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
cc0-1.0
haranicle/RealmRelationsSample
RealmRelationsSample/Person.swift
1
435
// // Person.swift // RealmRelationsSample // // Created by haranicle on 2015/02/27. // Copyright (c) 2015年 haranicle. All rights reserved. // import Realm class Person: RLMObject { dynamic var name = "" dynamic var age = 0 dynamic var face = Face() dynamic var sushi = RLMArray(objectClassName: "Sushi") dynamic var company = Company() dynamic var friends = RLMArray(objectClassName: "OtherPerson") }
mit
whiteshadow-gr/HatForIOS
HATTests/Services Tests/HATFileServiceTests.swift
1
16128
// /** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ import Alamofire import Mockingjay import SwiftyJSON import XCTest internal class HATFileServiceTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSearchFiles() { let body: [Dictionary<String, Any>] = [[ "fileId": "iphonerumpelphoto", "name": "rumpelPhoto", "source": "iPhone", "dateCreated": "2017-11-05T10:40:44.527Z", "lastUpdated": "2017-11-05T10:40:44.527Z", "tags": [ "iphone", "viewer", "photo" ], "status": [ "size": 4752033, "status": "Completed" ], "contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868", "contentPublic": false, "permissions": [ [ "userId": "de35e18d-147f-4664-8de7-409abf881754", "contentReadable": true ] ] ]] let userDomain: String = "testing.hubat.net" let urlToConnect: String = "https://testing.hubat.net/api/v2.6/files/search" let expectationTest: XCTestExpectation = expectation(description: "Searching files for photos...") MockingjayProtocol.addStub(matcher: http(.post, uri: urlToConnect), builder: json(body)) func completion(profileImages: [HATFileUpload], newToken: String?) { XCTAssertTrue(!profileImages.isEmpty) expectationTest.fulfill() } func failed(error: HATError) { XCTFail() expectationTest.fulfill() } HATFileService.searchFiles(userDomain: userDomain, token: "", successCallback: completion, errorCallBack: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } func testDeleteFile() { let body: [Dictionary<String, Any>] = [] let userDomain: String = "testing.hubat.net" let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/file/1)" let expectationTest: XCTestExpectation = expectation(description: "Deleting files from photos...") MockingjayProtocol.addStub(matcher: everything, builder: json(body)) func completion(result: Bool, newToken: String?) { XCTAssertTrue(result) expectationTest.fulfill() } func failed(error: HATError) { XCTFail() expectationTest.fulfill() } HATFileService.deleteFile(fileID: "1", token: "", userDomain: userDomain, successCallback: completion, errorCallBack: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } func testMakeFilePublic() { let body: [Dictionary<String, Any>] = [] let userDomain: String = "testing.hubat.net" let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/allowAccessPublic/1" let expectationTest: XCTestExpectation = expectation(description: "Making file Public...") MockingjayProtocol.addStub(matcher: http(.get, uri: urlToConnect), builder: json(body)) func completion(result: Bool) { XCTAssertTrue(result) expectationTest.fulfill() } func failed(error: HATError) { XCTFail() expectationTest.fulfill() } HATFileService.makeFilePublic(fileID: "1", token: "", userDomain: userDomain, successCallback: completion, errorCallBack: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } func testMakeFilePrivate() { let body: [Dictionary<String, Any>] = [] let userDomain: String = "testing.hubat.net" let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/restrictAccessPublic/1" let expectationTest: XCTestExpectation = expectation(description: "Making file Private...") MockingjayProtocol.addStub(matcher: http(.get, uri: urlToConnect), builder: json(body)) func completion(result: Bool) { XCTAssertTrue(result) expectationTest.fulfill() } func failed(error: HATError) { XCTFail() expectationTest.fulfill() } HATFileService.makeFilePrivate(fileID: "1", token: "", userDomain: userDomain, successCallback: completion, errorCallBack: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } func testMarkUploadedFileAsComplete() { let body: Dictionary<String, Any> = [ "fileId": "iphonerumpelphoto", "name": "rumpelPhoto", "source": "iPhone", "dateCreated": "2017-11-05T10:40:44.527Z", "lastUpdated": "2017-11-05T10:40:44.527Z", "tags": [ "iphone", "viewer", "photo" ], "status": [ "size": 4752033, "status": "Completed" ], "contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868", "contentPublic": false, "permissions": [ [ "userId": "de35e18d-147f-4664-8de7-409abf881754", "contentReadable": true ] ] ] let userDomain: String = "testing.hubat.net" let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/file/1/complete" let expectationTest: XCTestExpectation = expectation(description: "Marking up file as completed for photos...") MockingjayProtocol.addStub(matcher: http(.put, uri: urlToConnect), builder: json(body)) func completion(file: HATFileUpload, newToken: String?) { XCTAssertTrue(file.status.status == "Completed") expectationTest.fulfill() } func failed(error: HATTableError) { XCTFail() expectationTest.fulfill() } HATFileService.completeUploadFileToHAT(fileID: "1", token: "", tags: [], userDomain: userDomain, completion: completion, errorCallback: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } func testUploadFile() { let body: Dictionary<String, Any> = [ "fileId": "iphonerumpelphoto", "name": "rumpelPhoto", "source": "iPhone", "dateCreated": "2017-11-05T10:40:44.527Z", "lastUpdated": "2017-11-05T10:40:44.527Z", "tags": [ "iphone", "viewer", "photo" ], "status": [ "size": 4752033, "status": "Completed" ], "contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868", "contentPublic": false, "permissions": [ [ "userId": "de35e18d-147f-4664-8de7-409abf881754", "contentReadable": true ] ] ] let userDomain: String = "testing.hubat.net" let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/upload" let expectationTest: XCTestExpectation = expectation(description: "Upload file to HAT...") MockingjayProtocol.addStub(matcher: http(.post, uri: urlToConnect), builder: json(body)) func completion(file: HATFileUpload, newToken: String?) { XCTAssertTrue(file.status.status == "Completed") expectationTest.fulfill() } func failed(error: HATTableError) { XCTFail() expectationTest.fulfill() } HATFileService.uploadFileToHAT(fileName: "test", token: "", userDomain: userDomain, tags: [], completion: completion, errorCallback: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } func testUpdateParameters() { let body: Dictionary<String, Any> = [ "fileId": "iphonerumpelphoto", "name": "rumpelPhoto", "source": "iPhone", "dateCreated": "2017-11-05T10:40:44.527Z", "lastUpdated": "2017-11-05T10:40:44.527Z", "tags": [ "iphone", "viewer", "photo" ], "status": [ "size": 4752033, "status": "Completed" ], "contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868", "contentPublic": false, "permissions": [ [ "userId": "de35e18d-147f-4664-8de7-409abf881754", "contentReadable": true ] ] ] let userDomain: String = "testing.hubat.net" let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/file/1" let expectationTest: XCTestExpectation = expectation(description: "Updating parameters of a file from HAT...") MockingjayProtocol.addStub(matcher: http(.put, uri: urlToConnect), builder: json(body)) func completion(file: HATFileUpload, newToken: String?) { XCTAssertTrue(file.status.status == "Completed") expectationTest.fulfill() } func failed(error: HATTableError) { XCTFail() expectationTest.fulfill() } HATFileService.updateParametersOfFile(fileID: "1", fileName: "test", token: "", userDomain: userDomain, tags: [], completion: completion, errorCallback: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } @available(iOS 10.0, *) func testUploadToHATWrapper() { let body: Dictionary<String, Any> = [ "fileId": "iphonerumpelphoto", "name": "rumpelPhoto", "source": "iPhone", "dateCreated": "2017-11-05T10:40:44.527Z", "lastUpdated": "2017-11-05T10:40:44.527Z", "tags": [ "iphone", "viewer", "photo" ], "status": [ "size": 4752033, "status": "Completed" ], "contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868", "contentPublic": false, "permissions": [ [ "userId": "de35e18d-147f-4664-8de7-409abf881754", "contentReadable": true ] ] ] let userDomain: String = "testing.hubat.net" let expectationTest: XCTestExpectation = expectation(description: "Updating parameters of a file from HAT...") MockingjayProtocol.addStub(matcher: everything, builder: json(body)) func completion(file: HATFileUpload, newToken: String?) { XCTAssertTrue(file.status.status == "Completed") expectationTest.fulfill() } func failed(error: HATTableError) { XCTFail() expectationTest.fulfill() } let renderer: UIGraphicsImageRenderer = UIGraphicsImageRenderer(size: CGSize(width: 25, height: 25)) let image: UIImage = renderer.image { ctx in ctx.cgContext.setFillColor(UIColor.red.cgColor) ctx.cgContext.setStrokeColor(UIColor.green.cgColor) ctx.cgContext.setLineWidth(10) let rectangle: CGRect = CGRect(x: 0, y: 0, width: 25, height: 25) ctx.cgContext.addEllipse(in: rectangle) ctx.cgContext.drawPath(using: .fillStroke) } HATFileService.uploadFileToHATWrapper(token: "", userDomain: userDomain, fileToUpload: image, tags: [], progressUpdater: nil, completion: completion, errorCallBack: failed) waitForExpectations(timeout: 10) { error in if let error: Error = error { print("Error: \(error.localizedDescription)") } } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mpl-2.0
neiltest/neil_test_ios
neil_test_iosTests/neil_test_iosTests.swift
2
909
// // neil_test_iosTests.swift // neil_test_iosTests // // Created by weini on 15/3/26. // Copyright (c) 2015年 weini. All rights reserved. // import UIKit import XCTest class neil_test_iosTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
apache-2.0
Jitsusama/UInt128
Tests/UInt128Tests/UInt128Tests.swift
1
44977
// // UInt128UnitTests.swift // // UInt128 unit test cases. // // Copyright 2016 Joel Gerber // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest // Import UInt128 module and mark as testable so we can, y'know, test it. @testable import UInt128 // A UInt128 with a decently complicated bit pattern let bizarreUInt128 = UInt128("0xf1f3f5f7f9fbfdfffefcfaf0f8f6f4f2")! /// User tests that act as a basic smoke test on library functionality. class SystemTests : XCTestCase { func testCanReceiveAnInt() { let expectedResult = UInt128(upperBits: 0, lowerBits: 1) let testResult = UInt128(Int(1)) XCTAssertEqual(testResult, expectedResult) } func testCanBeSentToAnInt() { let expectedResult: Int = 1 let testResult = Int(UInt128(upperBits: 0, lowerBits: 1)) XCTAssertEqual(testResult, expectedResult) } func testIntegerLiteralInput() { let expectedResult = UInt128(upperBits: 0, lowerBits: 1) let testResult: UInt128 = 1 XCTAssertEqual(testResult, expectedResult) } func testCanReceiveAString() { let expectedResult = UInt128(upperBits: 0, lowerBits: 1) let testResult = UInt128(String("1")) XCTAssertEqual(testResult, expectedResult) } func testStringLiteralInput() { let expectedResult = UInt128(upperBits: 0, lowerBits: 1) let testResult = UInt128("1") XCTAssertEqual(testResult, expectedResult) } func testCanBeSentToAFloat() { let expectedResult: Float = 1 let testResult = Float(UInt128(upperBits: 0, lowerBits: 1)) XCTAssertEqual(testResult, expectedResult) } } /// Test properties and methods that are not tied to protocol conformance. class BaseTypeTests : XCTestCase { func testSignificantBitsReturnsProperBitCount() { var tests = [(input: UInt128(), expected: UInt128(upperBits: 0, lowerBits: 0))] tests.append((input: UInt128(upperBits: 0, lowerBits: 1), expected: UInt128(upperBits: 0, lowerBits: 1))) tests.append((input: UInt128(upperBits: 0, lowerBits: UInt64.max), expected: UInt128(upperBits: 0, lowerBits: 64))) tests.append((input: UInt128.max, expected: UInt128(upperBits: 0, lowerBits: 128))) tests.forEach { test in XCTAssertEqual(test.input.significantBits, test.expected) } } func testDesignatedInitializerProperlySetsInternalValue() { var tests = [(input: (upperBits: UInt64.min, lowerBits: UInt64.min), output: (upperBits: UInt64.min, lowerBits: UInt64.min))] tests.append((input: (upperBits: UInt64.max, lowerBits: UInt64.max), output: (upperBits: UInt64.max, lowerBits: UInt64.max))) tests.forEach { test in let result = UInt128(upperBits: test.input.upperBits, lowerBits: test.input.lowerBits) XCTAssertEqual(result.value.upperBits, test.output.upperBits) XCTAssertEqual(result.value.lowerBits, test.output.lowerBits) } } func testDefaultInitializerSetsUpperAndLowerBitsToZero() { let result = UInt128() XCTAssertEqual(result.value.upperBits, 0) XCTAssertEqual(result.value.lowerBits, 0) } func testInitWithUInt128() { var tests = [UInt128()] tests.append(UInt128(upperBits: 0, lowerBits: 1)) tests.append(UInt128(upperBits: 0, lowerBits: UInt64.max)) tests.append(UInt128.max) tests.forEach { test in XCTAssertEqual(UInt128(test), test) } } func testStringInitializerWithEmptyString() { XCTAssertNil(UInt128("" as String)) } func testStringInitializerWithSupportedNumberFormats() { var tests = ["0b2"] tests.append("0o8") tests.append("0xG") tests.forEach { test in XCTAssertNil(UInt128(test)) } } } class FixedWidthIntegerTests : XCTestCase { func testNonzeroBitCount() { var tests = [(input: UInt128.min, result: 0)] tests.append((input: UInt128(1), result: 1)) tests.append((input: UInt128(3), result: 2)) tests.append((input: UInt128(UInt64.max), result: 64)) tests.append((input: UInt128(upperBits: 1, lowerBits: 0), result: 1)) tests.append((input: UInt128(upperBits: 3, lowerBits: 0), result: 2)) tests.append((input: UInt128.max, result: 128)) tests.forEach { test in XCTAssertEqual(test.input.nonzeroBitCount, test.result) } } func testLeadingZeroBitCount() { var tests = [(input: UInt128.min, result: 128)] tests.append((input: UInt128(1), result: 127)) tests.append((input: UInt128(UInt64.max), result: 64)) tests.append((input: UInt128(upperBits: 1, lowerBits: 0), result: 63)) tests.append((input: UInt128.max, result: 0)) tests.forEach { test in XCTAssertEqual(test.input.leadingZeroBitCount, test.result) } } func endianTests() -> [(input: UInt128, byteSwapped: UInt128)] { var tests = [(input: UInt128(), byteSwapped: UInt128())] tests.append((input: UInt128(1), byteSwapped: UInt128(upperBits: 72057594037927936, lowerBits: 0))) tests.append((input: UInt128(upperBits: 17434549027881090559, lowerBits: 18373836492640810226), byteSwapped: UInt128(upperBits: 17506889200551263486, lowerBits: 18446176699804939249))) return tests } func testBigEndianProperty() { endianTests().forEach { test in #if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64) let expectedResult = test.byteSwapped #else let expectedResult = test.input #endif XCTAssertEqual(test.input.bigEndian, expectedResult) } } func testBigEndianInitializer() { endianTests().forEach { test in #if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64) let expectedResult = test.byteSwapped #else let expectedResult = test.input #endif XCTAssertEqual(UInt128(bigEndian: test.input), expectedResult) } } func testLittleEndianProperty() { endianTests().forEach { test in #if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64) let expectedResult = test.input #else let expectedResult = test.byteSwapped #endif XCTAssertEqual(test.input.littleEndian, expectedResult) } } func testLittleEndianInitializer() { endianTests().forEach { test in #if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64) let expectedResult = test.input #else let expectedResult = test.byteSwapped #endif XCTAssertEqual(UInt128(littleEndian: test.input), expectedResult) } } func testByteSwappedProperty() { endianTests().forEach { test in XCTAssertEqual(test.input.byteSwapped, test.byteSwapped) } } func testInitWithTruncatingBits() { let testResult = UInt128(_truncatingBits: UInt.max) XCTAssertEqual(testResult, UInt128(upperBits: 0, lowerBits: UInt64(UInt.max))) } func testAddingReportingOverflow() { // 0 + 0 = 0 var tests = [(augend: UInt128.min, addend: UInt128.min, sum: (partialValue: UInt128.min, overflow: false))] // UInt128.max + 0 = UInt128.max tests.append((augend: UInt128.max, addend: UInt128.min, sum: (partialValue: UInt128.max, overflow: false))) // UInt128.max + 1 = 0, with overflow tests.append((augend: UInt128.max, addend: UInt128(1), sum: (partialValue: UInt128.min, overflow: true))) // UInt128.max + 2 = 1, with overflow tests.append((augend: UInt128.max, addend: UInt128(2), sum: (partialValue: UInt128(1), overflow: true))) // UInt64.max + 1 = UInt64.max + 1 tests.append((augend: UInt128(UInt64.max), addend: UInt128(1), sum: (partialValue: UInt128(upperBits: 1, lowerBits: 0), overflow: false))) tests.forEach { test in let sum = test.augend.addingReportingOverflow(test.addend) XCTAssertEqual(sum.partialValue, test.sum.partialValue) XCTAssertEqual(sum.overflow, test.sum.overflow) } } func testSubtractingReportingOverflow() { // 0 - 0 = 0 var tests = [(minuend: UInt128.min, subtrahend: UInt128.min, difference: (partialValue: UInt128.min, overflow: false))] // Uint128.max - 0 = UInt128.max tests.append((minuend: UInt128.max, subtrahend: UInt128.min, difference: (partialValue: UInt128.max, overflow: false))) // UInt128.max - 1 = UInt128.max - 1 tests.append((minuend: UInt128.max, subtrahend: UInt128(1), difference: (partialValue: UInt128(upperBits: UInt64.max, lowerBits: (UInt64.max >> 1) << 1), overflow: false))) // UInt64.max + 1 - 1 = UInt64.max tests.append((minuend: UInt128(upperBits: 1, lowerBits: 0), subtrahend: UInt128(1), difference: (partialValue: UInt128(UInt64.max), overflow: false))) // 0 - 1 = UInt128.max, with overflow tests.append((minuend: UInt128.min, subtrahend: UInt128(1), difference: (partialValue: UInt128.max, overflow: true))) // 0 - 2 = UInt128.max - 1, with overflow tests.append((minuend: UInt128.min, subtrahend: UInt128(2), difference: (partialValue: (UInt128.max >> 1) << 1, overflow: true))) tests.forEach { test in let difference = test.minuend.subtractingReportingOverflow(test.subtrahend) XCTAssertEqual(difference.partialValue, test.difference.partialValue) XCTAssertEqual(difference.overflow, test.difference.overflow) } } func testMultipliedReportingOverflow() { // 0 * 0 = 0 var tests = [(multiplier: UInt128.min, multiplicator: UInt128.min, product: (partialValue: UInt128.min, overflow: false))] // UInt64.max * UInt64.max = UInt128.max - UInt64.max - 1 tests.append((multiplier: UInt128(UInt64.max), multiplicator: UInt128(UInt64.max), product: (partialValue: UInt128(upperBits: (UInt64.max >> 1) << 1, lowerBits: 1), overflow: false))) // UInt128.max * 0 = 0 tests.append((multiplier: UInt128.max, multiplicator: UInt128.min, product: (partialValue: UInt128.min, overflow: false))) // UInt128.max * 1 = UInt128.max tests.append((multiplier: UInt128.max, multiplicator: UInt128(1), product: (partialValue: UInt128.max, overflow: false))) // UInt128.max * 2 = UInt128.max - 1, with overflow tests.append((multiplier: UInt128.max, multiplicator: UInt128(2), product: (partialValue: (UInt128.max >> 1) << 1, overflow: true))) // UInt128.max * UInt128.max = 1, with overflow tests.append((multiplier: UInt128.max, multiplicator: UInt128.max, product: (partialValue: UInt128(1), overflow: true))) tests.forEach { test in let product = test.multiplier.multipliedReportingOverflow(by: test.multiplicator) XCTAssertEqual(product.partialValue, test.product.partialValue) XCTAssertEqual(product.overflow, test.product.overflow) } } func testMultipliedFullWidth() { var tests = [(multiplier: UInt128.min, multiplicator: UInt128.min, product: (high: UInt128.min, low: UInt128.min))] tests.append((multiplier: UInt128(1), multiplicator: UInt128(1), product: (high: UInt128.min, low: UInt128(1)))) tests.append((multiplier: UInt128(UInt64.max), multiplicator: UInt128(UInt64.max), product: (high: UInt128.min, low: UInt128(upperBits: UInt64.max - 1, lowerBits: 1)))) tests.append((multiplier: UInt128.max, multiplicator: UInt128.max, product: (high: UInt128.max ^ 1, low: UInt128(1)))) tests.forEach { test in let product = test.multiplier.multipliedFullWidth(by: test.multiplicator) XCTAssertEqual( product.high, test.product.high, "\n\(test.multiplier) * \(test.multiplicator) == (high: \(test.product.high), low: \(test.product.low)) != (high: \(product.high), low: \(product.low))\n") XCTAssertEqual( product.low, test.product.low, "\n\(test.multiplier) * \(test.multiplicator) == (high: \(test.product.high), low: \(test.product.low)) != (high: \(product.high), low: \(product.low))\n") } } func divisionTests() -> [(dividend: UInt128, divisor: UInt128, quotient: (partialValue: UInt128, overflow: Bool), remainder: (partialValue: UInt128, overflow: Bool))] { // 0 / 0 = 0, remainder 0, with overflow var tests = [(dividend: UInt128.min, divisor: UInt128.min, quotient: (partialValue: UInt128.min, overflow: true), remainder: (partialValue: UInt128.min, overflow: true))] // 0 / 1 = 0, remainder 0 tests.append((dividend: UInt128.min, divisor: UInt128(1), quotient: (partialValue: UInt128.min, overflow: false), remainder: (partialValue: UInt128.min, overflow: false))) // 0 / UInt128.max = 0, remainder 0 tests.append((dividend: UInt128.min, divisor: UInt128.max, quotient: (partialValue: UInt128.min, overflow: false), remainder: (partialValue: UInt128.min, overflow: false))) // 1 / 0 = 1, remainder 1, with overflow tests.append((dividend: UInt128(1), divisor: UInt128.min, quotient: (partialValue: UInt128(1), overflow: true), remainder: (partialValue: UInt128(1), overflow: true))) // UInt128.max / UInt64.max = UInt128(upperBits: 1, lowerBits: 1), remainder 0 tests.append((dividend: UInt128.max, divisor: UInt128(UInt64.max), quotient: (partialValue: UInt128(upperBits: 1, lowerBits: 1), overflow: false), remainder: (partialValue: UInt128.min, overflow: false))) // UInt128.max / UInt128.max = 1, remainder 0 tests.append((dividend: UInt128.max, divisor: UInt128.max, quotient: (partialValue: UInt128(1), overflow: false), remainder: (partialValue: UInt128.min, overflow: false))) // UInt64.max / UInt128.max = 0, remainder UInt64.max tests.append((dividend: UInt128(UInt64.max), divisor: UInt128.max, quotient: (partialValue: UInt128.min, overflow: false), remainder: (partialValue: UInt128(UInt64.max), overflow: false))) return tests } func testDividedReportingOverflow() { divisionTests().forEach { test in let quotient = test.dividend.dividedReportingOverflow(by: test.divisor) XCTAssertEqual( quotient.partialValue, test.quotient.partialValue, "\(test.dividend) / \(test.divisor) == \(test.quotient.partialValue)") XCTAssertEqual( quotient.overflow, test.quotient.overflow, "\(test.dividend) / \(test.divisor) has overflow? \(test.remainder.overflow)") } } func testBitFromDoubleWidth() { var tests = [(input: (high: UInt128(1), low: UInt128.min), position: UInt128.min, result: UInt128.min)] tests.append((input: (high: UInt128(1), low: UInt128.min), position: UInt128(128), result: UInt128(1))) tests.append((input: (high: UInt128(2), low: UInt128.min), position: UInt128(128), result: UInt128.min)) tests.append((input: (high: UInt128(2), low: UInt128.min), position: UInt128(129), result: UInt128(1))) tests.append((input: (high: UInt128.min, low: UInt128(2)), position: UInt128.min, result: UInt128.min)) tests.append((input: (high: UInt128.min, low: UInt128(2)), position: UInt128(1), result: UInt128(1))) tests.forEach { test in let result = UInt128._bitFromDoubleWidth(at: test.position, for: test.input) XCTAssertEqual( result, test.result, "\n\(test.input), bit \(test.position) != \(test.result)") } } func testDividingFullWidth() throws { // (0, 1) / 1 = 1r0 var tests = [(dividend: (high: UInt128.min, low: UInt128(1)), divisor: UInt128(1), result: (quotient: UInt128(1), remainder: UInt128.min))] // (1, 0) / 1 = 0r0 tests.append((dividend: (high: UInt128(1), low: UInt128.min), divisor: UInt128(1), result: (quotient: UInt128.min, remainder: UInt128.min))) // (1, 0) / 2 = 170141183460469231731687303715884105728r0 tests.append((dividend: (high: UInt128(1), low: UInt128.min), divisor: UInt128(2), result: (quotient: try XCTUnwrap(UInt128("170141183460469231731687303715884105728")), remainder: UInt128.min))) tests.forEach { test in let result = test.divisor.dividingFullWidth(test.dividend) XCTAssertEqual( result.quotient, test.result.quotient, "\n\(test.dividend) / \(test.divisor) == \(test.result)") XCTAssertEqual( result.remainder, test.result.remainder, "\n\(test.dividend) / \(test.divisor) == \(test.result)") } } func testRemainderReportingOverflow() { divisionTests().forEach { test in let remainder = test.dividend.remainderReportingOverflow(dividingBy: test.divisor) XCTAssertEqual( remainder.partialValue, test.remainder.partialValue, "\(test.dividend) / \(test.divisor) has a remainder of \(test.remainder.partialValue)") XCTAssertEqual( remainder.overflow, test.remainder.overflow, "\(test.dividend) / \(test.divisor) has overflow? \(test.remainder.overflow)") } } func testQuotientAndRemainder() { divisionTests().forEach { test in guard test.divisor != 0 else { return } let result = test.dividend.quotientAndRemainder(dividingBy: test.divisor) XCTAssertEqual( result.quotient, test.quotient.partialValue, "\(test.dividend) / \(test.divisor) == \(test.quotient.partialValue)") XCTAssertEqual( result.remainder, test.remainder.partialValue, "\(test.dividend) / \(test.divisor) has a remainder of \(test.remainder.partialValue)") } } } class BinaryIntegerTests : XCTestCase { func testBitWidthEquals128() { XCTAssertEqual(UInt128.bitWidth, 128) } func testTrailingZeroBitCount() { var tests = [(input: UInt128.min, expected: 128)] tests.append((input: UInt128(1), expected: 0)) tests.append((input: UInt128(upperBits: 1, lowerBits: 0), expected: 64)) tests.append((input: UInt128.max, expected: 0)) tests.forEach { test in XCTAssertEqual(test.input.trailingZeroBitCount, test.expected)} } func testInitFailableFloatingPointExactlyExpectedSuccesses() { var tests = [(input: Float(), result: UInt128())] tests.append((input: Float(1), result: UInt128(1))) tests.append((input: Float(1.0), result: UInt128(1))) tests.forEach { test in XCTAssertEqual(UInt128(exactly: test.input), test.result) } } func testInitFailableFloatingPointExactlyExpectedFailures() { var tests = [Float(1.1)] tests.append(Float(0.1)) tests.forEach { test in XCTAssertEqual(UInt128(exactly: test), nil) } } func testInitFloatingPoint() { #if arch(x86_64) var tests = [(input: Float80(), result: UInt128())] tests.append((input: Float80(0.1), result: UInt128())) tests.append((input: Float80(1.0), result: UInt128(1))) tests.append((input: Float80(UInt64.max), result: UInt128(UInt64.max))) #else var tests = [(input: 0.0, result: UInt128())] tests.append((input: 0.1, result: UInt128())) tests.append((input: 1.0, result: UInt128(1))) tests.append((input: Double(UInt32.max), result: UInt128(UInt32.max))) #endif tests.forEach { test in XCTAssertEqual(UInt128(test.input), test.result) } } func test_word() { let lowerBits = UInt64("100000000000000000000000000000001", radix: 2)! let upperBits = UInt64("100000000000000000000000000000001", radix: 2)! let testResult = UInt128(upperBits: upperBits, lowerBits: lowerBits) testResult.words.forEach { (currentWord) in if UInt.bitWidth == 64 { XCTAssertEqual(currentWord, 4294967297) } } } func divisionTests() -> [(dividend: UInt128, divisor: UInt128, quotient: UInt128, remainder: UInt128)] { // 0 / 1 = 0, remainder 0 var tests = [(dividend: UInt128.min, divisor: UInt128(1), quotient: UInt128.min, remainder: UInt128.min)] // 2 / 1 = 2, remainder 0 tests.append((dividend: UInt128(2), divisor: UInt128(1), quotient: UInt128(2), remainder: UInt128.min)) // 1 / 2 = 0, remainder 1 tests.append((dividend: UInt128(1), divisor: UInt128(2), quotient: UInt128(0), remainder: UInt128(1))) // UInt128.max / UInt64.max = UInt128(upperBits: 1, lowerBits: 1), remainder 0 tests.append((dividend: UInt128.max, divisor: UInt128(UInt64.max), quotient: UInt128(upperBits: 1, lowerBits: 1), remainder: UInt128.min)) // UInt128.max / UInt128.max = 1, remainder 0 tests.append((dividend: UInt128.max, divisor: UInt128.max, quotient: UInt128(1), remainder: UInt128.min)) // UInt64.max / UInt128.max = 0, remainder UInt64.max tests.append((dividend: UInt128(UInt64.max), divisor: UInt128.max, quotient: UInt128.min, remainder: UInt128(UInt64.max))) return tests } func testDivideOperator() { divisionTests().forEach { test in let quotient = test.dividend / test.divisor XCTAssertEqual( quotient, test.quotient, "\(test.dividend) / \(test.divisor) == \(test.quotient)") } } func testDivideEqualOperator() { divisionTests().forEach { test in var quotient = test.dividend quotient /= test.divisor XCTAssertEqual( quotient, test.quotient, "\(test.dividend) /= \(test.divisor) == \(test.quotient)") } } func moduloTests() -> [(dividend: UInt128, divisor: UInt128, remainder: UInt128)] { // 0 % 1 = 0 var tests = [(dividend: UInt128.min, divisor: UInt128(1), remainder: UInt128.min)] // 1 % 2 = 1 tests.append((dividend: UInt128(1), divisor: UInt128(2), remainder: UInt128(1))) // 0 % UInt128.max = 0 tests.append((dividend: UInt128.min, divisor: UInt128.max, remainder: UInt128.min)) // UInt128.max % UInt64.max = 0 tests.append((dividend: UInt128.max, divisor: UInt128(UInt64.max), remainder: UInt128.min)) // UInt128.max % UInt128.max = 0 tests.append((dividend: UInt128.max, divisor: UInt128.max, remainder: UInt128.min)) // UInt64.max % UInt128.max = UInt64.max tests.append((dividend: UInt128(UInt64.max), divisor: UInt128.max, remainder: UInt128(UInt64.max))) return tests } func testModuloOperator() { moduloTests().forEach { test in let remainder = test.dividend % test.divisor XCTAssertEqual( remainder, test.remainder, "\(test.dividend) % \(test.divisor) == \(test.remainder)") } } func testModuloEqualOperator() { moduloTests().forEach { test in var remainder = test.dividend remainder %= test.divisor XCTAssertEqual( remainder, test.remainder, "\(test.dividend) %= \(test.divisor) == \(test.remainder)") } } func testBooleanAndEqualOperator() { var tests = [(lhs: UInt128.min, rhs: UInt128.min, result: UInt128.min)] tests.append((lhs: UInt128(1), rhs: UInt128(1), result: UInt128(1))) tests.append((lhs: UInt128.min, rhs: UInt128.max, result: UInt128.min)) tests.append((lhs: UInt128(upperBits: UInt64.min, lowerBits: UInt64.max), rhs: UInt128(upperBits: UInt64.max, lowerBits: UInt64.min), result: UInt128.min)) tests.append((lhs: UInt128(upperBits: 17434549027881090559, lowerBits: 18373836492640810226), rhs: UInt128(upperBits: 17506889200551263486, lowerBits: 18446176699804939249), result: UInt128(upperBits: 17361645879185571070, lowerBits: 18373836492506460400))) tests.append((lhs: UInt128.max, rhs: UInt128.max, result: UInt128.max)) tests.forEach { test in var result = test.lhs result &= test.rhs XCTAssertEqual(result, test.result) } } func testBooleanOrEqualOperator() { var tests = [(lhs: UInt128.min, rhs: UInt128.min, result: UInt128.min)] tests.append((lhs: UInt128(1), rhs: UInt128(1), result: UInt128(1))) tests.append((lhs: UInt128.min, rhs: UInt128.max, result: UInt128.max)) tests.append((lhs: UInt128(upperBits: UInt64.min, lowerBits: UInt64.max), rhs: UInt128(upperBits: UInt64.max, lowerBits: UInt64.min), result: UInt128.max)) tests.append((lhs: UInt128(upperBits: 17434549027881090559, lowerBits: 18373836492640810226), rhs: UInt128(upperBits: 17506889200551263486, lowerBits: 18446176699804939249), result: UInt128(upperBits: 17579792349246782975, lowerBits: 18446176699939289075))) tests.append((lhs: UInt128.max, rhs: UInt128.max, result: UInt128.max)) tests.forEach { test in var result = test.lhs result |= test.rhs XCTAssertEqual(result, test.result) } } func testBooleanXorEqualOperator() { var tests = [(lhs: UInt128.min, rhs: UInt128.min, result: UInt128.min)] tests.append((lhs: UInt128(1), rhs: UInt128(1), result: UInt128.min)) tests.append((lhs: UInt128.min, rhs: UInt128.max, result: UInt128.max)) tests.append((lhs: UInt128(upperBits: UInt64.min, lowerBits: UInt64.max), rhs: UInt128(upperBits: UInt64.max, lowerBits: UInt64.min), result: UInt128.max)) tests.append((lhs: UInt128(upperBits: 17434549027881090559, lowerBits: 18373836492640810226), rhs: UInt128(upperBits: 17506889200551263486, lowerBits: 18446176699804939249), result: UInt128(upperBits: 218146470061211905, lowerBits: 72340207432828675))) tests.append((lhs: UInt128.max, rhs: UInt128.max, result: UInt128.min)) tests.forEach { test in var result = test.lhs result ^= test.rhs XCTAssertEqual(result, test.result) } } func testMaskingRightShiftEqualOperatorStandardCases() { var tests = [(input: UInt128(upperBits: UInt64.max, lowerBits: 0), shiftWidth: UInt64(127), expected: UInt128(upperBits: 0, lowerBits: 1))] tests.append((input: UInt128(upperBits: 1, lowerBits: 0), shiftWidth: UInt64(64), expected: UInt128(upperBits: 0, lowerBits: 1))) tests.append((input: UInt128(upperBits: 0, lowerBits: 1), shiftWidth: UInt64(1), expected: UInt128())) tests.forEach { test in var testValue = test.input testValue &>>= UInt128(upperBits: 0, lowerBits: test.shiftWidth) XCTAssertEqual(testValue, test.expected) } } func testMaskingRightShiftEqualOperatorEdgeCases() { var tests = [(input: UInt128(upperBits: 0, lowerBits: 2), shiftWidth: UInt64(129), expected: UInt128(upperBits: 0, lowerBits: 1))] tests.append((input: UInt128(upperBits: UInt64.max, lowerBits: 0), shiftWidth: UInt64(128), expected: UInt128(upperBits: UInt64.max, lowerBits: 0))) tests.append((input: UInt128(upperBits: 0, lowerBits: 1), shiftWidth: UInt64(0), expected: UInt128(upperBits: 0, lowerBits: 1))) tests.forEach { test in var testValue = test.input testValue &>>= UInt128(upperBits: 0, lowerBits: test.shiftWidth) XCTAssertEqual(testValue, test.expected) } } func testMaskingLeftShiftEqualOperatorStandardCases() { let uint64_1_in_msb: UInt64 = 2 << 62 var tests = [(input: UInt128(upperBits: 0, lowerBits: 1), shiftWidth: UInt64(127), expected: UInt128(upperBits: uint64_1_in_msb, lowerBits: 0))] tests.append((input: UInt128(upperBits: 0, lowerBits: 1), shiftWidth: UInt64(64), expected: UInt128(upperBits: 1, lowerBits: 0))) tests.append((input: UInt128(upperBits: 0, lowerBits: 1), shiftWidth: UInt64(1), expected: UInt128(upperBits: 0, lowerBits: 2))) tests.forEach { test in var testValue = test.input testValue &<<= UInt128(upperBits: 0, lowerBits: test.shiftWidth) XCTAssertEqual(testValue, test.expected) } } func testMaskingLeftShiftEqualOperatorEdgeCases() { var tests = [(input: UInt128(upperBits: 0, lowerBits: 2), shiftWidth: UInt64(129), expected: UInt128(upperBits: 0, lowerBits: 4))] tests.append((input: UInt128(upperBits: 0, lowerBits: 2), shiftWidth: UInt64(128), expected: UInt128(upperBits: 0, lowerBits: 2))) tests.append((input: UInt128(upperBits: 0, lowerBits: 1), shiftWidth: UInt64(0), expected: UInt128(upperBits: 0, lowerBits: 1))) tests.forEach { test in var testValue = test.input testValue &<<= UInt128(upperBits: 0, lowerBits: test.shiftWidth) XCTAssertEqual(testValue, test.expected) } } } class NumericTests : XCTestCase { func additionTests() -> [(augend: UInt128, addend: UInt128, sum: UInt128)] { // 0 + 0 = 0 var tests = [(augend: UInt128.min, addend: UInt128.min, sum: UInt128.min)] // 1 + 1 = 2 tests.append((augend: UInt128(1), addend: UInt128(1), sum: UInt128(2))) // UInt128.max + 0 = UInt128.max tests.append((augend: UInt128.max, addend: UInt128.min, sum: UInt128.max)) // UInt64.max + 1 = UInt64.max + 1 tests.append((augend: UInt128(UInt64.max), addend: UInt128(1), sum: UInt128(upperBits: 1, lowerBits: 0))) return tests } func testAdditionOperator() { additionTests().forEach { test in let sum = test.augend + test.addend XCTAssertEqual( sum, test.sum, "\(test.augend) + \(test.addend) == \(test.sum)") } } func testAdditionEqualOperator() { additionTests().forEach { test in var sum = test.augend sum += test.addend XCTAssertEqual( sum, test.sum, "\(test.augend) += \(test.addend) == \(test.sum)") } } func subtractionTests() -> [(minuend: UInt128, subtrahend: UInt128, difference: UInt128)] { // 0 - 0 = 0 var tests = [(minuend: UInt128.min, subtrahend: UInt128.min, difference: UInt128.min)] // Uint128.max - 0 = UInt128.max tests.append((minuend: UInt128.max, subtrahend: UInt128.min, difference: UInt128.max)) // UInt128.max - 1 = UInt128.max - 1 tests.append((minuend: UInt128.max, subtrahend: UInt128(1), difference: UInt128(upperBits: UInt64.max, lowerBits: (UInt64.max >> 1) << 1))) // UInt64.max + 1 - 1 = UInt64.max tests.append((minuend: UInt128(upperBits: 1, lowerBits: 0), subtrahend: UInt128(1), difference: UInt128(UInt64.max))) return tests } func testSubtractionOperator() { subtractionTests().forEach { test in let difference = test.minuend - test.subtrahend XCTAssertEqual( difference, test.difference, "\(test.minuend) - \(test.subtrahend) == \(test.difference)") } } func testSubtractionEqualOperator() { subtractionTests().forEach { test in var difference = test.minuend difference -= test.subtrahend XCTAssertEqual( difference, test.difference, "\(test.minuend) -= \(test.subtrahend) == \(test.difference)") } } func multiplicationTests() -> [(multiplier: UInt128, multiplicator: UInt128, product: UInt128)] { // 0 * 0 = 0 var tests = [(multiplier: UInt128.min, multiplicator: UInt128.min, product: UInt128.min)] // UInt64.max * UInt64.max = UInt128.max - UInt64.max - 1 tests.append((multiplier: UInt128(UInt64.max), multiplicator: UInt128(UInt64.max), product: UInt128(upperBits: (UInt64.max >> 1) << 1, lowerBits: 1))) // UInt128.max * 0 = 0 tests.append((multiplier: UInt128.max, multiplicator: UInt128.min, product: UInt128.min)) // UInt128.max * 1 = UInt128.max tests.append((multiplier: UInt128.max, multiplicator: UInt128(1), product: UInt128.max)) return tests } func testMultiplicationOperator() { multiplicationTests().forEach { test in let product = test.multiplier * test.multiplicator XCTAssertEqual( product, test.product, "\(test.multiplier) * \(test.multiplicator) == \(test.product)") } } func testMultiplicationEqualOperator() { multiplicationTests().forEach { test in var product = test.multiplier product *= test.multiplicator XCTAssertEqual( product, test.product, "\(test.multiplier) *= \(test.multiplicator) == \(test.product)") } } } class EquatableTests : XCTestCase { func testBooleanEqualsOperator() { var tests = [(lhs: UInt128.min, rhs: UInt128.min, result: true)] tests.append((lhs: UInt128.min, rhs: UInt128(1), result: false)) tests.append((lhs: UInt128.max, rhs: UInt128.max, result: true)) tests.append((lhs: UInt128(UInt64.max), rhs: UInt128(upperBits: UInt64.max, lowerBits: UInt64.min), result: false)) tests.append((lhs: UInt128(upperBits: 1, lowerBits: 0), rhs: UInt128(upperBits: 1, lowerBits: 0), result: true)) tests.append((lhs: UInt128(upperBits: 1, lowerBits: 0), rhs: UInt128(), result: false)) tests.forEach { test in XCTAssertEqual(test.lhs == test.rhs, test.result) } } } class ExpressibleByIntegerLiteralTests : XCTestCase { func testInitWithIntegerLiteral() { var tests = [(input: 0, result: UInt128())] tests.append((input: 1, result: UInt128(upperBits: 0, lowerBits: 1))) tests.append((input: Int.max, result: UInt128(upperBits: 0, lowerBits: UInt64(Int.max)))) tests.forEach { test in XCTAssertEqual(UInt128(integerLiteral: test.input), test.result) } } } class CustomStringConvertibleTests : XCTestCase { func stringTests() -> [(input: UInt128, result: [Int: String])] { var tests = [(input: UInt128(), result:[ 2: "0", 8: "0", 10: "0", 16: "0", 18: "0", 36: "0"])] tests.append((input: UInt128(1), result: [ 2: "1", 8: "1", 10: "1", 16: "1", 18: "1", 36: "1"])) tests.append((input: UInt128(UInt64.max), result: [ 2: "1111111111111111111111111111111111111111111111111111111111111111", 8: "1777777777777777777777", 10: "18446744073709551615", 16: "ffffffffffffffff", 18: "2d3fgb0b9cg4bd2f", 36: "3w5e11264sgsf"])) tests.append((input: UInt128(upperBits: 1, lowerBits: 0), result: [ 2: "10000000000000000000000000000000000000000000000000000000000000000", 8: "2000000000000000000000", 10: "18446744073709551616", 16: "10000000000000000", 18: "2d3fgb0b9cg4bd2g", 36: "3w5e11264sgsg"])) tests.append((input: UInt128.max, result: [ 2: "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", 8: "3777777777777777777777777777777777777777777", 10: "340282366920938463463374607431768211455", 16: "ffffffffffffffffffffffffffffffff", 18: "78a399ccdeb5bd6ha3184c0fh64da63", 36: "f5lxx1zz5pnorynqglhzmsp33"])) return tests } func testDescriptionProperty() { stringTests().forEach { test in XCTAssertEqual(test.input.description, test.result[10]) } } func testStringDescribingInitializer() { stringTests().forEach { test in XCTAssertEqual(String(describing: test.input), test.result[10]) } } func testStringUInt128InitializerLowercased() { stringTests().forEach { test in test.result.forEach { result in let (radix, result) = result let testOutput = String(test.input, radix: radix) XCTAssertEqual(testOutput, result) } } } func testStringUInt128InitializerUppercased() { stringTests().forEach { test in test.result.forEach { result in let (radix, result) = result let testOutput = String(test.input, radix: radix, uppercase: true) XCTAssertEqual(testOutput, result.uppercased()) } } } } class CustomDebugStringConvertible : XCTestCase { func stringTests() -> [(input: UInt128, result: String)] { var tests = [(input: UInt128(), result:"0")] tests.append((input: UInt128(1), result: "1")) tests.append((input: UInt128(UInt64.max), result: "18446744073709551615")) tests.append((input: UInt128(upperBits: 1, lowerBits: 0), result: "18446744073709551616")) tests.append((input: UInt128.max, result: "340282366920938463463374607431768211455")) return tests } func testDebugDescriptionProperty() { stringTests().forEach { test in XCTAssertEqual(test.input.debugDescription, test.result) } } func testStringReflectingInitializer() { stringTests().forEach { test in XCTAssertEqual(String(reflecting: test.input), test.result) } } } class ComparableTests : XCTestCase { func testLessThanOperator() { var tests = [(lhs: UInt128.min, rhs: UInt128(1), result: true)] tests.append((lhs: UInt128.min, rhs: UInt128(upperBits: 1, lowerBits: 0), result: true)) tests.append((lhs: UInt128(1), rhs: UInt128(upperBits: 1, lowerBits: 0), result: true)) tests.append((lhs: UInt128(UInt64.max), rhs: UInt128.max, result: true)) tests.append((lhs: UInt128.min, rhs: UInt128.min, result: false)) tests.append((lhs: UInt128.max, rhs: UInt128.max, result: false)) tests.append((lhs: UInt128.max, rhs: UInt128(UInt64.max), result: false)) tests.forEach { test in XCTAssertEqual(test.lhs < test.rhs, test.result) } } } class FailableStringInitializerTests : XCTestCase { func stringTests() -> [(input: String, result: UInt128?)] { var tests = [(input: "", result: nil as UInt128?)] tests.append((input: "0", result: UInt128())) tests.append((input: "1", result: UInt128(1))) tests.append((input: "99", result: UInt128(99))) tests.append((input: "0b0101", result: UInt128(5))) tests.append((input: "0o11", result: UInt128(9))) tests.append((input: "0xFF", result: UInt128(255))) tests.append((input: "0z1234", result: nil)) return tests } func testInitWithStringLiteral() { stringTests().forEach { test in XCTAssertEqual(UInt128(test.input), test.result) } } func testEvaluatedWithStringLiteral() { let binaryTest = UInt128("0b11") XCTAssertEqual(binaryTest, UInt128(3)) let octalTest = UInt128("0o11") XCTAssertEqual(octalTest, UInt128(9)) let decimalTest = UInt128("11") XCTAssertEqual(decimalTest, UInt128(11)) let hexTest = UInt128("0x11") XCTAssertEqual(hexTest, UInt128(17)) } } class CodableTests : XCTestCase { func testCodable() throws { let enc = try XCTUnwrap(UInt128("340282366920938463463374607431768211455")) let data = try! JSONEncoder().encode(enc) let dec = try! JSONDecoder().decode(UInt128.self, from: data) XCTAssertEqual(enc, dec) } } @available(swift, deprecated: 3.2) class DeprecatedAPITests : XCTestCase { func testFromUnparsedString() { XCTAssertThrowsError(try UInt128.fromUnparsedString("")) XCTAssertEqual(try UInt128.fromUnparsedString("1"), UInt128(1)) } } class FloatingPointInterworkingTests : XCTestCase { func testNonFailableInitializer() { var tests = [(input: UInt128(), output: Float(0))] tests.append((input: UInt128(upperBits: 0, lowerBits: UInt64.max), output: Float(UInt64.max))) tests.forEach { test in XCTAssertEqual(Float(test.input), test.output) } } func testFailableInitializer() { var tests = [(input: UInt128(), output: Float(0) as Float?)] tests.append((input: UInt128(upperBits: 0, lowerBits: UInt64.max), output: Float(UInt64.max) as Float?)) tests.append((input: UInt128(upperBits: 1, lowerBits: 0), output: nil)) tests.forEach { test in XCTAssertEqual(Float(exactly: test.input), test.output) } } func testSignBitIndex() { var tests = [(input: UInt128.min, output: Int(-1))] tests.append((input: UInt128.max, output: Int(127))) tests.forEach { test in XCTAssertEqual(test.input.signBitIndex, test.output) } } }
apache-2.0
XWJACK/Music
Music/Modules/Center/MusicCenterTableViewCell.swift
1
1472
// // MusicCenterTableViewCell.swift // Music // // Created by Jack on 5/7/17. // Copyright © 2017 Jack. All rights reserved. // import UIKit class MusicCenterClearCacheTableViewCell: MusicTableViewCell { var rightView = UIView() let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white) let cacheLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) rightView.backgroundColor = .clear cacheLabel.textColor = .white cacheLabel.text = "" rightView.addSubview(cacheLabel) rightView.addSubview(indicator) contentView.addSubview(rightView) rightView.snp.makeConstraints { (make) in make.right.equalToSuperview().offset(-20) make.centerY.equalToSuperview() make.top.equalToSuperview().offset(5) make.bottom.equalToSuperview().offset(-5) } indicator.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.right.equalToSuperview() } cacheLabel.snp.makeConstraints { (make) in make.left.right.equalToSuperview() make.centerY.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
koutalou/iOS-CleanArchitecture
iOSCleanArchitectureTwitterSampleUITests/iOSCleanArchitectureTwitterSampleUITests.swift
1
1322
// // iOSCleanArchitectureTwitterSampleUITests.swift // iOSCleanArchitectureTwitterSampleUITests // // Created by koutalou on 2015/12/20. // Copyright © 2015年 koutalou. All rights reserved. // import XCTest class iOSCleanArchitectureTwitterSampleUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
fabioalmeida/FAAutoLayout
FAAutoLayout/Classes/NSLayoutConstraint+FAAutoLayout.swift
1
11112
// // NSLayoutConstraint+FAAutoLayout.swift // FAAutoLayout // // Created by Fábio Almeida on 14/06/2017. // Copyright (c) 2017 Fábio Almeida. All rights reserved. // import UIKit // MARK: - Internal internal extension NSLayoutConstraint { /// Helper method to facilitate the creation of leading space constraints class func leadingSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .leading, toAttribute: .leading, relatedBy: relation, multiplier: m, constant: c) } /// Helper method to facilitate the creation of trailing space constraints class func trailingSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { // in trailing contraints we need to invert the views order so that we don't need to use negative constants return NSLayoutConstraint.createConstraint(fromItem: toView, toItem: fromView, fromAttribute: .trailing, toAttribute: .trailing, relatedBy: relation, multiplier: m, constant: c, itemUsingAutoLayout: fromView) } /// Helper method to facilitate the creation of top space constraints class func topSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .top, toAttribute: .top, relatedBy: relation, multiplier: m, constant: c) } /// Helper method to facilitate the creation of bottom space constraints class func bottomSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { // in bottom contraints we need to invert the views order so that we don't need to use negative constants return NSLayoutConstraint.createConstraint(fromItem: toView, toItem: fromView, fromAttribute: .bottom, toAttribute: .bottom, relatedBy: relation, multiplier: m, constant: c, itemUsingAutoLayout: fromView) } /// Helper method to facilitate the creation of width constraints class func widthConstraint(fromView: UIView, toView: UIView?, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { let toAttribute = toView != nil ? NSLayoutConstraint.Attribute.width : NSLayoutConstraint.Attribute.notAnAttribute return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .width, toAttribute: toAttribute, relatedBy: relation, multiplier: m, constant: c) } /// Helper method to facilitate the creation of height constraints class func heightConstraint(fromView: UIView, toView: UIView?, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { let toAttribute = toView != nil ? NSLayoutConstraint.Attribute.height : NSLayoutConstraint.Attribute.notAnAttribute return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .height, toAttribute: toAttribute, relatedBy: relation, multiplier: m, constant: c) } /// Helper method to facilitate the creation of horizontal centering constraints class func centerHorizontallyConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .centerX, toAttribute: .centerX, relatedBy: relation, multiplier: m, constant: c) } /// Helper method to facilitate the creation of vertical centering constraints class func centerVerticallyConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .centerY, toAttribute: .centerY, relatedBy: relation, multiplier: m, constant: c) } /// Helper method to facilitate the creation of horizontal spacing constraints class func horizontalSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .leading, toAttribute: .trailing, relatedBy: relation, multiplier: m, constant: c) } /// Helper method to facilitate the creation of vertical spacing constraints class func verticalSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: .top, toAttribute: .bottom, relatedBy: relation, multiplier: m, constant: c) } } // MARK: - Private fileprivate extension NSLayoutConstraint { /// Creates the constraint and set the `translatesAutoresizingMaskIntoConstraints` attribute to false on the `fromItem` class func createConstraint(fromItem fromView: UIView, toItem toView: UIView?, fromAttribute: NSLayoutConstraint.Attribute, toAttribute: NSLayoutConstraint.Attribute, relatedBy relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint.createConstraint(fromItem: fromView, toItem: toView, fromAttribute: fromAttribute, toAttribute: toAttribute, relatedBy: relation, multiplier: m, constant: c, itemUsingAutoLayout: fromView) } /// Creates the constraint and set the `translatesAutoresizingMaskIntoConstraints` attribute to false on the `itemUsingAutoLayout` class func createConstraint(fromItem fromView: UIView, toItem toView: UIView?, fromAttribute: NSLayoutConstraint.Attribute, toAttribute: NSLayoutConstraint.Attribute, relatedBy relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat, itemUsingAutoLayout: UIView?) -> NSLayoutConstraint { if let itemUsingAutoLayout = itemUsingAutoLayout { itemUsingAutoLayout.translatesAutoresizingMaskIntoConstraints = false } return NSLayoutConstraint(item: fromView, attribute: fromAttribute, relatedBy: relation, toItem: toView, attribute: toAttribute, multiplier: m, constant: c) } }
mit
tad-iizuka/swift-sdk
Package.swift
1
2584
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import PackageDescription let package = Package( name: "WatsonDeveloperCloud", targets: [ Target(name: "RestKit"), Target(name: "AlchemyDataNewsV1", dependencies: [.Target(name: "RestKit")]), Target(name: "AlchemyLanguageV1", dependencies: [.Target(name: "RestKit")]), Target(name: "AlchemyVisionV1", dependencies: [.Target(name: "RestKit")]), Target(name: "ConversationV1", dependencies: [.Target(name: "RestKit")]), Target(name: "DialogV1", dependencies: [.Target(name: "RestKit")]), Target(name: "DiscoveryV1", dependencies: [.Target(name: "RestKit")]), Target(name: "DocumentConversionV1", dependencies: [.Target(name: "RestKit")]), Target(name: "LanguageTranslatorV2", dependencies: [.Target(name: "RestKit")]), Target(name: "NaturalLanguageClassifierV1", dependencies: [.Target(name: "RestKit")]), Target(name: "NaturalLanguageUnderstandingV1", dependencies: [.Target(name: "RestKit")]), Target(name: "PersonalityInsightsV2", dependencies: [.Target(name: "RestKit")]), Target(name: "PersonalityInsightsV3", dependencies: [.Target(name: "RestKit")]), Target(name: "RelationshipExtractionV1Beta", dependencies: [.Target(name: "RestKit")]), Target(name: "RetrieveAndRankV1", dependencies: [.Target(name: "RestKit")]), Target(name: "TextToSpeechV1", dependencies: [.Target(name: "RestKit")]), Target(name: "ToneAnalyzerV3", dependencies: [.Target(name: "RestKit")]), Target(name: "TradeoffAnalyticsV1", dependencies: [.Target(name: "RestKit")]), Target(name: "VisualRecognitionV3", dependencies: [.Target(name: "RestKit")]), ], dependencies: [ ], exclude: [ "Source/SpeechToTextV1", "Tests/SpeechToTextV1Tests" ] )
apache-2.0
hrscy/TodayNews
News/News/Classes/Mine/View/PostVideoOrArticleView.swift
1
2025
// // PostVideoOrArticleView.swift // News // // Created by 杨蒙 on 2017/12/10. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit import Kingfisher class PostVideoOrArticleView: UIView, NibLoadable { /// 原内容是否已经删除 var delete = false { didSet { originContentHasDeleted() } } /// 原内容已经删除 func originContentHasDeleted() { titleLabel.text = "原内容已经删除" titleLabel.textAlignment = .center iconButtonWidth.constant = 0 layoutIfNeeded() } var group = DongtaiOriginGroup() { didSet { titleLabel.text = " " + group.title if group.thumb_url != "" { iconButton.kf.setBackgroundImage(with: URL(string: group.thumb_url)!, for: .normal) } else if group.user.avatar_url != "" { iconButton.kf.setBackgroundImage(with: URL(string: group.user.avatar_url)!, for: .normal) } else if group.delete { originContentHasDeleted() } switch group.media_type { case .postArticle: iconButton.setImage(nil, for: .normal) case .postVideo: iconButton.theme_setImage("images.smallvideo_all_32x32_", forState: .normal) } } } /// 图标 @IBOutlet weak var iconButton: UIButton! /// 标题 @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var iconButtonWidth: NSLayoutConstraint! /// 覆盖按钮点击 @IBAction func coverButtonClicked(_ sender: UIButton) { } override func awakeFromNib() { super.awakeFromNib() theme_backgroundColor = "colors.cellBackgroundColor" titleLabel.theme_textColor = "colors.black" titleLabel.theme_backgroundColor = "colors.grayColor247" } override func layoutSubviews() { super.layoutSubviews() width = screenWidth - 30 } }
mit
maxsokolov/Kee
Sources/KeyValueStorageError.swift
1
1367
// // Copyright (c) 2017 Max Sokolov https://twitter.com/max_sokolov // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation public enum KeyValueStorageError: Error { case valueNotFoundError case unsupportedValueTypeError(type: String) case typeError(reason: String) }
mit
nathawes/swift
test/SourceKit/CodeComplete/complete_structure.swift
7
4181
// RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_DOT | %FileCheck %s -check-prefix=S1_DOT // RUN: %complete-test %s -group=none -add-inner-results -fuzz -structure -tok=S1_POSTFIX | %FileCheck %s -check-prefix=S1_POSTFIX // RUN: %complete-test %s -group=none -add-inner-results -fuzz -structure -tok=S1_POSTFIX_INIT | %FileCheck %s -check-prefix=S1_INIT // RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_PAREN_INIT | %FileCheck %s -check-prefix=S1_INIT // RUN: %complete-test %s -group=none -hide-none -fuzz -structure -tok=STMT_0 | %FileCheck %s -check-prefix=STMT_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=ENUM_0 | %FileCheck %s -check-prefix=ENUM_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=OVERRIDE_0 | %FileCheck %s -check-prefix=OVERRIDE_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_INNER_0 | %FileCheck %s -check-prefix=S1_INNER_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=INT_INNER_0 | %FileCheck %s -check-prefix=INT_INNER_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=ASSOCIATED_TYPE_1 | %FileCheck %s -check-prefix=ASSOCIATED_TYPE_1 struct S1 { func method1() {} func method2(_ a: Int, b: Int) -> Int { return 1 } func method3(a a: Int, b: Int) {} func method4(_: Int, _: Int) {} func method5(_: inout Int, b: inout Int) {} func method6(_ c: Int) throws {} func method7(_ callback: () throws -> ()) rethrows {} func method8<T, U>(_ d: (T, U) -> T, e: T -> U) {} let v1: Int = 1 var v2: Int { return 1 } subscript(x: Int, y: Int) -> Int { return 1 } subscript(x x: Int, y y: Int) -> Int { return 1 } init() {} init(a: Int, b: Int) {} init(_: Int, _: Int) {} init(c: Int)? {} } func test1(_ x: S1) { x.#^S1_DOT^# } // S1_DOT: {name:method1}() // S1_DOT: {name:method2}({params:{l:a:}{t: Int}, {n:b:}{t: Int}}) // S1_DOT: {name:method3}({params:{n:a:}{t: Int}, {n:b:}{t: Int}}) // S1_DOT: {name:method4}({params:{t:Int}, {t:Int}}) // S1_DOT: {name:method5}({params:{t:&Int}, {n:b:}{t: &Int}}) // FIXME: put throws in a range! // S1_DOT: {name:method6}({params:{l:c:}{t: Int}}){throws: throws} // S1_DOT: {name:method7}({params:{l:callback:}{t: () throws -> ()}}){throws: rethrows} // S1_DOT: {name:method8}({params:{l:d:}{t: (T, U) -> T}, {n:e:}{t: (T) -> U}}) // S1_DOT: {name:v1} // S1_DOT: {name:v2} func test2(_ x: S1) { x#^S1_POSTFIX^# } // Subscripts! // S1_POSTFIX: {name:.} // S1_POSTFIX: [{params:{l:x:}{t: Int}, {l:y:}{t: Int}}] // S1_POSTFIX: [{params:{n:x:}{t: Int}, {n:y:}{t: Int}}] // The dot becomes part of the name // S1_POSTFIX: {name:.method1}() // S1_POSTFIX: {name:.method2}({params:{l:a:}{t: Int}, {n:b:}{t: Int}}) func test4() { S1#^S1_POSTFIX_INIT^# } func test5() { S1(#^S1_PAREN_INIT^# } // S1_INIT: ({params:{t:Int}, {t:Int}}) // S1_INIT: ({params:{n:a:}{t: Int}, {n:b:}{t: Int}}) // S1_INIT: ({params:{n:c:}{t: Int}}) func test6(_ xyz: S1, fgh: (S1) -> S1) { #^STMT_0^# } // STMT_0: {name:func} // STMT_0: {name:fgh} // STMT_0: {name:xyz} // STMT_0: {name:S1} // STMT_0: {name:test6}({params:{l:xyz:}{t: S1}, {n:fgh:}{t: (S1) -> S1}}) // STMT_0: {name:try!} enum E1 { case C1 case C2(S1) case C3(l1: S1, l2: S1) } func test7(_ x: E1) { test7(.#^ENUM_0^#) } // ENUM_0: {name:C1} // ENUM_0: {name:C2}({params:{t:S1}}) // ENUM_0: {name:C3}({params:{n:l1:}{t: S1}, {n:l2:}{t: S1}}) class C1 { func foo(x: S1, y: S1, z: (S1) -> S1) -> S1 {} func zap<T, U>(x: T, y: U, z: (T) -> U) -> T {} } class C2 : C1 { override func #^OVERRIDE_0^# } // FIXME: overrides don't break out their code completion string structure. // OVERRIDE_0: {name:foo(x: S1, y: S1, z: (S1) -> S1) -> S1} // OVERRIDE_0: {name:zap<T, U>(x: T, y: U, z: (T) -> U) -> T} func test8() { #^S1_INNER_0,S1^# } // S1_INNER_0: {name:S1.} // FIXME: should the ( go inside the name here? // S1_INNER_0: {name:S1}( func test9(_ x: inout Int) { #^INT_INNER_0,x^# } // INT_INNER_0: {name:x==} // INT_INNER_0: {name:x<} // INT_INNER_0: {name:x+} // INT_INNER_0: {name:x..<} protocol P1 { associatedtype T } struct S2: P1 { #^ASSOCIATED_TYPE_1^# } // ASSOCIATED_TYPE_1: {name:T = }{params:{l:Type}}
apache-2.0
TrustWallet/trust-wallet-ios
TrustTests/Lock/ViewControllers/LockEnterPasscodeViewControllerTests.swift
1
2043
// Copyright DApps Platform Inc. All rights reserved. import XCTest import KeychainSwift @testable import Trust class LockEnterPasscodeViewControllerTests: XCTestCase { let passcode = "123456" let incorrectPasscode = "111111" func testCorrectPasscodeInput() { let lock = Lock(keychain: KeychainSwift(keyPrefix: Constants.keychainTestsKeyPrefix)) let lockViewModel = LockEnterPasscodeViewModel(lock: lock) let vc = LockEnterPasscodeViewController(model: lockViewModel, lock: lock) vc.configureLockView() vc.configureInvisiblePasscodeField() lock.setPasscode(passcode: passcode) vc.enteredPasscode(passcode) XCTAssertTrue(lock.numberOfAttempts() == 0) } func testIncorrectPasscodeInput() { let lock = Lock(keychain: KeychainSwift(keyPrefix: Constants.keychainTestsKeyPrefix)) let lockViewModel = LockEnterPasscodeViewModel(lock: lock) let vc = LockEnterPasscodeViewController(model: lockViewModel, lock: lock) vc.configureLockView() vc.configureInvisiblePasscodeField() lock.setPasscode(passcode: passcode) vc.enteredPasscode(incorrectPasscode) XCTAssertTrue(lock.numberOfAttempts() > 0) } func testIncorrectPasscodeLimitInput() { let lock = Lock(keychain: KeychainSwift(keyPrefix: Constants.keychainTestsKeyPrefix)) XCTAssertFalse(lock.incorrectMaxAttemptTimeIsSet()) let lockViewModel = LockEnterPasscodeViewModel(lock: lock) let vc = LockEnterPasscodeViewController(model: lockViewModel, lock: lock) vc.configureLockView() vc.configureInvisiblePasscodeField() lock.setPasscode(passcode: passcode) while lock.numberOfAttempts() <= lockViewModel.passcodeAttemptLimit() { vc.enteredPasscode(incorrectPasscode) } XCTAssertTrue(lock.incorrectMaxAttemptTimeIsSet()) } }
gpl-3.0
TrustWallet/trust-wallet-ios
Trust/Export/Coordinators/ExportPrivateKeyCoordinator.swift
1
847
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit import TrustKeystore final class ExportPrivateKeyCoordinator: RootCoordinator { let privateKey: Data var coordinators: [Coordinator] = [] var rootViewController: UIViewController { return exportViewController } lazy var exportViewController: ExportPrivateKeyViewConroller = { let controller = ExportPrivateKeyViewConroller(viewModel: viewModel) controller.navigationItem.title = NSLocalizedString("export.privateKey.navigation.title", value: "Export Private Key", comment: "") return controller }() private lazy var viewModel: ExportPrivateKeyViewModel = { return .init(privateKey: privateKey) }() init( privateKey: Data ) { self.privateKey = privateKey } }
gpl-3.0
apple/swift-format
Tests/SwiftFormatPrettyPrintTests/KeyPathExprTests.swift
1
1947
// TODO: Add more tests and figure out how we want to wrap keypaths. Right now, they just get // printed without breaks. final class KeyPathExprTests: PrettyPrintTestCase { func testSimple() { let input = #""" let x = \.foo let y = \.foo.bar let z = a.map(\.foo.bar) """# let expected = #""" let x = \.foo let y = \.foo.bar let z = a.map(\.foo.bar) """# assertPrettyPrintEqual(input: input, expected: expected, linelength: 80) } func testWithType() { let input = #""" let x = \Type.foo let y = \Type.foo.bar let z = a.map(\Type.foo.bar) """# let expected = #""" let x = \Type.foo let y = \Type.foo.bar let z = a.map(\Type.foo.bar) """# assertPrettyPrintEqual(input: input, expected: expected, linelength: 80) } func testOptionalUnwrap() { let input = #""" let x = \.foo? let y = \.foo!.bar let z = a.map(\.foo!.bar) """# let expected = #""" let x = \.foo? let y = \.foo!.bar let z = a.map(\.foo!.bar) """# assertPrettyPrintEqual(input: input, expected: expected, linelength: 80) } func testSubscript() { let input = #""" let x = \.foo[0] let y = \.foo[0].bar let z = a.map(\.foo[0].bar) """# let expected = #""" let x = \.foo[0] let y = \.foo[0].bar let z = a.map(\.foo[0].bar) """# assertPrettyPrintEqual(input: input, expected: expected, linelength: 80) } func testImplicitSelfUnwrap() { let input = #""" //let x = \.?.foo //let y = \.?.foo.bar let z = a.map(\.?.foo.bar) """# let expected = #""" //let x = \.?.foo //let y = \.?.foo.bar let z = a.map(\.?.foo.bar) """# assertPrettyPrintEqual(input: input, expected: expected, linelength: 80) } }
apache-2.0
imjerrybao/FutureKit
FutureKitTests/PromiseTests.swift
1
37344
// // PromiseTests.swift // FutureKit // // Created by Skyler Gray on 6/25/15. // Copyright (c) 2015 Michael Gray. All rights reserved. // import FutureKit import Foundation import XCTest class FKTestCase : BlockBasedTestCase { var current_expecatation_count = 0 override func expectationWithDescription(description: String) -> XCTestExpectation { current_expecatation_count++ return super.expectationWithDescription(description) } override func waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler handlerOrNil: XCWaitCompletionHandler!) { super.waitForExpectationsWithTimeout(timeout, handler: handlerOrNil) self.current_expecatation_count = 0 } } private enum PromiseState : CustomStringConvertible, CustomDebugStringConvertible { case NotCompleted case Success(Any) case Fail(FutureKitError) case Cancelled var description : String { switch self { case .NotCompleted: return "NotCompleted" case let .Success(r): return "Success\(r)" case .Fail: return "Fail" case .Cancelled: return "Cancelled" } } var debugDescription : String { return self.description } init(errorMessage:String) { self = .Fail(FutureKitError.GenericError(errorMessage)) } init(exception:NSException) { self = .Fail(FutureKitError.ExceptionCaught(exception,nil)) } func create<T>() -> Promise<T> // create a promise in state { let p = Promise<T>() switch self { case .NotCompleted: break case let .Success(a): let result = a as! T p.completeWithSuccess(result) case let .Fail(e): p.completeWithFail(e) case .Cancelled: p.completeWithCancel() } return p } func addExpectations<T : Equatable>(promise : Promise<T>,testCase : FKTestCase,testVars: PromiseTestCase<T>, name : String) { // validate promise in this state let future = promise.future switch self { case NotCompleted: break case let .Success(r): let expectedResult = r as! T let futureExecuctor = testVars.futureExecutor let onCompleteExpecation = testCase.expectationWithDescription("OnComplete") let onSuccessExpectation = testCase.expectationWithDescription("OnSuccess") future.onSuccess (futureExecuctor) { (result) -> Void in XCTAssert(result == expectedResult, "unexpected result!") onSuccessExpectation.fulfill() } future.onComplete (futureExecuctor) { (completion) -> Void in switch completion { case let .Success(r): XCTAssert(r == expectedResult, "unexpected result!") default: XCTFail("completion in wrong state \(completion)") } XCTAssert(completion.state == .Success, "unexpected state!") XCTAssert(completion.result == expectedResult, "unexpected result!") XCTAssert(completion.error == nil, "unexpected error!") XCTAssert(completion.isSuccess == true, "unexpected state!") XCTAssert(completion.isFail == false, "unexpected state!") XCTAssert(completion.isCancelled == false, "unexpected state!") XCTAssert(completion.isCompleteUsing == false, "unexpected state!") onCompleteExpecation.fulfill() } case let .Fail(expectedError): let futureExecuctor = testVars.futureExecutor let onCompleteExpecation = testCase.expectationWithDescription("OnComplete") let onFailExpectation = testCase.expectationWithDescription("OnFail") future.onFail (futureExecuctor) { (error) -> Void in let nserror = error as! FutureKitError XCTAssert(nserror == expectedError, "unexpected error! [\(nserror)]\n expected [\(expectedError)]") onFailExpectation.fulfill() } future.onComplete (futureExecuctor) { (completion) -> Void in switch completion { case let .Fail(error): let nserror = error as! FutureKitError XCTAssert(nserror == expectedError, "unexpected error! [\(nserror)]\n expected [\(expectedError)]") default: XCTFail("completion in wrong state \(completion)") } XCTAssert(completion.state == .Fail, "unexpected state!") XCTAssert(completion.result == nil, "unexpected result!") let cnserror = completion.error as! FutureKitError XCTAssert(cnserror == expectedError, "unexpected error! \(cnserror) expected \(expectedError)") XCTAssert(completion.isSuccess == false, "unexpected state!") XCTAssert(completion.isFail == true, "unexpected state!") XCTAssert(completion.isCancelled == false, "unexpected state!") XCTAssert(completion.isCompleteUsing == false, "unexpected state!") onCompleteExpecation.fulfill() } case .Cancelled: let futureExecuctor = testVars.futureExecutor let onCompleteExpecation = testCase.expectationWithDescription("OnComplete") let onCancelExpectation = testCase.expectationWithDescription("OnCancel") future.onCancel (futureExecuctor) { (_) -> Void in onCancelExpectation.fulfill() } future.onComplete (futureExecuctor) { (completion) -> Void in switch completion { case .Cancelled: break; default: XCTFail("completion in wrong state \(completion)") } XCTAssert(completion.error == nil, "unexpected error \(completion)!") XCTAssert(completion.state == .Cancelled, "unexpected state! \(completion)") onCompleteExpecation.fulfill() } } } func validate<T : Equatable>(promise : Promise<T>,testCase : FKTestCase,testVars: PromiseTestCase<T>, name : String) { // validate promise in this state switch self { case NotCompleted: XCTAssert(!promise.isCompleted, "Promise is not in state \(self)") default: break } } } private var _testsNumber : Int = 0 private var _dateStarted : NSDate? private var _number_of_tests :Int = 0 func howMuchTimeLeft() -> String { if let date = _dateStarted { let howLongSinceWeStarted = -date.timeIntervalSinceNow let avg_time_per_test = howLongSinceWeStarted / Double(_testsNumber) let number_of_tests_left = _number_of_tests - _testsNumber let timeRemaining = NSTimeInterval(number_of_tests_left) * avg_time_per_test let timeWeWillFinished = NSDate(timeIntervalSinceNow: timeRemaining) let localTime = NSDateFormatter.localizedStringFromDate(timeWeWillFinished, dateStyle: .NoStyle, timeStyle: .ShortStyle) let minsRemaining = Int(timeRemaining / 60.0) return "\(minsRemaining) mins remaining. ETA:\(localTime)" } else { _dateStarted = NSDate() return "estimating..??" } } private struct PromiseFunctionTest<T : Equatable> { typealias TupleType = (PromiseState,PromiseFunctions,PromiseState) let initialState : PromiseState let functionToTest : PromiseFunctions let finalExpectedState : PromiseState init(_ initialState : PromiseState, _ functionToTest : PromiseFunctions,_ finalExpectedState : PromiseState) { self.initialState = initialState self.functionToTest = functionToTest self.finalExpectedState = finalExpectedState } var description : String { return "\(initialState.description)_\(functionToTest.description)_\(finalExpectedState.description)" } func executeTest(testCase : FKTestCase, testVars: PromiseTestCase<T>, name : String) { NSLog("testsNumber = \(_testsNumber) ") _testsNumber++ NSLog("PromiseFunctionTest = \(howMuchTimeLeft()), \(_testsNumber)/\(_number_of_tests)") let promise : Promise<T> = initialState.create() let expectation = testCase.expectationWithDescription("testFinished") let funcExpectation = self.functionToTest.addExpectation(testCase) self.finalExpectedState.addExpectations(promise,testCase: testCase,testVars: testVars, name :name) testVars.promiseExecutor.execute { () -> Void in self.functionToTest.executeWith(promise,test: testVars,testCase:testCase,expectation: funcExpectation) testVars.promiseExecutor.execute { () -> Void in self.finalExpectedState.validate(promise,testCase: testCase,testVars: testVars, name :name) expectation.fulfill() } } testCase.waitForExpectationsWithTimeout(maxWaitForExpecations, handler: nil) } } let maxWaitForExpecations : NSTimeInterval = 5.0 private struct PromiseTestCase<T : Equatable> { let functionTest : PromiseFunctionTest<T> let promiseExecutor: Executor let futureExecutor: Executor var description : String { return "\(functionTest.description)_\(promiseExecutor.description)_\(futureExecutor.description)" } func executeTest(testCase : FKTestCase, name : String) { self.functionTest.executeTest(testCase, testVars: self, name: name) } } extension PromiseFunctionTest { static func createAllTheTests(result:T, result2:T, promiseExecutor:Executor,futureExecutor:Executor) -> [PromiseFunctionTest] { var tests = [PromiseFunctionTest]() let error : FutureKitError = .GenericError("PromiseFunctionTest") let error2 : FutureKitError = .GenericError("PromiseFunctionTest2") let errorMessage = "PromiseFunctionTest Error Message!" let errorMessage2 = "PromiseFunctionTest Error Message 2!" let exception = NSException(name: "PromiseFunctionTest", reason: "Reason 1", userInfo: nil) let exception2 = NSException(name: "PromiseFunctionTest 2", reason: "Reason 2", userInfo: nil) let successFuture = Future<T>(success:result) let failedFuture = Future<T>(failed:error) let cancelledFuture = Future<T>(cancelled:()) let promiseForUnfinishedFuture = Promise<T>() let unfinishedFuture = promiseForUnfinishedFuture.future let failErrorMessage = PromiseState(errorMessage: errorMessage) let failException = PromiseState(exception:exception) let blockThatMakesDelayedFuture = { (delay : NSTimeInterval, completion:Completion<T>) -> Future<T> in let p = Promise<T>() promiseExecutor.executeAfterDelay(delay) { p.complete(completion) } return p.future } let autoDelay = NSTimeInterval(0.2) tests.append(PromiseFunctionTest(.NotCompleted, .automaticallyCancelAfter(autoDelay), .NotCompleted)) tests.append(PromiseFunctionTest(.NotCompleted, .automaticallyCancelAfter(autoDelay), .Cancelled)) tests.append(PromiseFunctionTest(.Success(result), .automaticallyCancelAfter(autoDelay), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .automaticallyCancelAfter(autoDelay), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .automaticallyCancelAfter(autoDelay), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .automaticallyFailAfter(autoDelay, error), .NotCompleted)) tests.append(PromiseFunctionTest(.NotCompleted, .automaticallyFailAfter(autoDelay, error), .Fail(error))) tests.append(PromiseFunctionTest(.Success(result), .automaticallyFailAfter(autoDelay, error), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .automaticallyFailAfter(autoDelay, error2), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .automaticallyFailAfter(autoDelay, error), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .complete(SUCCESS(result)), .Success(result))) tests.append(PromiseFunctionTest(.Success(result), .complete(SUCCESS(result2)), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .complete(SUCCESS(result)), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .complete(SUCCESS(result)), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .complete(FAIL(error)), .Fail(error))) tests.append(PromiseFunctionTest(.Success(result), .complete(FAIL(error)), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .complete(FAIL(error2)), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .complete(FAIL(error)), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .complete(CANCELLED()), .Cancelled)) tests.append(PromiseFunctionTest(.Success(result), .complete(CANCELLED()), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .complete(CANCELLED()), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .complete(CANCELLED()), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .complete(COMPLETE_USING(successFuture).As()), .Success(result))) tests.append(PromiseFunctionTest(.Success(result2),.complete(COMPLETE_USING(successFuture).As()), .Success(result2))) tests.append(PromiseFunctionTest(.Fail(error), .complete(COMPLETE_USING(successFuture).As()), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .complete(COMPLETE_USING(successFuture).As()), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .complete(COMPLETE_USING(failedFuture).As()), .Fail(error))) tests.append(PromiseFunctionTest(.Success(result), .complete(COMPLETE_USING(failedFuture).As()), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error2), .complete(COMPLETE_USING(failedFuture).As()), .Fail(error2))) tests.append(PromiseFunctionTest(.Cancelled, .complete(COMPLETE_USING(failedFuture).As()), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .complete(COMPLETE_USING(cancelledFuture).As()), .Cancelled)) tests.append(PromiseFunctionTest(.Success(result), .complete(COMPLETE_USING(cancelledFuture).As()), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .complete(COMPLETE_USING(cancelledFuture).As()), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .complete(COMPLETE_USING(cancelledFuture).As()), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .complete(COMPLETE_USING(unfinishedFuture).As()), .NotCompleted)) tests.append(PromiseFunctionTest(.Success(result), .complete(COMPLETE_USING(unfinishedFuture).As()), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .complete(COMPLETE_USING(unfinishedFuture).As()), .Fail(error))) tests.append(PromiseFunctionTest(.Cancelled, .complete(COMPLETE_USING(unfinishedFuture).As()), .Cancelled)) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithSuccess(result), .Success(result))) tests.append(PromiseFunctionTest(.Success(result), .completeWithSuccess(result2), .Success(result))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithFail(error), .Fail(error))) tests.append(PromiseFunctionTest(.Fail(error), .completeWithFail(error2), .Fail(error))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithFailErrorMessage(errorMessage), failErrorMessage)) tests.append(PromiseFunctionTest(failErrorMessage, .completeWithFailErrorMessage(errorMessage2), failErrorMessage)) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithException(exception), failException)) tests.append(PromiseFunctionTest(failException, .completeWithException(exception2), failException)) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithCancel, .Cancelled)) tests.append(PromiseFunctionTest(.Success(result), .completeWithCancel, .Success(result))) tests.append(PromiseFunctionTest(.NotCompleted, .completeUsingFuture(successFuture), .Success(result))) tests.append(PromiseFunctionTest(.Success(result2), .completeUsingFuture(successFuture), .Success(result2))) tests.append(PromiseFunctionTest(.Fail(error), .completeUsingFuture(successFuture), .Fail(error))) tests.append(PromiseFunctionTest(.NotCompleted, .completeUsingFuture(failedFuture), .Fail(error))) let successBlock = { () -> Completion<Any> in return SUCCESS(result) } let failBlock = { () -> Completion<Any> in return FAIL(error) } let delayedSuccessBlock = { () -> Completion<Any> in let f = blockThatMakesDelayedFuture(autoDelay,SUCCESS(result)) return .CompleteUsing(f.As()) } let extraDelayedSuccessBlock = { () -> Completion<Any> in let f = blockThatMakesDelayedFuture(autoDelay,SUCCESS(result)) let f2 = blockThatMakesDelayedFuture(autoDelay,COMPLETE_USING(f)) return .CompleteUsing(f2.As()) } let extraDelayedFailBlock = { () -> Completion<Any> in let f = blockThatMakesDelayedFuture(autoDelay,FAIL(error)) let f2 = blockThatMakesDelayedFuture(autoDelay,COMPLETE_USING(f)) return .CompleteUsing(f2.As()) } tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlock(successBlock), .Success(result))) tests.append(PromiseFunctionTest(.Success(result2), .completeWithBlock(successBlock), .Success(result2))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlock(failBlock), .Fail(error))) tests.append(PromiseFunctionTest(.Success(result), .completeWithBlock(failBlock), .Success(result))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlock(delayedSuccessBlock), .NotCompleted)) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlock(delayedSuccessBlock), .Success(result))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlock(extraDelayedSuccessBlock), .Success(result))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlock(extraDelayedFailBlock), .Fail(error))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlock(extraDelayedFailBlock), .Fail(error))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlocksOnAlreadyCompleted(successBlock,true), .Success(result))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlocksOnAlreadyCompleted(failBlock,true), .Fail(error))) tests.append(PromiseFunctionTest(.Success(result2), .completeWithBlocksOnAlreadyCompleted(successBlock,false), .Success(result2))) tests.append(PromiseFunctionTest(.Success(result), .completeWithBlocksOnAlreadyCompleted(failBlock,false), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .completeWithBlocksOnAlreadyCompleted(successBlock,false), .Fail(error))) tests.append(PromiseFunctionTest(.Fail(error2), .completeWithBlocksOnAlreadyCompleted(failBlock,false), .Fail(error2))) tests.append(PromiseFunctionTest(.NotCompleted, .tryComplete(SUCCESS(result),true), .Success(result))) tests.append(PromiseFunctionTest(.NotCompleted, .tryComplete(FAIL(error),true), .Fail(error))) tests.append(PromiseFunctionTest(.Success(result2), .tryComplete(SUCCESS(result),false), .Success(result2))) tests.append(PromiseFunctionTest(.Success(result), .tryComplete(FAIL(error),false), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .tryComplete(SUCCESS(result),false), .Fail(error))) tests.append(PromiseFunctionTest(.Fail(error2), .tryComplete(FAIL(error),false), .Fail(error2))) tests.append(PromiseFunctionTest(.NotCompleted, .completeWithBlocksOnAlreadyCompleted(failBlock,true), .Fail(error))) tests.append(PromiseFunctionTest(.Success(result2), .completeWithBlocksOnAlreadyCompleted(successBlock,false), .Success(result2))) tests.append(PromiseFunctionTest(.Success(result), .completeWithBlocksOnAlreadyCompleted(failBlock,false), .Success(result))) tests.append(PromiseFunctionTest(.Fail(error), .completeWithBlocksOnAlreadyCompleted(successBlock,false), .Fail(error))) tests.append(PromiseFunctionTest(.Fail(error2), .completeWithBlocksOnAlreadyCompleted(failBlock,false), .Fail(error2))) return tests } } private enum PromiseFunctions { case automaticallyCancelAfter(NSTimeInterval) case automaticallyFailAfter(NSTimeInterval,ErrorType) // case automaticallyAssertOnFail(NSTimeInterval) // can't test assert // TODO: Test Cancelation Requests // case onRequestCancelExecutor(CancelRequestHandler) // case onRequestCancel(CancelRequestHandler) // case automaticallyCancelOnRequestCancel case complete(Completion<Any>) case completeWithSuccess(Any) case completeWithFail(ErrorType) case completeWithFailErrorMessage(String) case completeWithException(NSException) case completeWithCancel case completeUsingFuture(FutureProtocol) case completeWithBlock(()->Completion<Any>) // The block is executed. The Bool should be TRUE is we expect that the completeWithBlocks will succeed. case completeWithBlocksOnAlreadyCompleted(()->Completion<Any>,Bool) case failIfNotCompleted(ErrorType) case failIfNotCompletedErrorMessage(String) case tryComplete(Completion<Any>,Bool) // The Bool should be TRUE is we expect that the tryComplete will succeed. case completeWithOnCompletionError(Completion<Any>,Bool) // last value is TRUE if we expect the completion to succeed func addExpectation(testCase : FKTestCase) -> XCTestExpectation? { switch self { case let .completeWithBlocksOnAlreadyCompleted(_,completeWillSucceed): if (!completeWillSucceed) { return testCase.expectationWithDescription("we expect OnAlreadyCompleted to be executed") } else { return nil } case let .completeWithOnCompletionError(_,completeWillSucceed): if (!completeWillSucceed) { return testCase.expectationWithDescription("we expect OnCompletionError to be executed") } else { return nil } default: return nil } } func executeWith<T>(promise : Promise<T>,test : PromiseTestCase<T>, testCase : FKTestCase, expectation:XCTestExpectation?) { switch self { case let .automaticallyCancelAfter(delay): promise.automaticallyCancelAfter(delay) case let .automaticallyFailAfter(delay,error): promise.automaticallyFailAfter(delay,error:error) /* case let .onRequestCancelExecutor(handler): promise.onRequestCancel(test.promiseExecutor, handler: handler) case let .onRequestCancel(handler): promise.onRequestCancel(handler) case .automaticallyCancelOnRequestCancel: promise.automaticallyCancelOnRequestCancel() */ case let .complete(completion): promise.complete(completion.As()) case let .completeWithSuccess(r): let result = r as! T promise.completeWithSuccess(result) case let .completeWithFail(error): promise.completeWithFail(error) case let .completeWithFailErrorMessage(message): promise.completeWithFail(message) case let .completeWithException(exception): promise.completeWithException(exception) case .completeWithCancel: promise.completeWithCancel() case let .completeUsingFuture(future): promise.completeUsingFuture(future.As()) case let .completeWithBlock(block): promise.completeWithBlock { () -> Completion<T> in return block().As() } case let .completeWithBlocksOnAlreadyCompleted(completeBlock,_): promise.completeWithBlocks( { () -> Completion<T> in return completeBlock().As() }, onAlreadyCompleted: { () -> Void in if let ex = expectation { ex.fulfill() } else { XCTFail("we did not expect onAlreadyCompleted to be executed!") } } ) case let .failIfNotCompleted(error): promise.failIfNotCompleted(error) case let .failIfNotCompletedErrorMessage(message): promise.failIfNotCompleted(message) case let .tryComplete(completion,expectedReturnValue): let r = promise.tryComplete(completion.As()) XCTAssert(r == expectedReturnValue, "tryComplete returned \(r)") case let .completeWithOnCompletionError(completion,_): promise.complete(completion.As(),onCompletionError: { () -> Void in if let ex = expectation { ex.fulfill() } else { XCTFail("we did not expect onAlreadyCompleted to be executed!") } }) } } var description : String { switch self { case let .automaticallyCancelAfter(delay): return "automaticallyCancelAfter\(delay)" case let .automaticallyFailAfter(delay,_): return "automaticallyFailAfter\(delay)" /* case let .onRequestCancelExecutor(handler): return "onRequestCancel(test.promiseExecutor, handler: handler) case let .onRequestCancel(handler): return "onRequestCancel(handler) case .automaticallyCancelOnRequestCancel: return "automaticallyCancelOnRequestCancel() */ case let .complete(completion): switch completion { case let .Success(r): return "complete_Success_\(r)" case let .Fail(e): return "complete_Fail_\(e)" case .Cancelled: return "complete_Cancelled" case .CompleteUsing(_): return "complete_CompleteUsing" } case let .completeWithSuccess(r): return "completeWithSuccess\(r)" case .completeWithFail(_): return "completeWithFail" case .completeWithFailErrorMessage(_): return "completeWithFailErrorMessage" case .completeWithException(_): return "completeWithException" case .completeWithCancel: return "completeWithCancel" case .completeUsingFuture(_): return "completeUsingFuture)" case .completeWithBlock(_): return "completeWithBlock" case .completeWithBlocksOnAlreadyCompleted(_,_): return "completeWithBlocksOnAlreadyCompleted" case .failIfNotCompleted(_): return "failIfNotCompleted" case .failIfNotCompletedErrorMessage(_): return "failIfNotCompletedErrorMessage" case let .tryComplete(completion,_): return "tryComplete\(completion.state)" case .completeWithOnCompletionError(_,_): return "completeWithOnCompletionError" } } } class PromiseTests: FKTestCase { class func testsFor<T : Equatable>(result:T, result2:T) -> [BlockBasedTest] { let custom : Executor.CustomCallBackBlock = { (callback) -> Void in Executor.Background.execute { Executor.Main.execute { callback() } } } let opQueue = NSOperationQueue() opQueue.maxConcurrentOperationCount = 2 let q = dispatch_queue_create("custom q", DISPATCH_QUEUE_CONCURRENT) let old_executors : [Executor] = [.Primary, .Main, .Async, .Current, .Immediate, .StackCheckingImmediate, .MainAsync, .MainImmediate, .UserInteractive, .UserInitiated, .Default, .Utility, .Background, .OperationQueue(opQueue), .Custom(custom), .Queue(q)] let full_executors_list : [Executor] = [ .Main, .Current, .MainAsync, .MainImmediate, .Default, .Immediate, .Background, .StackCheckingImmediate, .OperationQueue(opQueue), .Custom(custom), .Queue(q)] let quick_executors_list : [Executor] = [ .MainAsync, .Async, .Immediate] let future_executors : [Executor] = [.MainAsync, .MainImmediate] var blockTests = [BlockBasedTest]() let setOfCharsWeGottaGetRidOf = NSCharacterSet(charactersInString: ".(),\n\t {}[];:=-") for promiseE in quick_executors_list { for futureE in quick_executors_list { let tests = PromiseFunctionTest<T>.createAllTheTests(result,result2: result2,promiseExecutor: promiseE,futureExecutor: futureE) for (index,t) in tests.enumerate() { let tvars = PromiseTestCase<T>(functionTest:t, promiseExecutor:promiseE, futureExecutor:futureE) let n: NSString = "test_\(index)_\(T.self)_\(result)_\(tvars.description)" let c : NSArray = n.componentsSeparatedByCharactersInSet(setOfCharsWeGottaGetRidOf) let name = c.componentsJoinedByString("") let t = self.addTest(name, closure: { (_self : PromiseTests) -> Void in tvars.executeTest(_self, name: name) })! blockTests.append(t) } } } return blockTests } override class func myBlockBasedTests() -> [AnyObject] { var tests = [BlockBasedTest]() // let v: () = () // tests += self.testsFor(v, result2: v) tests += self.testsFor(["Bob" : 1.0],result2: ["Jane" : 2.0]) tests += self.testsFor(Int(0),result2: Int(1)) tests += self.testsFor(String("Hi"),result2: String("Bye")) tests += self.testsFor(Float(0.0),result2: Float(1.0)) // array tests += self.testsFor([0.0,1.0],result2: [2.0,3.0]) // dictionary _number_of_tests = tests.count return tests } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func onPromiseSuccessVoid(promiseExecutor p: Executor, futureExecutor : Executor) { let promise = Promise<Void>() let f = promise.future let success: () = () let completeExpectation = self.expectationWithDescription("Future.onComplete") // let successExpectation = self.expectationWithDescription("Future.onSuccess") let anySuccessExpectation = self.expectationWithDescription("Future.onAnySuccess") f.onComplete(futureExecutor) { (completion) -> Void in switch completion { case .Success(_): break default: XCTFail("unexpectad completion value \(completion)") } completeExpectation.fulfill() } // TODO: Can we get this to compile? /* f.onSuccess(futureExecutor) { (result:()) -> Void in successExpectation.fulfill() } */ f.onAnySuccess(futureExecutor) { (result) -> Void in XCTAssert(result is Void, "Didn't get expected success value \(success)") anySuccessExpectation.fulfill() } f.onFail(futureExecutor) { (error) -> Void in XCTFail("unexpectad onFail error \(error)") } f.onCancel(futureExecutor) { () -> Void in XCTFail("unexpectad onCancel" ) } promise.completeWithSuccess(success) self.waitForExpectationsWithTimeout(0.5, handler: nil) } func onPromiseSuccess<T : Equatable>(success:T, promiseExecutor : Executor, futureExecutor : Executor) { let promise = Promise<T>() let f = promise.future let completeExpectation = self.expectationWithDescription("Future.onComplete") let successExpectation = self.expectationWithDescription("Future.onSuccess") let anySuccessExpectation = self.expectationWithDescription("Future.onAnySuccess") f.onComplete(futureExecutor) { (completion) -> Void in switch completion { case let .Success(t): XCTAssert(t == success, "Didn't get expected success value \(success)") XCTAssert(completion.result == success, "Didn't get expected success value \(success)") default: XCTFail("unexpectad completion value \(completion)") } completeExpectation.fulfill() } f.onSuccess(futureExecutor) { (result) -> Void in XCTAssert(result == success, "Didn't get expected success value \(success)") successExpectation.fulfill() } f.onAnySuccess(futureExecutor) { (result) -> Void in let r = result as! T XCTAssert(r == success, "Didn't get expected success value \(success)") anySuccessExpectation.fulfill() } f.onFail(futureExecutor) { (error) -> Void in XCTFail("unexpectad onFail error \(error)") } f.onCancel(futureExecutor) { () -> Void in XCTFail("unexpectad onCancel" ) } promiseExecutor.execute { promise.completeWithSuccess(success) } self.waitForExpectationsWithTimeout(0.5, handler: nil) } func testPromiseSuccess() { self.onPromiseSuccess(0, promiseExecutor: .Primary, futureExecutor: .Primary) self.onPromiseSuccess("String", promiseExecutor: .Primary, futureExecutor: .Primary) self.onPromiseSuccess([1,2], promiseExecutor: .Primary, futureExecutor: .Primary) self.onPromiseSuccessVoid(promiseExecutor: .Primary, futureExecutor: .Primary) } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
vhart/PPL-iOS
PPL-iOS/PPL-iOS/ImageViewController.swift
1
1073
// // ImageViewController.swift // PPL-iOS // // Created by Jovanny Espinal on 3/2/16. // Copyright © 2016 Jovanny Espinal. All rights reserved. // import UIKit class ImageViewController: UIViewController { @IBOutlet weak var bodyImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/DNMColorManager.swift
1
480
// // DNMColorManager.swift // DNMView // // Created by James Bean on 10/31/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class DNMColorManager { public static var colorMode: ColorMode = .Dark public static var backgroundColor: UIColor { get { switch colorMode { case .Light: return UIColor.whiteColor() case .Dark: return UIColor.blackColor() } } } }
gpl-2.0
ashfurrow/eidolon
KioskTests/App/ArtsyProviderTests.swift
2
1522
import Quick import Nimble import RxSwift @testable import Kiosk import Moya class ArtsyProviderTests: QuickSpec { override func spec() { let fakeEndpointsClosure = { (target: ArtsyAPI) -> Endpoint in return Endpoint(url: url(target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: nil) } var fakeOnline: PublishSubject<Bool>! var subject: Networking! var defaults: UserDefaults! beforeEach { fakeOnline = PublishSubject<Bool>() subject = Networking(provider: OnlineProvider<ArtsyAPI>(endpointClosure: fakeEndpointsClosure, stubClosure: MoyaProvider<ArtsyAPI>.immediatelyStub, online: fakeOnline.asObservable())) // We fake our defaults to avoid actually hitting the network defaults = UserDefaults() defaults.set(NSDate.distantFuture, forKey: "TokenExpiry") defaults.set("Some key", forKey: "TokenKey") } it ("waits for the internet to happen before continuing with network operations") { var called = false let disposeBag = DisposeBag() subject.request(ArtsyAPI.ping, defaults: defaults).subscribe(onNext: { _ in called = true }).disposed(by: disposeBag) expect(called) == false // Fake getting online fakeOnline.onNext(true) expect(called) == true } } }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/ConfirmationPage/LocalizationConstants.swift
1
298
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization extension LocalizationConstants { enum Checkout { static let swapTitle = NSLocalizedString( "Confirm Swap", comment: "Swap confirmation navigation bar title" ) } }
lgpl-3.0
huonw/swift
test/Sema/synthesized_conformance_swift_3.swift
1
1870
// RUN: %target-typecheck-verify-swift -swift-version 3 // All of these cases should work in Swift 4, so do a normal without -verify should succeed: // RUN: %target-swift-frontend -typecheck %s -swift-version 4 struct Struct {} extension Struct: Equatable {} // expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in Swift 3}} extension Struct: Codable {} // expected-error@-1{{implementation of 'Encodable' cannot be automatically synthesized in an extension in Swift 3}} // expected-error@-2{{implementation of 'Decodable' cannot be automatically synthesized in an extension in Swift 3}} final class Final {} extension Final: Codable {} // expected-error@-1{{implementation of 'Encodable' cannot be automatically synthesized in an extension in Swift 3}} // expected-error@-2{{implementation of 'Decodable' cannot be automatically synthesized in an extension in Swift 3}} class Nonfinal {} extension Nonfinal: Encodable {} // expected-error@-1{{implementation of 'Encodable' cannot be automatically synthesized in an extension in Swift 3}} enum NoValues { case a, b } // This case has been able to be synthesized since at least Swift 3, so it // should work in that mode. extension NoValues: Equatable {} extension NoValues: Hashable {} extension NoValues: CaseIterable {} // expected-error@-1{{implementation of 'CaseIterable' cannot be automatically synthesized in an extension in Swift 3}} // expected-error@-2{{type 'NoValues' does not conform to protocol 'CaseIterable'}} enum Values { case a(Int), b } extension Values: Equatable {} // expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in Swift 3}} extension Values: Hashable {} // expected-error@-1{{implementation of 'Hashable' cannot be automatically synthesized in an extension in Swift 3}}
apache-2.0
RushingTwist/SwiftExamples
Swifttttt/Pods/Moya/Sources/Moya/Plugins/NetworkActivityPlugin.swift
9
1095
import Foundation import Result /// Network activity change notification type. public enum NetworkActivityChangeType { case began, ended } /// Notify a request's network activity changes (request begins or ends). public final class NetworkActivityPlugin: PluginType { public typealias NetworkActivityClosure = (_ change: NetworkActivityChangeType, _ target: TargetType) -> Void let networkActivityClosure: NetworkActivityClosure /// Initializes a NetworkActivityPlugin. public init(networkActivityClosure: @escaping NetworkActivityClosure) { self.networkActivityClosure = networkActivityClosure } // MARK: Plugin /// Called by the provider as soon as the request is about to start public func willSend(_ request: RequestType, target: TargetType) { networkActivityClosure(.began, target) } /// Called by the provider as soon as a response arrives, even if the request is canceled. public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) { networkActivityClosure(.ended, target) } }
apache-2.0
huonw/swift
validation-test/compiler_crashers_fixed/01432-swift-bracestmt-create.swift
65
704
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck enum B : a { struct c { class a) b, x { typealias F = { } } func a<T : a { func i(i<T.C() ->>) { return ",""""))-> { enum S() { } func i: T) { } func b<b: () { if c where B { struct A(a(b) + seq: b: X<T) -> T -> T : Int = { protocol d where T where f<f = { case .Iterator.a<H : a: d where T where I) { } }
apache-2.0
huonw/swift
validation-test/compiler_crashers_fixed/25443-swift-parser-parsedecl.swift
65
443
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var a={enum B{extension{ class a{class case,
apache-2.0
arsonik/SharpTv
Source/SharpTvSwitch.swift
1
958
// // YamahaAVSwitch.swift // Pods // // Created by Florian Morello on 21/11/15. // // import UIKit public class SharpTvSwitch : UISwitch { public weak var sharp:SharpTv? { didSet { let _ = sharp?.sendString(SharpTv.Power.Get.rawValue) } } public override func awakeFromNib() { super.awakeFromNib() addTarget(self, action: #selector(SharpTvSwitch.valueChanged), for: UIControlEvents.valueChanged) } internal func updated(_ notification: Notification) { /* if let v = (notification.object as? SharpTv)?.mainZonePower where !highlighted && notification.name == YamahaAV.updatedNotificationName { setOn(v, animated: true) } */ } @IBAction func valueChanged() { let _ = sharp?.sendString(isOn ? SharpTv.Power.On.rawValue : SharpTv.Power.Off.rawValue) } deinit { NotificationCenter.default.removeObserver(self) } }
mit
huonw/swift
validation-test/compiler_crashers_fixed/00774-unowned.swift
65
502
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol A : a { } protocol a { func e: b { } func c(() -> Any) { } protocol A { } typealias d : e: C {
apache-2.0
AndreyPanov/ApplicationCoordinator
ApplicationCoordinator/Flows/MainTabbarFlow/TabbarCoordinator.swift
1
1242
class TabbarCoordinator: BaseCoordinator { private let tabbarView: TabbarView private let coordinatorFactory: CoordinatorFactory init(tabbarView: TabbarView, coordinatorFactory: CoordinatorFactory) { self.tabbarView = tabbarView self.coordinatorFactory = coordinatorFactory } override func start() { tabbarView.onViewDidLoad = runItemFlow() tabbarView.onItemFlowSelect = runItemFlow() tabbarView.onSettingsFlowSelect = runSettingsFlow() } private func runItemFlow() -> ((UINavigationController) -> ()) { return { [unowned self] navController in if navController.viewControllers.isEmpty == true { let itemCoordinator = self.coordinatorFactory.makeItemCoordinator(navController: navController) self.addDependency(itemCoordinator) itemCoordinator.start() } } } private func runSettingsFlow() -> ((UINavigationController) -> ()) { return { [unowned self] navController in if navController.viewControllers.isEmpty == true { let settingsCoordinator = self.coordinatorFactory.makeSettingsCoordinator(navController: navController) self.addDependency(settingsCoordinator) settingsCoordinator.start() } } } }
mit
googlearchive/science-journal-ios
ScienceJournal/UI/TriggerListCell.swift
1
3576
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_CollectionCells_CollectionCells import third_party_objective_c_material_components_ios_components_Typography_Typography protocol TriggerListCellDelegate: class { /// Called when the switch value changes. func triggerListCellSwitchValueChanged(_ triggerListCell: TriggerListCell) /// Called when the menu button is pressed. func triggerListCellMenuButtonPressed(_ triggerListCell: TriggerListCell) } /// A cell used to display a trigger in the trigger list. class TriggerListCell: MDCCollectionViewCell { // MARK: - Constants /// The cell height. static let height: CGFloat = 54 private let horizontalPadding: CGFloat = 16 // MARK: - Properties /// The delegate. weak var delegate: TriggerListCellDelegate? /// The text label. let textLabel = UILabel() /// The switch. let aSwitch = UISwitch() /// The menu button. let menuButton = MenuButton() // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } // MARK: - Private private func configureView() { // Stack view. let stackView = UIStackView() stackView.alignment = .center stackView.spacing = horizontalPadding stackView.layoutMargins = UIEdgeInsets(top: 0, left: horizontalPadding, bottom: 0, right: horizontalPadding) stackView.isLayoutMarginsRelativeArrangement = true stackView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(stackView) stackView.pinToEdgesOfView(contentView) // Text label. textLabel.alpha = MDCTypography.body1FontOpacity() textLabel.font = MDCTypography.body1Font() textLabel.lineBreakMode = .byTruncatingTail textLabel.numberOfLines = 2 textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) stackView.addArrangedSubview(textLabel) // Switch. aSwitch.addTarget(self, action: #selector(switchValueChanged(_:)), for: .valueChanged) aSwitch.translatesAutoresizingMaskIntoConstraints = false aSwitch.setContentHuggingPriority(.required, for: .horizontal) stackView.addArrangedSubview(aSwitch) // Menu button. menuButton.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside) menuButton.tintColor = .darkGray menuButton.translatesAutoresizingMaskIntoConstraints = false menuButton.hitAreaInsets = UIEdgeInsets(top: -20, left: -10, bottom: -20, right: -10) stackView.addArrangedSubview(menuButton) } // MARK: - User actions @objc func switchValueChanged(_ aSwitch: UISwitch) { delegate?.triggerListCellSwitchValueChanged(self) } @objc func menuButtonPressed() { delegate?.triggerListCellMenuButtonPressed(self) } }
apache-2.0
kysonyangs/ysbilibili
ysbilibili/Classes/Home/Live/ViewModel/YSLiveReloadURLhelper.swift
1
3330
// // HomeLiveReloadURLhelper.swift // zhnbilibili // // Created by zhn on 16/11/30. // Copyright © 2016年 zhn. All rights reserved. // import UIKit class YSLiveReloadURLhelper: NSObject { // 加密过的,sign 和 area 有关系只能用这种方法拿 class func createReloadSectionURL(area: String) -> String { // 1. 推荐主播 if area == "hot" { return "http://live.bilibili.com/AppIndex/recommendRefresh?actionKey=appkey&appkey=27eb53fc9058f8c3&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=ee5759f6df79cf2abbaf7927ab35e983&ts=1479286545" } // 2. 绘画 if area == "draw" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=draw&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=dd48aa4f416222aadaa591af573c4faa&ts=1479286692" } // 3. 手机直播 if area == "mobile" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=mobile&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=b70507f063d8325b85426e6b4feddbc6&ts=1479286747" } // 4. 唱见舞见 if area == "sing-dance" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=sing-dance&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=4cd40a5e0073765d156e26ac6115e23a&ts=1479287001" } // 5. 手机游戏 if area == "mobile-game" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=mobile-game&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=6254a0cac7ff9da85a24c037971303f4&ts=1479287130" } // 6.单机 if area == "single"{ return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=single&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=b16eb80648d3eccd337d83bc97c8a5c2&ts=1479287170" } // 7. 网络游戏 if area == "online" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=online&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=0a987b8f320d44ff992ef14c82f8b840&ts=1479287203" } // 8.电子竞技 if area == "e-sports" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=e-sports&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=7b11eb5ad6446055e551ac3cffdfcfb9&ts=1479287244" } // 9. 御宅文化 if area == "otaku" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=otaku&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=59ccc610ead8551347fbbf414caf3191&ts=1479287296" } // 10.放映厅 if area == "movie" { return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=movie&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=07a772a0824d9289da692be8ed3044cb&ts=1479287345" } return "" } }
mit
googlearchive/science-journal-ios
ScienceJournal/UI/JumpToNowButton.swift
1
1578
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import third_party_objective_c_material_components_ios_components_Buttons_Buttons import third_party_objective_c_material_components_ios_components_Palettes_Palettes /// A floating jump-to-now button. class JumpToNowButton: MDCFloatingButton { private var diameter: CGFloat = 48 convenience init() { self.init(frame: .zero, shape: .default) } override init(frame: CGRect, shape: MDCFloatingButtonShape) { super.init(frame: frame, shape: shape) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } private func configureView() { accessibilityLabel = String.btnResetDescription tintColor = .white setImage(UIImage(named: "ic_last_page"), for: .normal) setBackgroundColor(MDCPalette.purple.tint900, for: .normal) } override var intrinsicContentSize: CGSize { return CGSize(width: diameter, height: diameter) } }
apache-2.0
IvanVorobei/ParallaxTableView
ParallaxTableView - project/ParallaxTableView/Sparrow/UI/Views/Views/SPUIViewExtenshion.swift
1
1697
// The MIT License (MIT) // Copyright © 2016 Ivan Vorobei (hello@ivanvorobei.by) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit // MARK: - convertToImage extension UIView { func convertToImage() -> UIImage { return UIImage.drawFromView(view: self) } } // MARK: - gradeView extension UIView { func addGrade(alpha: CGFloat, color: UIColor = UIColor.black) { let gradeView = UIView.init() gradeView.alpha = 0 self.addSubview(gradeView) SPConstraintsAssistent.setEqualSizeConstraint(gradeView, superVuew: self) gradeView.alpha = alpha gradeView.backgroundColor = color } }
mit
chrisk1ng/TransportApiSdk.iOS
TransportApiSdk/Classes/StopTimetable.swift
2
3313
/* Copyright (c) 2017 Swift Models Generated from JSON powered by http://www.json4swift.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation /* For support, please feel free to contact me at https://www.linkedin.com/in/syedabsar */ public class StopTimetable { public var vehicle : Vehicle? public var line : Line? public var departureTime : String? public var arrivalTime : String? /** Returns an array of models based on given dictionary. Sample usage: let json4Swift_Base_list = StopTimetable.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of StopTimetable Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [StopTimetable] { var models:[StopTimetable] = [] for item in array { models.append(StopTimetable(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let json4Swift_Base = StopTimetable(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: StopTimetable Instance. */ required public init?(dictionary: NSDictionary) { if (dictionary["vehicle"] != nil) { vehicle = Vehicle(dictionary: dictionary["vehicle"] as! NSDictionary) } if (dictionary["line"] != nil) { line = Line(dictionary: dictionary["line"] as! NSDictionary) } departureTime = dictionary["departureTime"] as? String arrivalTime = dictionary["arrivalTime"] as? String } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.vehicle?.dictionaryRepresentation(), forKey: "vehicle") dictionary.setValue(self.line?.dictionaryRepresentation(), forKey: "line") dictionary.setValue(self.departureTime, forKey: "departureTime") dictionary.setValue(self.arrivalTime, forKey: "arrivalTime") return dictionary } }
mit