repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SergeyPetrachkov/VIPERTemplates | VIPER/Siberian Table.xctemplate/UIViewController/___FILEBASENAME___Assembly.swift | 1 | 1915 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the SergeyPetrachkov VIPER Xcode Templates so
// you can apply VIPER architecture to your iOS projects
//
import UIKit
class ___VARIABLE_moduleName___Assembly {
// MARK: - Constants
fileprivate static let storyboardId = "Module"
fileprivate static let controllerStoryboardId = "___VARIABLE_moduleName___"
// MARK: - Public methods
static func createModule(moduleIn: ___VARIABLE_moduleName___.DataContext.ModuleIn) -> ___VARIABLE_moduleName___ViewController {
if let controller = UIStoryboard(name: storyboardId, bundle: nil).instantiateViewController(withIdentifier: controllerStoryboardId) as? ___VARIABLE_moduleName___ViewController {
var presenter = injectPresenter(moduleIn: moduleIn)
presenter.output = controller
presenter.view = controller
controller.presenter = presenter
return controller
} else {
fatalError("Could not create ___VARIABLE_moduleName___ module!!! Check ___VARIABLE_moduleName___ assembly")
}
}
// MARK: - Private injections
fileprivate static func injectPresenter(moduleIn: ___VARIABLE_moduleName___.DataContext.ModuleIn) -> ___VARIABLE_moduleName___PresenterInput {
let presenter = ___VARIABLE_moduleName___Presenter(moduleIn: moduleIn)
let interactor = injectInteractor()
interactor.output = presenter
presenter.interactor = interactor
let router = injectRouter()
presenter.router = router
return presenter
}
fileprivate static func injectInteractor() -> ___VARIABLE_moduleName___InteractorInput {
return ___VARIABLE_moduleName___Interactor()
}
fileprivate static func injectRouter() -> ___VARIABLE_moduleName___RoutingLogic {
return ___VARIABLE_moduleName___Router()
}
} | mit | 57f7e9d7213c6165ac09db53ceb01ddd | 40.652174 | 181 | 0.710183 | 4.885204 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/TagCollectionViewCell.swift | 1 | 2714 | public struct Tag {
let readingList: ReadingList
let index: Int
let indexPath: IndexPath
var isLast: Bool
var isCollapsed: Bool
init(readingList: ReadingList, index: Int, indexPath: IndexPath) {
self.readingList = readingList
self.index = index
self.indexPath = indexPath
self.isLast = false
self.isCollapsed = false
}
}
class TagCollectionViewCell: CollectionViewCell {
private let label = UILabel()
let margins = UIEdgeInsets(top: 3, left: 6, bottom: 3, right: 6)
private let maxWidth: CGFloat = 150
public let minWidth: CGFloat = 60
override func setup() {
contentView.addSubview(label)
layer.cornerRadius = 3
clipsToBounds = true
super.setup()
}
func configure(with tag: Tag, for count: Int, theme: Theme) {
guard !tag.isCollapsed, let name = tag.readingList.name else {
return
}
label.text = (tag.isLast ? "+\(count - tag.index)" : name)
apply(theme: theme)
updateFonts(with: traitCollection)
setNeedsLayout()
}
var semanticContentAttributeOverride: UISemanticContentAttribute = .unspecified {
didSet {
label.semanticContentAttribute = semanticContentAttributeOverride
}
}
override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
label.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
}
override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let availableWidth = (size.width == UIViewNoIntrinsicMetric ? maxWidth : size.width) - margins.left - margins.right
var origin = CGPoint(x: margins.left, y: margins.top)
let tagLabelFrame = label.wmf_preferredFrame(at: origin, maximumWidth: availableWidth, alignedBy: semanticContentAttributeOverride, apply: true)
origin.y += tagLabelFrame.height
origin.y += margins.bottom
return CGSize(width: tagLabelFrame.size.width + margins.left
+ margins.right, height: origin.y)
}
override func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
label.backgroundColor = labelBackgroundColor
}
}
extension TagCollectionViewCell: Themeable {
func apply(theme: Theme) {
label.textColor = theme.colors.secondaryText
let backgroundColor = theme.name == Theme.standard.name ? UIColor.wmf_lightestGray : theme.colors.midBackground
setBackgroundColors(backgroundColor, selected: theme.colors.baseBackground)
updateSelectedOrHighlighted()
}
}
| mit | bcd6474fbe44d7dab64fbde74136f6ad | 34.246753 | 152 | 0.66986 | 4.979817 | false | false | false | false |
sdhzwm/BaiSI-Swift- | BaiSi/BaiSi/Classes/FriendTrends(关注)/Controller/WMRecommendController.swift | 1 | 1106 | //
// WMRecommendController.swift
// BaiSi
//
// Created by 王蒙 on 15/7/22.
// Copyright © 2015年 wm. All rights reserved.
//
import UIKit
class WMRecommendController: UIViewController {
var channelController : WMConttainerController!
var friendsController : WMFirendsController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.LobalBg()
self.title = "推荐关注"
channelController.delegate = friendsController
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "channelEmbedSegue" {
if let controller = segue.destinationViewController as? WMConttainerController {
self.channelController = controller
}
} else if segue.identifier == "friendsEmbedSegue" {
if let controller = segue.destinationViewController as? WMFirendsController {
self.friendsController = controller
}
}
}
}
| apache-2.0 | 0beeadd2af297a9f78f05ae27fd9d001 | 26.974359 | 92 | 0.623281 | 5.004587 | false | false | false | false |
gsapoz/Social-Streamliner | SStreamliner/SStreamliner/InstagramModel.swift | 1 | 3107 | //
// PostModel.swift
// SStreamliner
//
// Created by GaryS on 7/6/17.
// Copyright © 2017 Gary Sapozhnikov. All rights reserved.
//
//Instagram Module
struct InstagramUser {
var token: String = ""
var uid: String = ""
var bio: String = ""
var followed_by: String = ""
var follows: String = ""
var media: String = ""
var username: String = ""
var image: String = ""
}
extension ProfileDashboardVC { // Instagram Module
func connectToInstagram() {
let auth: NSMutableDictionary = ["client_id": INSTAGRAM_CLIENT_ID,
SimpleAuthRedirectURIKey: INSTAGRAM_REDIRECT_URI]
SimpleAuth.configuration()["instagram"] = auth
SimpleAuth.authorize("instagram", options: [:]) { (result: Any?, error: Error?) -> Void in
if let result = result as? JSONDictionary {
var token = ""
var uid = ""
var bio = ""
var followed_by = ""
var follows = ""
var media = ""
var username = ""
var image = ""
token = (result["credentials"] as! JSONDictionary)["token"] as! String
uid = result["uid"] as! String
if let extra = result["extra"] as? JSONDictionary,
let rawInfo = extra ["raw_info"] as? JSONDictionary,
let data = rawInfo["data"] as? JSONDictionary {
bio = data["bio"] as! String
if let counts = data["counts"] as? JSONDictionary {
followed_by = String(describing: counts["followed_by"]!)
follows = String(describing: counts["follows"]!)
media = String(describing: counts["media"]!)
}
}
if let userInfo = result["user_info"] as? JSONDictionary {
username = userInfo["username"] as! String
image = userInfo["image"] as! String
}
self.user = InstagramUser(token: token, uid: uid, bio: bio, followed_by: followed_by, follows: follows, media: media, username: username, image: image)
} else {
// this handles if user aborts or the API has a problem like server issue
let alert = UIAlertController(title: "Error!", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
if let e = error {
print("Error during SimpleAuth.authorize: ", e.localizedDescription)
}
print("user = \(String(describing: self.user))")
}
}
}
| apache-2.0 | dece9df95a4ec8adb18c3d1feb621ca9 | 36.421687 | 167 | 0.490019 | 5.246622 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Utility/Formatters/TimeIntervalFormatter.swift | 2 | 2518 | //
// TimeIntervalFormatter.swift
// Neocom
//
// Created by Artem Shimanski on 11/25/19.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import Foundation
class TimeIntervalFormatter: Formatter {
enum Precision: Int {
case seconds
case minutes
case hours
case days
};
enum Format {
case `default`
case colonSeparated
}
var precision: Precision = .seconds
var format: Format = .default
class func localizedString(from timeInterval: TimeInterval, precision: Precision, format: Format = .default) -> String {
let t = UInt(timeInterval.clamped(to: 0...Double(Int.max)))
let d = t / (60 * 60 * 24);
let h = (t / (60 * 60)) % 24;
let m = (t / 60) % 60;
let s = t % 60;
if format == .colonSeparated {
switch precision {
case .days:
return String(format: "%.2d:%.2d:%.2d:%.2d", d, h, m, s)
case .hours:
return String(format: "%.2d:%.2d:%.2d", h, m, s)
case .minutes:
return String(format: "%.2d:%.2d", m, s)
case .seconds:
return String(format: "%.2d", m, s)
}
}
else {
var string = ""
var empty = true
if (precision.rawValue <= Precision.days.rawValue && d > 0) {
string += "\(d)\(NSLocalizedString("d", comment: "days"))"
empty = false
}
if (precision.rawValue <= Precision.hours.rawValue && h > 0) {
string += "\(empty ? "" : " ")\(h)\(NSLocalizedString("h", comment: "hours"))"
empty = false
}
if (precision.rawValue <= Precision.minutes.rawValue && m > 0) {
string += "\(empty ? "" : " ")\(m)\(NSLocalizedString("m", comment: "minutes"))"
empty = false
}
if (precision.rawValue <= Precision.seconds.rawValue && s > 0) {
string += "\(empty ? "" : " ")\(s)\(NSLocalizedString("s", comment: "seconds"))"
empty = false
}
return empty ? "0\(NSLocalizedString("s", comment: "seconds"))" : string;
}
}
override func string(for obj: Any?) -> String? {
guard let obj = obj as? TimeInterval else {return nil}
return TimeIntervalFormatter.localizedString(from: obj, precision: precision)
}
}
| lgpl-2.1 | 1b745bf5da9a201faf562f56e040ab62 | 32.56 | 124 | 0.497815 | 4.34715 | false | false | false | false |
wepay/wepay-ios | SwiftExample/SwiftApp/ViewController.swift | 1 | 20462 | //
// ViewController.swift
// SwiftApp
//
// Created by Amy Lin on 10/26/15.
// Copyright © 2015 WePay. All rights reserved.
//
import UIKit
let SETTINGS_CLIENT_ID_KEY = "settingClientId"
let SETTINGS_ENVIRONMENT_KEY = "settingEnvironment"
let SETTINGS_ACCOUNT_ID_KEY = "settingAccountId"
let EMV_AMOUNT_STRING = "22.61" // Magic success amount
let EMV_READER_SHOULD_RESET = false
let EMV_SELECT_APP_INDEX = 0
class ViewController: UIViewController, WPAuthorizationDelegate, WPCardReaderDelegate, WPCheckoutDelegate, WPTokenizationDelegate , WPBatteryLevelDelegate, UIActionSheetDelegate {
var wepay = WePay()
let userDefaults = UserDefaults.standard
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var statusLabel: UILabel!
var accountId = Int()
var selectCardReaderCompletion: ((Int) -> Void)!
override func viewDidLoad() {
super.viewDidLoad()
// Initialize WePay config with your clientId and environment
let clientId: String = self.fetchSetting(SETTINGS_CLIENT_ID_KEY, withDefault: "171482")
let environment: String = self.fetchSetting(SETTINGS_ENVIRONMENT_KEY, withDefault: kWPEnvironmentStage)
self.accountId = Int(self.fetchSetting(SETTINGS_ACCOUNT_ID_KEY, withDefault: "1170640190"))!
let config: WPConfig = WPConfig(clientId: clientId, environment: environment)
// Allow WePay to use location services
config.useLocation = true
config.stopCardReaderAfterOperation = false
config.restartTransactionAfterOtherErrors = false
// Initialize WePay
self.wepay = WePay(config: config)
// Do any additional setup after loading the view, typically from a nib
self.setupUserInterface()
var str: NSAttributedString = NSAttributedString(
string: "Environment: \(environment)",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
str = NSAttributedString(
string: "ClientId: \(clientId)",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
str = NSAttributedString(
string: "AccountId: \(self.accountId)",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func fetchSetting(_ key: String, withDefault value: String) -> String {
userDefaults.synchronize()
var settings: String? = userDefaults.string(forKey: key)
if settings == nil || settings!.isEmpty {
settings = value
userDefaults.set(settings, forKey: key)
userDefaults.synchronize()
}
return settings!
}
func setupUserInterface() {
self.showStatus("Choose a payment method")
}
@IBAction func swipeInfoBtnPressed(_ sender: AnyObject) {
// Change status label
self.showStatus("Please wait...")
// Print message to screen
let str: NSAttributedString = NSAttributedString(
string: "Info from credit card selected",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
// Make WePay API call
self.wepay.startTransactionForReading(with: self)
}
@IBAction func swipeTokenButtonPressed(_ sender: AnyObject) {
// Change status label
self.showStatus("Please wait...")
// Print message to screen
let str: NSAttributedString = NSAttributedString(
string: "Tokenize credit card selected",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
// Make WePay API call
self.wepay.startTransactionForTokenizing(with: self, tokenizationDelegate: self, authorizationDelegate: self)
}
@IBAction func stopCardReaderButtonPressed(_ sender: AnyObject) {
// Change status label
self.showStatus("Stopping Card Reader")
// Print message to screen
let str: NSAttributedString = NSAttributedString(
string: "Stop Card Reader selected",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
// Make WePay API call
self.wepay.stopCardReader()
}
@IBAction func manualEntryButtonPressed(_ sender: AnyObject) {
// Obtain card information
let paymentInfo: WPPaymentInfo = WPPaymentInfo(
firstName: "WPiOS",
lastName: "Example",
email: "[email protected]",
billingAddress: WPAddress(zip: "94306"),
shippingAddress: nil,
cardNumber: "5496198584584769",
cvv: "123",
expMonth: "04",
expYear: "2020",
virtualTerminal: true
)
// Change status label
self.showStatus("Please wait...")
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(
string: "Manual entry selected. Using sample info: \n",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
let info: NSAttributedString = NSAttributedString(
string: paymentInfo.description,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Make WePay API call
self.wepay.tokenizePaymentInfo(paymentInfo, tokenizationDelegate: self)
}
@IBAction func storeSignatureButtonPressed(_ sender: AnyObject) {
// Change status label
self.showStatus("Storing Signature")
// Print message to screen
let str: NSAttributedString = NSAttributedString(
string: "Store signature selected",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
let signature: UIImage = UIImage(named: "dd_signature.png")!
// Below, use a checkoutId from a checkout you created recently (via a /checkout/create API call), otherwise an error will occur.
// If you do obtain a valid checkout ID, remember to change the clientId above to the one associated with the checkout.
// The placeholder checkoutId below is invalid, and will result in an appropriate error.
let checkoutId: String = "12345678"
self.wepay.storeSignatureImage(
signature,
forCheckoutId: checkoutId,
checkoutDelegate: self
)
}
@IBAction func batteryLevelButtonPressed(_ sender: AnyObject) {
// Change status label
self.showStatus("Checking Battery")
// Print message to screen
let str: NSAttributedString = NSAttributedString(
string: "Check battery selected",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
self.wepay.getCardReaderBatteryLevel(with: self, batteryLevelDelegate: self)
}
@IBAction func getRememberedCardReaderButtonPressed(_ sender: AnyObject) {
self.showStatus("Getting remembered card reader")
let cardReader = self.wepay.getRememberedCardReader()
var rememberedCardReaderMessage = "No remembered card reader exists"
if (cardReader != nil) {
rememberedCardReaderMessage = String(format: "Remembered card reader is %@", cardReader!)
}
let str: NSAttributedString = NSAttributedString(
string: rememberedCardReaderMessage,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str);
}
@IBAction func forgetRememberedCardReaderButtonPressed(_ sender: AnyObject) {
self.showStatus("Forgetting remembered card reader")
self.wepay.forgetRememberedCardReader()
let str: NSAttributedString = NSAttributedString(
string: "Forgot the remembered card reader",
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str);
}
func consoleLog(_ data: NSAttributedString) {
// Fetch current text
let text: NSMutableAttributedString = self.textView.attributedText.mutableCopy() as! NSMutableAttributedString
// Create and append date string
let format: DateFormatter = DateFormatter()
format.dateStyle = .medium
let dateStr: String = format.string(from: Date())
text.append(NSAttributedString(string: "\n[\(dateStr)] "))
// Append new string
text.append(data)
self.textView.attributedText = text
// Scroll the text view to the bottom
self.textView.scrollRangeToVisible(NSMakeRange(self.textView.text.characters.count, 0))
// Log to console as well
NSLog("%@", data.string)
}
func showStatus(_ message: String) {
self.statusLabel.text = message
}
// MARK: WPCardReaderDelegate methods
public func selectEMVApplication(_ applications: [Any]!, completion: ((Int) -> Void)!) {
// In production apps, the payer must choose the application they want to use.
// Here, we always select the first application in the array
let selectedIndex: Int = Int(EMV_SELECT_APP_INDEX)
// Print message to console
var str: NSMutableAttributedString = NSMutableAttributedString(string: "Select App Id: \n")
let info: NSAttributedString = NSAttributedString(
string: applications.description,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
str = NSMutableAttributedString(string: "Selected App Id index: \(selectedIndex)")
self.consoleLog(str)
// Execute the completion
completion(selectedIndex)
}
func didRead(_ paymentInfo: WPPaymentInfo) {
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didReadPaymentInfo: \n")
let info: NSAttributedString = NSAttributedString(
string: paymentInfo.description,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Change status label
self.showStatus("Got payment info!")
}
func didFailToReadPaymentInfoWithError(_ error: Error) {
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didFailToReadPaymentInfoWithError: \n")
let info: NSAttributedString = NSAttributedString(
string: error.localizedDescription,
attributes: [NSForegroundColorAttributeName: UIColor(red: 1, green: 0, blue: 0, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Change status label
self.showStatus("Card Reader error")
}
func cardReaderDidChangeStatus(_ status: Any) {
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(string: "cardReaderDidChangeStatus: ")
let info: NSAttributedString = NSAttributedString(
string: (status as! String).description,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Change status label
switch status as! String {
case kWPCardReaderStatusNotConnected:
self.showStatus("Connect Card Reader")
case kWPCardReaderStatusWaitingForCard:
self.showStatus("Swipe/Dip Card")
case kWPCardReaderStatusSwipeDetected:
self.showStatus("Swipe Detected...")
case kWPCardReaderStatusTokenizing:
self.showStatus("Tokenizing...")
case kWPCardReaderStatusStopped:
self.showStatus("Card Reader Stopped")
default:
self.showStatus((status as! String).description)
}
}
@objc func shouldResetCardReader(completion: ((Bool) -> Void)!) {
// Change this to true if you want to reset the card reader
completion(EMV_READER_SHOULD_RESET)
}
func authorizeAmount(completion: ((NSDecimalNumber?, String?, Int) -> Void)!) {
let amount: NSDecimalNumber = NSDecimalNumber(string: EMV_AMOUNT_STRING)
let currencyCode: String = kWPCurrencyCodeUSD
// Change status label
self.showStatus("Providing auth info")
// Print message to console
let infoString: String = "amount: \(amount), currency: \(currencyCode), accountId: \(self.accountId)"
let str: NSAttributedString = NSAttributedString(
string: "Providing auth info: " + infoString,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
// execute the completion
completion(amount, currencyCode, self.accountId)
}
func selectCardReader(_ cardReaderNames: [Any]!, completion: ((Int) -> Void)!) {
let cardReaderNameStrings = cardReaderNames as! [String]
let selectController = UIActionSheet(title: "Choose a card reader device", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil)
selectController.actionSheetStyle = .default
for cardreaderName in cardReaderNameStrings as [String] {
selectController.addButton(withTitle: cardreaderName)
}
self.selectCardReaderCompletion = completion
selectController.show(in: self.view)
}
// MARK: UIActionSheetDelegate
func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
self.selectCardReaderCompletion(buttonIndex - 1)
}
// MARK: WPTokenizationDelegate methods
func paymentInfo(_ paymentInfo: WPPaymentInfo, didTokenize paymentToken: WPPaymentToken) {
// Change status label
self.showStatus("Tokenized!")
// Print message to console
let str: NSMutableAttributedString = NSMutableAttributedString(string: "paymentInfo:didTokenize: \n")
let info: NSAttributedString = NSAttributedString(
string: paymentToken.description,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
}
func paymentInfo(_ paymentInfo: WPPaymentInfo, didFailTokenization error: Error) {
// Change status label
self.showStatus("Tokenization error")
// Print message to console
let str: NSMutableAttributedString = NSMutableAttributedString(string: "paymentInfo:didFailTokenization: \n")
let info: NSAttributedString = NSAttributedString(
string: error.localizedDescription,
attributes: [NSForegroundColorAttributeName: UIColor(red: 1, green: 0, blue: 0, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
}
// MARK: WPCheckoutDelegate methods
func didStoreSignature(_ signatureUrl: String, forCheckoutId checkoutId: String) {
// Change status label
self.showStatus("Signature success!")
// Print message to console
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didStoreSignature: \n")
let info: NSAttributedString = NSAttributedString(
string: signatureUrl,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
}
func didFail(toStoreSignatureImage image: UIImage, forCheckoutId checkoutId: String, withError error: Error) {
// Change status label
self.showStatus("Signature error")
// Print message to console
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didFailToStoreSignatureImage: \n")
let info: NSAttributedString = NSAttributedString(
string: error.localizedDescription,
attributes: [NSForegroundColorAttributeName: UIColor(red: 1, green: 0, blue: 0, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
}
// MARK: WPAuthorizationDelegate methods
func insertPayerEmail(completion: ((String?) -> Void)!) {
let email: String = "[email protected]"
// Print message to console
let str: NSAttributedString = NSAttributedString(
string: "Providing email: " + email,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0.2, blue: 0, alpha: 1)]
)
self.consoleLog(str)
completion(email)
}
func paymentInfo(_ paymentInfo: WPPaymentInfo, didAuthorize authorizationInfo: WPAuthorizationInfo) {
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didAuthorize: \n")
let info: NSAttributedString = NSAttributedString(
string: authorizationInfo.description,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Change status label
self.showStatus("Authorized")
}
func paymentInfo(_ paymentInfo: WPPaymentInfo, didFailAuthorization error: Error) {
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didFailAuthorization: \n")
let info: NSAttributedString = NSAttributedString(
string: error.localizedDescription,
attributes: [NSForegroundColorAttributeName: UIColor(red: 1, green: 0, blue: 0, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Change status label
self.showStatus("Authorization failed")
}
// MARK: WPBatteryLevelDelegate methods
func didGetBatteryLevel(_ batteryLevel: Int32) {
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didGetBatteryLevel: \n")
let info: NSAttributedString = NSAttributedString(
string: batteryLevel.description,
attributes: [NSForegroundColorAttributeName: UIColor(red: 0, green: 0, blue: 1, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Change status label
self.showStatus("Battery Level: \(batteryLevel)")
}
func didFail(toGetBatteryLevelwithError error: Error!) {
// Print message to screen
let str: NSMutableAttributedString = NSMutableAttributedString(string: "didFailToGetBatteryLevelwithError: \n")
let info: NSAttributedString = NSAttributedString(
string: error.localizedDescription,
attributes: [NSForegroundColorAttributeName: UIColor(red: 1, green: 0, blue: 0, alpha: 1)]
)
str.append(info)
self.consoleLog(str)
// Change status label
self.showStatus("Battery Level error")
}
}
| mit | 47f61b1f6e1442929548f157fd03f0ee | 39.041096 | 179 | 0.635257 | 5.008813 | false | false | false | false |
rxwei/Parsey | Sources/Parsey/Function.swift | 1 | 4283 | //
// Function.swift
// Funky
//
// Created by Richard Wei on 8/27/16.
//
//
// (f•g)(x) = f(g(x))
@inline(__always)
public func •<A, B, C>(f: @escaping (B) -> C, g: @escaping (A) -> B) -> (A) -> C {
return { f(g($0)) }
}
// (f•g)(x, y) = f(g(x), g(y))
@inline(__always)
public func •<A, B, C>(f: @escaping (B, B) -> C, g: @escaping (A) -> B) -> (A, A) -> C {
return { f(g($0), g($1)) }
}
// (f•g)(x) = f(x, g(y))
@inline(__always)
public func •<A, B, C>(f: @escaping (B, B) -> C, g: @escaping (A) -> B) -> (B, A) -> C {
return { f($0, g($1)) }
}
// (f•g)(x) = f(g(x), y)
@inline(__always)
public func •<A, B, C>(f: @escaping (B, B) -> C, g: @escaping (A) -> B) -> (A, B) -> C {
return { f(g($0), $1) }
}
// (f•g)(x, y) = f(g(x, y))
@inline(__always)
public func •<A, B, C, D>(f: @escaping (C) -> D, g: @escaping (A, B) -> C) -> (A, B) -> D {
return { f(g($0, $1)) }
}
// (f•g)(x, y, z) = f(g(x, y, z))
@inline(__always)
public func •<A, B, C, D, E>(f: @escaping (D) -> E, g: @escaping (A, B, C) -> D) -> (A, B, C) -> E {
return { f(g($0, $1, $2)) }
}
// (f•g)(x, y, z, a) = f(g(x, y, z, a))
@inline(__always)
public func •<A, B, C, D, E, F>(f: @escaping (E) -> F, g: @escaping (A, B, C, D) -> E) -> (A, B, C, D) -> F {
return { f(g($0, $1, $2, $3)) }
}
// ((a, b) -> c) -> a -> b -> c
@inline(__always)
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { x in { y in f(x, y) } }
}
// ((a, b, c) -> d) -> a -> b -> c -> d
@inline(__always)
public func curry<A, B, C, D>(_ f: @escaping (A, B, C) -> D) -> (A) -> (B) -> (C) -> D {
return { x in { y in { z in f(x, y, z) } } }
}
// ((a, b, c, d) -> e) -> a -> b -> c -> d -> e
@inline(__always)
public func curry<A, B, C, D, E>(_ f: @escaping (A, B, C, D) -> E) -> (A) -> (B) -> (C) -> (D) -> E {
return { x in { y in { z in { a in f(x, y, z, a) } } } }
}
// ((a, b, c, d, e) -> f) -> a -> b -> c -> d -> e -> f
@inline(__always)
public func curry<A, B, C, D, E, F>(_ f: @escaping (A, B, C, D, E) -> F) -> (A) -> (B) -> (C) -> (D) -> (E) -> F {
return { x in { y in { z in { a in { b in f(x, y, z, a, b) } } } } }
}
// ((a, b, c, d, e, f) -> g) -> a -> b -> c -> d -> e -> f -> g
@inline(__always)
public func curry<A, B, C, D, E, F, G>(_ f: @escaping (A, B, C, D, E, F) -> G) -> (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> G {
return { x in { y in { z in { a in { b in { c in f(x, y, z, a, b, c) } } } } } }
}
// (a -> b -> c) -> (a, b) -> c
@inline(__always)
public func uncurry<A, B, C>(_ f: @escaping (A) -> (B) -> C) -> (A, B) -> C {
return { (x, y) in f(x)(y) }
}
// (a -> b -> c -> d) -> (a, b, c) -> d
@inline(__always)
public func uncurry<A, B, C, D>(_ f: @escaping (A) -> (B) -> (C) -> D) -> (A, B, C) -> D {
return { (x, y, z) in f(x)(y)(z) }
}
// (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
@inline(__always)
public func uncurry<A, B, C, D, E>(_ f: @escaping (A) -> (B) -> (C) -> (D) -> E) -> (A, B, C, D) -> E {
return { (x, y, z, a) in f(x)(y)(z)(a) }
}
// (a -> b -> c -> d -> e -> f) -> (a, b, c, d, e) -> f
@inline(__always)
public func uncurry<A, B, C, D, E, F>(_ f: @escaping (A) -> (B) -> (C) -> (D) -> (E) -> F) -> (A, B, C, D, E) -> F {
return { (x, y, z, a, b) in f(x)(y)(z)(a)(b) }
}
// (a -> b -> c -> d -> e -> f -> g) -> (a, b, c, d, e, f) -> g
@inline(__always)
public func uncurry<A, B, C, D, E, F, G>(_ f: @escaping (A) -> (B) -> (C) -> (D) -> (E) -> (F) -> G) -> (A, B, C, D, E, F) -> G {
return { (x, y, z, a, b, c) in f(x)(y)(z)(a)(b)(c) }
}
// Flip argument order of a binary function
@inline(__always)
public func flip<A, B, C>(_ f: @escaping (A, B) -> C) -> (B, A) -> C {
return { x, y in f(y, x) }
}
// Flip argument order of a curried binary function
@inline(__always)
public func flip<A, B, C>(_ f: @escaping (A) -> (B) -> C) -> (B) -> (A) -> C {
return { x in { y in f(y)(x) } }
}
// Fixed-Point combinator (simulated by recursion)
@available(*, renamed: "withFixedPoint")
public func fixedPoint<A, B>(_ f: @escaping (@escaping (A) -> B) -> (A) -> B) -> (A) -> B {
return { f(fixedPoint(f))($0) }
}
public func withFixedPoint<A, B>(_ f: @escaping (@escaping (A) -> B) -> (A) -> B) -> (A) -> B {
return { f(fixedPoint(f))($0) }
}
| mit | 467e1318c4c8ff6a5ae2c9537bed72fa | 31.730769 | 129 | 0.412691 | 2.123253 | false | false | false | false |
te-th/xID3 | Source/Frames.swift | 1 | 4988 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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
/// An abstraction for all ID3 Frames.
public protocol ID3Frame {
}
/// A FrameProcessor turns a ID3TagFrame to a ID3Frame.
public protocol FrameProcessor {
/// Turn a generic ID3TagFrame to a specific ID3Frame. May return nil oif source ID3TagFrame does not match the
/// expectations.
///
/// - parameters:
/// - id3TagFrame: Will be turned into a ID3Frame.
///
/// - returns: A corresponding ID3Frame or nil
func from(_ id3tagFrame: ID3TagFrame) -> ID3Frame?
/// Indicator method to find out which ID3 Frame ID is supported by this FrameHProcessor.
/// - parameters:
/// - frameId: 4-Char. Frame Identifier.
func supports(_ frameId: String) -> Bool
}
/// Singleton holding FrameHProcessors for ID3 Frames.
public final class FrameProcessorRegistry {
private var handlers: [FrameProcessor]
private init() {
handlers = [
ChapterFrameProcessor(),
TextInformationFrameProcessor(),
CommentFrameProcessor(),
AttachedPictureProcessor()
]
}
public static let instance = FrameProcessorRegistry()
/// Register a FrameHProcessor.
///
/// - parameters:
/// - processor_ FrameHProcessor to be registered.
func add(_ processor: FrameProcessor) {
handlers.append(processor)
}
/// Get a FrameProcessor for the given ID3 Frame ID
///
/// - parameters:
/// - frameId: ID of the Frame.
func forFrameId(_ frameId: String) -> FrameProcessor {
for handler in handlers {
if (handler.supports(frameId)) {
return handler
}
}
return DefaultFrameHandler()
}
}
/// Container for ID3Frames.
public final class Frames {
public typealias FrameFilter = (_ frame: ID3Frame) -> Bool
private var frames = [ID3Frame]()
/// Adds the given ID3Frame
///
/// - parameters:
/// - frame: The ID3Frame to add
func add(_ frame: ID3Frame) {
frames.append(frame)
}
/// Filters available frames with the given FrameFilter
///
/// - parameters:
/// - filter: Closure that represents the filter expression.
///
/// - returns: Filtered Frames
public func filter(_ filter: FrameFilter) -> Frames {
let filtered = Frames()
for frame in self.frames {
if filter(frame) {
filtered.add(frame)
}
}
return filtered
}
/// Get all available Frames for this instance.
///
/// - returns: An array of ID3Frames.
public func availableFrames() -> [ID3Frame] {
return frames
}
}
/// Maps given generic ID3TagFrame to specific ID3Frames.
public final class FrameExtractor {
/// Maps given generic ID3TagFrame to specific ID3Frames.
///
/// - parameters:
/// - frames: ID3TagFrames to be turned into specific ID3Frames.
///
/// - returns: A Frames instance containing mapped ID3Frames.
public static func extract(_ frames: [ID3TagFrame]) -> Frames {
return extractWithFailures(frames).extracted
}
/// Maps given generic ID3TagFrame to specific ID3Frames.
///
/// - parameters:
/// - frames: ID3TagFrames to be turned into specific ID3Frames.
///
/// - returns: A Frames instance containing mapped ID3Frames.
public static func extractWithFailures(_ frames: [ID3TagFrame]) -> (extracted: Frames, nonExtracted: [ID3TagFrame]) {
let extractedFrames = Frames()
var nonExtracted = [ID3TagFrame]()
for frame in frames {
if let id3frame = FrameProcessorRegistry.instance.forFrameId(frame.id).from(frame) {
extractedFrames.add(id3frame)
} else {
print("Frame \(frame.id) was not extracted.")
nonExtracted.append(frame)
}
}
return (extractedFrames, nonExtracted)
}
}
/// Doing nothing
private final class DefaultFrameHandler: FrameProcessor {
func from(_ id3tagFrame: ID3TagFrame) -> ID3Frame? {
return nil
}
func supports(_ frameId: String) -> Bool {
return true
}
}
| apache-2.0 | e0d274f286b9c8b932d61e97b0bc28b2 | 29.048193 | 121 | 0.639735 | 4.375439 | false | false | false | false |
tluquet3/MonTennis | MonTennis/Palmares/PalmaresTableViewController.swift | 1 | 8280 | //
// PalmaresTableViewController.swift
// MonTennis
//
// Created by Thomas Luquet on 27/05/2015.
// Copyright (c) 2015 Thomas Luquet. All rights reserved.
//
import UIKit
import CoreData
class PalmaresTableViewController: UITableViewController {
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()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
@IBAction func deletePalmares(sender: AnyObject) {
let alert = UIAlertController(title: "Supprimer Palmares?", message: "Tout le palmares sera supprimé", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: {
(action: UIAlertAction) in
barCtrl.user.viderPalmares()
barCtrl.clearCoreData()
self.tableView.reloadData()
}))
alert.addAction(UIAlertAction(title: "Annuler", style: .Default, handler: {
(action: UIAlertAction) in
}))
presentViewController(alert, animated: true, completion: nil)
}
@IBAction func cancelToPalmaresViewController(segue:UIStoryboardSegue) {
self.tableView.reloadData()
}
@IBAction func saveMatchDetails(segue:UIStoryboardSegue) {
if let ajoutMatchViewController = segue.sourceViewController as? AjoutMatchViewController {
//add the new match to the match array
barCtrl.user.ajoutMatch(ajoutMatchViewController.match)
//Update the coreData
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entityForName("Match",
inManagedObjectContext:
managedContext)
let match = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext:managedContext)
match.setValue(ajoutMatchViewController.match.resultat, forKey: "resultat")
match.setValue(ajoutMatchViewController.match.firstName, forKey: "firstName")
match.setValue(ajoutMatchViewController.match.lastName, forKey: "lastName")
match.setValue(ajoutMatchViewController.match.wo, forKey: "wo")
match.setValue(ajoutMatchViewController.match.classement.value, forKey: "classement")
match.setValue(ajoutMatchViewController.match.bonus, forKey: "bonus")
match.setValue(ajoutMatchViewController.match.coef, forKey: "coef")
match.setValue(ajoutMatchViewController.match.score, forKey: "score")
match.setValue(ajoutMatchViewController.match.tournoi, forKey: "tournoi")
var error: NSError?
do {
try managedContext.save()
} catch let error1 as NSError {
error = error1
print("Could not save \(error), \(error?.userInfo)")
}
// No need to update the table view as we will reload the data
}
self.tableView.reloadData()
}
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.
let result:Int
if(section == 0){
result = barCtrl.user.victoires.count
}else{
result = barCtrl.user.defaites.count
}
return result
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MatchCell", forIndexPath: indexPath)
cell.textLabel?.textColor = UIColor.blackColor()
cell.detailTextLabel?.textColor = UIColor.blackColor()
let tableau: [Match]
if (indexPath.section == 0){
tableau = barCtrl.user.victoires
}else{
tableau = barCtrl.user.defaites
}
let match = tableau[indexPath.row] as Match
if(match.wo){
cell.textLabel?.text = match.lastName + " " + match.firstName + " (wo)"
cell.textLabel?.textColor = UIColor.grayColor()
cell.detailTextLabel?.textColor = UIColor.grayColor()
}
else{
cell.textLabel?.text = match.lastName + " " + match.firstName
}
cell.detailTextLabel?.text = match.classement.string
return cell
}
/* override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell
if(section == 0){
headerCell.textLabel?.text = "Victoires"
}else{
headerCell.textLabel?.text = "Défaites"
}
return headerCell as UIView
}*/
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = ""
if(section == 0){
title = "Victoires ("+String(barCtrl.user.victoires.count)+")"
}
else if(section == 1){
title = "Défaites ("+String(barCtrl.user.defaites.count)+")"
}
return title
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40.0
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
// handle delete (by removing the data from your array and updating the tableview)
tableView.dequeueReusableCellWithIdentifier("MatchCell", forIndexPath: indexPath)
if(indexPath.section == 0){
barCtrl.user.victoires.removeAtIndex(indexPath.row)
}else{
barCtrl.user.defaites.removeAtIndex(indexPath.row)
}
barCtrl.clearCoreData()
barCtrl.fillCoreData()
self.tableView.reloadData()
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the match to the ModifierMatchController.
if(segue.identifier == "modifierMatch"){
if let cell = sender as? UITableViewCell {
if let controller = (segue.destinationViewController as! UINavigationController).topViewController as? ModifierMatchController{
let indexPath = self.tableView.indexPathForCell(cell)!
controller.id = indexPath.row
if(indexPath.section == 0){
controller.match = barCtrl.user.victoires[indexPath.row]
}else{
controller.match = barCtrl.user.defaites[indexPath.row]
}
}
}
}
}
}
| apache-2.0 | 819abc582fdb4b14bc65d089de977022 | 39.37561 | 157 | 0.620515 | 5.292199 | false | false | false | false |
alienorb/Vectorized | VectorizedTests/TransformParserTests.swift | 1 | 6497 | //---------------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2016 Alien Orb Software LLC
//
// 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 XCTest
@testable import Vectorized
class TransformParserTests: XCTestCase {
func transformFromStringNoFail(string: String?) -> CGAffineTransform {
do {
return try SVGParser.transformFromString(string)
} catch {
XCTFail("Should not throw: \(string!), \(error)")
return CGAffineTransformIdentity
}
}
func testEmptyStrings() {
XCTAssertTrue(CGAffineTransformIsIdentity(transformFromStringNoFail(nil)))
XCTAssertTrue(CGAffineTransformIsIdentity(transformFromStringNoFail("")))
XCTAssertTrue(CGAffineTransformIsIdentity(transformFromStringNoFail(" ")))
}
func testMatrixSpaceSeparated() {
let comparison = CGAffineTransform(a: 1, b: 2, c: 3, d: 4, tx: 5, ty: 6)
var transform = transformFromStringNoFail("matrix(1 2 3 4 5 6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
transform = transformFromStringNoFail("matrix(1 2.0 3 4.0 5 6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
transform = transformFromStringNoFail("matrix( 1.0000000 2.0 3.0000 4 5 6 )")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
transform = transformFromStringNoFail(" matrix (1 2 3 4 5 6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
}
func testMatrixCommaSeparated() {
let comparison = CGAffineTransform(a: 1, b: 2, c: 3, d: 4, tx: 5, ty: 6)
var transform = transformFromStringNoFail("matrix(1,2,3,4,5,6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
transform = transformFromStringNoFail("matrix( 1,2.0000, 3.0 , 4 , 5,6 )")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
}
func testMatrixMalformed() {
XCTAssertThrowsError(try SVGParser.transformFromString("matrix"))
XCTAssertThrowsError(try SVGParser.transformFromString("matrix(0)"))
XCTAssertThrowsError(try SVGParser.transformFromString("matrix ( 1 2 3 4 5 )"))
XCTAssertThrowsError(try SVGParser.transformFromString("matrix(1,2,3,4,5,6"))
XCTAssertThrowsError(try SVGParser.transformFromString("matrix(this is a garbage value)"))
}
func testTranslate() {
var comparison = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 5, ty: 6)
var transform = transformFromStringNoFail("translate(5 6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
transform = transformFromStringNoFail("translate(5,6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
comparison = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 5, ty: 0)
transform = transformFromStringNoFail("translate(5)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
}
func testScale() {
var comparison = CGAffineTransform(a: 15, b: 0, c: 0, d: 30, tx: 0, ty: 0)
var transform = transformFromStringNoFail("scale(15, 30)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
comparison = CGAffineTransform(a: 35, b: 0, c: 0, d: 0, tx: 0, ty: 0)
transform = transformFromStringNoFail("scale(35)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
}
func testRotate() {
var comparison = CGAffineTransformMakeRotation(90)
var transform = transformFromStringNoFail("rotate(90)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
comparison = CGAffineTransformMakeTranslation(15, 20)
comparison = CGAffineTransformRotate(comparison, 90)
comparison = CGAffineTransformTranslate(comparison, -15, -20)
transform = transformFromStringNoFail("rotate(90 15 20)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
}
func testRotateMalformed() {
XCTAssertThrowsError(try SVGParser.transformFromString("rotate"))
XCTAssertThrowsError(try SVGParser.transformFromString("rotate(45,15"))
}
func testCombinedCommands() {
var comparison = CGAffineTransformConcat(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 5, ty: 6), CGAffineTransform(a: 1, b: 2, c: 3, d: 4, tx: 5, ty: 6))
var transform = transformFromStringNoFail("matrix(1 2 3 4 5 6) translate(5,6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
comparison = CGAffineTransformConcat(CGAffineTransform(a: 1, b: 2, c: 3, d: 4, tx: 5, ty: 6), CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 5, ty: 6))
transform = transformFromStringNoFail("translate(5,6) matrix(1 2 3 4 5 6)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
}
func testUnrecognizedCommands() {
let comparison = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 5, ty: 6)
let transform = transformFromStringNoFail("unrecognized translate(5 6) ignore_this(unrecognized 0 1 2)")
XCTAssertTrue(CGAffineTransformEqualToTransform(comparison, transform), "\(transform)")
}
}
| mit | 36eb0a6c41be7145c37f5c7313b25027 | 45.407143 | 156 | 0.716023 | 4.148787 | false | true | false | false |
luowenxing/MTImagePicker | MTImagePicker/MTImagePicker/Controller/MTImagePickerPreviewController.swift | 1 | 6486 | import UIKit
import AVFoundation
class MTImagePickerPreviewController:UIViewController,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {
weak var delegate:MTImagePickerDataSourceDelegate!
var dataSource:[MTImagePickerModel]!
var initialIndexPath:IndexPath?
@IBOutlet weak var lbIndex: UILabel!
@IBOutlet weak var collectionView: MTImagePickerCollectionView!
@IBOutlet weak var btnCheck: UIButton!
@IBOutlet weak var lbSelected: UILabel!
@IBOutlet var topViews: [UIView]!
@IBOutlet var bottomViews: [UIView]!
private var initialScrollDone = false
class var instance:MTImagePickerPreviewController {
get {
let storyboard = UIStoryboard(name: "MTImagePicker", bundle: Bundle.getResourcesBundle())
let vc = storyboard.instantiateViewController(withIdentifier: "MTImagePickerPreviewController") as! MTImagePickerPreviewController
return vc
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.lbSelected.text = String(delegate.selectedSource.count)
self.lbIndex.text = "\(initialIndexPath?.row ?? 0 + 1)/\(dataSource.count)"
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
self.scrollViewDidEndDecelerating(self.collectionView)
}
override var prefersStatusBarHidden: Bool {
get {
return true
}
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !self.initialScrollDone {
self.initialScrollDone = true
if let initialIndexPath = self.initialIndexPath {
self.collectionView.scrollToItem(at: initialIndexPath, at: .right, animated: false)
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model = self.dataSource[indexPath.row]
if model.mediaType == .Photo {
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath as IndexPath) as! ImagePickerPreviewCell
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
cell.initWithModel(model, controller: self)
return cell
} else {
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath as IndexPath) as! VideoPickerPreviewCell
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
cell.initWithModel(model: model,controller:self)
return cell
}
}
// 旋转处理
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
if self.interfaceOrientation.isPortrait != toInterfaceOrientation.isPortrait {
if let videoCell = self.collectionView.visibleCells.first as? VideoPickerPreviewCell {
// CALayer 无法autolayout 需要重设frame
videoCell.resetLayer(frame: UIScreen.main.compatibleBounds)
}
self.collectionView.prevItemSize = (self.collectionView.collectionViewLayout as! MTImagePickerPreviewFlowLayout).itemSize
self.collectionView.prevOffset = self.collectionView.contentOffset.x
self.collectionView.collectionViewLayout.invalidateLayout()
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.collectionView.bounds.width, height: self.collectionView.bounds.height)
}
//MARK:UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let videoCell = self.collectionView.visibleCells.first as? VideoPickerPreviewCell {
videoCell.didScroll()
}
}
//防止visibleCells出现两个而不是一个,导致.first得到的是未显示的cell
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.perform(#selector(MTImagePickerPreviewController.didEndDecelerating), with: nil, afterDelay: 0)
}
@objc func didEndDecelerating() {
let cell = self.collectionView.visibleCells.first
if let videoCell = cell as? VideoPickerPreviewCell {
videoCell.didEndScroll()
} else if let imageCell = cell as? ImagePickerPreviewCell {
imageCell.didEndScroll()
}
if let index = self.collectionView.indexPathsForVisibleItems.first {
self.lbIndex.text = "\(index.row + 1)/\(dataSource.count)"
let model = self.dataSource[index.row]
self.btnCheck.isSelected = delegate.selectedSource.contains(model)
}
}
@IBAction func btnBackTouch(_ sender: AnyObject) {
let _ = self.navigationController?.popViewController(animated: true)
}
@IBAction func btnCheckTouch(_ sender: UIButton) {
if delegate.selectedSource.count < delegate.maxCount || sender.isSelected == true {
sender.isSelected = !sender.isSelected
if let indexPath = self.collectionView.indexPathsForVisibleItems.first {
let model = self.dataSource[indexPath.row]
if sender.isSelected {
delegate.selectedSource.append(model)
sender.heartbeatsAnimation(duration: 0.15)
}else {
if let removeIndex = delegate.selectedSource.index(of: self.dataSource[indexPath.row]) {
delegate.selectedSource.remove(at: removeIndex)
}
}
self.lbSelected.text = String(delegate.selectedSource.count)
self.lbSelected.heartbeatsAnimation(duration: 0.15)
}
} else {
let alertView = FlashAlertView(message: "Maxium selected".localized, delegate: nil)
alertView.show()
}
}
}
| mit | cc34833319de76dda81ad7ef46906e4a | 41.813333 | 160 | 0.666615 | 5.474851 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Trending/BFShowcaseDetailController.swift | 1 | 4048 | //
// BFShowcaseDetailController.swift
// BeeFun
//
// Created by WengHengcong on 3/10/16.
// Copyright © 2016 JungleSong. All rights reserved.
//
import UIKit
import Moya
import Foundation
import MJRefresh
import ObjectMapper
class BFShowcaseDetailController: BFBaseViewController {
var showcaseInfoV: BFShowcaseHeaderView = BFShowcaseHeaderView.loadViewFromNib()
var showcase: ObjShowcase!
override func viewDidLoad() {
self.title = showcase.name
super.viewDidLoad()
tsc_setupTableView()
tsc_updateContentView()
tsc_getShowcaseRequest()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func leftItemAction(_ sender: UIButton?) {
_ = self.navigationController?.popViewController(animated: true)
}
func tsc_setupTableView() {
refreshHidden = .all
self.view.addSubview(showcaseInfoV)
showcaseInfoV.frame = CGRect(x: 0, y: topOffset, w: ScreenSize.width, h: 121)
self.view.addSubview(tableView)
let tabY = showcaseInfoV.bottom + 15.0
let tabH = ScreenSize.height - tabY
tableView.frame = CGRect(x: 0, y: tabY, w: ScreenSize.width, h: tabH)
self.automaticallyAdjustsScrollViewInsets = false
}
func tsc_updateContentView() {
showcaseInfoV.showcase = showcase
self.tableView.reloadData()
}
// MARK: - Request
///
func tsc_getShowcaseRequest() {
if showcase.name == nil {
return
}
let hud = JSMBHUDBridge.showHud(view: self.view)
TrendingManager.shared.requestForTrendingShowcaseDetail(showcase: showcase.name!) { (repos) in
DispatchQueue.main.async {
hud.hide(animated: true)
}
if repos.isEmpty {
return
}
self.showcase.repositories?.removeAll()
self.showcase.repositories = repos
self.tableView.reloadData()
//self.tableView.setContentOffset(CGPoint.zero, animated:true)
}
}
override func reconnect() {
super.reconnect()
tsc_getShowcaseRequest()
}
}
extension BFShowcaseDetailController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if showcase.repositories == nil {
return 0
}
let reposCount = showcase.repositories!.count
return reposCount
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
let cellId = "BFRepositoryTypeThirdCellIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFRepositoryTypeThirdCell
if cell == nil {
cell = (BFRepositoryTypeThirdCell.cellFromNibNamed("BFRepositoryTypeThirdCell") as? BFRepositoryTypeThirdCell)
}
cell?.setBothEndsLines(row, all:self.showcase.repositories!.count)
let repos = self.showcase.repositories![row]
cell!.objRepos = repos
return cell!
}
}
extension BFShowcaseDetailController {
// 顶部刷新
override func headerRefresh() {
super.headerRefresh()
}
override func footerRefresh() {
super.footerRefresh()
}
}
extension BFShowcaseDetailController {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let repos = self.showcase.repositories![indexPath.row]
JumpManager.shared.jumpReposDetailView(repos: repos, from: .other)
}
}
| mit | 0681f79ba6f8b0ee80df080ede011b54 | 25.227273 | 122 | 0.651646 | 4.802616 | false | false | false | false |
yichizhang/SubjectiveCUnreadMenu_Swift | SCUnreadMenu/SCRootViewController.swift | 1 | 2955 | //
// SCRootViewController.swift
// SCUnreadMenu
//
// Created by Yichi on 27/02/2015.
// Copyright (c) 2015 Subjective-C. All rights reserved.
//
import Foundation
import UIKit
class SCRootViewController : UIViewController, UIScrollViewDelegate, UIViewControllerTransitioningDelegate {
lazy var enclosingScrollView:UIScrollView = {
let scrollView = UIScrollView(frame: self.view.bounds)
scrollView.alwaysBounceHorizontal = true
scrollView.decelerationRate = UIScrollViewDecelerationRateFast
scrollView.delegate = self
return scrollView
}()
lazy var textView:UITextView = {
let textView = UITextView(frame: self.view.bounds, textContainer: nil)
textView.textContainerInset = UIEdgeInsets(top: 40, left: 20, bottom: 20, right: 20)
textView.font = UIFont(name: "AvenirNext-Regular", size: 16)
textView.textColor = UIColor.darkGrayColor()
textView.editable = false
return textView
}()
lazy var menuViewController:SCMenuViewController = {
let viewController = SCMenuViewController(nibName: nil, bundle: nil)
viewController.transitioningDelegate = self
viewController.modalPresentationStyle = .Custom
return viewController
}()
lazy var menuDragAffordanceView:SCDragAffordanceView = {
let affordanceView = SCDragAffordanceView(frame: CGRect(x: self.enclosingScrollView.bounds.maxX + 10, y: self.enclosingScrollView.bounds.midY, width: 50, height: 50))
return affordanceView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
view.addSubview(enclosingScrollView)
enclosingScrollView.addSubview(textView)
enclosingScrollView.addSubview(menuDragAffordanceView)
if let contentPlistPath = NSBundle.mainBundle().pathForResource("ArticleContent", ofType: "plist") {
if let contentDictionary = NSDictionary(contentsOfFile: contentPlistPath) {
textView.text = contentDictionary.valueForKey("body") as String
}
}
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.dragging {
menuDragAffordanceView.progress = scrollView.contentOffset.x / menuDragAffordanceView.bounds.width
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if menuDragAffordanceView.progress >= 1 {
presentViewController(menuViewController, animated: true, completion: nil)
} else {
menuDragAffordanceView.progress = 0
}
}
// MARK: UIViewControllerTransitioningDelegate
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let t = SCOverlayTransition()
t.presenting = true
return t
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let t = SCOverlayTransition()
t.presenting = false
return t
}
}
| mit | cb0a8fd03e9513f2da01382cca20abb8 | 34.60241 | 214 | 0.783418 | 4.390788 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/Model/Search/MSearchRequestTranslations.swift | 1 | 3494 | import Foundation
class MSearchRequestTranslations:MSearchRequest
{
private weak var controller:CSearch?
private let kSuffix:String = "translations="
@discardableResult init(controller:CSearch, model:MSearchEntry)
{
super.init()
self.controller = controller
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
self.asyncRequest(model:model)
}
}
//MARK: private
private func asyncRequest(model:MSearchEntry)
{
guard
let urlHost:String = MSession.sharedInstance.modelUrls.urlHost(host:MUrls.Host.hostOxford),
let urlEndPoint:String = MSession.sharedInstance.modelUrls.urlEnpoint(endPoint:MUrls.EndPoint.oxfordEntries),
let currentLanguage:MLanguage = MSession.sharedInstance.settings?.currentLanguage()
else
{
return
}
let languageCode:String = currentLanguage.code
let translateOptions:[MLanguage] = currentLanguage.translateOptions()
guard
let translateTarget:MLanguage = translateOptions.first
else
{
return
}
let targetCode:String = translateTarget.code
let wordId:String = model.wordId
let urlString:String = "\(urlHost)/\(urlEndPoint)/\(languageCode)/\(wordId)/\(kSuffix)\(targetCode)"
let headers:[String:String] = MSession.sharedInstance.modelOxfordCredentials.credentialHeaders()
guard
let request:URLRequest = request(
urlString:urlString,
headers:headers)
else
{
return
}
task = session.dataTask(with:request)
{ (data:Data?, urlResponse:URLResponse?, error:Error?) in
let statusCode:Int = self.statusCode(
error:error,
urlResponse:urlResponse)
let modelTranslations:MSearchTranslations?
switch statusCode
{
case self.kStatusCodeSuccess:
modelTranslations = self.parseData(
language:translateTarget,
data:data)
break
default:
modelTranslations = MSearchTranslations()
break
}
model.translations = modelTranslations
self.controller?.showContent(modelEntry:model)
}
task?.resume()
session.finishTasksAndInvalidate()
}
private func parseData(
language:MLanguage,
data:Data?) -> MSearchTranslations?
{
guard
let dataStrong:Data = data
else
{
return nil
}
let json:Any
do
{
try json = JSONSerialization.jsonObject(
with:dataStrong,
options:
JSONSerialization.ReadingOptions.allowFragments)
}
catch
{
return nil
}
let modelTranslations:MSearchTranslations = MSearchTranslations(
language:language,
json:json)
return modelTranslations
}
}
| mit | cebecd75a39b7a12d7bf5d7d8c78848b | 26.296875 | 121 | 0.526331 | 5.993139 | false | false | false | false |
salmojunior/TMDb | TMDb/TMDb/Source/Controller/Movie/MoviesTableViewController.swift | 1 | 6116 | //
// MoviesTableViewController.swift
// TMDb
//
// Created by SalmoJunior on 13/05/17.
// Copyright © 2017 Salmo Junior. All rights reserved.
//
import UIKit
class MoviesTableViewController: UITableViewController, ViewCustomizable {
// MARK: - Private Constants
private let kManager = MovieManager()
private let kMovieCellIdentifier = "movieIdentifier"
// MARK: - Private Properties
typealias MainView = MovieTableView
private var nextPage: Int? = 1
private var genres: [Genre]?
private var movies = [Movie]()
fileprivate var selectedItemFrame = CGRect.zero
fileprivate var destinationItemFrame = CGRect.zero
fileprivate var sourceImageView: UIImageView?
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
title = LocalizableStrings.upcomingTitle.localize()
navigationController?.delegate = self
refreshControl?.addTarget(self, action: #selector(MoviesTableViewController.loadMovies), for: UIControlEvents.valueChanged)
mainView.initialSetup()
loadGenres()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else { return }
switch identifier {
case MovieDetailsViewController.identifier:
guard let movieDetailsViewController = segue.destination as? MovieDetailsViewController else {
return
}
guard let selectedMovie = sender as? Movie else { return }
movieDetailsViewController.selectedMovie(movie: selectedMovie)
destinationItemFrame = movieDetailsViewController.posterImageViewPosition()
default:
return
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kMovieCellIdentifier, for: indexPath) as! MovieTableViewCell
let movie = movies[indexPath.row]
cell.fillIn(movie: movie)
return cell
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let movie = movies[indexPath.row]
let cell = tableView.cellForRow(at: indexPath) as! MovieTableViewCell
sourceImageView = cell.posterImageView
if let imageView = sourceImageView {
selectedItemFrame = imageView.superview!.convert(imageView.frame, to: nil)
performSegue(withIdentifier: MovieDetailsViewController.identifier, sender: movie)
}
}
// MARK: - Private Functions
private func loadGenres() {
kManager.genres {[weak self] (result) in
guard let weakSelf = self else { return }
do {
weakSelf.genres = try result()
weakSelf.loadMovies()
} catch {
HandleError.handle(error: error)
}
}
}
private func endRefresing() {
refreshControl?.endRefreshing()
}
// Using @objc notation to let the function be private and also be visible to #selector usage
@objc private func loadMovies() {
guard let nextPage = nextPage else {
endRefresing()
return
}
kManager.upcoming(page: nextPage, genres: genres) {[weak self] (result) in
guard let weakSelf = self else { return }
do {
let (newMovies, nextPage) = try result()
weakSelf.movies = newMovies + weakSelf.movies
weakSelf.nextPage = nextPage
var indexPaths = [IndexPath]()
for (index, _) in newMovies.enumerated() {
let indexPath = IndexPath(item: index, section: 0)
indexPaths.append(indexPath)
}
weakSelf.endRefresing()
weakSelf.mainView.updateElements(at: indexPaths)
} catch {
weakSelf.endRefresing()
HandleError.handle(error: error)
}
}
}
}
// MARK: - Navigation controller delegate
extension MoviesTableViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard let imageView = sourceImageView else { return nil }
var animatorDelegate: SharedElementAnimationControllerDelegate?
var mode = SharedAnimationMode.push
if let toViewController = toVC as? SharedElementAnimationControllerDelegate {
animatorDelegate = toViewController
}
if toVC == self {
mode = .pop
}
let transition = SharedElementAnimationController(originFrame: selectedItemFrame, destineFrame: destinationItemFrame, sourceImageView: imageView, animationMode: mode, delegate: animatorDelegate)
return transition
}
}
// MARK: - SharedElementAnimation controller delegate
extension MoviesTableViewController: SharedElementAnimationControllerDelegate {
func willStartAnimation(animator: SharedElementAnimationController) {
guard let imageView = sourceImageView else { return }
mainView.initialSelectedElementStatus(imageView: imageView)
}
func didCompleteAnimation(animator: SharedElementAnimationController) {
guard let imageView = sourceImageView else { return }
mainView.presentingSelectedElementStatus(imageView: imageView)
}
}
| mit | 1f340f176cee787a6aaca2345af2425a | 34.552326 | 246 | 0.637122 | 5.79072 | false | false | false | false |
mleiv/SerializableData | SerializableDataDemo/SerializableDataDemo/UserDefaultsPersonController.swift | 1 | 2732 | //
// UserDefaultsPersonController.swift
// SerializableDataDemo
//
// Created by Emily Ivie on 10/16/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import UIKit
class UserDefaultsPersonController: UIViewController {
var isNew = true
var person = UserDefaultsPerson(name: "")
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var professionField: UITextField!
@IBOutlet weak var organizationField: UITextField!
@IBOutlet weak var notesField: UITextView!
@IBOutlet weak var deleteButton: UIButton!
var spinner: Spinner?
override func viewDidLoad() {
super.viewDidLoad()
spinner = Spinner(parent: self)
spinner?.start()
if person.name.isEmpty == false {
isNew = false
}
deleteButton.isHidden = isNew
setFieldValues()
spinner?.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func savePerson(_ sender: UIButton) {
spinner?.start()
saveFieldValues()
let name = person.name
if name.isEmpty == false {
_ = person.save()
showMessage("Saved \(name).", handler: { _ in
self.spinner?.stop()
_ = self.navigationController?.popViewController(animated: true)
})
} else {
showMessage("Please enter a name before saving.", handler: { _ in
self.spinner?.stop()
})
}
}
@IBAction func deletePerson(_ sender: UIButton) {
spinner?.start()
let name = person.name
_ = person.delete()
showMessage("Deleted \(name).", handler: { _ in
self.spinner?.stop()
_ = self.navigationController?.popViewController(animated: true)
})
}
func setFieldValues() {
nameField.text = person.name
professionField.text = person.profession
organizationField.text = person.organization
notesField.text = person.notes
}
func saveFieldValues() {
person.name = nameField.text ?? ""
person.profession = professionField.text
person.organization = organizationField.text
person.notes = notesField.text
}
func showMessage(_ message: String, handler: @escaping ((UIAlertAction) -> Void) = { _ in }) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Okay", style: .default, handler: handler))
self.present(alertController, animated: true) {}
}
}
| mit | 302f631fddb8fbf4a17e07125a56ff43 | 30.390805 | 101 | 0.610399 | 4.894265 | false | false | false | false |
jhaigler94/cs4720-iOS | Pensieve/Pensieve/ViewController.swift | 1 | 4924 | //
// ViewController.swift
// Pensieve
//
// Created by Jennifer Ruth Haigler on 10/19/15.
// Copyright © 2015 University of Virginia. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var TableView: UITableView!
var names = [String]()
var memName = String()
var memDate = String()
var memTime = String()
// MARK: Properties
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
title = "Pensieve"
/*populateNames()
TableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
*/
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
print("VIEWDIDAPPEAR: View Controller")
TableView.reloadData()
names = []
populateNames()
TableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
}
/*override func viewDidAppear(animated: Bool) {
print("VIEWDIDAPPEAR: View Controller")
TableView.reloadData()
names = []
populateNames()
TableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
}
*/
func populateNames(){
/* Create the fetch request first */
let fetchRequest = NSFetchRequest(entityName: "Memory")
/* And execute the fetch request on the context */
do {
let mems = try managedObjectContext.executeFetchRequest(fetchRequest)
for memory in mems{
if((memory.valueForKey("memloc")as? String!)==("MainNotPoint")){
names.append((memory.valueForKey("memname")as? String)!)
print((memory.valueForKey("memname")as? String)!)
}
}
}catch let error as NSError{
print(error)
}
print("Populate Names___")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func tableView(TableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
NSLog("You selected cell number: \(indexPath.row)!")
let fetchRequest = NSFetchRequest(entityName: "Memory")
/* And execute the fetch request on the context */
do {
let mems = try managedObjectContext.executeFetchRequest(fetchRequest)
for memory in mems{
if((memory.valueForKey("memname")as? String!)==((names[indexPath.row])as?String!)){
if((memory.valueForKey("memloc")as? String!)==("MainNotPoint")){
memName = ((memory.valueForKey("memname")as? String)!)
memDate = ((memory.valueForKey("memdate")as? String)!)
memTime = ((memory.valueForKey("memtime")as? String)!) }
}
}
}catch let error as NSError{
print(error)
}
NSLog(memName)
NSLog(memDate)
NSLog(memTime)
self.performSegueWithIdentifier("ToMemPtList", sender: self)
}
// MARK: Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ToMemPtList") {
var memVC = segue.destinationViewController as! MemoryViewController;
memVC.passName = memName
memVC.passDate = memDate
memVC.passTime = memTime
}
}
func tableView(TableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell =
TableView.dequeueReusableCellWithIdentifier("Cell")
cell!.textLabel!.text = names[indexPath.row]
return cell!
}
// MARK: Actions
// MARK: Segues
@IBAction func unwindToHome(unwindSegue: UIStoryboardSegue) {
if let memViewController = unwindSegue.sourceViewController as? MemoryViewController {
print("Coming from MemoryViewController")
}
}
}
| apache-2.0 | ce9aff4b8877ada97e39f9ad2809d0f2 | 29.202454 | 112 | 0.578103 | 5.457871 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 14--A-New-HIG/Cellect-Em-All/Cellect-Em-All/CardsCollectionViewController.swift | 1 | 5204 | //
// CardsCollectionViewController.swift
// Cellect-Em-All
//
// Created by Pedro Trujillo on 10/22/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
protocol CharacterListTableViewControllerDelegate
{
func characterWasChosen(chosenCharacter: String)
}
class CardsCollectionViewController: UICollectionViewController, UIPopoverPresentationControllerDelegate, CharacterListTableViewControllerDelegate
{
var visibleCards = [String]()
let allCards = ["Obi-Wan Kenobi": "Kenobi.jpg", "Leia Organa": "Organa.jpg", "R2-D2": "R2.jpg", "Luke Skywalker": "Skywalker.jpg", "Grand Moff Tarkin": "Tarkin.jpg", "Darth Vader": "Vader.jpg"]
var remainingCharacters = ["Obi-Wan Kenobi", "Leia Organa", "R2-D2", "Luke Skywalker", "Grand Moff Tarkin", "Darth Vader"]
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Collect 'Em-All"
//visibleCards.append("Luke Skywalker")
}
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.
if segue.identifier == "ShowCharacterListPopoverSegue"
{
let destVC = segue.destinationViewController as! CharacterListTableViewController
destVC.characters = remainingCharacters
destVC.popoverPresentationController?.delegate = self
destVC.delegate = self //CharacterListTableViewControllerDelegate
let contentHeight = 44.0 * CGFloat(remainingCharacters.count)
destVC.preferredContentSize = CGSizeMake(200.0, contentHeight)
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of items
return visibleCards.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CardCollectionViewCell", forIndexPath: indexPath) as! CardCollectionViewCell
// Configure the cell
let characterName = visibleCards[indexPath.item] // now is "item" besides row but is almost same
cell.nameLabel.text = characterName
cell.imageView.image = UIImage(named: allCards[characterName]!)
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
//MARK: - UIPopoverPresentationController Delegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle
{
return .None
}
//MARK: CharacterListTableViewController Delegate
func characterWasChosen(chosenCharacter: String)
{
navigationController?.dismissViewControllerAnimated(true, completion: nil) // this thing hides the popover
visibleCards.append(chosenCharacter)
let rowToRemove = (remainingCharacters as NSArray).indexOfObject(chosenCharacter)
remainingCharacters.removeAtIndex(rowToRemove)
collectionView?.reloadData()
}
}
| cc0-1.0 | 5c6f2af9dab371f737c345dbdba7c893 | 34.882759 | 197 | 0.706323 | 5.698795 | false | false | false | false |
iamtomcat/iostags | Tags/CollectionSetup/CollectionSetup.swift | 2 | 685 | //
// CollectionSetup.swift
// Tags
//
// Created by Tom Clark on 2016-08-02.
// Copyright © 2016 Fluiddynamics. All rights reserved.
//
import UIKit
extension UICollectionView {
public func setupCollectionAsTagView(_ tagDelegate: TagDelegate, withDataSource dataSource: TagsDataSource) {
self.registerNibWithTitle(String(describing: TagCell.self), withBundle: Bundle.tagBundle)
tagDelegate.tagDataSource = dataSource
tagDelegate.collectionViewRef = self
self.dataSource = tagDelegate.collectionDataSource
(self.collectionViewLayout as? UICollectionViewFlowLayout)?.estimatedItemSize = CGSize(width: 60, height: 20)
self.delegate = tagDelegate
}
}
| mit | 4011b86156bf410506cd5a64adea0871 | 30.090909 | 113 | 0.766082 | 4.384615 | false | false | false | false |
zybug/firefox-ios | SyncTests/RecordTests.swift | 2 | 12349 | /* 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
import XCTest
import Shared
import Storage
import Sync
class RecordTests: XCTestCase {
func testGUIDs() {
let s = Bytes.generateGUID()
print("Got GUID: \(s)", terminator: "\n")
XCTAssertEqual(12, s.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
}
func testEnvelopeNullTTL() {
let p = CleartextPayloadJSON(JSON([]))
let r = Record<CleartextPayloadJSON>(id: "guid", payload: p, modified: NSDate.now(), sortindex: 15, ttl: nil)
let k = KeyBundle.random()
let s = k.serializer({ $0 })
let json = s(r)!
XCTAssertEqual(json["id"].asString!, "guid")
XCTAssertTrue(json["ttl"].isNull)
}
func testEnvelopeJSON() {
let e = EnvelopeJSON(JSON.parse("{}"))
XCTAssertFalse(e.isValid())
let ee = EnvelopeJSON("{\"id\": \"foo\"}")
XCTAssertFalse(ee.isValid())
XCTAssertEqual(ee.id, "foo")
let eee = EnvelopeJSON(JSON.parse("{\"id\": \"foo\", \"collection\": \"bar\", \"payload\": \"baz\"}"))
XCTAssertTrue(eee.isValid())
XCTAssertEqual(eee.id, "foo")
XCTAssertEqual(eee.collection, "bar")
XCTAssertEqual(eee.payload, "baz")
}
func testRecord() {
let invalidPayload = "{\"id\": \"abcdefghijkl\", \"collection\": \"clients\", \"payload\": \"invalid\"}"
let emptyPayload = "{\"id\": \"abcdefghijkl\", \"collection\": \"clients\", \"payload\": \"{}\"}"
let clientBody: [String: AnyObject] = ["id": "abcdefghijkl", "name": "Foobar", "commands": [], "type": "mobile"]
let clientBodyString = JSON(clientBody).toString(false)
let clientRecord: [String : AnyObject] = ["id": "abcdefghijkl", "collection": "clients", "payload": clientBodyString]
let clientPayload = JSON(clientRecord).toString(false)
let cleartextClientsFactory: (String) -> ClientPayload? = {
(s: String) -> ClientPayload? in
return ClientPayload(s)
}
let clearFactory: (String) -> CleartextPayloadJSON? = {
(s: String) -> CleartextPayloadJSON? in
return CleartextPayloadJSON(s)
}
print(clientPayload, terminator: "\n")
// Only payloads that parse as JSON are valid.
XCTAssertNil(Record<CleartextPayloadJSON>.fromEnvelope(EnvelopeJSON(invalidPayload), payloadFactory: clearFactory))
// Missing ID.
XCTAssertNil(Record<CleartextPayloadJSON>.fromEnvelope(EnvelopeJSON(emptyPayload), payloadFactory: clearFactory))
// Only valid ClientPayloads are valid.
XCTAssertNil(Record<ClientPayload>.fromEnvelope(EnvelopeJSON(invalidPayload), payloadFactory: cleartextClientsFactory))
XCTAssertNotNil(Record<ClientPayload>.fromEnvelope(EnvelopeJSON(clientPayload), payloadFactory: cleartextClientsFactory))
}
func testEncryptedClientRecord() {
let b64E = "0A7mU5SZ/tu7ZqwXW1og4qHVHN+zgEi4Xwfwjw+vEJw="
let b64H = "11GN34O9QWXkjR06g8t0gWE1sGgQeWL0qxxWwl8Dmxs="
let expectedGUID = "0-P9fabp9vJD"
let expectedSortIndex = 131
let expectedLastModified: Timestamp = 1326254123650
let inputString = "{\"sortindex\": 131, \"payload\": \"{\\\"ciphertext\\\":\\\"YJB4dr0vZEIWPirfU2FCJvfzeSLiOP5QWasol2R6ILUxdHsJWuUuvTZVhxYQfTVNou6hVV67jfAvi5Cs+bqhhQsv7icZTiZhPTiTdVGt+uuMotxauVA5OryNGVEZgCCTvT3upzhDFdDbJzVd9O3/gU/b7r/CmAHykX8bTlthlbWeZ8oz6gwHJB5tPRU15nM/m/qW1vyKIw5pw/ZwtAy630AieRehGIGDk+33PWqsfyuT4EUFY9/Ly+8JlnqzxfiBCunIfuXGdLuqTjJOxgrK8mI4wccRFEdFEnmHvh5x7fjl1ID52qumFNQl8zkB75C8XK25alXqwvRR6/AQSP+BgQ==\\\",\\\"IV\\\":\\\"v/0BFgicqYQsd70T39rraA==\\\",\\\"hmac\\\":\\\"59605ed696f6e0e6e062a03510cff742bf6b50d695c042e8372a93f4c2d37dac\\\"}\", \"id\": \"0-P9fabp9vJD\", \"modified\": 1326254123.65}"
let keyBundle = KeyBundle(encKeyB64: b64E, hmacKeyB64: b64H)
let decryptClient = keyBundle.factory({ CleartextPayloadJSON($0) })
let encryptClient = keyBundle.serializer({ $0 }) // It's already a JSON.
let toRecord = {
return Record<CleartextPayloadJSON>.fromEnvelope($0, payloadFactory: decryptClient)
}
let envelope = EnvelopeJSON(inputString)
if let r = toRecord(envelope) {
XCTAssertEqual(r.id, expectedGUID)
XCTAssertTrue(r.modified == expectedLastModified)
XCTAssertEqual(r.sortindex, expectedSortIndex)
if let ee = encryptClient(r) {
let envelopePrime = EnvelopeJSON(ee)
XCTAssertEqual(envelopePrime.id, expectedGUID)
XCTAssertEqual(envelopePrime.id, envelope.id)
XCTAssertEqual(envelopePrime.sortindex, envelope.sortindex)
XCTAssertTrue(envelopePrime.modified == 0)
if let rPrime = toRecord(envelopePrime) {
// The payloads should be identical.
XCTAssertTrue(rPrime.equalPayloads(r))
} else {
XCTFail("No record.")
}
} else {
XCTFail("No record.")
}
} else {
XCTFail("No record.")
}
}
func testMeta() {
let fullRecord = "{\"id\":\"global\"," +
"\"payload\":" +
"\"{\\\"syncID\\\":\\\"zPSQTm7WBVWB\\\"," +
"\\\"declined\\\":[\\\"bookmarks\\\"]," +
"\\\"storageVersion\\\":5," +
"\\\"engines\\\":{" +
"\\\"clients\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"fDg0MS5bDtV7\\\"}," +
"\\\"forms\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"GXF29AFprnvc\\\"}," +
"\\\"history\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"av75g4vm-_rp\\\"}," +
"\\\"passwords\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"LT_ACGpuKZ6a\\\"}," +
"\\\"prefs\\\":{\\\"version\\\":2,\\\"syncID\\\":\\\"-3nsksP9wSAs\\\"}," +
"\\\"tabs\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"W4H5lOMChkYA\\\"}}}\"," +
"\"username\":\"5817483\"," +
"\"modified\":1.32046073744E9}"
let record = GlobalEnvelope(fullRecord)
XCTAssertTrue(record.isValid())
let global = MetaGlobal.fromPayload(JSON.parse(record.payload))
XCTAssertTrue(global != nil)
if let global = global {
XCTAssertTrue(global.declined != nil)
XCTAssertTrue(global.engines != nil)
XCTAssertEqual(["bookmarks"], global.declined!)
XCTAssertEqual(5, global.storageVersion)
let modified = record.modified
XCTAssertTrue(1320460737440 == modified)
let forms = global.engines!["forms"]
let syncID = forms!.syncID
XCTAssertEqual("GXF29AFprnvc", syncID)
let payload: JSON = global.toPayload()
XCTAssertEqual("GXF29AFprnvc", payload["engines"]["forms"]["syncID"].asString!)
XCTAssertEqual(1, payload["engines"]["forms"]["version"].asInt!)
XCTAssertEqual("bookmarks", payload["declined"].asArray![0].asString!)
}
}
func testHistoryPayload() {
let payloadJSON = "{\"id\":\"--DzSJTCw-zb\",\"histUri\":\"https://bugzilla.mozilla.org/show_bug.cgi?id=1154549\",\"title\":\"1154549 – Encapsulate synced profile data within an account-centric object\",\"visits\":[{\"date\":1429061233163240,\"type\":1}]}"
let json = JSON(string: payloadJSON)
if let payload = HistoryPayload.fromJSON(json) {
XCTAssertEqual("--DzSJTCw-zb", payload["id"].asString!)
XCTAssertEqual("1154549 – Encapsulate synced profile data within an account-centric object", payload["title"].asString!)
XCTAssertEqual(1, payload.visits[0].type.rawValue)
XCTAssertEqual(1429061233163240, payload.visits[0].date)
let v = payload.visits[0]
let j = v.toJSON()
XCTAssertEqual(1, j["type"].asInt!)
XCTAssertEqual(1429061233163240, j["date"].asInt64!)
} else {
XCTFail("Should have parsed.")
}
}
func testHistoryPayloadWithNoTitle() {
let payloadJSON = "{\"id\":\"--DzSJTCw-zb\",\"histUri\":\"https://foo.com/\",\"title\":null,\"visits\":[{\"date\":1429061233163240,\"type\":1}]}"
let json = JSON(string: payloadJSON)
if let payload = HistoryPayload.fromJSON(json) {
XCTAssertEqual("", payload.title)
} else {
XCTFail("Should have parsed.")
}
}
func testLoginPayload() {
let input = JSON([
"id": "abcdefabcdef",
"hostname": "http://foo.com/",
"username": "foo",
"password": "bar",
"usernameField": "field",
"passwordField": "bar",
// No formSubmitURL.
"httpRealm": "",
])
// fromJSON returns nil if not valid.
XCTAssertNotNil(LoginPayload.fromJSON(input))
}
func testSeparators() {
// Mistyped parentid.
let invalidSeparator = JSON(["type": "separator", "arentid": "toolbar", "parentName": "Bookmarks Toolbar", "pos": 3])
XCTAssertNil(BookmarkType.payloadFromJSON(invalidSeparator))
// This one's right.
let validSeparator = JSON(["id": "abcabcabcabc", "type": "separator", "parentid": "toolbar", "parentName": "Bookmarks Toolbar", "pos": 3])
let separator = BookmarkType.payloadFromJSON(validSeparator)!
XCTAssertTrue(separator is SeparatorPayload)
XCTAssertTrue(separator.isValid())
XCTAssertEqual(3, separator["pos"].asInt!)
}
func testFolders() {
let validFolder = JSON([
"id": "abcabcabcabc",
"type": "folder",
"parentid": "toolbar",
"parentName": "Bookmarks Toolbar",
"title": "Sóme stüff",
"description": "",
"children": ["foo", "bar"],
])
let folder = BookmarkType.payloadFromJSON(validFolder)!
XCTAssertTrue(folder is FolderPayload)
XCTAssertEqual((folder as! FolderPayload).children, ["foo", "bar"])
}
func testBookmarks() {
let validBookmark = JSON([
"id": "abcabcabcabc",
"type": "bookmark",
"parentid": "menu",
"parentName": "Bookmarks Menu",
"title": "Anøther",
"bmkUri": "http://terrible.sync/naming",
"description": "",
"tags": [],
"keyword": "",
])
let bookmark = BookmarkType.payloadFromJSON(validBookmark)
XCTAssertTrue(bookmark is BookmarkPayload)
let query = JSON.parse("{\"id\":\"ShCZLGEFQMam\",\"type\":\"query\",\"title\":\"Downloads\",\"parentName\":\"\",\"bmkUri\":\"place:transition=7&sort=4\",\"tags\":[],\"keyword\":null,\"description\":null,\"loadInSidebar\":false,\"parentid\":\"T6XK5oJMU8ih\"}")
let q = BookmarkType.payloadFromJSON(query)
XCTAssertTrue(q is BookmarkQueryPayload)
XCTAssertTrue(q is MirrorItemable)
guard let item = (q as? MirrorItemable)?.toMirrorItem(NSDate.now()) else {
XCTFail("Not mirrorable!")
return
}
XCTAssertEqual(6, item.type.rawValue)
XCTAssertEqual("ShCZLGEFQMam", item.guid)
let places = JSON.parse("{\"id\":\"places\",\"type\":\"folder\",\"title\":\"\",\"description\":null,\"children\":[\"menu________\",\"toolbar_____\",\"tags________\",\"unfiled_____\",\"jKnyPDrBQSDg\",\"T6XK5oJMU8ih\"],\"parentid\":\"2hYxKgBwvkEH\"}")
let p = BookmarkType.payloadFromJSON(places)
XCTAssertTrue(p is FolderPayload)
XCTAssertTrue(p is MirrorItemable)
// Items keep their GUID until they're written into the mirror table.
XCTAssertEqual("places", p!.id)
guard let pMirror = (p as? MirrorItemable)?.toMirrorItem(NSDate.now()) else {
XCTFail("Not mirrorable!")
return
}
XCTAssertEqual(2, pMirror.type.rawValue)
// The mirror item has a translated GUID.
XCTAssertEqual(BookmarkRoots.RootGUID, pMirror.guid)
}
}
| mpl-2.0 | a3736e64379e6719a463d5ed952b0b2d | 43.395683 | 625 | 0.589127 | 4.100332 | false | true | false | false |
VicFrolov/Markit | iOS/Markit/Pods/PromiseKit/Sources/Promise.swift | 1 | 19958 | import class Dispatch.DispatchQueue
import class Foundation.NSError
import func Foundation.NSLog
/**
A *promise* represents the future value of a (usually) asynchronous task.
To obtain the value of a promise we call `then`.
Promises are chainable: `then` returns a promise, you can call `then` on
that promise, which returns a promise, you can call `then` on that
promise, et cetera.
Promises start in a pending state and *resolve* with a value to become
*fulfilled* or an `Error` to become rejected.
- SeeAlso: [PromiseKit `then` Guide](http://promisekit.org/docs/)
*/
open class Promise<T> {
let state: State<T>
/**
Create a new, pending promise.
func fetchAvatar(user: String) -> Promise<UIImage> {
return Promise { fulfill, reject in
MyWebHelper.GET("\(user)/avatar") { data, err in
guard let data = data else { return reject(err) }
guard let img = UIImage(data: data) else { return reject(MyError.InvalidImage) }
guard let img.size.width > 0 else { return reject(MyError.ImageTooSmall) }
fulfill(img)
}
}
}
- Parameter resolvers: The provided closure is called immediately on the active thread; commence your asynchronous task, calling either fulfill or reject when it completes.
- Parameter fulfill: Fulfills this promise with the provided value.
- Parameter reject: Rejects this promise with the provided error.
- Returns: A new promise.
- Note: If you are wrapping a delegate-based system, we recommend
to use instead: `Promise.pending()`
- SeeAlso: http://promisekit.org/docs/sealing-promises/
- SeeAlso: http://promisekit.org/docs/cookbook/wrapping-delegation/
- SeeAlso: pending()
*/
required public init(resolvers: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void) {
var resolve: ((Resolution<T>) -> Void)!
do {
state = UnsealedState(resolver: &resolve)
try resolvers({ resolve(.fulfilled($0)) }, { error in
#if !PMKDisableWarnings
if self.isPending {
resolve(Resolution(error))
} else {
NSLog("PromiseKit: warning: reject called on already rejected Promise: \(error)")
}
#else
resolve(Resolution(error))
#endif
})
} catch {
resolve(Resolution(error))
}
}
/**
Create an already fulfilled promise.
*/
required public init(value: T) {
state = SealedState(resolution: .fulfilled(value))
}
/**
Create an already rejected promise.
*/
required public init(error: Error) {
state = SealedState(resolution: Resolution(error))
}
/**
Careful with this, it is imperative that sealant can only be called once
or you will end up with spurious unhandled-errors due to possible double
rejections and thus immediately deallocated ErrorConsumptionTokens.
*/
init(sealant: (@escaping (Resolution<T>) -> Void) -> Void) {
var resolve: ((Resolution<T>) -> Void)!
state = UnsealedState(resolver: &resolve)
sealant(resolve)
}
/**
A `typealias` for the return values of `pending()`. Simplifies declaration of properties that reference the values' containing tuple when this is necessary. For example, when working with multiple `pendingPromise(value: ())`s within the same scope, or when the promise initialization must occur outside of the caller's initialization.
class Foo: BarDelegate {
var task: Promise<Int>.PendingTuple?
}
- SeeAlso: pending()
*/
public typealias PendingTuple = (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void)
/**
Making promises that wrap asynchronous delegation systems or other larger asynchronous systems without a simple completion handler is easier with pending.
class Foo: BarDelegate {
let (promise, fulfill, reject) = Promise<Int>.pending()
func barDidFinishWithResult(result: Int) {
fulfill(result)
}
func barDidError(error: NSError) {
reject(error)
}
}
- Returns: A tuple consisting of:
1) A promise
2) A function that fulfills that promise
3) A function that rejects that promise
*/
public final class func pending() -> PendingTuple {
var fulfill: ((T) -> Void)!
var reject: ((Error) -> Void)!
let promise = self.init { fulfill = $0; reject = $1 }
return (promise, fulfill, reject)
}
/**
The provided closure is executed when this promise is resolved.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The closure that is executed when this Promise is fulfilled.
- Returns: A new promise that is resolved with the value returned from the provided closure. For example:
NSURLSession.GET(url).then { data -> Int in
//…
return data.length
}.then { length in
//…
}
*/
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U> {
return Promise<U> { resolve in
state.then(on: q, else: resolve) { value in
resolve(.fulfilled(try body(value)))
}
}
}
/**
The provided closure executes when this promise resolves.
This variant of `then` allows chaining promises, the promise returned by the provided closure is resolved before the promise returned by this closure resolves.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise fulfills.
- Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example:
URLSession.GET(url1).then { data in
return CLLocationManager.promise()
}.then { location in
//…
}
*/
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U> {
var rv: Promise<U>!
rv = Promise<U> { resolve in
state.then(on: q, else: resolve) { value in
let promise = try body(value)
guard promise !== rv else { throw PMKError.returnedSelf }
promise.state.pipe(resolve)
}
}
return rv
}
/**
The provided closure executes when this promise rejects.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- Returns: `self`
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
- Important: The promise that is returned is `self`. `catch` cannot affect the chain, in PromiseKit 3 no promise was returned to strongly imply this, however for PromiseKit 4 we started returning a promise so that you can `always` after a catch or return from a function that has an error handler.
*/
@discardableResult
public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) -> Promise {
state.catch(on: q, policy: policy, else: { _ in }, execute: body)
return self
}
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
CLLocationManager.promise().recover { error in
guard error == CLError.unknownLocation else { throw error }
return CLLocation.Chicago
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise) -> Promise {
var rv: Promise!
rv = Promise { resolve in
state.catch(on: q, policy: policy, else: resolve) { error in
let promise = try body(error)
guard promise !== rv else { throw PMKError.returnedSelf }
promise.state.pipe(resolve)
}
}
return rv
}
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
CLLocationManager.promise().recover { error in
guard error == CLError.unknownLocation else { throw error }
return CLLocation.Chicago
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> T) -> Promise {
return Promise { resolve in
state.catch(on: q, policy: policy, else: resolve) { error in
resolve(.fulfilled(try body(error)))
}
}
}
/**
The provided closure executes when this promise resolves.
firstly {
UIApplication.shared.networkActivityIndicatorVisible = true
}.then {
//…
}.always {
UIApplication.shared.networkActivityIndicatorVisible = false
}.catch {
//…
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
public func always(on q: DispatchQueue = .default, execute body: @escaping () -> Void) -> Promise {
state.always(on: q) { resolution in
body()
}
return self
}
/**
Allows you to “tap” into a promise chain and inspect its result.
The function you provide cannot mutate the chain.
NSURLSession.GET(/*…*/).tap { result in
print(result)
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
@discardableResult
public func tap(on q: DispatchQueue = .default, execute body: @escaping (Result<T>) -> Void) -> Promise {
state.always(on: q) { resolution in
body(Result(resolution))
}
return self
}
/**
Void promises are less prone to generics-of-doom scenarios.
- SeeAlso: when.swift contains enlightening examples of using `Promise<Void>` to simplify your code.
*/
public func asVoid() -> Promise<Void> {
return then(on: zalgo) { _ in return }
}
//MARK: deprecations
@available(*, unavailable, renamed: "always()")
public func finally(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() }
@available(*, unavailable, renamed: "always()")
public func ensure(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() }
@available(*, unavailable, renamed: "pending()")
public class func `defer`() -> PendingTuple { fatalError() }
@available(*, unavailable, renamed: "pending()")
public class func `pendingPromise`() -> PendingTuple { fatalError() }
@available(*, unavailable, message: "deprecated: use then(on: .global())")
public func thenInBackground<U>(execute body: (T) throws -> U) -> Promise<U> { fatalError() }
@available(*, unavailable, renamed: "catch")
public func onError(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func errorOnQueue(_ on: DispatchQueue, policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func error(policy: CatchPolicy, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func report(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "init(value:)")
public init(_ value: T) { fatalError() }
//MARK: disallow `Promise<Error>`
@available(*, unavailable, message: "cannot instantiate Promise<Error>")
public init<T: Error>(resolvers: (_ fulfill: (T) -> Void, _ reject: (Error) -> Void) throws -> Void) { fatalError() }
@available(*, unavailable, message: "cannot instantiate Promise<Error>")
public class func pending<T: Error>() -> (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void) { fatalError() }
//MARK: disallow returning `Error`
@available (*, unavailable, message: "instead of returning the error; throw")
public func then<U: Error>(on: DispatchQueue = .default, execute body: (T) throws -> U) -> Promise<U> { fatalError() }
@available (*, unavailable, message: "instead of returning the error; throw")
public func recover<T: Error>(on: DispatchQueue = .default, execute body: (Error) throws -> T) -> Promise { fatalError() }
//MARK: disallow returning `Promise?`
@available(*, unavailable, message: "unwrap the promise")
public func then<U>(on: DispatchQueue = .default, execute body: (T) throws -> Promise<U>?) -> Promise<U> { fatalError() }
@available(*, unavailable, message: "unwrap the promise")
public func recover(on: DispatchQueue = .default, execute body: (Error) throws -> Promise?) -> Promise { fatalError() }
}
extension Promise: CustomStringConvertible {
public var description: String {
return "Promise: \(state)"
}
}
/**
Judicious use of `firstly` *may* make chains more readable.
Compare:
NSURLSession.GET(url1).then {
NSURLSession.GET(url2)
}.then {
NSURLSession.GET(url3)
}
With:
firstly {
NSURLSession.GET(url1)
}.then {
NSURLSession.GET(url2)
}.then {
NSURLSession.GET(url3)
}
*/
public func firstly<T>(execute body: () throws -> Promise<T>) -> Promise<T> {
do {
return try body()
} catch {
return Promise(error: error)
}
}
@available(*, unavailable, message: "instead of returning the error; throw")
public func firstly<T: Error>(execute body: () throws -> T) -> Promise<T> { fatalError() }
@available(*, unavailable, message: "use DispatchQueue.promise")
public func firstly<T>(on: DispatchQueue, execute body: () throws -> Promise<T>) -> Promise<T> { fatalError() }
/**
- SeeAlso: `DispatchQueue.promise(group:qos:flags:execute:)`
*/
@available(*, deprecated: 4.0, renamed: "DispatchQueue.promise")
public func dispatch_promise<T>(_ on: DispatchQueue, _ body: @escaping () throws -> T) -> Promise<T> {
return Promise(value: ()).then(on: on, execute: body)
}
/**
The underlying resolved state of a promise.
- Remark: Same as `Resolution<T>` but without the associated `ErrorConsumptionToken`.
*/
public enum Result<T> {
/// Fulfillment
case fulfilled(T)
/// Rejection
case rejected(Error)
init(_ resolution: Resolution<T>) {
switch resolution {
case .fulfilled(let value):
self = .fulfilled(value)
case .rejected(let error, _):
self = .rejected(error)
}
}
/**
- Returns: `true` if the result is `fulfilled` or `false` if it is `rejected`.
*/
public var boolValue: Bool {
switch self {
case .fulfilled:
return true
case .rejected:
return false
}
}
}
/**
An object produced by `Promise.joint()`, along with a promise to which it is bound.
Joining with a promise via `Promise.join(_:)` will pipe the resolution of that promise to
the joint's bound promise.
- SeeAlso: `Promise.joint()`
- SeeAlso: `Promise.join(_:)`
*/
public class PMKJoint<T> {
fileprivate var resolve: ((Resolution<T>) -> Void)!
}
extension Promise {
/**
Provides a safe way to instantiate a `Promise` and resolve it later via its joint and another
promise.
class Engine {
static func make() -> Promise<Engine> {
let (enginePromise, joint) = Promise<Engine>.joint()
let cylinder: Cylinder = Cylinder(explodeAction: {
// We *could* use an IUO, but there are no guarantees about when
// this callback will be called. Having an actual promise is safe.
enginePromise.then { engine in
engine.checkOilPressure()
}
})
firstly {
Ignition.default.start()
}.then { plugs in
Engine(cylinders: [cylinder], sparkPlugs: plugs)
}.join(joint)
return enginePromise
}
}
- Returns: A new promise and its joint.
- SeeAlso: `Promise.join(_:)`
*/
public final class func joint() -> (Promise<T>, PMKJoint<T>) {
let pipe = PMKJoint<T>()
let promise = Promise(sealant: { pipe.resolve = $0 })
return (promise, pipe)
}
/**
Pipes the value of this promise to the promise created with the joint.
- Parameter joint: The joint on which to join.
- SeeAlso: `Promise.joint()`
*/
public func join(_ joint: PMKJoint<T>) {
state.pipe(joint.resolve)
}
}
extension Promise where T: Collection {
/**
Transforms a `Promise` where `T` is a `Collection` into a `Promise<[U]>`
URLSession.shared.dataTask(url: /*…*/).asArray().map { result in
return download(result)
}.then { images in
// images is `[UIImage]`
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter transform: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
public func map<U>(on: DispatchQueue = .default, transform: @escaping (T.Iterator.Element) throws -> Promise<U>) -> Promise<[U]> {
return Promise<[U]> { resolve in
return state.then(on: zalgo, else: resolve) { tt in
when(fulfilled: try tt.map(transform)).state.pipe(resolve)
}
}
}
}
| apache-2.0 | 1d9abc93046601f002ae092582ca3bb6 | 36.753788 | 339 | 0.621651 | 4.563645 | false | false | false | false |
Urinx/SublimeCode | Sublime/Pods/AlamofireRSSParser/Pod/Classes/RSSItem.swift | 1 | 2683 | //
// RSSItem.swift
// AlamofireRSSParser
//
// Created by Donald Angelillo on 3/1/16.
// Copyright © 2016 Donald Angelillo. All rights reserved.
//
import Foundation
/**
Item-level elements are deserialized into `RSSItem` objects and stored in the `items` array of an `RSSFeed` instance
*/
public class RSSItem: CustomStringConvertible {
public var title: String? = nil
public var link: String? = nil
/**
Upon setting this property the `itemDescription` will be scanned for HTML and all image urls will be extracted and stored in `imagesFromDescription`
*/
public var itemDescription: String? = nil {
didSet {
if let itemDescription = self.itemDescription {
self.imagesFromDescription = self.imagesFromHTMLString(itemDescription)
}
}
}
public var guid: String? = nil
public var author: String? = nil
public var comments: String? = nil
public var source: String? = nil
public var pubDate: NSDate? = nil
public var mediaThumbnail: String? = nil;
public var mediaContent: String? = nil;
public var imagesFromDescription: [String]? = nil;
public var description: String {
return "\ttitle: \(self.title)\n\tlink: \(self.link)\n\titemDescription: \(self.itemDescription)\n\tguid: \(self.guid)\n\tauthor: \(self.author)\n\tcomments: \(self.comments)\n\tsource: \(self.source)\n\tpubDate: \(self.pubDate)\nmediaThumbnail: \(self.mediaThumbnail)\nmediaContent: \(self.mediaContent)\nimagesFromDescription: \(self.imagesFromDescription)\n\n"
}
/**
Retrieves all the images (\<img\> tags) from a given String contaning HTML using a regex.
- Parameter htmlString: A String containing HTML
- Returns: an array of image url Strings ([String])
*/
private func imagesFromHTMLString(htmlString: String) -> [String] {
let htmlNSString = htmlString as NSString;
var images: [String] = Array();
do {
let regex = try NSRegularExpression(pattern: "(https?)\\S*(png|jpg|jpeg|gif)", options: [NSRegularExpressionOptions.CaseInsensitive])
regex.enumerateMatchesInString(htmlString, options: [NSMatchingOptions.ReportProgress], range: NSMakeRange(0, htmlString.characters.count)) { (result, flags, stop) -> Void in
if let range = result?.range {
images.append(htmlNSString.substringWithRange(range)) //because Swift ranges are still completely ridiculous
}
}
}
catch {
}
return images;
}
} | gpl-3.0 | 0f18302657980769fcc41a2be4104f98 | 37.328571 | 371 | 0.640194 | 4.447761 | false | false | false | false |
ducyen/ClasHStamP | samples/CalcSub/swift/Main/CalcController.swift | 3 | 1443 | import Foundation
import Main.CalcModel
class CalcController : System.Object
{
var _calcModel: CalcModel
public init (
) {
_calcModel = new CalcModel()
}
public Run(): void {
_calcModel.Start();
_calcModel.RunToCompletion();
char key = '\0';
do {
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
key = keyInfo.KeyChar;
switch (Char.ToLower(key)) {
case '0':
_calcModel.Digit0();
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
_calcModel.Digit19(key);
break;
case 'a':
_calcModel.Ac();
break;
case 'c':
_calcModel.Ce();
break;
case '+':
case '-':
case '*':
case '/':
_calcModel.Oper(key);
break;
case '.':
_calcModel.Point();
break;
case 'q':
_calcModel.Off();
break;
case '=':
_calcModel.Equals();
break;
default:
break;
}
} while (key != 'q');
} // Run
}
}
| gpl-3.0 | bf5cbc3acc5f5d3c6777fb094bf7eea5 | 23.016667 | 59 | 0.361554 | 4.589172 | false | false | false | false |
gabmarfer/CucumberPicker | CucumberPicker/CucumberPicker/Commons/Extensions/UIImageSwiftExtension/UIImage+Resize.swift | 1 | 6927 | //
// UIImage+Resize.swift
//
// Created by Trevor Harmon on 08/05/09.
// Swift 3 port by Giacomo Boccardo on 09/15/2016.
//
// Free for personal or commercial use, with or without modification
// No warranty is expressed or implied.
//
import UIKit
public extension UIImage {
// Returns a copy of this image that is cropped to the given bounds.
// The bounds will be adjusted using CGRectIntegral.
// This method ignores the image's imageOrientation setting.
public func croppedImage(_ bounds: CGRect) -> UIImage {
let imageRef: CGImage = (self.cgImage)!.cropping(to: bounds)!
return UIImage(cgImage: imageRef)
}
public func thumbnailImage(_ thumbnailSize: Int, transparentBorder borderSize:Int, cornerRadius:Int, interpolationQuality quality:CGInterpolationQuality) -> UIImage {
let resizedImage = self.resizedImageWithContentMode(.scaleAspectFill, bounds: CGSize(width: CGFloat(thumbnailSize), height: CGFloat(thumbnailSize)), interpolationQuality: quality)
// Crop out any part of the image that's larger than the thumbnail size
// The cropped rect must be centered on the resized image
// Round the origin points so that the size isn't altered when CGRectIntegral is later invoked
let cropRect = CGRect(
x: round((resizedImage.size.width - CGFloat(thumbnailSize))/2),
y: round((resizedImage.size.height - CGFloat(thumbnailSize))/2),
width: CGFloat(thumbnailSize),
height: CGFloat(thumbnailSize)
)
let croppedImage = resizedImage.croppedImage(cropRect)
let transparentBorderImage = borderSize != 0 ? croppedImage.transparentBorderImage(borderSize) : croppedImage
return transparentBorderImage.roundedCornerImage(cornerSize: cornerRadius, borderSize: borderSize)
}
// Returns a rescaled copy of the image, taking into account its orientation
// The image will be scaled disproportionately if necessary to fit the bounds specified by the parameter
public func resizedImage(_ newSize: CGSize, interpolationQuality quality: CGInterpolationQuality) -> UIImage {
var drawTransposed: Bool
switch(self.imageOrientation) {
case .left, .leftMirrored, .right, .rightMirrored:
drawTransposed = true
default:
drawTransposed = false
}
return self.resizedImage(
newSize,
transform: self.transformForOrientation(newSize),
drawTransposed: drawTransposed,
interpolationQuality: quality
)
}
public func resizedImageWithContentMode(_ contentMode: UIViewContentMode, bounds: CGSize, interpolationQuality quality: CGInterpolationQuality) -> UIImage {
let horizontalRatio = bounds.width / self.size.width
let verticalRatio = bounds.height / self.size.height
var ratio: CGFloat = 1
switch(contentMode) {
case .scaleAspectFill:
ratio = max(horizontalRatio, verticalRatio)
case .scaleAspectFit:
ratio = min(horizontalRatio, verticalRatio)
default:
fatalError("Unsupported content mode \(contentMode)")
}
let newSize: CGSize = CGSize(width: self.size.width * ratio, height: self.size.height * ratio)
return self.resizedImage(newSize, interpolationQuality: quality)
}
fileprivate func normalizeBitmapInfo(_ bI: CGBitmapInfo) -> UInt32 {
var alphaInfo: UInt32 = bI.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
if alphaInfo == CGImageAlphaInfo.last.rawValue {
alphaInfo = CGImageAlphaInfo.premultipliedLast.rawValue
}
if alphaInfo == CGImageAlphaInfo.first.rawValue {
alphaInfo = CGImageAlphaInfo.premultipliedFirst.rawValue
}
var newBI: UInt32 = bI.rawValue & ~CGBitmapInfo.alphaInfoMask.rawValue;
newBI |= alphaInfo;
return newBI
}
fileprivate func resizedImage(_ newSize: CGSize, transform: CGAffineTransform, drawTransposed transpose: Bool, interpolationQuality quality: CGInterpolationQuality) -> UIImage {
let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
let transposedRect = CGRect(x: 0, y: 0, width: newRect.size.height, height: newRect.size.width)
let imageRef: CGImage = self.cgImage!
// Build a context that's the same dimensions as the new size
let bitmap: CGContext = CGContext(
data: nil,
width: Int(newRect.size.width),
height: Int(newRect.size.height),
bitsPerComponent: imageRef.bitsPerComponent,
bytesPerRow: 0,
space: imageRef.colorSpace!,
bitmapInfo: normalizeBitmapInfo(imageRef.bitmapInfo)
)!
// Rotate and/or flip the image if required by its orientation
bitmap.concatenate(transform)
// Set the quality level to use when rescaling
bitmap.interpolationQuality = quality
// Draw into the context; this scales the image
bitmap.draw(imageRef, in: transpose ? transposedRect: newRect)
// Get the resized image from the context and a UIImage
let newImageRef: CGImage = bitmap.makeImage()!
return UIImage(cgImage: newImageRef)
}
fileprivate func transformForOrientation(_ newSize: CGSize) -> CGAffineTransform {
var transform: CGAffineTransform = CGAffineTransform.identity
switch (self.imageOrientation) {
case .down, .downMirrored:
// EXIF = 3 / 4
transform = transform.translatedBy(x: newSize.width, y: newSize.height)
transform = transform.rotated(by: CGFloat(M_PI))
case .left, .leftMirrored:
// EXIF = 6 / 5
transform = transform.translatedBy(x: newSize.width, y: 0)
transform = transform.rotated(by: CGFloat(M_PI_2))
case .right, .rightMirrored:
// EXIF = 8 / 7
transform = transform.translatedBy(x: 0, y: newSize.height)
transform = transform.rotated(by: -CGFloat(M_PI_2))
default:
break
}
switch(self.imageOrientation) {
case .upMirrored, .downMirrored:
// EXIF = 2 / 4
transform = transform.translatedBy(x: newSize.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
// EXIF = 5 / 7
transform = transform.translatedBy(x: newSize.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
break
}
return transform
}
}
| mit | 693754fd5f7e2a85cc3ef92d66eef396 | 41.759259 | 187 | 0.635629 | 5.07101 | false | false | false | false |
material-motion/material-motion-swift | src/interactions/ArcMove.swift | 2 | 8382 | /*
Copyright 2016-present The Material Motion Authors. 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 UIKit
/**
Calculates an arc path between two points and uses a PathTween interaction to move between the two
points.
**Affected properties**
- `view.layer.position`
*/
public final class ArcMove: Interaction, Togglable, Stateful {
/**
The initial position of the arc move animation.
*/
public let from = createProperty(withInitialValue: CGPoint.zero)
/**
The final position of the arc move animation.
*/
public let to = createProperty(withInitialValue: CGPoint.zero)
/**
The tween interaction that will interpolate between the from and to values.
*/
public let tween: PathTween
/**
Initializes an arc move instance with its required properties.
*/
public init(tween: PathTween = PathTween()) {
self.tween = tween
}
public func add(to view: UIView, withRuntime runtime: MotionRuntime, constraints: NoConstraints) {
runtime.connect(arcMove(from: from, to: to), to: tween.path)
runtime.add(tween, to: runtime.get(view.layer).position)
}
public var enabled: ReactiveProperty<Bool> {
return tween.enabled
}
public var state: MotionObservable<MotionState> {
return tween.state
}
}
// Given two positional streams, returns a stream that emits an arc move path between the two
// positions.
private func arcMove<O1: MotionObservableConvertible, O2: MotionObservableConvertible>
(from: O1, to: O2)
-> MotionObservable<CGPath> where O1.T == CGPoint, O2.T == CGPoint {
return MotionObservable { observer in
var latestFrom: CGPoint?
var latestTo: CGPoint?
let checkAndEmit = {
guard let from = latestFrom, let to = latestTo else {
return
}
let path = UIBezierPath()
path.move(to: from)
let controlPoints = arcMovement(from: from, to: to)
path.addCurve(to: to, controlPoint1: controlPoints.point1, controlPoint2: controlPoints.point2)
observer.next(path.cgPath)
}
let fromSubscription = from.subscribeToValue { fromValue in
latestFrom = fromValue
checkAndEmit()
}
let toSubscription = to.subscribeToValue { toValue in
latestTo = toValue
checkAndEmit()
}
return {
fromSubscription.unsubscribe()
toSubscription.unsubscribe()
}
}
}
private let defaultMinArcAngle: CGFloat = 10.0
private let defaultMaxArcAngle: CGFloat = 90.0
private func rad2deg(_ radians: CGFloat) -> CGFloat {
return radians * 180.0 / CGFloat(Double.pi)
}
private func deg2rad(_ degrees: CGFloat) -> CGFloat {
return degrees * CGFloat(Double.pi) / 180.0
}
private func distance(from: CGPoint, to: CGPoint) -> CGFloat {
let deltaX = to.x - from.x
let deltaY = to.y - from.y
return sqrt(deltaX * deltaX + deltaY * deltaY)
}
private func normalized(_ point: CGPoint) -> CGPoint {
let length = sqrt(point.x * point.x + point.y * point.y)
if length < CGFloat(Double.ulpOfOne) {
return .zero
}
return CGPoint(x: point.x / length, y: point.y / length)
}
private struct ControlPoints {
let point1: CGPoint
let point2: CGPoint
}
// Returns control points for usage when calculating a cubic bezier path that matches
// material motion spec. This typically results in a curve that is part of a circle.
//
// The naming of variables in this method follows the diagram available here:
// https://github.com/material-motion/material-motion/blob/gh-pages/assets/arcmove.png
private func arcMovement(from: CGPoint, to: CGPoint) -> ControlPoints {
if from == to {
return ControlPoints(point1: from, point2: to)
}
let minArcAngleRad = deg2rad(defaultMinArcAngle)
let deltaX = to.x - from.x
let deltaY = to.y - from.y
let pointC = CGPoint(x: to.x, y: from.y)
let pointD = CGPoint(x: (from.x + to.x) * 0.5, y: (from.y + to.y) * 0.5)
// Calculate side lengths
let lenAB = distance(from: from, to: to)
let lenAC = distance(from: from, to: pointC)
let lenBC = distance(from: to, to: pointC)
// Length AD is half length AB
let lenAD = lenAB * 0.5
// Angle alpha
let alpha: CGFloat
if abs(deltaX) > abs(deltaY) {
alpha = cos(lenAC / lenAB)
} else {
alpha = cos(lenBC / lenAB)
}
// Alpha in degrees
let alphaDeg = rad2deg(alpha)
// Calculate point E
let lenAE = lenAD / cos(alpha)
let pointE: CGPoint
if from.y == to.y {
pointE = pointD
} else if abs(deltaX) > abs(deltaY) {
let normalizedCFrom = normalized(CGPoint(x: pointC.x - from.x, y: pointC.y - from.y))
pointE = CGPoint(x: from.x + (normalizedCFrom.x * lenAE),
y: from.y + (normalizedCFrom.y * lenAE))
} else {
let normalizedCTo = normalized(CGPoint(x: pointC.x - to.x, y: pointC.y - to.y))
pointE = CGPoint(x: to.x + (normalizedCTo.x * lenAE),
y: to.y + (normalizedCTo.y * lenAE))
}
// Constrain DE to account for min/max arc segment
let arcAngleClampDeg = min(defaultMaxArcAngle, max(defaultMinArcAngle, alphaDeg * 2.0))
let arcAngleClamp = deg2rad(arcAngleClampDeg)
let alphaClamp = arcAngleClamp / 2.0
let maxLen = lenAD * tan(alphaClamp)
// Point E'
let pointE2: CGPoint
let vDE = CGPoint(x: pointE.x - pointD.x, y: pointE.y - pointD.y)
let lenDE = distance(from: .zero, to: vDE)
var adjMinLen: CGFloat
if defaultMinArcAngle > 0 {
let tanMinArcAngleRad = tan(minArcAngleRad)
if abs(tanMinArcAngleRad) < CGFloat(Double.ulpOfOne) {
// Protection against possible divide by zero - shouldn't happen in practice.
adjMinLen = .greatestFiniteMagnitude
} else {
let lenADOverTanMinArcAngleRad = lenAD / tanMinArcAngleRad;
adjMinLen = sqrt(lenAD * lenAD + pow(lenADOverTanMinArcAngleRad, 2)) - lenADOverTanMinArcAngleRad
}
} else {
adjMinLen = 0
}
if abs(deltaY) > abs(deltaX) {
adjMinLen = max(0, min(lenDE, maxLen))
}
let newLen = max(adjMinLen, min(lenDE, maxLen))
if from.y == to.y {
pointE2 = CGPoint(x: pointD.x, y: pointD.y + newLen)
} else {
let normalizedVDE = normalized(vDE)
pointE2 = CGPoint(x: pointD.x + (normalizedVDE.x * newLen),
y: pointD.y + (normalizedVDE.y * newLen))
}
// Alpha'
let lenDE2 = distance(from: pointD, to: pointE2)
let alpha2 = atan(lenDE2 / lenAD)
// Alpha' degrees.
let alpha2deg = rad2deg(alpha2)
// Beta' degrees.
let beta2deg = 90.0 - alpha2deg
// Beta'.
let beta2 = deg2rad(beta2deg)
// Radius'.
let radius2 = lenAD / cos(beta2)
// Calculate the cubic bezier tangent handle length
//
// The following method is for a 90 degree arc
//
// tangent length = radius * k * scaleFactor
//
// radius: radius of our circle
// kappa: constant with value of ~0.5522847498
// scaleFactor: proportion of our arc to a 90 degree arc (arc angle / 90)
let kappa: CGFloat = 0.5522847498
let radScaling: CGFloat = (alpha2deg * 2.0) / 90.0
let tangentLength = radius2 * kappa * radScaling
// Calculate the in tangent position in world coordinates
// The tangent handle lies along the line between points B and E'
// with magnitude of tangentLength
let vBEnorm = normalized(CGPoint(x: pointE2.x - to.x, y: pointE2.y - to.y))
let inTangent = CGPoint(x: to.x + (vBEnorm.x * tangentLength),
y: to.y + (vBEnorm.y * tangentLength))
// Calculate the out tangent position in world coordinates
// The tangent handle lies along the line between points A and E'
// with magnitude of tangentLength
let vAEnorm = normalized(CGPoint(x: pointE2.x - from.x, y: pointE2.y - from.y))
let outTangent = CGPoint(x: from.x + (vAEnorm.x * tangentLength),
y: from.y + (vAEnorm.y * tangentLength))
return ControlPoints(point1: outTangent, point2: inTangent)
}
| apache-2.0 | ea274e71529171135472344d22d104ff | 29.929889 | 103 | 0.67633 | 3.59897 | false | false | false | false |
8bytes/drift-sdk-ios | Drift/Models/User.swift | 2 | 1097 | //
// User.swift
// Drift
//
// Created by Eoin O'Connell on 25/01/2016.
// Copyright © 2016 Drift. All rights reserved.
//
///Codable for caching
struct User: Codable, Equatable, UserDisplayable {
let userId: Int64?
let email: String?
let name: String?
let avatarURL: String?
let bot: Bool
func getUserName() -> String{
return name ?? email ?? "No Name Set"
}
}
class UserDTO: Codable, DTO {
typealias DataObject = User
var userId: Int64?
var email: String?
var name: String?
var avatarURL: String?
var bot: Bool?
enum CodingKeys: String, CodingKey {
case userId = "id"
case email = "email"
case name = "name"
case avatarURL = "avatarUrl"
case bot = "bot"
}
func mapToObject() -> User? {
return User(userId: userId,
email: email,
name: name,
avatarURL: avatarURL,
bot: bot ?? false)
}
}
func ==(lhs: User, rhs: User) -> Bool {
return lhs.userId == rhs.userId
}
| mit | 451df74618234d8c51d012d674709151 | 19.679245 | 50 | 0.546533 | 3.985455 | false | false | false | false |
mozilla-mobile/prox | Prox/Prox/Extensions/TimeInterval.swift | 1 | 940 | /* 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/. */
public extension TimeInterval {
public func asHoursAndMinutesString() -> String {
let (hours, mins) = asHoursAndMinutes()
var timeString: String = ""
if hours > 0 {
timeString += "\(hours) hour"
if hours > 1 {
timeString += "s"
}
if mins > 0 {
timeString += ", "
}
}
if mins > 0 {
timeString += "\(mins) minute"
if mins != 1 {
timeString += "s"
}
}
return timeString
}
public func asHoursAndMinutes () -> (Int, Int) {
let selfAsInt = Int(self)
return (selfAsInt / 3600, (selfAsInt % 3600) / 60)
}
}
| mpl-2.0 | 208f49d7e7bc9438222ec751e29e7455 | 28.375 | 70 | 0.498936 | 4.433962 | false | false | false | false |
DungeonKeepers/DnDInventoryManager | DnDInventoryManager/DnDInventoryManager/CharacterGalleryFlowLayout.swift | 1 | 1231 | //
// CharacterGalleryFlowLayout.swift
// DnDInventoryManager
//
// Created by Mike Miksch on 4/11/17.
// Copyright © 2017 Mike Miksch. All rights reserved.
//
import UIKit
class CharacterGalleryFlowLayout: UICollectionViewFlowLayout {
var columns = 2
var rows = 3
let spacing: CGFloat = 10.0
var screenWidth : CGFloat {
return UIScreen.main.bounds.width
}
var screenHeight : CGFloat {
return UIScreen.main.bounds.height
}
var itemWidth : CGFloat {
let avaialbleScreen = screenWidth - (CGFloat(self.columns) * self.spacing)
return avaialbleScreen / CGFloat(self.columns)
}
var itemHeight: CGFloat {
let availableScreen = screenHeight - (CGFloat(self.rows) * self.spacing)
return availableScreen / CGFloat(self.rows)
}
init(columns : Int = 2) {
self.columns = columns
super.init()
self.minimumLineSpacing = spacing
self.minimumInteritemSpacing = spacing
self.itemSize = CGSize(width: itemWidth, height: itemWidth)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | db301a02729cf436c074e9a159f33c08 | 23.6 | 82 | 0.631707 | 4.505495 | false | false | false | false |
arrrnas/vinted-ab-ios | Carthage/Checkouts/CryptoSwift/Tests/CryptoSwiftTests/DigestTests.swift | 1 | 15801 | //
// DigestTests.swift
// CryptoSwiftTests
//
// Created by Marcin Krzyzanowski on 06/07/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
// http://www.di-mgt.com.au/sha_testvectors.html (http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf)
//
import XCTest
import Foundation
@testable import CryptoSwift
final class DigestTests: XCTestCase {
func testMD5() {
XCTAssertEqual("123".md5(), "202cb962ac59075b964b07152d234b70", "MD5 calculation failed")
XCTAssertEqual("".md5(), "d41d8cd98f00b204e9800998ecf8427e", "MD5 calculation failed")
XCTAssertEqual("a".md5(), "0cc175b9c0f1b6a831c399e269772661", "MD5 calculation failed")
XCTAssertEqual("abc".md5(), "900150983cd24fb0d6963f7d28e17f72", "MD5 calculation failed")
XCTAssertEqual("message digest".md5(), "f96b697d7cb7938d525a2f31aaf161d0", "MD5 calculation failed")
XCTAssertEqual("abcdefghijklmnopqrstuvwxyz".md5(), "c3fcd3d76192e4007dfb496cca67e13b", "MD5 calculation failed")
XCTAssertEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".md5(), "d174ab98d277d9f5a5611c2c9f419d9f", "MD5 calculation failed")
XCTAssertEqual("12345678901234567890123456789012345678901234567890123456789012345678901234567890".md5(), "57edf4a22be3c955ac49da2e2107b67a", "MD5 calculation failed")
}
func testSHA1() {
XCTAssertEqual(SHA1().calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "a9993e364706816aba3e25717850c26c9cd0d89d")
XCTAssertEqual(SHA1().calculate(for: Array<UInt8>(hex: "")).toHexString(), "da39a3ee5e6b4b0d3255bfef95601890afd80709")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha1(), "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha1(), "a49b2446a02c645bf419f995b67091253a04a259")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha1(), Array<UInt8>(hex: "34aa973cd4c4daa4f61eeb2bdbad27316534016f"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
// https://github.com/krzyzanowskim/CryptoSwift/issues/363
XCTAssertEqual("1477304791&1XpnGSRhOlZz2etXMeOdfNaHILTjW16U&8mpBBbzwsgs".sha1(), "0809bbf8489c594131c2030a84be364a0851a635", "Failed")
XCTAssertEqual("1477304791&1XpnGSRhOlZz2etXMeOdfNaHILTjW16U&8mpBBbzwsgsa".sha1(), "d345b525ebada7becc8107c54e07fa88644471f5", "Failed")
XCTAssertEqual("1477304791&1XpnGSRhOlZz2etXMeOdfNaHILTjW16U&8mpBBbzwsg".sha1(), "c106aa0a98606294ee35fd2d937e928ebb5339e0", "Failed")
}
func testSHA2() {
XCTAssertEqual(SHA2(variant: .sha224).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
XCTAssertEqual(SHA2(variant: .sha256).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
XCTAssertEqual(SHA2(variant: .sha384).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7")
XCTAssertEqual(SHA2(variant: .sha512).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
XCTAssertEqual(SHA2(variant: .sha224).calculate(for: Array<UInt8>(hex: "")).toHexString(), "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
XCTAssertEqual(SHA2(variant: .sha256).calculate(for: Array<UInt8>(hex: "")).toHexString(), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
XCTAssertEqual(SHA2(variant: .sha384).calculate(for: Array<UInt8>(hex: "")).toHexString(), "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b")
XCTAssertEqual(SHA2(variant: .sha512).calculate(for: Array<UInt8>(hex: "")).toHexString(), "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha224(), "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha256(), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha384(), "3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha512(), "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha224(), "c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha256(), "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha384(), "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha512(), "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha224(), Array<UInt8>(hex: "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha256(), Array<UInt8>(hex: "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha384(), Array<UInt8>(hex: "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha512(), Array<UInt8>(hex: "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
XCTAssertEqual("Rosetta code".sha256(), "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf", "SHA256 calculation failed")
XCTAssertEqual("The quick brown fox jumps over the lazy dog.".sha384(), "ed892481d8272ca6df370bf706e4d7bc1b5739fa2177aae6c50e946678718fc67a7af2819a021c2fc34e91bdb63409d7", "SHA384 calculation failed")
}
func testSHA3() {
XCTAssertEqual(SHA3(variant: .sha224).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf")
XCTAssertEqual(SHA3(variant: .sha256).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532")
XCTAssertEqual(SHA3(variant: .sha384).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25")
XCTAssertEqual(SHA3(variant: .sha512).calculate(for: Array<UInt8>(hex: "616263")).toHexString(), "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0")
XCTAssertEqual(SHA3(variant: .sha224).calculate(for: Array<UInt8>(hex: "")).toHexString(), "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7")
XCTAssertEqual(SHA3(variant: .sha256).calculate(for: Array<UInt8>(hex: "")).toHexString(), "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")
XCTAssertEqual(SHA3(variant: .sha384).calculate(for: Array<UInt8>(hex: "")).toHexString(), "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004")
XCTAssertEqual(SHA3(variant: .sha512).calculate(for: Array<UInt8>(hex: "")).toHexString(), "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha3(.sha224), "8a24108b154ada21c9fd5574494479ba5c7e7ab76ef264ead0fcce33")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha3(.sha256), "41c0dba2a9d6240849100376a8235e2c82e1b9998a999e21db32dd97496d3376")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha3(.sha384), "991c665755eb3a4b6bbdfb75c78a492e8c56a22c5c4d7e429bfdbc32b9d4ad5aa04a1f076e62fea19eef51acd0657c22")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha3(.sha512), "04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha3(.sha224), "543e6868e1666c1a643630df77367ae5a62a85070a51c14cbf665cbc")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha3(.sha256), "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha3(.sha384), "79407d3b5916b59c3e30b09822974791c313fb9ecc849e406f23592d04f625dc8c709b98b43b3852b337216179aa7fc7")
XCTAssertEqual("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".sha3(.sha512), "afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha3(.sha224), Array<UInt8>(hex: "d69335b93325192e516a912e6d19a15cb51c6ed5c15243e7a7fd653c"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha3(.sha256), Array<UInt8>(hex: "5c8875ae474a3634ba4fd55ec85bffd661f32aca75c6d699d0cdcb6c115891c1"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha3(.sha384), Array<UInt8>(hex: "eee9e24d78c1855337983451df97c8ad9eedf256c6334f8e948d252d5e0e76847aa0774ddb90a842190d2c558b4b8340"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
XCTAssertEqual(Array<UInt8>(repeating: 0x61, count: 1_000_000).sha3(.sha512), Array<UInt8>(hex: "3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87"), "One million (1,000,000) repetitions of the character 'a' (0x61)")
}
func testMD5Data() {
let data = [0x31, 0x32, 0x33] as Array<UInt8> // "1", "2", "3"
XCTAssertEqual(Digest.md5(data), [0x20, 0x2c, 0xb9, 0x62, 0xac, 0x59, 0x07, 0x5b, 0x96, 0x4b, 0x07, 0x15, 0x2d, 0x23, 0x4b, 0x70], "MD5 calculation failed")
}
func testMD5Updates() {
do {
var hash = MD5()
let _ = try hash.update(withBytes: [0x31, 0x32])
let _ = try hash.update(withBytes: [0x33])
let result = try hash.finish()
XCTAssertEqual(result, [0x20, 0x2c, 0xb9, 0x62, 0xac, 0x59, 0x07, 0x5b, 0x96, 0x4b, 0x07, 0x15, 0x2d, 0x23, 0x4b, 0x70])
} catch {
XCTFail()
}
}
func testSHA1Updatable1() {
do {
var hash = SHA1()
let _ = try hash.update(withBytes: [0x31, 0x32])
let _ = try hash.update(withBytes: [0x33])
XCTAssertEqual(try hash.finish().toHexString(), "40bd001563085fc35165329ea1ff5c5ecbdbbeef", "Failed")
} catch {
XCTFail()
}
}
func testSHA1Updatable2() {
do {
var hash = SHA1()
let _ = try hash.update(withBytes: [0x31, 0x32])
let _ = try hash.update(withBytes: [0x33])
let _ = try hash.update(withBytes: Array<UInt8>.init(repeating: 0x33, count: 64))
XCTAssertEqual(try hash.finish().toHexString(), "0e659367eff83a6b868a35b96ac305b270025e86", "Failed")
} catch {
XCTFail()
}
}
func testCRC32() {
let data: Data = Data(bytes: UnsafePointer<UInt8>([49, 50, 51] as Array<UInt8>), count: 3)
XCTAssertEqual(data.crc32(seed: nil).toHexString(), "884863d2", "CRC32 calculation failed")
XCTAssertEqual("".crc32(seed: nil), "00000000", "CRC32 calculation failed")
}
func testCRC32NotReflected() {
let bytes: Array<UInt8> = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]
let data: Data = Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
XCTAssertEqual(data.crc32(seed: nil, reflect: false).toHexString(), "fc891918", "CRC32 (with reflection) calculation failed")
XCTAssertEqual("".crc32(seed: nil, reflect: false), "00000000", "CRC32 (with reflection) calculation failed")
}
func testCRC16() {
let result = Checksum.crc16([49, 50, 51, 52, 53, 54, 55, 56, 57] as Array<UInt8>)
XCTAssert(result == 0xBB3D, "CRC16 failed")
}
func testChecksum() {
let data: Data = Data(bytes: UnsafePointer<UInt8>([49, 50, 51] as Array<UInt8>), count: 3)
XCTAssert(data.checksum() == 0x96, "Invalid checksum")
}
}
#if !CI
extension DigestTests {
func testMD5Performance() {
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, for: { () -> Void in
let arr = Array<UInt8>(repeating: 200, count: 1024 * 1024)
self.startMeasuring()
_ = Digest.md5(arr)
self.stopMeasuring()
})
}
func testSHA1Performance() {
self.measure {
for _ in 0 ..< 10_000 {
let _ = "".sha1()
}
}
}
}
#endif
extension DigestTests {
static func allTests() -> [(String, (DigestTests) -> () -> Void)] {
var tests = [
("testMD5", testMD5),
("testSHA1", testSHA1),
("testSHA2", testSHA2),
("testSHA3", testSHA3),
("testMD5Data", testMD5Data),
("testMD5Updates", testMD5Updates),
("testSHA1Updatable1", testSHA1Updatable1),
("testSHA1Updatable2", testSHA1Updatable2),
("testCRC32", testCRC32),
("testCRC32NotReflected", testCRC32NotReflected),
("testCRC15", testCRC16),
("testChecksum", testChecksum),
]
#if !CI
tests += [
("testMD5Performance", testMD5Performance),
("testSHA1Performance", testSHA1Performance),
]
#endif
return tests
}
}
| mit | 492151ec0ed0b3a5942afa06fc0f63bf | 72.836449 | 303 | 0.751471 | 2.707969 | false | true | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/PropertyListEncoder.swift | 1 | 82825 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CoreFoundation
//===----------------------------------------------------------------------===//
// Plist Encoder
//===----------------------------------------------------------------------===//
/// `PropertyListEncoder` facilitates the encoding of `Encodable` values into property lists.
// NOTE: older overlays had Foundation.PropertyListEncoder as the ObjC
// name. The two must coexist, so it was renamed. The old name must not
// be used in the new runtime. _TtC10Foundation20_PropertyListEncoder
// is the mangled name for Foundation._PropertyListEncoder.
// @_objcRuntimeName(_TtC10Foundation20_PropertyListEncoder)
open class PropertyListEncoder {
// MARK: - Options
/// The output format to write the property list data in. Defaults to `.binary`.
open var outputFormat: PropertyListSerialization.PropertyListFormat = .binary
/// Contextual user-provided information for use during encoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the encoding hierarchy.
fileprivate struct _Options {
let outputFormat: PropertyListSerialization.PropertyListFormat
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level encoder.
fileprivate var options: _Options {
return _Options(outputFormat: outputFormat, userInfo: userInfo)
}
// MARK: - Constructing a Property List Encoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Encoding Values
/// Encodes the given top-level value and returns its property list representation.
///
/// - parameter value: The value to encode.
/// - returns: A new `Data` value containing the encoded property list data.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
open func encode<Value : Encodable>(_ value: Value) throws -> Data {
let topLevel = try encodeToTopLevelContainer(value)
if topLevel is NSNumber {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) encoded as number property list fragment."))
} else if topLevel is NSString {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) encoded as string property list fragment."))
} else if topLevel is NSDate {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) encoded as date property list fragment."))
}
do {
return try PropertyListSerialization.data(fromPropertyList: topLevel, format: self.outputFormat, options: 0)
} catch {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value as a property list", underlyingError: error))
}
}
/// Encodes the given top-level value and returns its plist-type representation.
///
/// - parameter value: The value to encode.
/// - returns: A new top-level array or dictionary representing the value.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
internal func encodeToTopLevelContainer<Value : Encodable>(_ value: Value) throws -> Any {
let encoder = __PlistEncoder(options: self.options)
guard let topLevel = try encoder.box_(value) else {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) did not encode any values."))
}
return topLevel
}
}
// MARK: - __PlistEncoder
// NOTE: older overlays called this class _PlistEncoder. The two must
// coexist without a conflicting ObjC class name, so it was renamed.
// The old name must not be used in the new runtime.
fileprivate class __PlistEncoder : Encoder {
// MARK: Properties
/// The encoder's storage.
fileprivate var storage: _PlistEncodingStorage
/// Options set on the top-level encoder.
fileprivate let options: PropertyListEncoder._Options
/// The path to the current point in encoding.
fileprivate(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level encoder options.
fileprivate init(options: PropertyListEncoder._Options, codingPath: [CodingKey] = []) {
self.options = options
self.storage = _PlistEncodingStorage()
self.codingPath = codingPath
}
/// Returns whether a new element can be encoded at this coding path.
///
/// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
fileprivate var canEncodeNewValue: Bool {
// Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
// At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
// If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
//
// This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path.
// Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here).
return self.storage.count == self.codingPath.count
}
// MARK: - Encoder Methods
public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
// If an existing keyed container was already requested, return that one.
let topContainer: NSMutableDictionary
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushKeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableDictionary else {
preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
let container = _PlistKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
return KeyedEncodingContainer(container)
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
// If an existing unkeyed container was already requested, return that one.
let topContainer: NSMutableArray
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushUnkeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableArray else {
preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
return _PlistUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
}
public func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
}
// MARK: - Encoding Storage and Containers
fileprivate struct _PlistEncodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the plist types (NSNumber, NSString, NSDate, NSArray, NSDictionary).
private(set) fileprivate var containers: [NSObject] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary {
let dictionary = NSMutableDictionary()
self.containers.append(dictionary)
return dictionary
}
fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray {
let array = NSMutableArray()
self.containers.append(array)
return array
}
fileprivate mutating func push(container: __owned NSObject) {
self.containers.append(container)
}
fileprivate mutating func popContainer() -> NSObject {
precondition(!self.containers.isEmpty, "Empty container stack.")
return self.containers.popLast()!
}
}
// MARK: - Encoding Containers
fileprivate struct _PlistKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: __PlistEncoder
/// A reference to the container we're writing to.
private let container: NSMutableDictionary
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: __PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - KeyedEncodingContainerProtocol Methods
public mutating func encodeNil(forKey key: Key) throws { self.container[key.stringValue] = _plistNullNSString }
public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: String, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Float, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Double, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[key.stringValue] = try self.encoder.box(value)
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
let dictionary = NSMutableDictionary()
self.container[key.stringValue] = dictionary
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
let container = _PlistKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
let array = NSMutableArray()
self.container[key.stringValue] = array
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
return _PlistUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return __PlistReferencingEncoder(referencing: self.encoder, at: _PlistKey.super, wrapping: self.container)
}
public mutating func superEncoder(forKey key: Key) -> Encoder {
return __PlistReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container)
}
}
fileprivate struct _PlistUnkeyedEncodingContainer : UnkeyedEncodingContainer {
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: __PlistEncoder
/// A reference to the container we're writing to.
private let container: NSMutableArray
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
/// The number of elements encoded into the container.
public var count: Int {
return self.container.count
}
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: __PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - UnkeyedEncodingContainer Methods
public mutating func encodeNil() throws { self.container.add(_plistNullNSString) }
public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Float) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Double) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode<T : Encodable>(_ value: T) throws {
self.encoder.codingPath.append(_PlistKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
self.codingPath.append(_PlistKey(index: self.count))
defer { self.codingPath.removeLast() }
let dictionary = NSMutableDictionary()
self.container.add(dictionary)
let container = _PlistKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
self.codingPath.append(_PlistKey(index: self.count))
defer { self.codingPath.removeLast() }
let array = NSMutableArray()
self.container.add(array)
return _PlistUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return __PlistReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
}
}
extension __PlistEncoder : SingleValueEncodingContainer {
// MARK: - SingleValueEncodingContainer Methods
private func assertCanEncodeNewValue() {
precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
}
public func encodeNil() throws {
assertCanEncodeNewValue()
self.storage.push(container: _plistNullNSString)
}
public func encode(_ value: Bool) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: String) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Float) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Double) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode<T : Encodable>(_ value: T) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
}
// MARK: - Concrete Value Representations
extension __PlistEncoder {
/// Returns the given value boxed in a container appropriate for pushing onto the container stack.
fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Float) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Double) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) }
fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject {
return try self.box_(value) ?? NSDictionary()
}
fileprivate func box_<T : Encodable>(_ value: T) throws -> NSObject? {
if T.self == Date.self || T.self == NSDate.self {
// PropertyListSerialization handles NSDate directly.
return (value as! NSDate)
} else if T.self == Data.self || T.self == NSData.self {
// PropertyListSerialization handles NSData directly.
return (value as! NSData)
}
// The value should request a container from the __PlistEncoder.
let depth = self.storage.count
do {
try value.encode(to: self)
} catch let error {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
// The top container should be a new container.
guard self.storage.count > depth else {
return nil
}
return self.storage.popContainer()
}
}
// MARK: - __PlistReferencingEncoder
/// __PlistReferencingEncoder is a special subclass of __PlistEncoder which has its own storage, but references the contents of a different encoder.
/// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
// NOTE: older overlays called this class _PlistReferencingEncoder.
// The two must coexist without a conflicting ObjC class name, so it
// was renamed. The old name must not be used in the new runtime.
fileprivate class __PlistReferencingEncoder : __PlistEncoder {
// MARK: Reference types.
/// The type of container we're referencing.
private enum Reference {
/// Referencing a specific index in an array container.
case array(NSMutableArray, Int)
/// Referencing a specific key in a dictionary container.
case dictionary(NSMutableDictionary, String)
}
// MARK: - Properties
/// The encoder we're referencing.
private let encoder: __PlistEncoder
/// The container reference itself.
private let reference: Reference
// MARK: - Initialization
/// Initializes `self` by referencing the given array container in the given encoder.
fileprivate init(referencing encoder: __PlistEncoder, at index: Int, wrapping array: NSMutableArray) {
self.encoder = encoder
self.reference = .array(array, index)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(_PlistKey(index: index))
}
/// Initializes `self` by referencing the given dictionary container in the given encoder.
fileprivate init(referencing encoder: __PlistEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) {
self.encoder = encoder
self.reference = .dictionary(dictionary, key.stringValue)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(key)
}
// MARK: - Coding Path Operations
fileprivate override var canEncodeNewValue: Bool {
// With a regular encoder, the storage and coding path grow together.
// A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
// We have to take this into account.
return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
}
// MARK: - Deinitialization
// Finalizes `self` by writing the contents of our storage to the referenced encoder's storage.
deinit {
let value: Any
switch self.storage.count {
case 0: value = NSDictionary()
case 1: value = self.storage.popContainer()
default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
}
switch self.reference {
case .array(let array, let index):
array.insert(value, at: index)
case .dictionary(let dictionary, let key):
dictionary[NSString(string: key)] = value
}
}
}
//===----------------------------------------------------------------------===//
// Plist Decoder
//===----------------------------------------------------------------------===//
/// `PropertyListDecoder` facilitates the decoding of property list values into semantic `Decodable` types.
// NOTE: older overlays had Foundation.PropertyListDecoder as the ObjC
// name. The two must coexist, so it was renamed. The old name must not
// be used in the new runtime. _TtC10Foundation20_PropertyListDecoder
// is the mangled name for Foundation._PropertyListDecoder.
@_objcRuntimeName(_TtC10Foundation20_PropertyListDecoder)
open class PropertyListDecoder {
// MARK: Options
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the decoding hierarchy.
fileprivate struct _Options {
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level decoder.
fileprivate var options: _Options {
return _Options(userInfo: userInfo)
}
// MARK: - Constructing a Property List Decoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given property list representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
var format: PropertyListSerialization.PropertyListFormat = .binary
return try decode(type, from: data, format: &format)
}
/// Decodes a top-level value of the given type from the given property list representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - parameter format: The parsed property list format.
/// - returns: A value of the requested type along with the detected format of the property list.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data, format: inout PropertyListSerialization.PropertyListFormat) throws -> T {
let topLevel: Any
do {
topLevel = try PropertyListSerialization.propertyList(from: data, options: [], format: &format)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not a valid property list.", underlyingError: error))
}
return try decode(type, fromTopLevel: topLevel)
}
/// Decodes a top-level value of the given type from the given property list container (top-level array or dictionary).
///
/// - parameter type: The type of the value to decode.
/// - parameter container: The top-level plist container.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list.
/// - throws: An error if any value throws an error during decoding.
internal func decode<T : Decodable>(_ type: T.Type, fromTopLevel container: Any) throws -> T {
let decoder = __PlistDecoder(referencing: container, options: self.options)
guard let value = try decoder.unbox(container, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}
return value
}
}
// MARK: - __PlistDecoder
// NOTE: older overlays called this class _PlistDecoder. The two must
// coexist without a conflicting ObjC class name, so it was renamed.
// The old name must not be used in the new runtime.
fileprivate class __PlistDecoder : Decoder {
// MARK: Properties
/// The decoder's storage.
fileprivate var storage: _PlistDecodingStorage
/// Options set on the top-level decoder.
fileprivate let options: PropertyListDecoder._Options
/// The path to the current point in encoding.
fileprivate(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: PropertyListDecoder._Options) {
self.storage = _PlistDecodingStorage()
self.storage.push(container: container)
self.codingPath = codingPath
self.options = options
}
// MARK: - Decoder Methods
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer)
}
let container = _PlistKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer)
}
return _PlistUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
// MARK: - Decoding Storage
fileprivate struct _PlistDecodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the plist types (NSNumber, Date, String, Array, [String : Any]).
private(set) fileprivate var containers: [Any] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate var topContainer: Any {
precondition(!self.containers.isEmpty, "Empty container stack.")
return self.containers.last!
}
fileprivate mutating func push(container: __owned Any) {
self.containers.append(container)
}
fileprivate mutating func popContainer() {
precondition(!self.containers.isEmpty, "Empty container stack.")
self.containers.removeLast()
}
}
// MARK: Decoding Containers
fileprivate struct _PlistKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: __PlistDecoder
/// A reference to the container we're reading from.
private let container: [String : Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: __PlistDecoder, wrapping container: [String : Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
}
// MARK: - KeyedDecodingContainerProtocol Methods
public var allKeys: [Key] {
return self.container.keys.compactMap { Key(stringValue: $0) }
}
public func contains(_ key: Key) -> Bool {
return self.container[key.stringValue] != nil
}
public func decodeNil(forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let value = entry as? String else {
return false
}
return value == _plistNull
}
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- no value found for key \"\(key.stringValue)\""))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
let container = _PlistKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested unkeyed container -- no value found for key \"\(key.stringValue)\""))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
return _PlistUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
private func _superDecoder(forKey key: __owned CodingKey) throws -> Decoder {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
let value: Any = self.container[key.stringValue] ?? NSNull()
return __PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
public func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: _PlistKey.super)
}
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
}
fileprivate struct _PlistUnkeyedDecodingContainer : UnkeyedDecodingContainer {
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: __PlistDecoder
/// A reference to the container we're reading from.
private let container: [Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
/// The index of the element we're about to decode.
private(set) public var currentIndex: Int
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: __PlistDecoder, wrapping container: [Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
self.currentIndex = 0
}
// MARK: - UnkeyedDecodingContainer Methods
public var count: Int? {
return self.container.count
}
public var isAtEnd: Bool {
return self.currentIndex >= self.count!
}
public mutating func decodeNil() throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
if self.container[self.currentIndex] is NSNull {
self.currentIndex += 1
return true
} else {
return false
}
}
public mutating func decode(_ type: Bool.Type) throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int.Type) throws -> Int {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int8.Type) throws -> Int8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int16.Type) throws -> Int16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int32.Type) throws -> Int32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int64.Type) throws -> Int64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt.Type) throws -> UInt {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Float.Type) throws -> Float {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Double.Type) throws -> Double {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: String.Type) throws -> String {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
self.currentIndex += 1
let container = _PlistKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested unkeyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
self.currentIndex += 1
return _PlistUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
public mutating func superDecoder() throws -> Decoder {
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get superDecoder() -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
self.currentIndex += 1
return __PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
}
extension __PlistDecoder : SingleValueDecodingContainer {
// MARK: SingleValueDecodingContainer Methods
private func expectNonNull<T>(_ type: T.Type) throws {
guard !self.decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
public func decodeNil() -> Bool {
guard let string = self.storage.topContainer as? String else {
return false
}
return string == _plistNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
try expectNonNull(Bool.self)
return try self.unbox(self.storage.topContainer, as: Bool.self)!
}
public func decode(_ type: Int.Type) throws -> Int {
try expectNonNull(Int.self)
return try self.unbox(self.storage.topContainer, as: Int.self)!
}
public func decode(_ type: Int8.Type) throws -> Int8 {
try expectNonNull(Int8.self)
return try self.unbox(self.storage.topContainer, as: Int8.self)!
}
public func decode(_ type: Int16.Type) throws -> Int16 {
try expectNonNull(Int16.self)
return try self.unbox(self.storage.topContainer, as: Int16.self)!
}
public func decode(_ type: Int32.Type) throws -> Int32 {
try expectNonNull(Int32.self)
return try self.unbox(self.storage.topContainer, as: Int32.self)!
}
public func decode(_ type: Int64.Type) throws -> Int64 {
try expectNonNull(Int64.self)
return try self.unbox(self.storage.topContainer, as: Int64.self)!
}
public func decode(_ type: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try self.unbox(self.storage.topContainer, as: UInt.self)!
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try self.unbox(self.storage.topContainer, as: UInt8.self)!
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try self.unbox(self.storage.topContainer, as: UInt16.self)!
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try self.unbox(self.storage.topContainer, as: UInt32.self)!
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try self.unbox(self.storage.topContainer, as: UInt64.self)!
}
public func decode(_ type: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try self.unbox(self.storage.topContainer, as: Float.self)!
}
public func decode(_ type: Double.Type) throws -> Double {
try expectNonNull(Double.self)
return try self.unbox(self.storage.topContainer, as: Double.self)!
}
public func decode(_ type: String.Type) throws -> String {
try expectNonNull(String.self)
return try self.unbox(self.storage.topContainer, as: String.self)!
}
public func decode<T : Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(type)
return try self.unbox(self.storage.topContainer, as: type)!
}
}
// MARK: - Concrete Value Representations
extension __PlistDecoder {
/// Returns the given value unboxed from a container.
fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
if let string = value as? String, string == _plistNull { return nil }
if let number = value as? NSNumber {
// TODO: Add a flag to coerce non-boolean numbers into Bools?
if number === NSNumber(booleanLiteral: true) {
return true
} else if number === NSNumber(booleanLiteral: false) {
return false
}
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let bool = value as? Bool {
return bool
*/
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int = number.intValue
guard NSNumber(value: int) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int
}
fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int8 = number.int8Value
guard NSNumber(value: int8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int8
}
fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int16 = number.int16Value
guard NSNumber(value: int16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int16
}
fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int32 = number.int32Value
guard NSNumber(value: int32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int32
}
fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int64 = number.int64Value
guard NSNumber(value: int64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int64
}
fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint = number.uintValue
guard NSNumber(value: uint) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint
}
fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint8 = number.uint8Value
guard NSNumber(value: uint8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint8
}
fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint16 = number.uint16Value
guard NSNumber(value: uint16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint16
}
fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint32 = number.uint32Value
guard NSNumber(value: uint32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint32
}
fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint64 = number.uint64Value
guard NSNumber(value: uint64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint64
}
fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let float = number.floatValue
guard NSNumber(value: float) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return float
}
fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let double = number.doubleValue
guard NSNumber(value: double) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return double
}
fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return string == _plistNull ? nil : string
}
fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
if let string = value as? String, string == _plistNull { return nil }
guard let date = value as? Date else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return date
}
fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
if let string = value as? String, string == _plistNull { return nil }
guard let data = value as? Data else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return data
}
fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
if type == Date.self || type == NSDate.self {
return try self.unbox(value, as: Date.self) as? T
} else if type == Data.self || type == NSData.self {
return try self.unbox(value, as: Data.self) as? T
} else {
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try type.init(from: self)
}
}
}
//===----------------------------------------------------------------------===//
// Shared Plist Null Representation
//===----------------------------------------------------------------------===//
// Since plists do not support null values by default, we will encode them as "$null".
fileprivate let _plistNull = "$null"
fileprivate let _plistNullNSString = NSString(string: _plistNull)
//===----------------------------------------------------------------------===//
// Shared Key Types
//===----------------------------------------------------------------------===//
fileprivate struct _PlistKey : CodingKey {
public var stringValue: String
public var intValue: Int?
public init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
public init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
fileprivate init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
fileprivate static let `super` = _PlistKey(stringValue: "super")!
}
| apache-2.0 | 0c229cd94b12cdf5aad5e6d17cf866dd | 44.185488 | 258 | 0.661914 | 4.850375 | false | false | false | false |
modocache/swift | stdlib/public/core/Unicode.swift | 2 | 44807 | //===----------------------------------------------------------------------===//
//
// 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
///
/// - SeeAlso: `UnicodeCodec.decode(next:)`
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(UnicodeScalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
public static func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `UnicodeScalar` type to work with
/// decoded Unicode scalar values.
///
/// - SeeAlso: `UTF8`, `UTF16`, `UTF32`, `UnicodeScalar`
public protocol UnicodeCodec {
/// A type that can hold code unit values for this encoding.
associatedtype CodeUnit
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
///
/// - Complexity: O(*n*)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
public struct UTF8 : UnicodeCodec {
// See Unicode 8.0.0, Ch 3.9, UTF-8.
// http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt8
/// Creates an instance of the UTF-8 codec.
public init() {}
/// Lookahead buffer used for UTF-8 decoding. New bytes are inserted at MSB,
/// and bytes are read at LSB. Note that we need to use a buffer, because
/// in case of invalid subsequences we sometimes don't know whether we should
/// consume a certain byte before looking at it.
internal var _decodeBuffer: UInt32 = 0
/// The number of bits in `_decodeBuffer` that are current filled.
internal var _bitsInBuffer: UInt8 = 0
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
// Bufferless ASCII fastpath.
if _fastPath(_bitsInBuffer == 0) {
guard let codeUnit = input.next() else { return .emptyInput }
// ASCII, return immediately.
if codeUnit & 0x80 == 0 {
return .scalarValue(UnicodeScalar(_unchecked: UInt32(codeUnit)))
}
// Non-ASCII, proceed to buffering mode.
_decodeBuffer = UInt32(codeUnit)
_bitsInBuffer = 8
} else if (_decodeBuffer & 0x80 == 0) {
// ASCII in buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
let codeUnit = _decodeBuffer & 0xff
_decodeBuffer >>= 8
_bitsInBuffer = _bitsInBuffer &- 8
return .scalarValue(UnicodeScalar(_unchecked: codeUnit))
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
_sanityCheck(_bitsInBuffer < 32)
repeat {
if let codeUnit = input.next() {
// We know _bitsInBuffer < 32 so we use `& 0x1f` (31) to make the
// compiler omit a bounds check branch for the bitshift.
_decodeBuffer |= (UInt32(codeUnit) << UInt32(_bitsInBuffer & 0x1f))
_bitsInBuffer = _bitsInBuffer &+ 8
} else {
if _bitsInBuffer == 0 { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _bitsInBuffer < 32
// Decode one unicode scalar.
// Note our empty bytes are always 0x00, which is required for this call.
let (result, length) = UTF8._decodeOne(_decodeBuffer)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let bitsConsumed = 8 &* length
_sanityCheck(1...4 ~= length && bitsConsumed <= _bitsInBuffer)
// Swift doesn't allow shifts greater than or equal to the type width.
// _decodeBuffer >>= UInt32(bitsConsumed) // >>= 32 crashes.
// Mask with 0x3f (63) to let the compiler omit the '>= 64' bounds check.
_decodeBuffer = UInt32(truncatingBitPattern:
UInt64(_decodeBuffer) >> (UInt64(bitsConsumed) & 0x3f))
_bitsInBuffer = _bitsInBuffer &- bitsConsumed
guard _fastPath(result != nil) else { return .error }
return .scalarValue(UnicodeScalar(_unchecked: result!))
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ … … … CU0 ].
let value = buffer & 0xff
return (value, 1)
}
// Determine sequence length using high 5 bits of 1st byte. We use a
// look-up table to branch less. 1-byte sequences are handled above.
//
// case | pattern | description
// ----------------------------
// 00 | 110xx | 2-byte sequence
// 01 | 1110x | 3-byte sequence
// 10 | 11110 | 4-byte sequence
// 11 | other | invalid
//
// 11xxx 10xxx 01xxx 00xxx
let lut0: UInt32 = 0b1011_0000__1111_1111__1111_1111__1111_1111
let lut1: UInt32 = 0b1100_0000__1111_1111__1111_1111__1111_1111
let index = (buffer >> 3) & 0x1f
let bit0 = (lut0 >> index) & 1
let bit1 = (lut1 >> index) & 1
switch (bit1, bit0) {
case (0, 0): // 2-byte sequence, buffer: [ … … CU1 CU0 ].
// Require 10xx xxxx 110x xxxx.
if _slowPath(buffer & 0xc0e0 != 0x80c0) { return (nil, 1) }
// Disallow xxxx xxxx xxx0 000x (<= 7 bits case).
if _slowPath(buffer & 0x001e == 0x0000) { return (nil, 1) }
// Extract data bits.
let value = (buffer & 0x3f00) >> 8
| (buffer & 0x001f) << 6
return (value, 2)
case (0, 1): // 3-byte sequence, buffer: [ … CU2 CU1 CU0 ].
// Disallow xxxx xxxx xx0x xxxx xxxx 0000 (<= 11 bits case).
if _slowPath(buffer & 0x00200f == 0x000000) { return (nil, 1) }
// Disallow xxxx xxxx xx1x xxxx xxxx 1101 (surrogate code points).
if _slowPath(buffer & 0x00200f == 0x00200d) { return (nil, 1) }
// Require 10xx xxxx 10xx xxxx 1110 xxxx.
if _slowPath(buffer & 0xc0c0f0 != 0x8080e0) {
if buffer & 0x00c000 != 0x008000 { return (nil, 1) }
return (nil, 2) // All checks on CU0 & CU1 passed.
}
// Extract data bits.
let value = (buffer & 0x3f0000) >> 16
| (buffer & 0x003f00) >> 2
| (buffer & 0x00000f) << 12
return (value, 3)
case (1, 0): // 4-byte sequence, buffer: [ CU3 CU2 CU1 CU0 ].
// Disallow xxxx xxxx xxxx xxxx xx00 xxxx xxxx x000 (<= 16 bits case).
if _slowPath(buffer & 0x00003007 == 0x00000000) { return (nil, 1) }
// If xxxx xxxx xxxx xxxx xxxx xxxx xxxx x1xx.
if buffer & 0x00000004 == 0x00000004 {
// Require xxxx xxxx xxxx xxxx xx00 xxxx xxxx xx00 (<= 0x10FFFF).
if _slowPath(buffer & 0x00003003 != 0x00000000) { return (nil, 1) }
}
// Require 10xx xxxx 10xx xxxx 10xx xxxx 1111 0xxx.
if _slowPath(buffer & 0xc0c0c0f8 != 0x808080f0) {
if buffer & 0x0000c000 != 0x00008000 { return (nil, 1) }
// All other checks on CU0, CU1 & CU2 passed.
if buffer & 0x00c00000 != 0x00800000 { return (nil, 2) }
return (nil, 3)
}
// Extract data bits.
// FIXME(integers): remove extra type casts
let value = (buffer & 0x3f000000) >> (24 as UInt32)
| (buffer & 0x003f0000) >> (10 as UInt32)
| (buffer & 0x00003f00) << (4 as UInt32)
| (buffer & 0x00000007) << (18 as UInt32)
return (value, 4)
default: // Invalid sequence (CU0 invalid).
return (nil, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var c = UInt32(input)
var buf3 = UInt8(c & 0xFF)
if c >= UInt32(1<<7) {
c >>= 6
buf3 = (buf3 & 0x3F) | 0x80 // 10xxxxxx
var buf2 = UInt8(c & 0xFF)
if c < UInt32(1<<5) {
buf2 |= 0xC0 // 110xxxxx
}
else {
c >>= 6
buf2 = (buf2 & 0x3F) | 0x80 // 10xxxxxx
var buf1 = UInt8(c & 0xFF)
if c < UInt32(1<<4) {
buf1 |= 0xE0 // 1110xxxx
}
else {
c >>= 6
buf1 = (buf1 & 0x3F) | 0x80 // 10xxxxxx
processCodeUnit(UInt8(c | 0xF0)) // 11110xxx
}
processCodeUnit(buf1)
}
processCodeUnit(buf2)
}
processCodeUnit(buf3)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codePoint in eAcute.utf8 {
/// print(codePoint, UTF8.isContinuation(codePoint))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
// Relying on a permissive memory model in C.
let cstr = unsafeBitCast(input, to: UnsafePointer<CChar>.self)
return Int(_swift_stdlib_strlen(cstr))
}
// Support parsing C strings as-if they are UTF8 strings.
public static func _nullCodeUnitOffset(in input: UnsafePointer<CChar>) -> Int {
return Int(_swift_stdlib_strlen(input))
}
}
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
public struct UTF16 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt16
/// Creates an instance of the UTF-16 codec.
public init() {}
/// A lookahead buffer for one UTF-16 code unit.
internal var _decodeLookahead: UInt16?
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
// Note: maximal subpart of ill-formed sequence for UTF-16 can only have
// length 1. Length 0 does not make sense. Neither does length 2 -- in
// that case the sequence is valid.
let unit0: UInt16
if _fastPath(_decodeLookahead == nil) {
guard let next = input.next() else { return .emptyInput }
unit0 = next
} else { // Consume lookahead first.
unit0 = _decodeLookahead!
_decodeLookahead = nil
}
// A well-formed pair of surrogates looks like this:
// high-surrogate low-surrogate
// [1101 10xx xxxx xxxx] [1101 11xx xxxx xxxx]
// Common case first, non-surrogate -- just a sequence of 1 code unit.
if _fastPath((unit0 >> 11) != 0b1101_1) {
return .scalarValue(UnicodeScalar(_unchecked: UInt32(unit0)))
}
// Ensure `unit0` is a high-surrogate.
guard _fastPath((unit0 >> 10) == 0b1101_10) else { return .error }
// We already have a high-surrogate, so there should be a next code unit.
guard let unit1 = input.next() else { return .error }
// `unit0` is a high-surrogate, so `unit1` should be a low-surrogate.
guard _fastPath((unit1 >> 10) == 0b1101_11) else {
// Invalid sequence, discard `unit0` and store `unit1` for the next call.
_decodeLookahead = unit1
return .error
}
// We have a well-formed surrogate pair, decode it.
let result = 0x10000 + ((UInt32(unit0 & 0x03ff) << 10) | UInt32(unit1 & 0x03ff))
return .scalarValue(UnicodeScalar(_unchecked: result))
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_versioned
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", into: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
) {
let scalarValue: UInt32 = UInt32(input)
if scalarValue <= UInt32(UInt16.max) {
processCodeUnit(UInt16(scalarValue))
}
else {
let lead_offset = UInt32(0xd800) - UInt32(0x10000 >> 10)
processCodeUnit(UInt16(lead_offset + (scalarValue >> 10)))
processCodeUnit(UInt16(0xdc00 + (scalarValue & 0x3ff)))
}
}
}
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
public struct UTF32 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt32
/// Creates an instance of the UTF-32 codec.
public init() {}
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `UnicodeScalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard let x = input.next() else { return .emptyInput }
// Check code unit is valid: not surrogate-reserved and within range.
guard _fastPath((x >> 11) != 0b1101_1 && x <= 0x10ffff)
else { return .error }
// x is a valid scalar.
return .scalarValue(UnicodeScalar(_unchecked: x))
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", into: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, into: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
public func transcode<Input, InputEncoding, OutputEncoding>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
into processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var inputDecoder = inputEncoding.init()
var hadError = false
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
OutputEncoding.encode(us, into: processCodeUnit)
case .emptyInput:
break loop
case .error:
hadError = true
if stopOnError {
break loop
}
OutputEncoding.encode("\u{fffd}", into: processCodeUnit)
}
}
return hadError
}
/// Transcode UTF-16 to UTF-8, replacing ill-formed sequences with U+FFFD.
///
/// Returns the index of the first unhandled code unit and the UTF-8 data
/// that was encoded.
internal func _transcodeSomeUTF16AsUTF8<Input>(
_ input: Input, _ startIndex: Input.Index
) -> (Input.Index, _StringCore._UTF8Chunk)
where
Input : Collection,
Input.Iterator.Element == UInt16 {
typealias _UTF8Chunk = _StringCore._UTF8Chunk
let endIndex = input.endIndex
let utf8Max = MemoryLayout<_UTF8Chunk>.size
var result: _UTF8Chunk = 0
var utf8Count = 0
var nextIndex = startIndex
while nextIndex != input.endIndex && utf8Count != utf8Max {
let u = UInt(input[nextIndex])
let shift = _UTF8Chunk(utf8Count * 8)
var utf16Length: Input.IndexDistance = 1
if _fastPath(u <= 0x7f) {
result |= _UTF8Chunk(u) << shift
utf8Count += 1
} else {
var scalarUtf8Length: Int
var r: UInt
if _fastPath((u >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit, decoding is trivial.
if u < 0x800 {
r = 0b10__00_0000__110__0_0000
r |= u >> 6
r |= (u & 0b11_1111) << 8
scalarUtf8Length = 2
}
else {
r = 0b10__00_0000__10__00_0000__1110__0000
r |= u >> 12
r |= ((u >> 6) & 0b11_1111) << 8
r |= (u & 0b11_1111) << 16
scalarUtf8Length = 3
}
} else {
let unit0 = u
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
// Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else if _slowPath(input.index(nextIndex, offsetBy: 1) == endIndex) {
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence. Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else {
let unit1 = UInt(input[input.index(nextIndex, offsetBy: 1)])
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate
// pair.
let v = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
r = 0b10__00_0000__10__00_0000__10__00_0000__1111_0__000
r |= v >> 18
r |= ((v >> 12) & 0b11_1111) << 8
r |= ((v >> 6) & 0b11_1111) << 16
r |= (v & 0b11_1111) << 24
scalarUtf8Length = 4
utf16Length = 2
} else {
// Otherwise, we have an ill-formed sequence. Replace it with
// U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
}
}
}
// Don't overrun the buffer
if utf8Count + scalarUtf8Length > utf8Max {
break
}
result |= numericCast(r) << shift
utf8Count += scalarUtf8Length
}
nextIndex = input.index(nextIndex, offsetBy: utf16Length)
}
// FIXME: Annoying check, courtesy of <rdar://problem/16740169>
if utf8Count < MemoryLayout.size(ofValue: result) {
result |= ~0 << numericCast(utf8Count * 8)
}
return (nextIndex, result)
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(x)
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: UnicodeScalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: UnicodeScalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
public static func width(_ x: UnicodeScalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.trailSurrogate(_:)`
public static func leadSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit((x.value - 0x1_0000) >> (10 as UInt32)) + 0xD800
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func trailSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit(
(x.value - 0x1_0000) & (((1 as UInt32) << 10) - 1)
) + 0xDC00
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return 0xD800...0xDBFF ~= x
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return 0xDC00...0xDFFF ~= x
}
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if MemoryLayout<T>.stride == MemoryLayout<U>.stride {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(MemoryLayout<U>.stride))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
public static func transcodedLength<Input, Encoding>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where
Input : IteratorProtocol,
Encoding : UnicodeCodec,
Encoding.CodeUnit == Input.Element {
var input = input
var count = 0
var isAscii = true
var inputDecoder = Encoding()
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
if us.value > 0x7f {
isAscii = false
}
count += width(us)
case .emptyInput:
break loop
case .error:
if !repairingIllFormedSequences {
return nil
}
isAscii = false
count += width(UnicodeScalar(0xfffd)!)
}
}
return (count, isAscii)
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension UnicodeScalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec where CodeUnit : UnsignedInteger {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
extension UnicodeCodec {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
fatalError("_nullCodeUnitOffset(in:) implementation should be provided")
}
}
@available(*, unavailable, renamed: "UnicodeCodec")
public typealias UnicodeCodecType = UnicodeCodec
extension UnicodeCodec {
@available(*, unavailable, renamed: "encode(_:into:)")
public static func encode(
_ input: UnicodeScalar,
output put: (CodeUnit) -> Void
) {
Builtin.unreachable()
}
}
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
extension UTF16 {
@available(*, unavailable, message: "use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'")
public static func measure<Encoding, Input>(
_: Encoding.Type, input: Input, repairIllFormedSequences: Bool
) -> (Int, Bool)?
where
Encoding : UnicodeCodec,
Input : IteratorProtocol,
Encoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
}
/// A namespace for Unicode utilities.
internal enum _Unicode {}
| apache-2.0 | 914cc1ac4a864e5be31ad030f5a3fef5 | 36.839255 | 106 | 0.625632 | 3.86335 | false | false | false | false |
Jnosh/swift | test/DebugInfo/ImportClangSubmodule.swift | 6 | 2138 | // RUN: %target-swift-frontend -emit-ir %s -g -I %S/Inputs \
// RUN: -Xcc -DFOO="foo" -Xcc -UBAR -o - | %FileCheck %s
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Bar",
// CHECK-SAME: scope: ![[SUBMODULE:[0-9]+]]
// CHECK: ![[SUBMODULE]] = !DIModule(scope: ![[CLANGMODULE:[0-9]+]],
// CHECK-SAME: name: "SubModule",
// CHECK: ![[CLANGMODULE]] = !DIModule(scope: null, name: "ClangModule",
// CHECK-SAME: configMacros:
// CHECK-SAME: {{..}}-DFOO=foo{{..}}
// CHECK-SAME: {{..}}-UBAR{{..}}
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "OtherBar",
// CHECK-SAME: scope: ![[OTHERSUBMODULE:[0-9]+]]
// CHECK: ![[OTHERSUBMODULE]] = !DIModule(scope: ![[OTHERCLANGMODULE:[0-9]+]],
// CHECK-SAME: name: "SubModule",
// CHECK: ![[OTHERCLANGMODULE]] = !DIModule(scope: null,
// CHECK-SAME: name: "OtherClangModule",
// CHECK-SAME: configMacros:
// CHECK-SAME: {{..}}-DFOO=foo{{..}}
// CHECK-SAME: {{..}}-UBAR{{..}}
// CHECK: !DIImportedEntity({{.*}}, entity: ![[SUBMODULE]], line: [[@LINE+1]])
import ClangModule.SubModule
// CHECK: !DIImportedEntity({{.*}}, entity: ![[OTHERSUBMODULE]],
// CHECK-SAME: line: [[@LINE+1]])
import OtherClangModule.SubModule
// The Swift compiler uses an ugly hack that auto-imports a
// submodule's top-level-module, even if we didn't ask for it.
// CHECK-NOT: !DIImportedEntity({{.*}}, entity: ![[SUBMODULE]]
// CHECK-NOT: !DIImportedEntity({{.*}}, entity: ![[OTHERSUBMODULE]]
// CHECK: !DIImportedEntity({{.*}}, entity: ![[CLANGMODULE]])
// CHECK-NOT: !DIImportedEntity({{.*}}, entity: ![[SUBMODULE]]
// CHECK-NOT: !DIImportedEntity({{.*}}, entity: ![[OTHERSUBMODULE]]
// CHECK: !DIImportedEntity({{.*}}, entity: ![[OTHERCLANGMODULE]])
// CHECK-NOT: !DIImportedEntity({{.*}}, entity: ![[SUBMODULE]]
// CHECK-NOT: !DIImportedEntity({{.*}}, entity: ![[OTHERSUBMODULE]]
let bar = Bar()
let baz = OtherBar()
| apache-2.0 | 99d25394171c237fa6f64f0f27d13eca | 48.72093 | 78 | 0.55145 | 3.563333 | false | false | false | false |
JerrySir/YCOA | YCOA/Main/DetailPage/Model/DetailPageTableViewControllerModel.swift | 1 | 892 | //
// DetailPageTableViewControllerModel.swift
// YCOA
//
// Created by Jerry on 2017/1/30.
// Copyright © 2017年 com.baochunsteel. All rights reserved.
//
import UIKit
class DetailPageTableViewControllerModel: NSObject {
/// ID
open var id_: String = ""
/// 类型
open var type: String = ""
/// 是否显示Base相关的内容
open var isShowBaseRelatedContent: Bool = false
/// 是否显示删除
open var isShowDeleteView: Bool = false
/// 是否显示操作(处理)
open var isShowHandleView: Bool = false
/// 是否显示回复
open var isShowReplyView: Bool = false
/// 显示的内容
open var contentList: [(key: String, value: String)] = []
/// 发送工作报告的下拉选项(只有任务回复才会有)
open var sendDropDownOptionsForTheWorkReport: [String] = []
}
| mit | e8ebf392c66e50d2e08147544ecc5c57 | 20.583333 | 63 | 0.624196 | 3.924242 | false | false | false | false |
zhiquan911/chance_btc_wallet | chance_btc_wallet/chance_btc_wallet/viewcontrollers/welcome/WelcomeCreateAccountViewController.swift | 1 | 5901 | //
// WelcomeCreateAccountViewController.swift
// Chance_wallet
//
// Created by Chance on 16/4/18.
// Copyright © 2016年 Chance. All rights reserved.
//
import UIKit
import RealmSwift
class WelcomeCreateAccountViewController: BaseViewController {
/// MARK: - 成员变量
@IBOutlet var buttonConfirm: UIButton!
@IBOutlet var labelTitle: UILabel!
@IBOutlet var labelTextNickname: CHLabelTextField!
@IBOutlet var labelTextPassword: CHLabelTextField!
@IBOutlet var labelTextConfirm: CHLabelTextField!
var phrase = "" //密语
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 控制器方法
extension WelcomeCreateAccountViewController {
/// 配置UI
func setupUI() {
self.navigationItem.title = "Wallet Account".localized()
self.labelTitle.text = "Create Account".localized()
self.labelTextNickname.title = "First Account Nickname".localized()
self.labelTextNickname.placeholder = "Give your account a nickname".localized()
self.labelTextNickname.textField?.keyboardType = .default
self.labelTextNickname.delegate = self
self.labelTextPassword.title = "Wallet Password".localized()
self.labelTextPassword.placeholder = "More complex the more secure".localized()
self.labelTextPassword.textField?.isSecureTextEntry = true
self.labelTextPassword.delegate = self
self.labelTextConfirm.title = "Validate Password".localized()
self.labelTextConfirm.placeholder = "Input the wallet password again".localized()
self.labelTextConfirm.textField?.isSecureTextEntry = true
self.labelTextConfirm.textField?.returnKeyType = .done
self.labelTextConfirm.delegate = self
self.buttonConfirm.setTitle("Create".localized(), for: [.normal])
}
//检测输入值是否合法
func checkValue() -> Bool {
if self.labelTextNickname.text.isEmpty {
SVProgressHUD.showInfo(withStatus: "Nickname is empty".localized())
return false
}
if self.labelTextPassword.text.isEmpty {
SVProgressHUD.showInfo(withStatus: "Password is empty".localized())
return false
}
if self.labelTextConfirm.text.isEmpty {
SVProgressHUD.showInfo(withStatus: "Confirm password is empty".localized())
return false
}
if self.labelTextConfirm.text != self.labelTextPassword.text {
SVProgressHUD.showInfo(withStatus: "Two Passwords is different".localized())
return false
}
return true
}
/**
点击确认按钮
- parameter sender:
*/
@IBAction func handleConfirmPress(_ sender: AnyObject?) {
if self.checkValue() {
let password = self.labelTextPassword.text.trim()
//创建钱包系统
CHWalletWrapper.create(phrase: self.phrase, password: password, complete: {
(success, mnemonic) in
if !success { //创建失败
SVProgressHUD.showError(withStatus: "Create wallet failed".localized())
return
}
//目前只有比特币钱包,创建默认的比特币钱包
let wallet = CHBTCWallet.createWallet(mnemonic: mnemonic!)
//创建默认HD账户
let nickName = self.labelTextNickname.text
guard let account = wallet.createHDAccount(by: nickName) else {
SVProgressHUD.showError(withStatus: "Create wallet account failed".localized())
return
}
//记录当前使用的比特币账户
CHBTCWallet.sharedInstance.selectedAccountIndex = account.index
self.gotoSuccessView()
})
}
}
func gotoSuccessView() {
guard let vc = StoryBoard.welcome.initView(type: WelcomeSuccessViewController.self) else {
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
/// 关闭键盘
///
/// - Parameter sender:
@IBAction func closeKeyboard(sender: AnyObject?) {
AppDelegate.sharedInstance().closeKeyBoard()
}
}
// MARK: - 实现输入框代理方法
extension WelcomeCreateAccountViewController: CHLabelTextFieldDelegate {
func textFieldShouldReturn(_ ltf: CHLabelTextField) -> Bool {
if ltf.textField === self.labelTextNickname.textField {
self.labelTextPassword.textField?.becomeFirstResponder()
} else if ltf.textField === self.labelTextPassword.textField {
self.labelTextConfirm.textField?.becomeFirstResponder()
} else if ltf.textField === self.labelTextConfirm.textField {
ltf.textField?.resignFirstResponder()
}
return true
}
func textField(_ ltf: CHLabelTextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxCharOfPassword = 50
if(ltf.textField === self.labelTextNickname.textField
|| ltf.textField === self.labelTextPassword.textField
|| ltf.textField === self.labelTextConfirm.textField) {
if (range.location>(maxCharOfPassword - 1)) {
return false
}
}
return true;
}
}
| mit | 241b1d83a84e8414196a08b2c233e581 | 31.134831 | 128 | 0.601399 | 5.345794 | false | false | false | false |
BiteCoda/icebreaker-app | IceBreaker-iOS/IceBreaker/Utilities/Constants.swift | 1 | 1825 | //
// Constants.swift
// IceBreaker
//
// Created by Jacob Chen on 2/21/15.
// Copyright (c) 2015 floridapoly.IceMakers. All rights reserved.
//
import Foundation
// MARK: NSNotifications
public let NOTIF_NONE_FOUND = "NOTIF_NO_BEACONS_FOUND"
public let NOTIF_ALL_BEACONS_FOUND = "NOTIF_ALL_BEACONS_FOUND"
public let NOTIF_BEACON_FOUND = "NOTIF_BEACON_FOUND"
public let NOTIF_ALL_BEACONS_KEY = "NOTIF_ALL_BEACONS_KEY"
public let NOTIF_BEACON_KEY = "NOTIF_BEACON_KEY"
public let NOTIF_BEACON_PAIRED = "NOTIF_BEACON_PAIRED"
public let NOTIF_CONTENT_KEY = "NOTIF_CONTENT_KEY"
public let NOTIF_REQUEST_FAILED = "NOTIF_REQUEST_FAILED"
public let NOTIF_ANSWER_RECEIVED = "NOTIF_ANSWER_RECEIVED"
public let NOTIF_ERROR_PAIR_EXISTS_SOURCE = "NOTIF_ERROR_PAIR_EXISTS_SOURCE"
public let NOTIF_ERROR_PAIR_EXISTS_TARGET = "NOTIF_ERROR_PAIR_EXISTS_TARGET"
public let NOTIF_ERROR_TARGET_NOT_SUBSCRIBED = "NOTIF_ERROR_TARGET_NOT_SUBSCRIBED"
public let NOTIF_ERROR_INVALID_REQUEST = "NOTIF_ERROR_INVALID_REQUEST"
// MARK: Http Requests
public let API_SUCCESS = "success"
public let API_OBJECT = "object"
public let API_ERRORS = "errors"
public let API_QUESTION = "quote"
public let API_AUTHOR = "author"
public let API_CATEGORY = "category"
// MARK: Apple Push Notifications
public let APS_KEY = "aps"
public let APS_ALERT = "alert"
// MARK: Error codes
public let ERROR_KEY_LOCALIZED = "NSLocalizedDescription"
public let ERROR_PAIR_EXISTS_SOURCE = "ERROR_PAIR_EXISTS_SOURCE"
public let ERROR_PAIR_EXISTS_TARGET = "ERROR_PAIR_EXISTS_TARGET"
public let ERROR_TARGET_NOT_SUBSCRIBED = "ERROR_TARGET_NOT_SUBSCRIBED"
public let ERROR_INVALID_REQUEST = "ERROR_INVALID_REQUEST"
public let ERROR_KEY = "ERROR"
public let ANSWER_KEY = "ANSWER"
// MARK: Storyboard IDs
public let AUTHENTICATION_CONTROLLER = "AuthenticationViewController"
| gpl-3.0 | 33a6b02d7e1ad5f8112f8f7e2d1dc1ad | 36.244898 | 82 | 0.763836 | 3.067227 | false | false | false | false |
MitchellPhillips22/TIY-Assignments | Day 14/yelqApp/Menu.swift | 1 | 774 | //
// Menu.swift
// yelqApp
//
// Created by Mitchell Phillips on 2/18/16.
// Copyright © 2016 Mitchell Phillips. All rights reserved.
//
import Foundation
class Menu {
var menuName: String = ""
var dishes = [Dishes]()
init(dict: JSONDictionary){
if let menuName = dict["menuName"] as? String {
self.menuName = menuName
}
if let results = dict["dishes"] as? JSONArray {
for result in results {
let d = Dishes(dict: result)
self.dishes.append(d)
}
}
}
}
//if let results = dict["menu"] as? JSONArray {
// for result in results {
// let m = Menu(dict: result)
// self.menuArray.append(m)
// print("menuAppended")
| cc0-1.0 | 82c384fb735ac7b86f8008cae12dc812 | 21.735294 | 60 | 0.54075 | 3.789216 | false | false | false | false |
stripe/stripe-ios | StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/OcrDD.swift | 1 | 546 | //
// OcrDD.swift
// CardScan
//
// Created by xaen on 4/14/20.
//
import CoreGraphics
import Foundation
import UIKit
class OcrDD {
var lastDetectedBoxes: [CGRect] = []
var ssdOcr = SSDOcrDetect()
init() {}
static func configure() {
let ssdOcr = SSDOcrDetect()
ssdOcr.warmUp()
}
func perform(croppedCardImage: CGImage) -> String? {
let number = ssdOcr.predict(image: UIImage(cgImage: croppedCardImage))
self.lastDetectedBoxes = ssdOcr.lastDetectedBoxes
return number
}
}
| mit | 23437239a6bde2afb1e588bed61fedf6 | 19.222222 | 78 | 0.639194 | 3.522581 | false | false | false | false |
mihaicris/digi-cloud | Digi Cloud/Managers/AppSettings.swift | 1 | 11903 | //
// AppSettings.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 02/11/16.
// Copyright © 2016 Mihai Cristescu. All rights reserved.
//
import UIKit
class AppSettings {
// MARK: - Properties
static var tableViewRowHeight: CGFloat = 50
static var textFieldRowHeight: CGFloat = 44
static var hasRunBefore: Bool {
get {
return UserDefaults.standard.bool(forKey: UserDefaults.UserDefaultsKeys.hasRunBefore.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.hasRunBefore.rawValue)
UserDefaults.standard.synchronize()
}
}
static var shouldReplayIntro: Bool {
get {
return UserDefaults.standard.bool(forKey: UserDefaults.UserDefaultsKeys.shouldReplayIntro.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.shouldReplayIntro.rawValue)
UserDefaults.standard.synchronize()
}
}
static var loggedUserID: String? {
get {
return UserDefaults.standard.string(forKey: UserDefaults.UserDefaultsKeys.userLogged.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.userLogged.rawValue)
UserDefaults.standard.synchronize()
}
}
static var userLogged: User? {
if let userID = loggedUserID {
if let user = getPersistedUserInfo(userID: userID) {
return user
}
}
return nil
}
static var showsFoldersFirst: Bool {
get {
return UserDefaults.standard.bool(forKey: UserDefaults.UserDefaultsKeys.showsFoldersFirst.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.showsFoldersFirst.rawValue)
UserDefaults.standard.synchronize()
}
}
static var shouldPasswordDownloadLink: Bool {
get {
return UserDefaults.standard.bool(forKey: UserDefaults.UserDefaultsKeys.shouldPasswordDownloadLink.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.shouldPasswordDownloadLink.rawValue)
UserDefaults.standard.synchronize()
}
}
static var shouldPasswordReceiveLink: Bool {
get {
return UserDefaults.standard.bool(forKey: UserDefaults.UserDefaultsKeys.shouldPasswordReceiveLink.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.shouldPasswordReceiveLink.rawValue)
UserDefaults.standard.synchronize()
}
}
static var sortMethod: SortMethodType {
get {
let value = UserDefaults.standard.integer(forKey: UserDefaults.UserDefaultsKeys.sortMethod.rawValue)
return SortMethodType(rawValue: value)!
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: UserDefaults.UserDefaultsKeys.sortMethod.rawValue)
UserDefaults.standard.synchronize()
}
}
static var sortAscending: Bool {
get {
return UserDefaults.standard.bool(forKey: UserDefaults.UserDefaultsKeys.sortAscending.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.sortAscending.rawValue)
UserDefaults.standard.synchronize()
}
}
static var allowsCellularAccess: Bool {
get {
return UserDefaults.standard.bool(forKey: UserDefaults.UserDefaultsKeys.allowsCellularAccess.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.UserDefaultsKeys.allowsCellularAccess.rawValue)
UserDefaults.standard.synchronize()
}
}
static func tokenForAccount(account: Account) -> String {
guard let token = try? account.readToken() else {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error reading account from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
return ""
}
return token
}
static func persistUserInfo(user: User) {
UserDefaults.standard.set(user.firstName, forKey: "firstName-\(user.identifier)")
UserDefaults.standard.set(user.lastName, forKey: "lastName-\(user.identifier)")
UserDefaults.standard.set(user.email, forKey: "email-\(user.identifier)")
UserDefaults.standard.synchronize()
}
static func getPersistedUserInfo(userID: String) -> User? {
guard let firstName = UserDefaults.standard.string(forKey: "firstName-\(userID)"),
let lastName = UserDefaults.standard.string(forKey: "lastName-\(userID)"),
let email = UserDefaults.standard.string(forKey: "email-\(userID)") else {
return nil
}
return User(identifier: userID, firstName: firstName, lastName: lastName, email: email, permissions: Permissions())
}
static func deletePersistedUserInfo(userID: String) {
UserDefaults.standard.set(nil, forKey: "name-\(userID)")
UserDefaults.standard.set(nil, forKey: "email-\(userID)")
UserDefaults.standard.synchronize()
}
static func saveUser(forToken token: String, completion: @escaping (User?, Error?) -> Void) {
DigiClient.shared.getUser(forToken: token) { userResult, error in
guard error == nil else {
completion(nil, error)
return
}
guard let user = userResult else {
completion(nil, error)
return
}
let account = Account(userID: user.identifier)
do {
try account.save(token: token)
} catch {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error saving account to Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
}
persistUserInfo(user: user)
DigiClient.shared.loggedAccount = account
DigiClient.shared.getUserProfileImage(for: user) { image, error in
guard error == nil else {
return
}
let cache = Cache()
let key = user.identifier + ".png"
if let image = image, let data = UIImagePNGRepresentation(image) {
cache.save(type: .profile, data: data, for: key)
}
completion(user, nil)
}
}
}
static func clearKeychainItems() {
do {
let accounts = try Account.accountItems()
for account in accounts {
try account.deleteItem()
}
} catch {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error deleting account from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
}
}
static func setDefaultAppSettings() {
// Set that App has been started for the first time
hasRunBefore = true
// Sorting settings
showsFoldersFirst = true
sortMethod = .byName
sortAscending = true
// Network settings
allowsCellularAccess = true
}
static func showErrorMessageAndCrash(title: String, subtitle: String) {
if let window = UIApplication.shared.keyWindow {
let blackView = UIView()
blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
window.addSubview(blackView)
blackView.frame = window.frame
blackView.alpha = 0.0
let frameAlert: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.black.withAlphaComponent(0.85)
view.layer.cornerRadius = 10
view.layer.borderWidth = 0.6
view.layer.borderColor = UIColor(red: 0.8, green: 0.0, blue: 0.0, alpha: 1.0).cgColor
view.clipsToBounds = true
return view
}()
let titleMessageLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.fontHelveticaNeueLight(size: 24)
label.textColor = UIColor.white
label.text = title
label.textAlignment = .center
label.numberOfLines = 2
return label
}()
let subtitleMessageLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.fontHelveticaNeueLight(size: 18)
label.textColor = UIColor.white
label.text = subtitle
label.textAlignment = .center
label.textColor = UIColor.lightGray
label.numberOfLines = 3
return label
}()
let okButton: UIButton = {
let button = UIButton(type: UIButtonType.custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor(red: 0.9, green: 0.0, blue: 0.0, alpha: 1.0)
button.layer.cornerRadius = 10
button.layer.masksToBounds = true
button.setTitle(NSLocalizedString("OK", comment: ""), for: .normal)
button.setTitleColor(.white, for: [.normal, .selected])
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 35, bottom: 5, right: 35)
button.addTarget(self, action: #selector(handleOKButtonTouched), for: .touchUpInside)
return button
}()
blackView.addSubview(frameAlert)
frameAlert.addSubview(titleMessageLabel)
frameAlert.addSubview(subtitleMessageLabel)
frameAlert.addSubview(okButton)
NSLayoutConstraint.activate([
frameAlert.centerXAnchor.constraint(equalTo: blackView.centerXAnchor),
frameAlert.centerYAnchor.constraint(equalTo: blackView.centerYAnchor),
frameAlert.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width * 0.9),
frameAlert.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height * 0.4),
titleMessageLabel.leftAnchor.constraint(equalTo: frameAlert.layoutMarginsGuide.leftAnchor),
titleMessageLabel.rightAnchor.constraint(equalTo: frameAlert.layoutMarginsGuide.rightAnchor),
titleMessageLabel.centerYAnchor.constraint(equalTo: frameAlert.centerYAnchor, constant: -30),
subtitleMessageLabel.leftAnchor.constraint(equalTo: frameAlert.layoutMarginsGuide.leftAnchor),
subtitleMessageLabel.rightAnchor.constraint(equalTo: frameAlert.layoutMarginsGuide.rightAnchor),
subtitleMessageLabel.topAnchor.constraint(equalTo: titleMessageLabel.bottomAnchor, constant: 10),
okButton.centerXAnchor.constraint(equalTo: frameAlert.centerXAnchor),
okButton.bottomAnchor.constraint(equalTo: frameAlert.bottomAnchor, constant: -20)
])
UIView.animate(withDuration: 0.5) { blackView.alpha = 1 }
}
}
@objc private func handleOKButtonTouched() {
fatalError()
}
}
| mit | 6028ee888f69d01c6bc0f2667a982b1a | 36.427673 | 123 | 0.612754 | 5.37579 | false | false | false | false |
audiokit/AudioKit | Tests/AudioKitTests/MIDI Tests/Support/TestSender.swift | 1 | 1503 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import CoreMIDI
@available(iOS 14.0, OSX 11.0, *)
private extension MIDIEventList.Builder {
// for some reason MIDIEventList.Builder causes a crash when called with a size smaller than MIDIEventList word-size
convenience init(inProtocol: MIDIProtocolID) {
self.init(inProtocol: inProtocol, wordSize: MemoryLayout<MIDIEventList>.size / MemoryLayout<UInt32>.stride)
}
}
// simple test sender only for testing, will not work on simulator
class TestSender {
var client: MIDIClientRef = 0
var source: MIDIEndpointRef = 0
init() {
MIDIClientCreateWithBlock("TestClient" as CFString, &client, nil)
if #available(iOS 14.0, OSX 11.0, *) {
MIDISourceCreateWithProtocol(client, "TestSender" as CFString, ._1_0, &source)
}
}
deinit {
MIDIEndpointDispose(source)
MIDIClientDispose(client)
}
func send(words: [UInt32]) {
if #available(iOS 14.0, OSX 11.0, *) {
let builder = MIDIEventList.Builder(inProtocol: ._1_0)
builder.append(timestamp: mach_absolute_time(), words: words)
_ = builder.withUnsafePointer {
MIDIReceivedEventList(source, $0)
}
}
}
var uniqueID: MIDIUniqueID {
var uniqueID: Int32 = 0
MIDIObjectGetIntegerProperty(source, kMIDIPropertyUniqueID, &uniqueID)
return uniqueID
}
}
| mit | 6bc0f7988ea86e9a1946e9d165265ad3 | 32.4 | 120 | 0.657352 | 4.140496 | false | true | false | false |
xiaoxionglaoshi/DNSwiftProject | DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/UITableViewExtensions.swift | 1 | 1771 | //
// UITableViewExtensions.swift
// DNSwiftProject
//
// Created by mainone on 16/12/22.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
public extension UITableView {
// 返回section最后一行
public func indexPathForLastRow(in section: Int) -> IndexPath? {
return IndexPath(row: numberOfRows(inSection: section) - 1, section: section)
}
// 返回table最后一行
public var indexPathForLastRow: IndexPath? {
guard numberOfRows > 0 else {
return nil
}
return IndexPath(row: numberOfRows - 1, section: lastSection)
}
// 返回table最后一个section
var lastSection: Int {
guard numberOfSections > 1 else {
return 0
}
return numberOfSections - 1
}
// 移除footerView
public func removeTableFooterView() {
tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
}
// 移除headerView
public func removeTableHeaderView() {
tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
}
// 滚动到底部
public func scrollToBottom(animated: Bool = true) {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
setContentOffset(bottomOffset, animated: animated)
}
// 滚动到顶部
public func scrollToTop(animated: Bool = true) {
setContentOffset(CGPoint.zero, animated: animated)
}
public var numberOfRows: Int {
var section = 0
var rowCount = 0
while section < self.numberOfSections {
rowCount += self.numberOfRows(inSection: section)
section += 1
}
return rowCount
}
}
| apache-2.0 | 12a635a93241f509e51e544bb12fabfb | 25.625 | 85 | 0.607394 | 4.531915 | false | false | false | false |
NghiaTranUIT/Titan | TitanCore/TitanCore/AutosizeVerticalFlowLayout.swift | 2 | 5094 | //
// AutosizeVerticalFlowLayout.swift
// TitanCore
//
// Created by Nghia Tran on 4/12/17.
// Copyright © 2017 nghiatran. All rights reserved.
//
import Cocoa
open class AutosizeVerticalFlowLayout: NSCollectionViewFlowLayout {
//
// MARK: - Variable
fileprivate var sizeCell = CGSize.zero
fileprivate var sizeHeader = CGSize.zero
fileprivate var cellSectionAttributes: [IndexPath: NSCollectionViewLayoutAttributes] = [:]
fileprivate var headerAttribute: [NSCollectionViewLayoutAttributes] = []
fileprivate var contentSize = CGSize.zero
fileprivate var numberOfSection = 0
fileprivate var itemCount: [Int: Int] = [:]
fileprivate let paddingSection: CGFloat = 6.0
//
// MARK: - Init
public override init() {
super.init()
self.scrollDirection = .vertical
self.minimumLineSpacing = 0
self.minimumInteritemSpacing = 0
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//
// MARK: - Override
fileprivate func updateDataSource() {
guard let collectionView = self.collectionView else {return}
// Get section
self.numberOfSection = collectionView.dataSource?.numberOfSections!(in: collectionView) ?? 0
// Get item count for each section
for i in 0..<self.numberOfSection {
let count = collectionView.dataSource?.collectionView(collectionView, numberOfItemsInSection: i) ?? 0
self.itemCount[i] = count
}
// Size
let sizeScreen = collectionView.frame.size
self.sizeCell = CGSize(width: sizeScreen.width, height: 32)
self.sizeHeader = CGSize(width: sizeScreen.width, height: 32)
}
override open func prepare() {
super.prepare()
// Update data
self.updateDataSource()
// Data
var lastY = self.paddingSection
// Prepare data
var cells: [IndexPath: NSCollectionViewLayoutAttributes] = [:]
var headerAtts: [NSCollectionViewLayoutAttributes] = []
for section in 0..<self.numberOfSection {
// Header
let headerAtt = NSCollectionViewLayoutAttributes(forSupplementaryViewOfKind: NSCollectionElementKindSectionHeader, with: IndexPath(item: 0, section: section))
let yHeader = lastY
headerAtt.frame = CGRect(x: 0.0, y: yHeader, width: self.sizeHeader.width, height: self.sizeHeader.height)
headerAtts.append(headerAtt)
lastY = lastY + self.sizeHeader.height
// Cells
let sectionCount = self.itemCount[section] ?? 0
for item in 0..<sectionCount {
// Frame
let y = lastY
// INdex
let indexPath = IndexPath(item: item, section: section)
let att = NSCollectionViewLayoutAttributes(forItemWith: indexPath)
att.frame = CGRect(x: 0.0, y: y, width: self.sizeCell.width, height: self.sizeCell.height)
cells[indexPath] = att
// Minus
lastY = lastY + self.sizeCell.height
}
// Padding section
lastY = lastY + self.paddingSection
}
// Content Size
self.contentSize = self.calculateContentSize()
// Save data
self.cellSectionAttributes = cells
self.headerAttribute = headerAtts
}
fileprivate func calculateContentSize() -> CGSize {
guard let collectionView = self.collectionView else {
return CGSize.zero
}
var height = CGFloat(self.numberOfSection) * (self.sizeHeader.height + self.paddingSection)
for count in self.itemCount.values {
height += CGFloat(count) * self.sizeCell.height
}
height = max(height, collectionView.frame.height)
return CGSize(width: collectionView.frame.width, height: height)
}
//
// MARK: - Override
override open func layoutAttributesForItem(at indexPath: IndexPath) -> NSCollectionViewLayoutAttributes? {
return self.cellSectionAttributes[indexPath]
}
override open func layoutAttributesForElements(in rect: CGRect) -> [NSCollectionViewLayoutAttributes] {
var cells: [NSCollectionViewLayoutAttributes] = []
// Header
for att in self.headerAttribute {
if att.frame.intersects(rect) {
cells.append(att)
}
}
// Cell
for att in self.cellSectionAttributes.values {
if att.frame.intersects(rect) {
cells.append(att)
}
}
return cells
}
override open var collectionViewContentSize: CGSize {
return self.contentSize
}
}
| mit | 881bd9d4ab118511b270eb5771c44053 | 31.647436 | 170 | 0.588455 | 5.239712 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Nodes/Effects/Reverb/Costello Reverb/AKCostelloReverb.swift | 1 | 5270 | //
// AKCostelloReverb.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// 8 delay line stereo FDN reverb, with feedback matrix based upon physical
/// modeling scattering junction of 8 lossless waveguides of equal
/// characteristic impedance.
///
/// - parameter input: Input node to process
/// - parameter feedback: Feedback level in the range 0 to 1. 0.6 gives a good small 'live' room sound, 0.8 a small hall, and 0.9 a large hall. A setting of exactly 1 means infinite length, while higher values will make the opcode unstable.
/// - parameter cutoffFrequency: Low-pass cutoff frequency.
///
public class AKCostelloReverb: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKCostelloReverbAudioUnit?
internal var token: AUParameterObserverToken?
private var feedbackParameter: AUParameter?
private var cutoffFrequencyParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet(newValue) {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Feedback level in the range 0 to 1. 0.6 gives a good small 'live' room sound, 0.8 a small hall, and 0.9 a large hall. A setting of exactly 1 means infinite length, while higher values will make the opcode unstable.
public var feedback: Double = 0.6 {
willSet(newValue) {
if feedback != newValue {
if internalAU!.isSetUp() {
feedbackParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.feedback = Float(newValue)
}
}
}
}
/// Low-pass cutoff frequency.
public var cutoffFrequency: Double = 4000 {
willSet(newValue) {
if cutoffFrequency != newValue {
if internalAU!.isSetUp() {
cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.cutoffFrequency = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this reverb node
///
/// - parameter input: Input node to process
/// - parameter feedback: Feedback level in the range 0 to 1. 0.6 gives a good small 'live' room sound, 0.8 a small hall, and 0.9 a large hall. A setting of exactly 1 means infinite length, while higher values will make the opcode unstable.
/// - parameter cutoffFrequency: Low-pass cutoff frequency.
///
public init(
_ input: AKNode,
feedback: Double = 0.6,
cutoffFrequency: Double = 4000) {
self.feedback = feedback
self.cutoffFrequency = cutoffFrequency
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x72767363 /*'rvsc'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKCostelloReverbAudioUnit.self,
asComponentDescription: description,
name: "Local AKCostelloReverb",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKCostelloReverbAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
feedbackParameter = tree.valueForKey("feedback") as? AUParameter
cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.feedbackParameter!.address {
self.feedback = Double(value)
} else if address == self.cutoffFrequencyParameter!.address {
self.cutoffFrequency = Double(value)
}
}
}
internalAU?.feedback = Float(feedback)
internalAU?.cutoffFrequency = Float(cutoffFrequency)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| apache-2.0 | 05a54462dff853236ce897d507eb9727 | 36.112676 | 244 | 0.629981 | 5.181908 | false | false | false | false |
ios-archy/Sinaweibo_swift | SinaWeibo_swift/SinaWeibo_swift/Classess/Tools/Emotion/EmotionController.swift | 1 | 6944 | //
// EmotionController.swift
// Emotion
//
// Created by archy on 16/11/18.
// Copyright © 2016年 archy. All rights reserved.
//
import UIKit
private let EmotionCell = "EmotionCell"
class EmotionController: UIViewController {
//定义属性
var emoticonCallBack : (emoticon : Emoticon) -> ()
//懒加载属性
private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmotionCollectionViewLayout())
private lazy var tooBar : UIToolbar = UIToolbar()
private lazy var manager = EmoticonManager()
// MARK:-自定义构造函数
init(emoticonCallBack : (emoticon : Emoticon)-> ())
{
self.emoticonCallBack = emoticonCallBack
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension EmotionController {
private func setupUI(){
//1.添加子控件
view.addSubview(collectionView)
view.addSubview(tooBar)
collectionView.backgroundColor = UIColor.purpleColor()
tooBar.backgroundColor = UIColor.darkGrayColor()
//2.设置子控件的frame
collectionView.translatesAutoresizingMaskIntoConstraints = false
tooBar.translatesAutoresizingMaskIntoConstraints = false
// let views = ["tBar" : tooBar, "cView" : collectionView]
// var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0- [tBar]-0-|", options: [], metrics: nil, views: views)
// cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cView]-0-[tBar]-0-|", options: [.AlignAllLeft, .AlignAllRight], metrics: nil, views: views)
// view.addConstraints(cons)
let views = ["tBar" : tooBar, "cView" : collectionView]
var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tBar]-0-|", options: [], metrics: nil, views: views)
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cView]-0-[tBar]-0-|", options: [.AlignAllLeft, .AlignAllRight], metrics: nil, views: views)
view.addConstraints(cons)
//3.准备collectionview
prepareForCollectionView()
//4.准备tooBarar
prepareForTooBar()
}
private func prepareForCollectionView(){
collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmotionCell)
collectionView.dataSource = self
collectionView.delegate = self
}
private func prepareForTooBar(){
//1.定义toolBar中titles
let titles = ["最近", "默认", "emoji", "浪小花"]
//2.遍历标题,创建item
var index = 0
var tempItems = [UIBarButtonItem]()
for title in titles {
let item = UIBarButtonItem(title: title, style: .Plain, target: self, action: "itemClick:");
item.tag = index
index++
tempItems.append(item)
tempItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
}
//3.设置toolBar的items数组
tempItems.removeLast()
tooBar.items = tempItems
tooBar.tintColor = UIColor.orangeColor()
}
@objc private func itemClick(item : UIBarButtonItem)
{
//1.点击获取item的tag
let tag = item.tag
//2.根据tag获取到当前数组
let indexpath = NSIndexPath(forItem: 0, inSection: tag)
//3.滚动到对应的位置
collectionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: true)
}
}
extension EmotionController : UICollectionViewDataSource ,UICollectionViewDelegate{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return manager.packages.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let package = manager.packages[section]
return package.emoticons.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmotionCell, forIndexPath: indexPath) as! EmoticonViewCell
//2.给cell设置数据
// cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.orangeColor()
let package = manager.packages[indexPath.section]
let emoticon = package.emoticons[indexPath.item]
cell.emoticon = emoticon
return cell
}
/// 代理方法
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//1.去除点击的表情
let package = manager.packages[indexPath.section]
let emoticon = package.emoticons[indexPath.item]
//2.将点击的表情插入最近分组中
insertRecentlyEmotion(emoticon)
//3.将表情回调给外界控制器
emoticonCallBack(emoticon: emoticon)
}
private func insertRecentlyEmotion(emotion : Emoticon){
//1.如果是空白表情或者删除按钮,不需要插入
if emotion.isRemove || emotion.isEmpty {
return
}
//2.删除一个表情
if manager.packages.first!.emoticons.contains(emotion) {
let index = (manager.packages.first?.emoticons.indexOf(emotion))!
manager.packages.first?.emoticons.removeAtIndex(index)
}else
{ //原来没有这个表情
manager.packages.first?.emoticons.removeAtIndex(19)
}
//3。将emoticon插入最近分组中
manager.packages.first?.emoticons.insert(emotion, atIndex: 0)
}
}
class EmotionCollectionViewLayout : UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
//1.计算item
let itemWH = UIScreen.mainScreen().bounds.width / 7
//2.设置layout的属性
itemSize = CGSize(width: itemWH, height: itemWH)
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = .Horizontal
//3.设置collectionView的属性
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = false
let insertMargin = (collectionView!.bounds.height - 3 * itemWH) / 2
collectionView?.contentInset = UIEdgeInsets(top: insertMargin, left: 0, bottom: insertMargin, right: 0)
}
} | mit | 0985cb56bd506e1a4c40876d1d8f18bf | 31.835821 | 164 | 0.642067 | 4.980377 | false | false | false | false |
turbolinks/turbolinks-ios | Turbolinks/VisitableViewController.swift | 1 | 2109 | import UIKit
open class VisitableViewController: UIViewController, Visitable {
open weak var visitableDelegate: VisitableDelegate?
open var visitableURL: URL!
public convenience init(url: URL) {
self.init()
self.visitableURL = url
}
// MARK: Visitable View
open private(set) lazy var visitableView: VisitableView! = {
let view = VisitableView(frame: CGRect.zero)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
fileprivate func installVisitableView() {
view.addSubview(visitableView)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: [ "view": visitableView! ]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: [ "view": visitableView! ]))
}
// MARK: Visitable
open func visitableDidRender() {
self.title = visitableView.webView?.title
}
// MARK: View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
installVisitableView()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
visitableDelegate?.visitableViewWillAppear(self)
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
visitableDelegate?.visitableViewDidAppear(self)
}
/*
If the visitableView is a child of the main view, and anchored to its top and bottom, then it's
unlikely you will need to customize the layout. But more complicated view hierarchies and layout
may require explicit control over the contentInset. Below is an example of setting the contentInset
to the layout guides.
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
visitableView.contentInset = UIEdgeInsets(top: topLayoutGuide.length, left: 0, bottom: bottomLayoutGuide.length, right: 0)
}
*/
}
| mit | dad2a1e61061e9e01d3836725813b93f | 33.016129 | 153 | 0.688478 | 5.106538 | false | false | false | false |
congnt24/AwesomeMVVM | AwesomeMVVM/Classes/Extension/UIImageViewExtension.swift | 1 | 2289 | //
// UIImageViewExtension.swift
// Pods
//
// Created by Cong on 6/20/17.
//
//
import UIKit
public extension UIImageView {
/// Set image from a URL.
///
/// - Parameters:
/// - url: URL of image.
/// - contentMode: imageView content mode (default is .scaleAspectFit).
/// - placeHolder: optional placeholder image
/// - completionHandler: optional completion handler to run when download finishs (default is nil).
public func download(from url: URL,
contentMode: UIViewContentMode = .scaleAspectFit,
placeholder: UIImage? = nil,
completionHandler: ((UIImage?) -> Void)? = nil) {
image = placeholder
self.contentMode = contentMode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data,
let image = UIImage(data: data)
else {
completionHandler?(nil)
return
}
DispatchQueue.main.async() { () -> Void in
self.image = image
completionHandler?(image)
}
}.resume()
}
/// Make image view blurry
///
/// - Parameter style: UIBlurEffectStyle (default is .light).
public func blur(withStyle style: UIBlurEffectStyle = .light) {
let blurEffect = UIBlurEffect(style: style)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
addSubview(blurEffectView)
clipsToBounds = true
}
/// Blurred version of an image view
///
/// - Parameter style: UIBlurEffectStyle (default is .light).
/// - Returns: blurred version of self.
public func blurred(withStyle style: UIBlurEffectStyle = .light) -> UIImageView {
let imgView = self
imgView.blur(withStyle: style)
return imgView
}
}
| mit | 2351889ef081023d6c887b6e3e9b9d78 | 34.215385 | 109 | 0.58104 | 5.310905 | false | false | false | false |
avaidyam/Parrot | MochaUI/ShortcutRecognizer.swift | 1 | 3303 | import Foundation
//
// MARK: - ShortcutRecognizer Root Protocol
//
/// Defines a shortcut recognition mechanism that operates globally.
/// It executes a subclass-defined action upon its activation.
/// Think, similar to `NSGestureRecognizer`, but not `NSWindow` or `NSApp`-bound.
public protocol ShortcutRecognizer: class {
/// Invoke this when the shortcut key is pressed.
func keyDown()
/// Invoke this when the shortcut key is released.
func keyUp()
}
//
// MARK: - Simple Press Recognizer
//
/// Simple press recognizer that executes its `handler`.
public final class PressShortcutRecognizer: ShortcutRecognizer {
/// The handler is invoked when the shortcut is pressed.
public let handler: () -> ()
/// Create a new tracker with the given handler.
public init(_ handler: @escaping () -> ()) {
self.handler = handler
}
public func keyDown() {
/// ignored!
}
public func keyUp() {
self.handler()
}
}
//
// MARK: - Complex Tap & Hold Recognizer
//
/// Naive double tap & hold mechanism that executes its `handler`.
public final class TapHoldShortcutRecognizer: ShortcutRecognizer {
private var timeReference: CFAbsoluteTime = 0.0
private var inDoubleTap = false
private var timeInterval = DispatchTimeInterval.seconds(0)
/// The handler is invoked when the criteria for this recognizer are met:
/// tap the shortcut twice (< 1s gap) and keep it pressed (> 2s hold).
public let handler: () -> ()
/// Create a new tracker with the given handler.
public init(for t: DispatchTimeInterval = .seconds(2), _ handler: @escaping () -> ()) {
self.timeInterval = t
self.handler = handler
}
public func keyDown() {
defer { self.timeReference = CFAbsoluteTimeGetCurrent() }
guard CFAbsoluteTimeGetCurrent() - self.timeReference < 1.0 else { return } // double-tapped
self.inDoubleTap = true
DispatchQueue.main.asyncAfter(deadline: .now() + self.timeInterval) {
guard self.inDoubleTap else { return }
self.inDoubleTap = false
DispatchQueue.main.async(execute: self.handler)
}
}
public func keyUp() {
guard self.inDoubleTap else { return }
self.inDoubleTap = false
print("shortcut recognizer failed because hold duration was \(CFAbsoluteTimeGetCurrent() - self.timeReference)s")
}
}
//
// MARK: - Shortcut <-> Recognizer Binding
//
public extension ShortcutRecognizer {
/// Bind a recognizer to a shortcut. Retain the returned object to ensure the binding.
public func bind(to shortcut: CGSKeyboardShortcut) -> Any {
let x = NotificationCenter.default.addObserver(forName: CGSKeyboardShortcut.pressedNotification, object: shortcut, queue: nil) { _ in
self.keyDown()
}
let y = NotificationCenter.default.addObserver(forName: CGSKeyboardShortcut.releasedNotification, object: shortcut, queue: nil) { _ in
self.keyUp()
}
return _Holder([x, y])
}
}
// Implementation Detail:
class _Holder {
private let observers: [Any]
public init(_ observers: [Any]) {
self.observers = observers
}
}
// MARK: -
| mpl-2.0 | 67fa5a666e4487d77aed3ab51b45d7c5 | 27.474138 | 142 | 0.647896 | 4.61958 | false | false | false | false |
shaunstanislaus/Ji | Source/Ji.swift | 3 | 9395 | //
// Ji.swift
// Ji
//
// Created by Honghao Zhang on 2015-07-21.
// Copyright (c) 2015 Honghao Zhang (张宏昊)
//
// 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
/// Ji document
public class Ji {
/// A flag specifies whether the data is XML or not.
private var isXML: Bool = true
/// The XML/HTML data.
private(set) public var data: NSData?
/// The encoding used by in this document.
private(set) public var encoding: NSStringEncoding = NSUTF8StringEncoding
public typealias htmlDocPtr = xmlDocPtr
/// The xmlDocPtr for this document
private(set) public var xmlDoc: xmlDocPtr = nil
/// Alias for xmlDoc
private(set) public var htmlDoc: htmlDocPtr {
get { return xmlDoc }
set { xmlDoc = newValue }
}
// MARK: - Init
/**
Initializes a Ji document object with the supplied data, encoding and boolean flag.
:param: data The XML/HTML data.
:param: encoding The encoding used by data.
:param: isXML Whether this is a XML data, true for XML, false for HTML.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public required init?(data: NSData?, encoding: NSStringEncoding, isXML: Bool) {
if let data = data where data.length > 0 {
self.isXML = isXML
self.data = data
self.encoding = encoding
let cBuffer = UnsafePointer<CChar>(data.bytes)
let cSize = CInt(data.length)
let cfEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
let cfEncodingAsString: CFStringRef = CFStringConvertEncodingToIANACharSetName(cfEncoding)
let cEncoding: UnsafePointer<CChar> = CFStringGetCStringPtr(cfEncodingAsString, 0)
if isXML {
let options = CInt(XML_PARSE_RECOVER.value)
xmlDoc = xmlReadMemory(cBuffer, cSize, nil, cEncoding, options)
} else {
let options = CInt(HTML_PARSE_RECOVER.value | HTML_PARSE_NOWARNING.value | HTML_PARSE_NOERROR.value)
htmlDoc = htmlReadMemory(cBuffer, cSize, nil, cEncoding, options)
}
if xmlDoc == nil { return nil }
} else {
return nil
}
}
/**
Initializes a Ji document object with the supplied data and boolean flag, using NSUTF8StringEncoding.
:param: data The XML/HTML data.
:param: isXML Whether this is a XML data, true for XML, false for HTML.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(data: NSData?, isXML: Bool) {
self.init(data: data, encoding: NSUTF8StringEncoding, isXML: isXML)
}
// MARK: - Data Init
/**
Initializes a Ji document object with the supplied XML data and encoding.
:param: xmlData The XML data.
:param: encoding The encoding used by data.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(xmlData: NSData, encoding: NSStringEncoding) {
self.init(data: xmlData, encoding: encoding, isXML: true)
}
/**
Initializes a Ji document object with the supplied XML data, using NSUTF8StringEncoding.
:param: xmlData The XML data.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(xmlData: NSData) {
self.init(data: xmlData, isXML: true)
}
/**
Initializes a Ji document object with the supplied HTML data and encoding.
:param: htmlData The HTML data.
:param: encoding The encoding used by data.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(htmlData: NSData, encoding: NSStringEncoding) {
self.init(data: htmlData, encoding: encoding, isXML: false)
}
/**
Initializes a Ji document object with the supplied HTML data, using NSUTF8StringEncoding.
:param: htmlData The HTML data.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(htmlData: NSData) {
self.init(data: htmlData, isXML: false)
}
// MARK: - URL Init
/**
Initializes a Ji document object with the contents of supplied URL, encoding and boolean flag.
:param: url The URL from which to read data.
:param: encoding The encoding used by data.
:param: isXML Whether this is a XML data URL, true for XML, false for HTML.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(contentsOfURL url: NSURL, encoding: NSStringEncoding, isXML: Bool) {
let data = NSData(contentsOfURL: url)
self.init(data: data, encoding: encoding, isXML: isXML)
}
/**
Initializes a Ji document object with the contents of supplied URL, and boolean flag, using NSUTF8StringEncoding.
:param: url The URL from which to read data.
:param: isXML Whether this is a XML data URL, true for XML, false for HTML.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(contentsOfURL url: NSURL, isXML: Bool) {
self.init(contentsOfURL: url, encoding: NSUTF8StringEncoding, isXML: isXML)
}
/**
Initializes a Ji document object with the contents of supplied XML URL, using NSUTF8StringEncoding.
:param: xmlURL The XML URL from which to read data.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(xmlURL: NSURL) {
self.init(contentsOfURL: xmlURL, isXML: true)
}
/**
Initializes a Ji document object with the contents of supplied HTML URL, using NSUTF8StringEncoding.
:param: htmlURL The HTML URL from which to read data.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(htmlURL: NSURL) {
self.init(contentsOfURL: htmlURL, isXML: false)
}
// MARK: - String Init
/**
Initializes a Ji document object with a XML string and it's encoding.
:param: xmlString XML string.
:param: encoding The encoding used by xmlString.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(xmlString: String, encoding: NSStringEncoding) {
let data = xmlString.dataUsingEncoding(encoding, allowLossyConversion: false)
self.init(data: data, encoding: encoding, isXML: true)
}
/**
Initializes a Ji document object with a HTML string and it's encoding.
:param: htmlString HTML string.
:param: encoding The encoding used by htmlString.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(htmlString: String, encoding: NSStringEncoding) {
let data = htmlString.dataUsingEncoding(encoding, allowLossyConversion: false)
self.init(data: data, encoding: encoding, isXML: false)
}
/**
Initializes a Ji document object with a XML string, using NSUTF8StringEncoding.
:param: xmlString XML string.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(xmlString: String) {
let data = xmlString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
self.init(data: data, isXML: true)
}
/**
Initializes a Ji document object with a HTML string, using NSUTF8StringEncoding.
:param: htmlString HTML string.
:returns: The initialized Ji document object or nil if the object could not be initialized.
*/
public convenience init?(htmlString: String) {
let data = htmlString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
self.init(data: data, isXML: false)
}
// MARK: - Deinit
deinit {
xmlFreeDoc(xmlDoc)
}
// MARK: - Public methods
/// Root node of this Ji document object.
public lazy var rootNode: JiNode? = {
let rootNodePointer = xmlDocGetRootElement(self.xmlDoc)
if rootNodePointer == nil {
return nil
} else {
return JiNode(xmlNode: rootNodePointer, jiDocument: self)
}
}()
/**
Perform XPath query on this document.
:param: xPath XPath query string.
:returns: An array of JiNode or nil if rootNode is nil. An empty array will be returned if XPath matches no nodes.
*/
public func xPath(xPath: String) -> [JiNode]? {
return self.rootNode?.xPath(xPath)
}
}
// MARK: - Equatable
extension Ji: Equatable { }
public func ==(lhs: Ji, rhs: Ji) -> Bool {
return lhs.xmlDoc == rhs.xmlDoc
}
| mit | 705e9f53f84fe58f93c2455a56783d24 | 31.264605 | 115 | 0.730536 | 3.889395 | false | false | false | false |
lukesutton/uut | Sources/PropertyValues-Table.swift | 1 | 1377 | extension PropertyValues {
public enum BorderCollapse: String, PropertyValue {
case Separate = "separate"
case Collapse = "collapse"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum BorderSpacing: PropertyValue {
case Both(Measurement)
case Each(Measurement, Measurement)
case Initial
case Inherit
public var stringValue: String {
switch self {
case let Both(x): return x.stringValue
case let Each(x, y): return "\(x.stringValue) \(y.stringValue)"
case Initial: return "initial"
case Inherit: return "inherit"
}
}
}
public enum CaptionSide: String, PropertyValue {
case Top = "top"
case Bottom = "bottom"
case Intitial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum EmptyCells: String, PropertyValue {
case Show = "show"
case Hide = "hide"
case Intitial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum TableLayout: String, PropertyValue {
case Auto = "auto"
case Fixed = "fixed"
case Intitial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
}
| mit | f70b2583247b5a4802cef3d1a2e03102 | 21.57377 | 71 | 0.633261 | 4.371429 | false | false | false | false |
huangboju/ADController | Classes/OverlayAnimationController.swift | 1 | 2862 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
class OverlayAnimationController: AnimatedTransitioning {
private lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.image = ADConfig.shared.firstImage
return imageView
}()
override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to) else {
return
}
let containerView = transitionContext.containerView
guard let fromView = fromVC.view else { return }
guard let toView = toVC.view else { return }
let duration = transitionDuration(using: transitionContext)
let isVertical = ADConfig.shared.isVertical
let completion = { (_: Bool) in
UIView.animate(withDuration: 0.4, animations: {
self.imageView.alpha = 0
}, completion: { _ in
self.imageView.removeFromSuperview()
})
let isCancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!isCancelled)
}
if toVC.isBeingPresented {
containerView.addSubview(toView)
let toViewWidth = ADConfig.shared.ADViewSize.width
let toViewHeight = ADConfig.shared.ADViewSize.height
toView.center = containerView.center
let size = isVertical ? CGSize(width: 1, height: toViewHeight) : CGSize(width: toViewWidth, height: 1)
toView.bounds = CGRect(origin: .zero, size: size)
imageView.frame = toView.frame
containerView.addSubview(imageView)
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: {
self.setBounds(with: toView, width: toViewWidth, height: toViewHeight)
}, completion: completion)
}
// Dismissal 转场中不要将 toView 添加到 containerView
if fromVC.isBeingDismissed {
fromView.alpha = 0
containerView.addSubview(imageView)
imageView.frame = fromView.frame
imageView.image = ADConfig.shared.lastImage
UIView.animate(withDuration: duration, animations: {
self.setBounds(with: fromView, width: 1, height: 1)
}, completion: completion)
}
}
func setBounds(with view: UIView, width: CGFloat, height: CGFloat) {
if ADConfig.shared.isVertical {
imageView.bounds.size.width = width
view.bounds.size.width = width
} else {
imageView.bounds.size.height = height
view.bounds.size.height = height
}
}
}
| mit | e86f5bb564e226b0f8fbcdaa3efe5775 | 34.962025 | 114 | 0.627948 | 5.193784 | false | true | false | false |
bigfish24/ABFRealmGridController | SwiftExample/SwiftRealmGridController/MainCollectionViewController.swift | 1 | 3707 | //
// MainCollectionViewController.swift
// SwiftRealmGridController
//
// Created by Adam Fish on 9/8/15.
// Copyright (c) 2015 Adam Fish. All rights reserved.
//
import UIKit
import RealmSwift
import SwiftFetchedResultsController
import TOWebViewController
import Haneke
import RealmSwiftNYTStories
let reuseIdentifier = "DefaultCell"
class MainCollectionViewController: RealmGridController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
self.entityName = "NYTStory"
// Do any additional setup after loading the view.
self.sortDescriptors = [SortDescriptor(property: "publishedDate", ascending: false)]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MainCollectionViewCell
// Configure the cell
let aStory = self.objectAtIndexPath(NYTStory.self, indexPath: indexPath)
cell.titleLabel.text = aStory?.title
cell.excerptLabel.text = aStory?.abstract
if let date = aStory?.publishedDate {
cell.dateLabel.text = NYTStory.stringFromDate(date)
}
if let imageURL = aStory?.storyImage?.url {
cell.imageView.hnk_setImageFromURL(imageURL)
}
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
let story = self.objectAtIndexPath(NYTStory.self, indexPath: indexPath)
if let urlString = story?.urlString {
let webController = TOWebViewController(URLString: urlString)
let navController = UINavigationController(rootViewController: webController)
self.navigationController?.presentViewController(navController, animated: true, completion: nil)
}
}
// MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let height: CGFloat = 250.0
if UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.Portrait {
let columns: CGFloat = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad ? 3.0 : 2.0
let width = CGRectGetWidth(self.view.frame) / columns
return CGSizeMake(width, height)
}
else {
let columns: CGFloat = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad ? 4.0 : 3.0
let width = CGRectGetWidth(self.view.frame) / columns
return CGSizeMake(width, height)
}
}
// MARK: Private
@IBAction func didPressRefreshButton(sender: UIBarButtonItem) {
NYTStory.loadLatestStories(intoRealm: try! Realm(), withAPIKey: "388ce6e70d2a8e825757af7a0a67c397:13:59285541")
}
}
class MainCollectionViewCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var excerptLabel: UILabel!
}
| mit | c4bfc005314283d195c0ed566b212faa | 34.304762 | 169 | 0.682762 | 5.491852 | false | false | false | false |
Plopix/Dose | Sources/Kernel.swift | 1 | 2903 | //
// Kernel.swift
// Dose
//
// Created by Sebastien Morel on 6/26/15.
// Copyright (c) 2015 Plopix. All rights reserved.
//
import Foundation
/// The Kernel
public class Kernel {
/// The Container
public let container: Container!
/**
Constructor of am abstract Kernel
Config the parameters
- returns: Kernel
*/
public init() {
container = Container()
}
/**
Return the configuration file
By Default from the mainBundle
- returns: the Path
*/
public func getConfigurationFilePath() -> String? {
return NSBundle.mainBundle().pathForResource("services", ofType: "plist")
}
/**
Bootstrap the services
*/
public func bootstrap() {
if let path = self.getConfigurationFilePath() {
if let dict = NSDictionary(contentsOfFile: path) {
// parameters
if let parameters: [String: AnyObject] = dict["parameters"] as? [String: AnyObject] {
for (key, value) in parameters {
container[key] = value
}
}
// services
if let services: [String: AnyObject] = dict["services"] as? [String: AnyObject] {
//@todo: Check circular reference here
// if service1 need service2 and service2 need service1 ...
// could be more complex
for (serviceName, definition) in services {
let className: String = definition.objectForKey("class") as! String!
let aClass = (NSClassFromString(className) as! Service.Type)
let arguments: [String] = definition.objectForKey("arguments") as! [String]
container.attach(serviceName) { (container: Container) -> Any? in
var parsedArguments: [Any] = [Any]()
for value: String in arguments {
let valueArray = Array(value.characters)
if (valueArray[0]=="@") {
let serviceNamed = String(value.characters.dropFirst())
parsedArguments.append(self.get(serviceNamed))
} else {
parsedArguments.append(value)
}
}
return aClass.init(args: parsedArguments)
}
}
}
}
}
}
/**
Get a service or a parameter
- parameter key: The Key
- returns: The servive/parameter
*/
public func get<U>(key: String) -> U {
let c = self.container
return c[key] as! U
}
} | mit | b927f88a7dbe4ed8eab57f2aaf978ded | 31.629213 | 101 | 0.484671 | 5.456767 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Database/TypeGroups.swift | 2 | 2314 | //
// TypeGroups.swift
// Neocom
//
// Created by Artem Shimanski on 26.11.2019.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import SwiftUI
import CoreData
import Expressible
struct TypeGroups: View {
@Environment(\.managedObjectContext) var managedObjectContext
var category: SDEInvCategory
private func getGroups() -> FetchedResultsController<SDEInvGroup> {
let controller = managedObjectContext.from(SDEInvGroup.self)
.filter(/\SDEInvGroup.category == category)
.sort(by: \SDEInvGroup.published, ascending: false)
.sort(by: \SDEInvGroup.groupName, ascending: true)
.fetchedResultsController(sectionName: /\SDEInvGroup.published)
return FetchedResultsController(controller)
}
@StateObject private var groups = Lazy<FetchedResultsController<SDEInvGroup>, Never>()
func section(_ section: FetchedResultsController<SDEInvGroup>.Section) -> some View {
Section(header: section.name == "0" ? Text("UNPUBLISHED") : Text("PUBLISHED")) {
ForEach(section.objects, id: \.objectID) { group in
NavigationLink(destination: Types(.group(group))) {
GroupCell(group: group)
}
}
}
}
var body: some View {
let groups = self.groups.get(initial: getGroups())
let predicate = /\SDEInvType.group?.category == self.category && /\SDEInvType.published == true
return List {
ForEach(groups.sections, id: \.name, content: section)
}
.listStyle(GroupedListStyle())
.search { publisher in
TypesSearchResults(publisher: publisher, predicate: predicate) { type in
NavigationLink(destination: TypeInfo(type: type)) {
TypeCell(type: type)
}
}
}
.navigationBarTitle(category.categoryName ?? NSLocalizedString("Groups", comment: ""))
}
}
#if DEBUG
struct TypeGroups_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
TypeGroups(category: try! Storage.testStorage.persistentContainer.viewContext.from(SDEInvCategory.self).first()!)
}.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| lgpl-2.1 | 891572c2a782c7321b01d01903480fab | 34.584615 | 125 | 0.635971 | 4.749487 | false | false | false | false |
heptorsj/ProjectEulerSwift | Solutions/Problem1.swift | 1 | 337 | // Find the 3 or 5 multiplies below 1000
// Answer: 233168
let limit : Int = 1000
// Imperative style solution
func solution(end : Int)-> Int{
var result = 0
for actual in 3..<end{
if (actual % 3 == 0 || actual % 5 == 0){
result = result + actual
}
}
return result
}
let result = solution(end: limit)
print(result)
| apache-2.0 | 01982d2012321748580f828fa60ddb2a | 21.466667 | 44 | 0.623145 | 3.37 | false | false | false | false |
lorentey/swift | test/Inputs/conditional_conformance_subclass.swift | 3 | 13126 | public func takes_p1<T: P1>(_: T.Type) {}
public protocol P1 {
func normal()
func generic<T: P3>(_: T)
}
public protocol P2 {}
public protocol P3 {}
public struct IsP2: P2 {}
public class Base<A> {}
extension Base: P1 where A: P2 {
public func normal() {}
public func generic<T: P3>(_: T) {}
}
// witness method for Base.normal
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T32conditional_conformance_subclass4BaseC.0** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8**
// CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.0*, %T32conditional_conformance_subclass4BaseC.0** %0
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE6normalyyF"(i8** %"\CF\84_0_0.P2", %T32conditional_conformance_subclass4BaseC.0* swiftself [[SELF]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness method for Base.generic
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8**
// CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.1*, %T32conditional_conformance_subclass4BaseC.1** %1, align 8
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public class SubclassGeneric<T>: Base<T> {}
public class SubclassConcrete: Base<IsP2> {}
public class SubclassGenericConcrete: SubclassGeneric<IsP2> {}
public func subclassgeneric_generic<T: P2>(_: T.Type) {
takes_p1(SubclassGeneric<T>.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgeneric_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCMa"(i64 0, %swift.type* %T)
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func subclassgeneric_concrete() {
takes_p1(SubclassGeneric<IsP2>.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass24subclassgeneric_concreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = call {{.*}}@"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMD"
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// Lazy witness table accessor for the concrete SubclassGeneric<IsP2> : Base.
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// macosx-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 255)
// macosx-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// macosx-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// ios-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 255)
// ios-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// ios-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// watchos-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 255)
// watchos-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// watchos-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// tvos-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 255)
// tvos-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// tvos-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// linux-gnu-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMD")
// linux-android-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMD")
// windows-msvc-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMD")
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
public func subclassconcrete() {
takes_p1(SubclassConcrete.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass16subclassconcreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0)
// CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[SubclassConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 255)
// CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
public func subclassgenericconcrete() {
takes_p1(SubclassGenericConcrete.self)
}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgenericconcreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0)
// CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[SubclassGenericConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 255)
// CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
| apache-2.0 | d5d5da1f253b7d3b2e011d3b7e3fcbe7 | 70.336957 | 373 | 0.695261 | 3.250619 | false | false | false | false |
P0ed/Magikombat | Magikombat/GameScenes/LevelGeneratorScene.swift | 1 | 3268 | import Foundation
import SpriteKit
func delay(delay: Double, on queue: dispatch_queue_t = dispatch_get_main_queue(), closure: ()->()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(time, queue, closure)
}
final class LevelGeneratorScene: BaseScene {
var world: SKNode!
var level: Level?
override func controlsMap() -> DeviceConfiguration {
return DeviceConfiguration(
buttonsMapTable: [
.Circle: PressAction { self.promise!.failure(.Nothing) }
],
dPadMapTable: [:],
keyboardMapTable: [
DeviceConfiguration.keyCodeForVirtualKey(kVK_Delete): PressAction {
self.promise!.failure(.Nothing)
}
]
)
}
override func didMoveToView(view: SKView) {
scaleMode = .AspectFill
world = SKNode()
addChild(world)
let camera = SKCameraNode()
addChild(camera)
self.camera = camera
camera.position = CGPoint(x: 128 * tileSize, y: 32 * tileSize)
camera.setScale(8)
generateMap()
}
func generateMap() {
let generator = TileMapGenerator(seed: Int(arc4random_uniform(256) + 1), width: 256, height: 64)
let level = generator.generateLevel()
var platforms = level.allNodes
self.level = level
func schedule() {
renderPlatform(platforms.removeFirst().platform)
if platforms.count > 0 { delay(0.05, closure: schedule) }
}
schedule()
}
func renderPlatform(platform: Platform) {
func tileColor(tile: Tile) -> SKColor {
switch tile {
case .Wall: return SKColor(red: 0.8, green: 0.7, blue: 0.3, alpha: 1.0)
case .Platform: return SKColor(red: 0.4, green: 0.5, blue: 0.5, alpha: 1.0)
}
}
let size = CGSize(width: platform.size.width * tileSize, height: platform.size.height * tileSize)
let node = SKSpriteNode(color: tileColor(platform.type), size: size)
node.position = CGPoint(x: platform.position.x * tileSize, y: platform.position.y * tileSize)
node.anchorPoint = CGPointZero
world.addChild(node)
}
override func update(currentTime: NSTimeInterval) {
// Camera movement
let dsVector = appDelegate().eventsController.leftJoystick
if abs(dsVector.dx) + abs(dsVector.dy) > 0.0 {
let cgVector = CGVector(dx: dsVector.dx * 16, dy: dsVector.dy * 16)
let moveAction = SKAction.moveBy(cgVector, duration: 0.2)
self.camera?.runAction(moveAction)
}
// Zooming
var zoom: Double?
if appDelegate().eventsController.leftTrigger > 0 {
zoom = 1 + appDelegate().eventsController.leftTrigger / 24.0
}
if appDelegate().eventsController.rightTrigger > 0 {
zoom = 1 - appDelegate().eventsController.rightTrigger / 24.0
}
if let zoom = zoom {
let action = SKAction.scaleBy(CGFloat(zoom), duration: 0.2)
self.camera?.runAction(action)
}
}
func renderTileMap(tileMap: TileMap) {
tileMap.forEach { tile, position in
func tileColor(tile: Tile) -> SKColor {
switch tile {
case .Wall: return SKColor(red: 0.8, green: 0.7, blue: 0.3, alpha: 1.0)
case .Platform: return SKColor(red: 0.4, green: 0.5, blue: 0.5, alpha: 1.0)
}
}
let node = SKSpriteNode(color: tileColor(tile), size: CGSize(width: tileSize, height: tileSize))
node.position = CGPoint(x: position.x * tileSize, y: position.y * tileSize)
node.anchorPoint = CGPointZero
world.addChild(node)
}
}
}
| mit | 5377bde4b36ca78d68e41e0baa7307a1 | 27.666667 | 100 | 0.690942 | 3.258225 | false | false | false | false |
sgr-ksmt/SUSwiftSugar | SUSwiftSugar/Extensions/UIKit/CGGeometryExtensions.swift | 1 | 3968 | //
// CGGeometryExtensions.swift
import Foundation
import UIKit
public protocol CGFloatType {
var f: CGFloat { get }
}
extension Int: CGFloatType {
public var f: CGFloat {
return CGFloat(self)
}
}
extension Float: CGFloatType {
public var f: CGFloat {
return CGFloat(self)
}
}
extension Double: CGFloatType {
public var f: CGFloat {
return CGFloat(self)
}
}
extension CGFloat: CGFloatType {
public var f: CGFloat {
return self
}
}
public extension CGPoint {
public init(_ x: CGFloatType, _ y: CGFloatType) {
self.init(x: x.f, y: y.f)
}
}
public func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(lhs.x + rhs.x, lhs.y + rhs.y)
}
public func += (inout lhs: CGPoint, rhs: CGPoint) {
lhs = lhs + rhs
}
public func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(lhs.x - rhs.x, lhs.y - rhs.y)
}
public func -= (inout lhs: CGPoint, rhs: CGPoint) {
lhs = lhs - rhs
}
public func * (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(lhs.x * rhs.x, lhs.y * rhs.y)
}
public func *= (inout lhs: CGPoint, rhs: CGPoint) {
lhs = lhs * rhs
}
public func * (point: CGPoint, scalar: CGFloatType) -> CGPoint {
return CGPoint(point.x * scalar.f, point.y * scalar.f)
}
public func *= (inout point: CGPoint, scalar: CGFloatType) {
point = point * scalar
}
public func / (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(lhs.x / rhs.x, lhs.y / rhs.y)
}
public func /= (inout lhs: CGPoint, rhs: CGPoint) {
lhs = lhs / rhs
}
public func / (point: CGPoint, scalar: CGFloatType) -> CGPoint {
return CGPoint(point.x / scalar.f, point.y / scalar.f)
}
public func /= (inout point: CGPoint, scalar: CGFloatType) {
point = point / scalar
}
public extension CGSize {
public init(_ width: CGFloatType, _ height: CGFloatType) {
self.init(width: width.f, height: height.f)
}
}
public func + (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(lhs.width + rhs.width, lhs.height + rhs.height)
}
public func += (inout lhs: CGSize, rhs: CGSize) {
lhs = lhs + rhs
}
public func - (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(lhs.width - rhs.width, lhs.height - rhs.height)
}
public func -= (inout lhs: CGSize, rhs: CGSize) {
lhs = lhs - rhs
}
public func * (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(lhs.width * rhs.width, lhs.height * rhs.height)
}
public func *= (inout lhs: CGSize, rhs: CGSize) {
lhs = lhs * rhs
}
public func * (size: CGSize, scalar: CGFloatType) -> CGSize {
return CGSize(size.width * scalar.f, size.height * scalar.f)
}
public func *= (inout size: CGSize, scalar: CGFloatType) {
size = size * scalar
}
public func / (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(lhs.width / rhs.width, lhs.height / rhs.height)
}
public func /= (inout lhs: CGSize, rhs: CGSize) {
lhs = lhs / rhs
}
public func / (size: CGSize, scalar: CGFloatType) -> CGSize {
return CGSize(size.width / scalar.f, size.height / scalar.f)
}
public func /= (inout size: CGSize, scalar: CGFloatType) {
size = size / scalar
}
public extension CGRect {
public init(_ origin: CGPoint, _ size: CGSize) {
self.init(origin: origin, size: size)
}
public init(_ x: CGFloatType, _ y: CGFloatType, _ width: CGFloatType, _ height: CGFloatType) {
self.init(x: x.f, y: y.f, width: width.f, height: height.f)
}
}
public func + (lhs: CGRect, rhs: CGRect) -> CGRect {
return CGRect(lhs.origin + rhs.origin, lhs.size + rhs.size)
}
public func += (inout lhs: CGRect, rhs: CGRect) {
lhs = lhs + rhs
}
public func - (lhs: CGRect, rhs: CGRect) -> CGRect {
return CGRect(lhs.origin - rhs.origin, lhs.size - rhs.size)
}
public func -= (inout lhs: CGRect, rhs: CGRect) {
lhs = lhs - rhs
}
public func CGRectUnion(rects: [CGRect]) -> CGRect {
return rects.reduce(.null) { CGRectUnion($0, $1) }
} | mit | fdf6e2053da3cc379afd092a63f48e46 | 21.810345 | 98 | 0.628024 | 3.207761 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/model/draw/Stroke.swift | 1 | 396 | import Foundation
open class Stroke {
open let fill: Fill
open let width: Double
open let cap: LineCap
open let join: LineJoin
open let dashes: [Double]
public init(fill: Fill = Color.black, width: Double = 1, cap: LineCap = .butt, join: LineJoin = .miter, dashes: [Double] = []) {
self.fill = fill
self.width = width
self.cap = cap
self.join = join
self.dashes = dashes
}
}
| mit | 9015e999bf265eaff703e9d89d863b5d | 19.842105 | 129 | 0.671717 | 3.069767 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Components/CGFloat+Const.swift | 1 | 3207 | //
// 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 Foundation
import UIKit
import WireCommonComponents
extension Float {
enum ConversationButtonMessageCell {
static let verticalInset: Float = 8
}
}
extension StyleKitIcon.Size {
enum CreatePasscode {
static let iconSize: StyleKitIcon.Size = .custom(11)
static let errorIconSize: StyleKitIcon.Size = .custom(13)
}
}
extension CGFloat {
enum iPhone4Inch {
static let width: CGFloat = 320
static let height: CGFloat = 568
}
enum iPhone4_7Inch {
static let width: CGFloat = 375
static let height: CGFloat = 667
}
enum WipeCompletion {
static let buttonHeight: CGFloat = 48
}
enum PasscodeUnlock {
static let textFieldHeight: CGFloat = 40
static let buttonHeight: CGFloat = 40
static let buttonPadding: CGFloat = 24
static let textFieldPadding: CGFloat = 19
}
enum AccessoryTextField {
static let horizonalInset: CGFloat = 16
}
enum SpinnerButton {
static let contentInset: CGFloat = 16
static let iconSize: CGFloat = StyleKitIcon.Size.tiny.rawValue
static let spinnerBackgroundAlpha: CGFloat = 0.93
}
enum MessageCell {
static var paragraphSpacing: CGFloat = 8
}
enum IconCell {
static let IconWidth: CGFloat = 64
static let IconSpacing: CGFloat = 16
}
enum StartUI {
static public let CellHeight: CGFloat = 56
}
enum SplitView {
static public let LeftViewWidth: CGFloat = 336
/// on iPad 9.7 inch 2/3 mode, right view's width is 396pt, use the compact mode's narrower margin
/// when the window is small then or equal to (396 + LeftViewWidth = 732), use compact mode margin
static public let IPadMarginLimit: CGFloat = 732
}
enum ConversationList {
static let horizontalMargin: CGFloat = 16
}
enum ConversationListHeader {
static let iconWidth: CGFloat = 32
/// 75% of ConversationAvatarView.iconWidth + TeamAccountView.imageInset * 2 = 24 + 2 * 2
static let avatarSize: CGFloat = 28
static let barHeight: CGFloat = 44
}
enum ConversationListSectionHeader {
static let height: CGFloat = 51
}
enum ConversationAvatarView {
static let iconSize: CGFloat = 32
}
enum AccountView {
static let iconWidth: CGFloat = 32
}
enum TeamAccountView {
static let imageInset: CGFloat = 2
}
}
| gpl-3.0 | 3272689cdba109c6036ed497b9760696 | 26.410256 | 107 | 0.663548 | 4.702346 | false | false | false | false |
jngd/advanced-ios10-training | T12E01/ImagesOperation.swift | 1 | 2209 | //
// ImagesOperation.swift
// T12E01
//
// Created by jngd on 30/10/16.
// Copyright © 2016 jngd. All rights reserved.
//
import UIKit
protocol ImagesOperationDelegate {
func imageOperation(_ imagesOperations: ImagesOperation, appData: AppInfo)
}
protocol DataOperationDelegate {
func dataOperation(_ dataOperations: DataOperation, appData: [AppInfo])
}
class DataOperation: Operation {
let dataURL = "https://itunes.apple.com/es/rss/topfreeapplications/limit=50/json"
var delegate: DataOperationDelegate?
var apps: Array<AppInfo> = []
override func main() {
let session = URLSession(configuration:
URLSessionConfiguration.default)
session.downloadTask(with: URL(string: dataURL)!, completionHandler: {
(url,response,error) -> Void in
print(url)
let dataTopApps = try? Data(contentsOf: url!)
var dicTopApps : NSDictionary!
do {
dicTopApps = try JSONSerialization.jsonObject(
with: dataTopApps!,
options: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary
let applications = (dicTopApps["feed"] as! NSDictionary) ["entry"] as!
[NSDictionary]
print(applications)
for app in applications {
let appTemp = AppInfo()
appTemp.name = (app["im:name"] as! NSDictionary) ["label"] as! String
appTemp.index = self.apps.count
appTemp.urlApp = ((app["link"] as! NSDictionary)["attributes"] as!
NSDictionary)["href"] as! String
appTemp.urlImage = (((app["im:image"]
as! NSArray)[2] as! NSDictionary)["label"] as! String)
self.apps.append(appTemp)
}
} catch {
print("Parse failed")
}
self.delegate?.dataOperation(self, appData: self.apps)
}) .resume()
}
}
class ImagesOperation: Operation {
var delegate: ImagesOperationDelegate?
var app: AppInfo!
override func main() {
let session = URLSession(configuration:
URLSessionConfiguration.default)
session.downloadTask(with: URL(string: app.urlImage)!, completionHandler: {
(url,response,error) -> Void in
let image = UIImage(data: try! Data(contentsOf: url!))
self.app.image = image
self.delegate?.imageOperation(self, appData: self.app)
}) .resume()
}
}
| apache-2.0 | 0743da15a1d006b7708a1dc7474b9fab | 25.285714 | 82 | 0.686594 | 3.661692 | false | false | false | false |
tangShunZhi/EmotionTest | EmotionsTest/EmotionsTest/EmoticonKeyBoard/UITextView+Extension.swift | 2 | 2933 | //
// UITextView+Extension.swift
/// 表情键盘的实现
import UIKit
extension UITextView{
//插入我们的每一个每一个点击的表情
func insertEmoticon(emoticon: TSZEmoticons){
//emoji本质是一个字符串
if emoticon.emoji != nil{
replaceRange(selectedTextRange!, withText: emoticon.emoji!)
return
}
//如果是表情图片,需要去拿到本地的图片
if emoticon.chs != nil{
//MARK: 难点: 富文本属性
// 1、创建图片属性的字符串
let attachment = TSZEmoticonsAttachment()
//2、记录默认的表情文字
attachment.chs = emoticon.chs
//表情文字 对应的文字
attachment.image = UIImage(contentsOfFile: emoticon.imagePath)
//3、设置边界
let hight = font?.lineHeight
//设置 文字属性的大小
attachment.bounds = CGRect(x: 0, y: -4, width: hight!, height: hight!)
//图文混排
let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//图片添加到属性
imageText.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
//MARK: 图片文字插入到textView
//1、获取 可变的文字属性
let attrString = NSMutableAttributedString(attributedString: attributedText)
//2、插入图片文字
attrString.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
//3、 使用 可变属性文本 替换文本试图
//光标的位置
let range = selectedRange
//设置内容
attributedText = attrString
//恢复光标的位置
selectedRange = NSRange(location: range.location + 1, length: 0)
}
//我是删除键盘
if emoticon.removeEmotion {
print("我是删除按钮")
// deleteBackward()
}
}
var EmoticonsText: String {
/**
* 属性的保存
*/
let attrString = attributedText
var strM = String()
attrString.enumerateAttributesInRange(NSMakeRange(0, attrString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
if let attrachment = dict["NSAttachment"] as? TSZEmoticonsAttachment{
strM += attrachment.chs!
} else {
//使用range获取文本文字
let str = (attrString.string as NSString).substringWithRange(range)
strM += str
}
}
return strM
}
}
| mit | 0c91f39a5ea60b5f790a005447fdcb8d | 26.408602 | 166 | 0.533543 | 4.988258 | false | false | false | false |
kwakuoowusu/tipApp | tips/TipViewController.swift | 1 | 6141 | //
// TipViewController.swift
// tips
//
// Created by Kwaku Owusu on 12/1/15.
// Copyright © 2015 Kwaku Owusu. All rights reserved.
//
import UIKit
class TipViewController: UIViewController {
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var onePayerLabel: UILabel!
@IBOutlet weak var twoPayerLabel: UILabel!
@IBOutlet weak var threePayerLabel: UILabel!
@IBOutlet weak var fourPayerLabel: UILabel!
@IBOutlet weak var billInfo: UIView!
@IBOutlet weak var tipControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
//load up user preferences
let defaults = NSUserDefaults.standardUserDefaults()
if let defaultIndex = defaults.objectForKey("loadInt"){
tipControl.selectedSegmentIndex = defaultIndex as! Int
}
else{
tipControl.selectedSegmentIndex = 0
}
//check to see if ten minutes has passed
//if ten minutes has expired the dfault bill value becomes 0
//else it will be loaded up from defaults
if let storedTime = defaults.objectForKey("loadtime"){
let loadedMinutes = storedTime as! Int
let timeAtLoad = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.Year.union(NSCalendarUnit.Minute),fromDate: timeAtLoad)
let currentMinutes = components.minute
if (loadedMinutes <= 50 && currentMinutes <= 50 && currentMinutes - loadedMinutes < 10){
if (currentMinutes > loadedMinutes + 10){
billField.text = ""
}
else{
//load up all values in place them into appropriate fields
billField.text = defaults.objectForKey("loadbill") as? String
tipLabel.text = defaults.objectForKey("loadtip") as? String
totalLabel.text = defaults.objectForKey("loadtotal") as? String
onEditingChanged(billField)
}
}
//if the current minutes and stored minutes are greater than 50 and the diffrenc between their value is greater than negative 40 make bill field empty
else{
if(loadedMinutes > -40){
billField.text = ""
}
//else load up defaults
else{
billField.text = defaults.objectForKey("loadbill") as? String
tipLabel.text = defaults.objectForKey("loadtip") as? String
totalLabel.text = defaults.objectForKey("loadtotal") as? String
onEditingChanged(billField)
}
}
}
//make keyboard pop up upon entering app
self.billField.becomeFirstResponder()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//if billfield is empty make the labels fade
if(NSString(string:billField.text!).doubleValue == 0){
//set bottom row to be invisible until user edits
self.billInfo.alpha = 0
}
//load up user prefs
let defaults = NSUserDefaults.standardUserDefaults()
if let defaultIndex = defaults.objectForKey("loadInt"){
tipControl.selectedSegmentIndex = defaultIndex as! Int
}
else{
tipControl.selectedSegmentIndex = 0
}
self.billField.becomeFirstResponder()
}
@IBAction func onEditingChanged(sender: AnyObject) {
UIView.animateWithDuration(0.4, animations: {
//makes all labels in the billInfo subview appear
self.billInfo.alpha = 1
})
let defaults = NSUserDefaults.standardUserDefaults()
//save the time at which the bill was entered
if billField.text != ""{
let timeAtPress = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.Year.union(NSCalendarUnit.Minute),fromDate: timeAtPress)
let minutes = components.minute
defaults.setObject(minutes,forKey:"loadtime")
defaults.setObject(NSString(string:billField.text!),forKey:"loadbill")
defaults.synchronize()
}
var tipPercentages = [0.18,0.2,0.22]
let tipPercentage = tipPercentages[tipControl.selectedSegmentIndex]
let billAmount = NSString(string:billField.text!).doubleValue
let tip = billAmount * tipPercentage
let total = billAmount + tip
//create tip totals for multiple people
let twoSplit = total / 2
let threeSplit = total / 3
let fourSplit = total / 4
tipLabel.text = "\(tip)"
totalLabel.text = "\(total)"
twoPayerLabel.text = "\(twoSplit)"
threePayerLabel.text = "\(threeSplit)"
fourPayerLabel.text = "\(fourSplit)"
//format the strings so that they display with commas and currency sign
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
twoPayerLabel.text = String(format:"$%.2f",twoSplit)
threePayerLabel.text = String(format:"$%.2f",threeSplit)
fourPayerLabel.text = String(format:"$%.2f",fourSplit)
//save bill amounts to display later when view loaded
defaults.setObject(NSString(string:tipLabel.text!).doubleValue,forKey: "loadtip")
defaults.setObject(NSString(string:totalLabel.text!).doubleValue,forKey:"loadtotal")
defaults.synchronize()
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
}
| gpl-2.0 | 55a3837926e0ddb40f488bb59c24824b | 32.369565 | 162 | 0.593485 | 5.20339 | false | false | false | false |
sochalewski/TinySwift | TinySwift/AVAsset.swift | 1 | 737 | //
// AVAsset.swift
// TinySwift
//
// Created by Piotr Sochalewski on 25.09.2016.
// Copyright © 2016 Piotr Sochalewski. All rights reserved.
//
#if !os(watchOS)
import AVFoundation
public extension AVAsset {
/// Returns an image generated from the first frame of the given asset.
var thumbnail: UIImage? {
let thumbnailGenerator = AVAssetImageGenerator(asset: self)
thumbnailGenerator.appliesPreferredTrackTransform = true
var time = duration
time.value = 0
guard let imageRef = try? thumbnailGenerator.copyCGImage(at: time, actualTime: nil) else { return nil }
return UIImage(cgImage: imageRef)
}
}
#endif
| mit | 1e2eb1677d14c0dd097eff6ed739f312 | 29.666667 | 115 | 0.63587 | 4.658228 | false | false | false | false |
BrisyIOS/zhangxuWeiBo | zhangxuWeiBo/zhangxuWeiBo/classes/Compose/View/ZXEmotionGridView.swift | 1 | 6259 | //
// ZXEmotionGridView.swift
// zhangxuWeiBo
//
// Created by zhangxu on 16/6/26.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class ZXEmotionGridView: UIView {
var emotions : NSArray? {
didSet {
// 添加表情
let count = (emotions?.count)!;
let currentEmotionViewCount = (emotionViews?.count)!;
for i in 0..<count {
var emotionView : ZXEmotionView?;
if i >= currentEmotionViewCount {
emotionView = ZXEmotionView();
emotionView?.addTarget(self, action: #selector(emotionClick(_:)), forControlEvents: UIControlEvents.TouchUpInside);
addSubview(emotionView!);
emotionViews?.addObject(emotionView!);
} else {
emotionView = emotionViews![i] as? ZXEmotionView;
}
// 传递模型数据
emotionView?.emotion = emotions![i] as? ZXEmotion;
emotionView?.hidden = false;
}
// 隐藏多余的emotionView
if currentEmotionViewCount > count {
for i in count..<currentEmotionViewCount {
let emotionView = emotionViews![i] as? ZXEmotionView;
emotionView?.hidden = true;
}
}
}
};
private var deleteButton : UIButton?;
lazy var emotionViews : NSMutableArray? = {
let emotionViews = NSMutableArray();
return emotionViews;
}();
private var popView : ZXEmotionPopView? {
didSet {
if popView == nil {
popView = ZXEmotionPopView();
}
}
};
override init(frame: CGRect) {
super.init(frame: frame);
// 添加删除按钮
deleteButton = UIButton();
deleteButton?.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal);
deleteButton?.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted);
deleteButton?.addTarget(self, action: #selector(deleteClick), forControlEvents: UIControlEvents.TouchUpInside);
addSubview(deleteButton!);
// 给自己添加一个长按手势
let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(longPress(_:)));
addGestureRecognizer(longPress);
}
func emotionClick(emotionView : ZXEmotionView?) -> Void {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64.init(UInt64.init(0.25) * NSEC_PER_SEC)), dispatch_get_main_queue()) {
self.selecteEmotion(emotionView?.emotion);
}
}
func longPress(longPress : UILongPressGestureRecognizer?) -> Void {
// 捕获触控点
let point = longPress?.locationInView(longPress?.view);
// 检测触摸点落在哪个表情上
let emotionView = emotionViewWithPoint(point);
if longPress?.state == UIGestureRecognizerState.Ended {
// 移除表情弹出控件
self.popView?.dismiss();
// 选中表情
selecteEmotion(emotionView?.emotion);
} else {
self.popView?.showFromEmotionView(emotionView);
}
}
func selecteEmotion(emotion : ZXEmotion?) -> Void {
// 保存使用记录
ZXEmotionManager.addRecentEmotion(emotion);
// 发出一个选中表情的通知
NSNotificationCenter.defaultCenter().postNotificationName(ZXEmotionDidSelectedNotification, object: nil, userInfo: [ZXSelectedEmotion : emotion!]);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func deleteClick() -> Void {
// 发出一个选中表情的通知
NSNotificationCenter.defaultCenter().postNotificationName(ZXEmotionDidSelectedNotification, object: nil, userInfo: nil);
}
// 根据触摸点返回对应的表情控件
func emotionViewWithPoint(point : CGPoint?) -> ZXEmotionView? {
var foundEmotionView : ZXEmotionView?;
self.emotionViews?.enumerateObjectsUsingBlock({ (emotionView, idx, stop) in
if CGRectContainsPoint(emotionView.frame, point!) && emotionView.hidden == false {
foundEmotionView = emotionView as? ZXEmotionView;
}
})
return foundEmotionView;
}
override func layoutSubviews() {
super.layoutSubviews();
let leftInset = CGFloat(15);
let topInset = CGFloat(15);
// 排序所有表情
let count = self.emotionViews?.count;
let emotionViewW = (self.frame.size.width - 2 * leftInset) / CGFloat(kEmotionMaxCols);
let emotionViewH = (self.frame.size.height - topInset) / CGFloat(kEmotionMaxRows);
print(count);
for i in 0..<count! {
let emotionView = self.emotionViews![i] as? ZXEmotionView;
let emotionViewX = leftInset + CGFloat(i % kEmotionMaxCols) * emotionViewW;
let emotionViewY = topInset + CGFloat(i / kEmotionMaxCols) * emotionViewH;
emotionView?.frame = CGRectMake(emotionViewX, emotionViewY, emotionViewW, emotionViewH);
}
// 删除按钮
let deleteButtonW = emotionViewW;
let deleteButtonH = emotionViewH;
let deleteButtonX = self.frame.size.width - leftInset - deleteButtonW;
let deleteButtonY = self.frame.size.height - deleteButtonH;
deleteButton?.frame = CGRectMake(deleteButtonX, deleteButtonY, deleteButtonW, deleteButtonH);
}
}
| apache-2.0 | 6cf018edc4d3320fc4c0bdc262332b57 | 29.765306 | 155 | 0.550083 | 5.30343 | false | false | false | false |
diegosanchezr/Chatto | ChattoAdditions/Source/Input/Photos/PhotosChatInputItem.swift | 1 | 3389 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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
@objc public class PhotosChatInputItem: NSObject {
public var photoInputHandler: ((UIImage) -> Void)?
public weak var presentingController: UIViewController?
public init(presentingController: UIViewController?) {
self.presentingController = presentingController
}
lazy private var internalTabView: UIButton = {
var button = UIButton(type: .Custom)
button.exclusiveTouch = true
button.setImage(UIImage(named: "camera-icon-unselected", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil), forState: .Normal)
button.setImage(UIImage(named: "camera-icon-selected", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil), forState: .Highlighted)
button.setImage(UIImage(named: "camera-icon-selected", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil), forState: .Selected)
return button
}()
lazy var photosInputView: PhotosInputViewProtocol = {
let photosInputView = PhotosInputView(presentingController: self.presentingController)
photosInputView.delegate = self
return photosInputView
}()
public var selected = false {
didSet {
self.internalTabView.selected = self.selected
if self.selected != oldValue {
self.photosInputView.reload()
}
}
}
}
// MARK: - ChatInputItemProtocol
extension PhotosChatInputItem : ChatInputItemProtocol {
public var presentationMode: ChatInputItemPresentationMode {
return .CustomView
}
public var showsSendButton: Bool {
return false
}
public var inputView: UIView? {
return self.photosInputView as? UIView
}
public var tabView: UIView {
return self.internalTabView
}
public func handleInput(input: AnyObject) {
if let image = input as? UIImage {
self.photoInputHandler?(image)
}
}
}
// MARK: - PhotosChatInputCollectionViewWrapperDelegate
extension PhotosChatInputItem: PhotosInputViewDelegate {
func inputView(inputView: PhotosInputViewProtocol, didSelectImage image: UIImage) {
self.photoInputHandler?(image)
}
}
| mit | 4e81a1d097fb854ceda799d4a655e656 | 37.078652 | 171 | 0.727058 | 5.043155 | false | false | false | false |
WhitneyLand/Jsonable | Jsonable/ViewController.swift | 1 | 4514 | //
// ViewController.swift
// Jsonable
//
// Created by Lee Whitney on 10/15/14.
// Copyright (c) 2014 WhitneyLand. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var jsonView: UITextView!
@IBOutlet weak var swiftView: UITextView!
@IBOutlet weak var getJsonButton: UIButton!
@IBOutlet weak var getSwiftButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
//--------------------------------------------------
// Convert a Swift object to JSON
//
@IBAction func getJson_TouchUp(sender: AnyObject) {
var car = Car()
car.manufacturer = "Porche"
car.height = 51.02
car.weight = 3538
car.cabriolet = true
car.doors = 2
car.maxSpeed = 197
car.buildDate = NSDate(iso: "2014-09-19T07:22:00Z")
car.url = NSURL(string: "http://whitneyland.com")!
car.upgrades = ["Leather Dashboard", "Sport Chrono"]
car.engine = Car.Engine()
car.engine.cooling = "Water"
car.engine.torque = 516.2
car.engine.horsePower = 560
car.engine.turbo = true
var carGuage1 = Car.Gauge()
carGuage1.name = "Spedometer"
carGuage1.max = 200
carGuage1.size = 4
carGuage1.analog = true
car.gauges.append(carGuage1)
var carGuage2 = Car.Gauge()
carGuage2.name = "Tachometer"
carGuage2.max = 9000
carGuage2.size = 6
carGuage2.analog = true
car.gauges.append(carGuage2)
jsonView.text = car.toJsonString()
}
//---------------------------------------------------
// Convert JSON to a Swift object
//
@IBAction func getSwift_TouchUp(sender: AnyObject) {
var json = String(sep:" ",
"{",
" \"cabriolet\": true,",
" \"maxSpeed\": 197,",
" \"doors\": 2,",
" \"url\": \"http://whitneyland.com\",",
" \"weight\": 3538,",
" \"engine\": {",
" \"horsePower\": 560,",
" \"turbo\": true,",
" \"torque\": 516.2,",
" \"cooling\": \"Water\"",
" },",
" \"gauges\": [",
" {",
" \"size\": 4,",
" \"analog\": true,",
" \"name\": \"Spedometer\",",
" \"max\": 200",
" },",
" {",
" \"size\": 6,",
" \"analog\": true,",
" \"name\": \"Tachometer\",",
" \"max\": 9000",
" }",
" ],",
" \"manufacturer\": \"Porche\",",
" \"height\": 51.02,",
" \"upgrades\": [",
" \"Leather Dashboard\",",
" \"Sport Chrono\"",
" ],",
" \"pcodes\": [],",
" \"buildDate\": \"2014-09-19T02:22:00-05:00\"",
"}")
var car = Car()
car.fromJsonString(json)
swiftView.text = car.description
}
//---------------------------------------------
// Use swift classes in API
//
var photos = SampleApi<Photo>()
var users = SampleApi<User>()
func apiTests() {
users.get(1) { (result) in
println(result.text)
if result.success {
dispatch_async(dispatch_get_main_queue(), { // Run UI code on main thread
var user = self.users[0]
self.swiftView.text = user.description
})
}
}
/*
photos.get() { (result) in
dispatch_async(dispatch_get_main_queue(), { // Run UI code on main thread
for photo in self.photos {
println(photo.description)
}
})
}
println(car.toJsonString())
println()
var tests = SampleApi<TestEntity>()
var test = TestEntity()
var text = test.toJsonString()
println(text)
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 00398397f0b63b0dfe3ab26f3af21131 | 28.122581 | 93 | 0.42623 | 4.374031 | false | false | false | false |
oskarpearson/rileylink_ios | MinimedKit/PumpEvents/TempBasalDurationPumpEvent.swift | 1 | 1257 | //
// TempBasalDurationPumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 3/20/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct TempBasalDurationPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let duration: Int
public let timestamp: DateComponents
public init?(availableData: Data, pumpModel: PumpModel) {
length = 7
func d(_ idx:Int) -> Int {
return Int(availableData[idx] as UInt8)
}
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
duration = d(1) * 30
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "TempBasalDuration",
"duration": duration,
]
}
public var description: String {
return String(format: NSLocalizedString("Temporary Basal: %1$d min", comment: "The format string description of a TempBasalDurationPumpEvent. (1: The duration of the temp basal in minutes)"), duration)
}
}
| mit | a8f3373ef25c7a97a5249977e447dbd1 | 27.545455 | 209 | 0.625796 | 4.669145 | false | false | false | false |
Witcast/witcast-ios | WiTcast/ViewController/MainEP/MainEPListView/MainEPToolbarController.swift | 1 | 2620 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
class MainEPToolbarController: ToolbarController {
fileprivate var menuButton: IconButton!
open override func prepare() {
super.prepare()
prepareMenuButton()
prepareStatusBar()
prepareToolbar()
}
}
extension MainEPToolbarController {
fileprivate func prepareMenuButton() {
menuButton = IconButton(image: Icon.cm.menu, tintColor: .black)
menuButton.pulseColor = .white
}
fileprivate func prepareStatusBar() {
statusBarStyle = .lightContent
statusBar.backgroundColor = UIColor.white
}
fileprivate func prepareToolbar() {
toolbar.backgroundColor = UIColor.white
toolbar.leftViews = [menuButton]
menuButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
}
func buttonAction(sender: UIButton!) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "menu"), object: nil)
}
}
| apache-2.0 | a24e27726e815fbc2fc743931d5a6ff7 | 38.69697 | 97 | 0.729389 | 4.789762 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-push | Source/BMSPushUtils.swift | 1 | 5044 | /*
* Copyright 2016 IBM Corp.
* 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 BMSCore
// MARK: - Swift 3 & Swift 4
#if swift(>=3.0)
/**
Utils class for `BMSPush`
*/
open class BMSPushUtils: NSObject {
static var loggerMessage:String = ""
@objc dynamic open class func saveValueToNSUserDefaults (value:Any, key:String) {
UserDefaults.standard.set(value, forKey: key)
UserDefaults.standard.synchronize()
loggerMessage = ("Saving value to NSUserDefaults with Key: \(key) and Value: \(value)")
self.sendLoggerData()
}
@objc dynamic open class func getValueToNSUserDefaults (key:String) -> Any {
var value:Any = ""
if(UserDefaults.standard.value(forKey: key) != nil){
value = UserDefaults.standard.value(forKey: key) ?? ""
}
loggerMessage = ("Getting value for NSUserDefaults Key: \(key) and Value: \(value)")
self.sendLoggerData()
return value
}
@objc dynamic open class func getPushOptionsNSUserDefaults (key:String) -> String {
var value = ""
if key == IMFPUSH_VARIABLES {
if let hasVariable = UserDefaults.standard.value(forKey: HAS_IMFPUSH_VARIABLES) as? Bool, hasVariable != true {
return value
}
}
if(UserDefaults.standard.value(forKey: key) != nil){
let dataValue = UserDefaults.standard.value(forKey: key) as? [String: String]
let jsonData = try! JSONSerialization.data(withJSONObject: dataValue!, options: .prettyPrinted)
value = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
}
loggerMessage = ("Getting value for NSUserDefaults Key: \(key) and Value: \(value)")
self.sendLoggerData()
return value
}
class func getPushSettingValue() -> Bool {
var pushEnabled = false
if ((UIDevice.current.systemVersion as NSString).floatValue >= 8.0) {
if (UIApplication.shared.isRegisteredForRemoteNotifications) {
pushEnabled = true
}
else {
pushEnabled = false
}
} else {
let grantedSettings = UIApplication.shared.currentUserNotificationSettings
if grantedSettings!.types.rawValue & UIUserNotificationType.alert.rawValue != 0 {
// Alert permission granted
pushEnabled = true
}
else{
pushEnabled = false
}
}
return pushEnabled;
}
class func sendLoggerData () {
let devId = BMSPushClient.sharedInstance.getDeviceID()
let testLogger = Logger.logger(name:devId)
Logger.logLevelFilter = LogLevel.debug
testLogger.debug(message: loggerMessage)
Logger.logLevelFilter = LogLevel.info
testLogger.info(message: loggerMessage)
}
class func checkTemplateNotifications(_ body:String) -> String {
let regex = "\\{\\{.*?\\}\\}"
var text = body
guard let optionVariables = UserDefaults.standard.value(forKey: IMFPUSH_VARIABLES) as? [String: String] else { return text }
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
let resultMap = results.flatMap {
Range($0.range, in: text).map {
String(text[$0])
}
}
for val in resultMap {
var temp = val
temp = temp.replacingOccurrences(of: "{{", with: "", options: NSString.CompareOptions.literal, range: nil)
temp = temp.replacingOccurrences(of: "}}", with: "", options: NSString.CompareOptions.literal, range: nil)
temp = temp.replacingOccurrences(of: " ", with: "", options: NSString.CompareOptions.literal, range: nil)
if let templateValue = optionVariables[temp] {
text = text.replacingOccurrences(of: val, with: templateValue)
}
}
return text
} catch {
return text
}
}
}
#endif
| apache-2.0 | da85cb3995c426ff4cca7542a862f373 | 35.59854 | 132 | 0.576984 | 4.896484 | false | false | false | false |
omarojo/MyC4FW | Pods/C4/C4/UI/Filters/DotScreen.swift | 2 | 2502 | // Copyright © 2014 C4
//
// 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 CoreImage
/// Simulates the dot patterns of a halftone screen.
///
/// ````
/// let logo = Image("logo")
/// logo.apply(DotScreen())
/// canvas.add(logo)
/// ````
public struct DotScreen: Filter {
/// The name of the Core Image filter.
public let filterName = "CIDotScreen"
/// The center of the pattern. Defaults to {0,0}
public var center: Point = Point()
/// The width of the dots. Defaults to 2.0
public var width: Double = 2.0
/// The angle of the pattern. Defaults to 0.0
public var angle: Double = 0
/// The sharpness of the edges of the pattern. Defaults to 0.5
public var sharpness: Double = 0.5
///Initializes a new filter
public init() {}
/// Applies the properties of the receiver to create a new CIFilter object
///
/// - parameter inputImage: The image to use as input to the filter.
/// - returns: The new CIFilter object.
public func createCoreImageFilter(_ inputImage: CIImage) -> CIFilter {
let filter = CIFilter(name: filterName)!
filter.setDefaults()
filter.setValue(width, forKey:"inputWidth")
filter.setValue(angle, forKey:"inputAngle")
filter.setValue(sharpness, forKey:"inputSharpness")
filter.setValue(CIVector(cgPoint: CGPoint(center)), forKey:"inputCenter")
filter.setValue(inputImage, forKey: "inputImage")
return filter
}
}
| mit | 2ad48c867c8b0ea183634e3103540849 | 42.12069 | 81 | 0.702119 | 4.410935 | false | false | false | false |
huonw/swift | test/attr/attr_noreturn.swift | 34 | 2780 | // RUN: %target-typecheck-verify-swift
@noreturn func noReturn1(_: Int) {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{33-33= -> Never }}
@noreturn func noReturn2(_: Int)
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{33-33= -> Never}}
@noreturn
func noReturn3(_: Int)
{}
// expected-error@-3 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-10=}}{{23-23= -> Never}}
@noreturn func noReturnInt1(_: Int) -> Int {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{40-43=Never}}
@noreturn func noReturnInt2(_: Int) -> Int
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{40-43=Never}}
@noreturn func noReturnThrows1(_: Int) throws {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{46-46= -> Never }}
@noreturn func noReturnThrows2(_: Int) throws
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{46-46= -> Never}}
@noreturn func noReturnThrowsInt1(_: Int) throws -> Int {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{53-56=Never}}
@noreturn func noReturnThrowsInt2(_: Int) throws -> Int
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{53-56=Never}}
// Test that error recovery gives us the 'Never' return type
let x: Never = noReturn1(0) // No error
// @noreturn in function type declarations
let valueNoReturn: @noreturn () -> ()
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{20-30=}}{{36-38=Never}}
let valueNoReturnInt: @noreturn () -> Int
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{23-33=}}{{39-42=Never}}
let valueNoReturnInt2: @noreturn
() -> Int
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{24-1=}}{{7-10=Never}}
let valueNoReturn2: @noreturn () -> () = {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{21-31=}}{{37-39=Never}}
| apache-2.0 | ecc126cc144bf7748f4bc10ae3efccf4 | 53.509804 | 156 | 0.692806 | 3.721553 | false | false | false | false |
zane001/ZMTuan | ZMTuan/View/Map/CustomCalloutView.swift | 1 | 3499 | //
// CustomCalloutView.swift
// ZMTuan
//
// Created by zm on 5/22/16.
// Copyright © 2016 zm. All rights reserved.
//
import UIKit
let kArrorHeight: CGFloat = 10
let kPortraitMargin: CGFloat = 5
let kImageWidth: CGFloat = 70
let kImageHeight: CGFloat = 50
let kTitleWidth: CGFloat = 120
let kTitleHeight: CGFloat = 20
class CustomCalloutView: UIView {
var image: UIImage!
var title: String!
var subtitle: String!
var imageView: UIImageView!
var titleLabel: UILabel!
var subtitleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.initSubViews()
}
func initSubViews() {
let tap = UITapGestureRecognizer(target: self, action: #selector(onTapCalloutView))
self.addGestureRecognizer(tap)
// 图
self.imageView = UIImageView(frame: CGRectMake(kPortraitMargin, kPortraitMargin, kImageWidth, kImageHeight))
imageView.backgroundColor = UIColor.blackColor()
self.addSubview(imageView)
// 标题
self.titleLabel = UILabel(frame: CGRectMake(kPortraitMargin*2+kImageWidth, kPortraitMargin, kTitleWidth, kTitleHeight))
titleLabel.font = UIFont.systemFontOfSize(14)
titleLabel.textColor = UIColor.whiteColor()
self.addSubview(titleLabel)
// 子标题
self.subtitleLabel = UILabel(frame: CGRectMake(kPortraitMargin*2+kImageWidth, kPortraitMargin*2+kTitleHeight, kTitleWidth, kTitleHeight))
subtitleLabel.font = UIFont.systemFontOfSize(12)
subtitleLabel.textColor = UIColor.lightGrayColor()
self.addSubview(subtitleLabel)
}
override func drawRect(rect: CGRect) {
self.drawInContext(UIGraphicsGetCurrentContext()!)
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOpacity = 1.0
self.layer.shadowOffset = CGSizeMake(0.0, 0.0)
}
func drawInContext(context: CGContextRef) {
CGContextSetLineWidth(context, 2.0)
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
self.getDrawPath(context)
CGContextFillPath(context)
}
func getDrawPath(context: CGContextRef) {
let rect: CGRect = self.bounds
let radius: CGFloat = 6.0
let minX: CGFloat = CGRectGetMinX(rect)
let midX: CGFloat = CGRectGetMidX(rect)
let maxX: CGFloat = CGRectGetMaxX(rect)
let minY: CGFloat = CGRectGetMinY(rect)
let maxY: CGFloat = CGRectGetMaxY(rect) - kArrorHeight
// 画向下的三角形
CGContextMoveToPoint(context, midX+kArrorHeight, maxY)
CGContextAddLineToPoint(context, midX, maxY+kArrorHeight)
CGContextAddLineToPoint(context, midX-kArrorHeight, maxY)
// 画4个圆弧,画完后 current point不在minx,miny,而是在圆弧结束的地方
CGContextAddArcToPoint(context, minX, maxY, minX, minY, radius);
CGContextAddArcToPoint(context, minX, minY, maxX, minY, radius);
CGContextAddArcToPoint(context, maxX, minY, maxX, maxY, radius);
CGContextAddArcToPoint(context, maxX, maxY, midX, maxY, radius);
CGContextClosePath(context);
}
func onTapCalloutView() {
print("title: \(title)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | ad39428c479fcb7b340aeedc540d727c | 32.627451 | 145 | 0.667638 | 4.489529 | false | false | false | false |
DonMag/ScratchPad | Swift3/scratchy/XC8.playground/Pages/CollectionView.xcplaygroundpage/Contents.swift | 1 | 1977 |
import UIKit
import PlaygroundSupport
class MyCVC : UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = .white
self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "PlayCell")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PlayCell", for: indexPath)
cell.backgroundColor = .green
if cell.subviews.count == 1 {
let l = UILabel(frame: cell.bounds.insetBy(dx: 8, dy: 8))
l.backgroundColor = UIColor.lightGray
cell.addSubview(l)
l.text = "\(indexPath.row)"
l.textAlignment = .center
}
return cell
}
}
class MyViewController: UIViewController, UICollectionViewDelegate {
var cvc1: MyCVC?
private func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print(indexPath)
}
init(frame: CGRect) {
super.init(nibName: nil, bundle: nil)
self.view = UIView(frame: frame)
self.view.backgroundColor = UIColor.red
let r = CGRect(x: 20, y: 20, width: 400, height: 140)
cvc1 = MyCVC(collectionViewLayout: UICollectionViewFlowLayout())
// self.addChildViewController(cvc1!)
cvc1?.view.frame = r
self.view.addSubview((cvc1?.view)!)
// cvc1?.didMove(toParentViewController: self)
cvc1?.collectionView?.delegate = self
cvc1?.collectionView?.allowsSelection = true
cvc1?.collectionView?.allowsMultipleSelection = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let rootVC = MyViewController(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
PlaygroundPage.current.liveView = rootVC.view
| mit | 7bf86fb1c1a4d951bc07137619028ba6 | 24.346154 | 127 | 0.735458 | 4.059548 | false | false | false | false |
ualch9/onebusaway-iphone | Carthage/Checkouts/CocoaLumberjack/Sources/CocoaLumberjackSwift/CocoaLumberjack.swift | 2 | 8168 | // Software License Agreement (BSD License)
//
// Copyright (c) 2010-2020, Deusty, LLC
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms,
// with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Neither the name of Deusty nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission of Deusty, LLC.
@_exported import CocoaLumberjack
#if SWIFT_PACKAGE
import CocoaLumberjackSwiftSupport
#endif
extension DDLogFlag {
public static func from(_ logLevel: DDLogLevel) -> DDLogFlag {
return DDLogFlag(rawValue: logLevel.rawValue)
}
public init(_ logLevel: DDLogLevel) {
self = DDLogFlag(rawValue: logLevel.rawValue)
}
/// Returns the log level, or the lowest equivalent.
public func toLogLevel() -> DDLogLevel {
if let ourValid = DDLogLevel(rawValue: rawValue) {
return ourValid
} else {
if contains(.verbose) {
return .verbose
} else if contains(.debug) {
return .debug
} else if contains(.info) {
return .info
} else if contains(.warning) {
return .warning
} else if contains(.error) {
return .error
} else {
return .off
}
}
}
}
/// The log level that can dynamically limit log messages (vs. the static DDDefaultLogLevel). This log level will only be checked, if the message passes the `DDDefaultLogLevel`.
public var dynamicLogLevel = DDLogLevel.all
/// Resets the `dynamicLogLevel` to `.all`.
/// - SeeAlso: `dynamicLogLevel`
@inlinable
public func resetDynamicLogLevel() {
dynamicLogLevel = .all
}
@available(*, deprecated, message: "Please use dynamicLogLevel", renamed: "dynamicLogLevel")
public var defaultDebugLevel: DDLogLevel {
get {
return dynamicLogLevel
}
set {
dynamicLogLevel = newValue
}
}
@available(*, deprecated, message: "Please use resetDynamicLogLevel", renamed: "resetDynamicLogLevel")
public func resetDefaultDebugLevel() {
resetDynamicLogLevel()
}
/// If `true`, all logs (except errors) are logged asynchronously by default.
public var asyncLoggingEnabled = true
@inlinable
public func _DDLogMessage(_ message: @autoclosure () -> Any,
level: DDLogLevel,
flag: DDLogFlag,
context: Int,
file: StaticString,
function: StaticString,
line: UInt,
tag: Any?,
asynchronous: Bool,
ddlog: DDLog) {
// The `dynamicLogLevel` will always be checked here (instead of being passed in).
// We cannot "mix" it with the `DDDefaultLogLevel`, because otherwise the compiler won't strip strings that are not logged.
if level.rawValue & flag.rawValue != 0 && dynamicLogLevel.rawValue & flag.rawValue != 0 {
// Tell the DDLogMessage constructor to copy the C strings that get passed to it.
let logMessage = DDLogMessage(message: String(describing: message()),
level: level,
flag: flag,
context: context,
file: String(describing: file),
function: String(describing: function),
line: line,
tag: tag,
options: [.copyFile, .copyFunction],
timestamp: nil)
ddlog.log(asynchronous: asynchronous, message: logMessage)
}
}
@inlinable
public func DDLogDebug(_ message: @autoclosure () -> Any,
level: DDLogLevel = DDDefaultLogLevel,
context: Int = 0,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line,
tag: Any? = nil,
asynchronous async: Bool = asyncLoggingEnabled,
ddlog: DDLog = .sharedInstance) {
_DDLogMessage(message(), level: level, flag: .debug, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
@inlinable
public func DDLogInfo(_ message: @autoclosure () -> Any,
level: DDLogLevel = DDDefaultLogLevel,
context: Int = 0,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line,
tag: Any? = nil,
asynchronous async: Bool = asyncLoggingEnabled,
ddlog: DDLog = .sharedInstance) {
_DDLogMessage(message(), level: level, flag: .info, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
@inlinable
public func DDLogWarn(_ message: @autoclosure () -> Any,
level: DDLogLevel = DDDefaultLogLevel,
context: Int = 0,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line,
tag: Any? = nil,
asynchronous async: Bool = asyncLoggingEnabled,
ddlog: DDLog = .sharedInstance) {
_DDLogMessage(message(), level: level, flag: .warning, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
@inlinable
public func DDLogVerbose(_ message: @autoclosure () -> Any,
level: DDLogLevel = DDDefaultLogLevel,
context: Int = 0,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line,
tag: Any? = nil,
asynchronous async: Bool = asyncLoggingEnabled,
ddlog: DDLog = .sharedInstance) {
_DDLogMessage(message(), level: level, flag: .verbose, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
@inlinable
public func DDLogError(_ message: @autoclosure () -> Any,
level: DDLogLevel = DDDefaultLogLevel,
context: Int = 0,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line,
tag: Any? = nil,
asynchronous async: Bool = false,
ddlog: DDLog = .sharedInstance) {
_DDLogMessage(message(), level: level, flag: .error, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
/// Returns a String of the current filename, without full path or extension.
///
/// Analogous to the C preprocessor macro `THIS_FILE`.
public func currentFileName(_ fileName: StaticString = #file) -> String {
var str = String(describing: fileName)
if let idx = str.range(of: "/", options: .backwards)?.upperBound {
str = String(str[idx...])
}
if let idx = str.range(of: ".", options: .backwards)?.lowerBound {
str = String(str[..<idx])
}
return str
}
// swiftlint:disable identifier_name
// swiftlint doesn't like func names that begin with a capital letter - deprecated
@available(*, deprecated, message: "Please use currentFileName", renamed: "currentFileName")
public func CurrentFileName(_ fileName: StaticString = #file) -> String {
return currentFileName(fileName)
}
| apache-2.0 | 738d5dc0b1cad41b5a80645cc154ac82 | 41.321244 | 177 | 0.56856 | 5.079602 | false | false | false | false |
liuduoios/DLTagView | DLTagView/DLTagView/DLTagInfo.swift | 1 | 1171 | //
// DLTag.swift
// DLTagView
//
// Created by 刘铎 on 15/11/23.
// Copyright © 2015年 liuduoios. All rights reserved.
//
import UIKit
public protocol TagInfo {
var text: String? { get set }
var attributedText: NSAttributedString? { get set }
var textColor: UIColor { get set }
var backgroundColor: UIColor { get set }
var cornerRadius: CGFloat { get set }
var borderColor: UIColor { get set }
var borderWidth: CGFloat { get set }
var fontSize: CGFloat { get set }
var padding: UIEdgeInsets { get set }
var enabled: Bool { get set }
}
public struct DLTag: TagInfo {
public var text: String?
public var attributedText: NSAttributedString?
public var textColor = UIColor.blackColor()
public var backgroundColor = UIColor.whiteColor()
public var cornerRadius = 0 as CGFloat
public var borderColor = UIColor.blackColor()
public var borderWidth = 1 as CGFloat
public var fontSize = 17 as CGFloat
public var padding = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
public var enabled = true
public init(text: String) {
self.text = text
}
}
| mit | 0fcf6529e5714312df6177d74b3b4bf0 | 26.069767 | 75 | 0.659794 | 4.172043 | false | false | false | false |
mlatham/AFToolkit | Sources/AFToolkit/Extensions/URL+Extensions.swift | 1 | 696 | import Foundation
public extension URL {
// MARK: - Functions
/// Gets this URL's query parameters.
var queryParameters: [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems
else { return nil }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
/// Gets this URL, minus the query.
var urlWithoutQuery: URL? {
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: true) else {
return self
}
components.query = nil
return components.url
}
}
| mit | b825d3cbe38530b0ac79e4a49ddd930e | 26.84 | 87 | 0.645115 | 4.296296 | false | false | false | false |
aestesis/Aether | Sources/Aether/Foundation/Stream.swift | 1 | 19473 | //
// Stream.swift
// Aether
//
// Created by renan jegouzo on 31/03/2016.
// Copyright © 2016 aestesis. 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
#if os(macOS) || os(iOS) || os(tvOS)
import Darwin
#else
import Glibc
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public protocol StreamControl {
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Stream : Atom {
public let onOpen=Event<Void>()
public let onData=Event<Void>()
public let onFreespace=Event<Void>()
public let onClose=Event<Void>()
public let onError=Event<Error>()
public private(set) var timeout:Double=5
var pipes = [Stream : (data:Action<Void>,free:Action<Void>,error:Action<Error>)]()
public var available:Int {
Debug.notImplemented()
return 0
}
public var free:Int {
return Int.max
}
public var availableControl:Int {
return 0
}
public var freeControl:Int {
return Int.max
}
public func close() {
onClose.dispatch(())
for p in pipes.keys {
unpipe(p)
p.close()
}
pipes.removeAll()
onOpen.removeAll()
onData.removeAll()
onFreespace.removeAll()
onClose.removeAll()
onError.removeAll()
}
public func flush() {
if available>0 {
onData.dispatch(())
}
}
public func pipe(to:Stream,pipeError:Bool=false) {
let update = {
let mb=min(to.free,self.available)
if mb > 0 {
if let b=self.read(mb) {
let w = to.write(b,offset:0,count:b.count)
if w != b.count {
Debug.error(Error("write \(w)/\(b.count)",#file,#line))
}
}
}
let mc=min(to.freeControl,self.availableControl)
if mc > 0 {
if let b=self.readControl(mc) {
let w = to.writeControl(b, offset: 0, count: b.count)
if w != b.count {
Debug.error(Error("write \(w)/\(b.count)",#file,#line))
}
}
}
}
if pipeError {
let error = { error in
to.onError.dispatch(error)
}
pipes[to]=(data:onData.always(update),free:to.onFreespace.always(update),error:onError.always(error))
} else {
let error : (Error)->() = { error in
// no piping...
}
pipes[to]=(data:onData.always(update),free:to.onFreespace.always(update),error:onError.always(error))
}
if available>0 {
onData.dispatch(())
}
}
public func unpipe(_ to:Stream) {
if let p = pipes[to] {
self.onData.remove(p.data)
to.onFreespace.remove(p.free)
self.onError.remove(p.error)
pipes[to]=nil
}
}
public func read(_ desired:Int) -> [UInt8]? {
Debug.notImplemented()
return nil
}
public func write(_ data:[UInt8],offset:Int,count:Int) -> Int {
Debug.notImplemented()
return 0
}
public func readControl(_ desired:Int) -> [StreamControl]? {
Debug.notImplemented()
return nil
}
public func writeControl(_ data:[StreamControl],offset:Int,count:Int) -> Int {
Debug.notImplemented()
return 0
}
init(timeout:Double=5,data:(()->())?=nil,free:(()->())?=nil,error:((Error)->())?=nil) {
self.timeout=timeout
if let d=data {
let _ = onData.always(d)
}
if let f=free {
let _ = onFreespace.always(f)
}
if let e=error {
let _ = onError.always(e)
}
super.init()
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class CircularStream : Stream {
private let lock=Lock()
var buffer:[UInt8]
var ro:Int=0
var wo:Int=0
public override var available:Int {
return (ro<=wo) ? (wo-ro) : (buffer.count-(ro-wo))
}
public override var free:Int {
return buffer.count - available
}
public override func write(_ data:[UInt8],offset o:Int,count c:Int) -> Int {
var ret:Int=0
lock.synced {
var offset=o
var count=c
if self.free < count {
let max = ß.time + self.timeout
while self.free<count && ß.time<max {
Thread.sleep(0.01)
}
}
if self.free<count {
ret=0
return
}
while true {
let n=min(self.buffer.count-self.wo, count)
if n<=0 {
break
}
self.buffer.replaceSubrange(self.wo..<self.wo+n, with: data[offset..<offset+n])
offset += n
count -= n
self.wo = (self.wo + n) % self.buffer.count
}
ret = c-count
}
self.onData.dispatch(())
return ret
}
public override func read(_ desired:Int) -> [UInt8]? {
if available == 0 {
let max=ß.time+timeout
while available==0 && ß.time<max {
Thread.sleep(0.01)
}
if available == 0 {
return nil
}
}
var count=min(available,desired)
var data=[UInt8](repeating: 0, count: count)
lock.synced {
var w=0
while true {
let n=min((self.ro>self.wo) ? (self.buffer.count-self.ro) : (self.wo-self.ro), count)
if n<=0 {
break
}
data.replaceSubrange(w..<w+n, with: self.buffer[self.ro..<self.ro+n])
self.ro = (self.ro + n) % self.buffer.count
count -= n
w += n
}
}
onFreespace.dispatch(())
return data
}
init(capacity:Int,timeout:Double=5,data:(()->())?=nil,error:((Error)->())?=nil) {
buffer=[UInt8](repeating: 0, count: capacity)
super.init(timeout:timeout,data:data,error:error)
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class BufferedStream : Stream {
let lock=Lock()
var buffer=[UInt8]()
public override var free:Int {
return Int.max
}
public override var available:Int {
return buffer.count
}
public override func read(_ desired:Int) -> [UInt8]? {
var ret:[UInt8]?=nil
lock.synced {
let n=min(desired,self.buffer.count)
if n>0 {
ret=Array(self.buffer[0..<n])
self.buffer.removeSubrange(0..<n)
}
}
if ret != nil {
onFreespace.dispatch(())
}
return ret
}
public override func write(_ data:[UInt8],offset:Int,count:Int) -> Int {
lock.synced {
self.buffer.append(contentsOf: data[offset..<(offset+count)])
}
onData.dispatch(())
return count
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class UTF8Writer : BufferedStream {
public func write(_ string:String) -> Int {
let b=Array(string.utf8)
return self.write(b, offset: 0, count: b.count)
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class UTF8Reader : BufferedStream {
var cursor=0
public var bigEndian : Bool = false
public func readLine() -> String? {
var str:String?
lock.synced {
while self.cursor<self.buffer.count {
if self.buffer[self.cursor]==10 {
let sub=self.buffer[0..<self.cursor]
str=String(bytes:sub,encoding:String.Encoding.utf8)
if let s=str {
str=s.replacingOccurrences(of:"\r",with:"")
}
self.buffer.removeSubrange(0...self.cursor)
self.cursor=0
break
}
self.cursor += 1
}
}
return str
}
public func readAll() -> String? {
var str:String?
self.onFreespace.dispatch(())
lock.synced {
str=String(bytes: self.buffer, encoding: String.Encoding.utf8)
self.buffer.removeAll()
}
return str
}
public func readUInt8() -> UInt8? {
var b : UInt8? = nil
if available>1 {
if let t=self.read(1) {
b = t[0]
}
}
return b
}
public func readUInt16() -> UInt16? {
var b : UInt16? = nil
if available>2 {
if let t=self.read(2) {
if bigEndian {
b = UInt16(t[1]) | (UInt16(t[0])<<8)
} else {
b = UInt16(t[0]) | (UInt16(t[1])<<8)
}
}
}
return b
}
public func readUInt32() -> UInt32? {
var b : UInt32? = nil
if available>4 {
if let t=self.read(4) {
if bigEndian {
let v0 = UInt32(t[3])
let v1 = UInt32(t[2])<<8
let v2 = UInt32(t[1])<<16
let v3 = UInt32(t[0])<<24
b = v0 | v1 | v2 | v3
} else {
let v0 = UInt32(t[0])
let v1 = UInt32(t[1])<<8
let v2 = UInt32(t[2])<<16
let v3 = UInt32(t[3])<<24
b = v0 | v1 | v2 | v3
}
}
}
return b
}
public func readUInt64() -> UInt64? {
var b : UInt64? = nil
if available>4 {
if let t=self.read(8) {
if bigEndian {
let v0 = UInt64(t[7])
let v1 = UInt64(t[6])<<8
let v2 = UInt64(t[5])<<16
let v3 = UInt64(t[4])<<24
let v4 = UInt64(t[3])<<32
let v5 = UInt64(t[2])<<40
let v6 = UInt64(t[1])<<48
let v7 = UInt64(t[0])<<56
b = v0 | v1 | v2 | v3 | v4 | v5 | v6 | v7
} else {
let v0 = UInt64(t[0])
let v1 = UInt64(t[1])<<8
let v2 = UInt64(t[2])<<16
let v3 = UInt64(t[3])<<24
let v4 = UInt64(t[4])<<32
let v5 = UInt64(t[5])<<40
let v6 = UInt64(t[6])<<48
let v7 = UInt64(t[7])<<56
b = v0 | v1 | v2 | v3 | v4 | v5 | v6 | v7
}
}
}
return b
}
init(bigEndian:Bool=false) {
self.bigEndian = bigEndian
super.init()
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class DataReader : Stream {
let data : Data
var cursor : Int
public init(data:Data) {
self.cursor = 0
self.data = data
super.init()
}
override public var available: Int {
return data.count - cursor
}
override public func read(_ desired: Int) -> [UInt8]? {
let r = min(desired,available)
let b = [UInt8](repeating:0,count:r)
data.copyBytes(to: UnsafeMutablePointer(mutating:b), from: cursor..<cursor+r)
cursor += r
return b
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#if os(iOS) || os(tvOS) || os(OSX)
public class FileReader : Stream {
let filename:String
var file:InputStream?
let size:Int
var read:Int=0
public override var available:Int {
return size-read
}
public override func read(_ desired:Int) -> [UInt8]? {
var data=[UInt8](repeating: 0, count: desired)
//let n=fread(UnsafeMutablePointer(data),1,desired,file)
let n=file!.read(UnsafeMutablePointer(mutating:data), maxLength: desired)
if n>0 {
read += n
if read<size {
wait(0.001).then { _ in
if self.read<self.size {
self.onData.dispatch(())
}
}
} else if read == size {
wait(0.001).then { _ in
self.close()
}
}
if n==desired {
return data
}
data.removeSubrange(n..<desired)
return data
}
return nil
}
public override func close() {
if let f=file {
f.close()
self.file = nil
}
read=size
super.close()
}
init(filename:String,timeout:Double=5,data:(()->())?=nil,error:((Error)->())?=nil) {
self.filename=filename
file = InputStream(fileAtPath: filename)
file!.open()
do {
let ai = try FileManager.default.attributesOfItem(atPath: filename)
size = Int((ai[FileAttributeKey.size]! as AnyObject).int64Value)
} catch {
size = 0
}
super.init(timeout:timeout,data:data,error:error)
wait(0.001).then { _ in
if self.read<self.size {
self.onData.dispatch(())
}
}
}
}
public class FileWriter : Stream {
let filename:String
var file:OutputStream?
let he=HE()
public override func write(_ data:[UInt8],offset:Int,count:Int) -> Int {
return file!.write(UnsafePointer<UInt8>(data)!.advanced(by:offset), maxLength:count)
}
public override func close() {
if let f=file {
f.close()
file = nil
}
}
init(filename:String,timeout:Double=5,data:(()->())?=nil,error:((Error)->())?=nil) {
self.filename=filename
file=OutputStream(toFileAtPath: filename, append: false)
file!.delegate = he
file!.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
file!.open()
super.init(timeout:timeout,data:data,error:error)
}
}
class HE : NSObject,StreamDelegate {
@objc func stream(_ aStream: Foundation.Stream, handle eventCode: Foundation.Stream.Event) {
Debug.info("stream event: \(eventCode)")
}
}
#else
public class FileReader : Stream {
let filename:String
var file:UnsafeMutablePointer<FILE>!
let size:Int
var read:Int=0
public override var available:Int {
return size-read
}
public override func read(_ desired:Int) -> [UInt8]? {
var data=[UInt8](repeating:0, count:desired)
let n=fread(&data,1,desired,file)
if n>0 {
read += n
if read<size {
wait(0.001).then { _ in
if self.read<self.size {
self.onData.dispatch(())
}
}
} else if read == size {
wait(0.001).then { _ in
self.close()
}
}
if n==desired {
return data
}
data.removeSubrange(n..<desired)
return data
}
return nil
}
public override func close() {
if file != nil {
fclose(file)
file = nil
}
read=size
super.close()
}
init(filename:String,timeout:Double=5,data:(()->())?=nil,error:((Error)->())?=nil) {
self.filename=filename
file=fopen(filename, "r")
fseek(file, 0, SEEK_END)
size=ftell(file)
fseek(file, 0,SEEK_SET)
super.init(timeout:timeout,data:data,error:error)
wait(0.001).then { _ in
if self.read<self.size {
self.onData.dispatch(())
}
}
}
}
public class FileWriter : Stream {
let filename:String
let file:UnsafeMutablePointer<FILE>!
public override func write(_ data:[UInt8],offset:Int,count:Int) -> Int {
return fwrite(UnsafePointer<UInt8>(data)!.advanced(by:offset), 1, count, file)
}
public override func close() {
fclose(file)
super.close()
}
init(filename:String,timeout:Double=5,data:(()->())?=nil,error:((Error)->())?=nil) {
self.filename=filename
file=fopen(filename, "w")
super.init(timeout:timeout,data:data,error:error)
}
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
| apache-2.0 | 3f7c8d133744e2cf5c7fac4926a04f81 | 33.702317 | 113 | 0.419663 | 4.595845 | false | false | false | false |
Eonil/Monolith.Swift | Standards/Sources/RFC4627/RFC4627.Operators.swift | 3 | 1259 | //
// RFC4627.Operators.swift
// Monolith
//
// Created by Hoon H. on 10/21/14.
//
//
import Foundation
public func == (l:JSON.Value, r:JSON.Value) -> Bool {
typealias Value = JSON.Value
switch (l,r) {
case let (.Null, .Null): return true
case let (.Boolean(l2), .Boolean(r2)): return l2 == r2
case let (.Number(l2), .Number(r2)): return l2 == r2
case let (.String(l2), .String(r2)): return l2 == r2
case let (.Array(l2), .Array(r2)): return l2 == r2
case let (.Object(l2), .Object(r2)): return l2 == r2
default: return false
}
}
public func == (l:JSON.Number, r:JSON.Number) -> Bool {
typealias Value = JSON.Number
switch (l,r) {
case let (.Integer(l2), .Integer(r2)): return l2 == r2
case let (.Float(l2), .Float(r2)): return l2 == r2
default: return false
}
}
public func == (l:JSON.Value, r:()) -> Bool {
return l.null == true
}
public func == (l:JSON.Value, r:Bool) -> Bool {
return l.boolean == r
}
public func == (l:JSON.Value, r:Int64) -> Bool {
if let v1 = l.number?.integer {
return v1 == r
}
return false
}
public func == (l:JSON.Value, r:Float64) -> Bool {
if let v1 = l.number?.float {
return v1 == r
}
return false
}
public func == (l:JSON.Value, r:String) -> Bool {
return l.string == r
}
| mit | 83f6e5a9fcaacbbf6dcf6a505b09ed5d | 22.754717 | 55 | 0.606037 | 2.398095 | false | false | false | false |
tardieu/swift | test/stdlib/UnicodeScalarDiagnostics.swift | 10 | 3316 | // RUN: %target-typecheck-verify-swift
func isString(_ s: inout String) {}
func test_UnicodeScalarDoesNotImplementArithmetic(_ us: UnicodeScalar, i: Int) {
var a1 = "a" + "b" // OK
isString(&a1)
let a2 = "a" - "b" // expected-error {{binary operator '-' cannot be applied to two 'String' operands}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists:}}
let a3 = "a" * "b" // expected-error {{binary operator '*' cannot be applied to two 'String' operands}}
// expected-note @-1 {{overloads for '*' exist with these partially matching parameter lists:}}
let a4 = "a" / "b" // expected-error {{binary operator '/' cannot be applied to two 'String' operands}}
// expected-note @-1 {{overloads for '/' exist with these partially matching parameter lists:}}
let b1 = us + us // expected-error {{binary operator '+' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
let b2 = us - us // expected-error {{binary operator '-' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists:}}
let b3 = us * us // expected-error {{binary operator '*' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '*' exist with these partially matching parameter lists:}}
let b4 = us / us // expected-error {{binary operator '/' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '/' exist with these partially matching parameter lists:}}
let c1 = us + i // expected-error {{binary operator '+' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note{{overloads for '+' exist with these partially matching parameter lists:}}
let c2 = us - i // expected-error {{binary operator '-' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note{{overloads for '-' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
let c3 = us * i // expected-error {{binary operator '*' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}}
let c4 = us / i // expected-error {{binary operator '/' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}}
let d1 = i + us // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note{{overloads for '+' exist with these partially matching parameter lists:}}
let d2 = i - us // expected-error {{binary operator '-' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note {{expected an argument list of type '(Int, Int)'}}
let d3 = i * us // expected-error {{binary operator '*' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note {{expected an argument list of type '(Int, Int)'}}
let d4 = i / us // expected-error {{binary operator '/' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note {{expected an argument list of type '(Int, Int)'}}
}
| apache-2.0 | 21789f636adc9af32df60e3fcdc0afcc | 96.529412 | 291 | 0.698432 | 4.295337 | false | false | false | false |
blitzagency/events | Events/Channels/Drivers/WatchKitSerializers.swift | 1 | 3664 | //
// WatchKitSerializers.swift
// Events
//
// Created by Adam Venturella on 7/29/16.
// Copyright © 2016 BLITZ. All rights reserved.
//
import Foundation
func serializeWatchKitEvent<Publisher: WatchKitChannel>(_ event: EventPublisher<Publisher>) -> [String: Any]{
var payload = [String: Any]()
payload["channel"] = event.publisher.label as AnyObject
payload["event"] = event.name as AnyObject
return payload
}
func serializeWatchKitEvent<Publisher: WatchKitChannel, Data: Any>(_ event: EventPublisherData<Publisher, Data>) -> [String: Any]{
var payload = [String: Any]()
payload["channel"] = event.publisher.label
payload["event"] = event.name
payload["data"] = event.data
return payload
}
func serializeWatchKitRequestEvent<Publisher: WatchKitChannel>(_ event: EventPublisherData<Publisher, RequestArguments<None>>) -> [String: Any]{
var payload = [String: Any]()
payload["channel"] = event.publisher.label
payload["event"] = event.name
payload["request"] = ["reply": event.data.reply]
return payload
}
func serializeWatchKitRequestEvent<Publisher: WatchKitChannel, Arg0>(_ event: EventPublisherData<Publisher, RequestArguments<(Arg0)>>) -> [String: Any]{
var payload = [String: Any]()
let args = [event.data.tuple!] as [Any]
payload["channel"] = event.publisher.label as AnyObject
payload["event"] = event.name as AnyObject
payload["request"] = ["reply": event.data.reply, "args": args as AnyObject] as AnyObject
return payload
}
func serializeWatchKitRequestEvent<Publisher: WatchKitChannel, Arg0, Arg1>(_ event: EventPublisherData<Publisher, RequestArguments<(Arg0, Arg1)>>) -> [String: Any]{
var payload = [String: Any]()
let (arg0, arg1) = event.data.tuple!
let args = [arg0, arg1] as [Any]
payload["channel"] = event.publisher.label as AnyObject
payload["event"] = event.name as AnyObject
payload["request"] = ["reply": event.data.reply, "args": args as AnyObject] as AnyObject
return payload
}
func deserializeWatchKitRequestReply(_ data: [String: Any]) -> String{
guard let reply = data["reply"] as? String else {
fatalError("WatchKitChannel request must use reply's that are strings, got '\(type(of: data["reply"]))'")
}
return reply
}
func deserializeWatchKitRequestArgs(_ data: [String: Any]) -> [AnyObject]{
guard let args = data["args"] as? [AnyObject] else {
fatalError("WatchKitChannel request must use arguments that are compatible with AnyObject got '\(type(of: data["args"]))'")
}
return args
}
func deserializeWatchKitRequestEventNoArgs(_ data: [String: Any]) -> RequestArguments<None>{
let reply = deserializeWatchKitRequestReply(data)
let args = RequestArguments<None>(reply: reply)
return args
}
func deserializeWatchKitRequestEventArgs1(_ data: [String: Any]) -> RequestArguments<(Any)> {
let reply = deserializeWatchKitRequestReply(data)
let args = deserializeWatchKitRequestArgs(data)
return RequestArguments(reply: reply, tuple: (args[0]))
}
func deserializeWatchKitRequestEventArgs2(_ data: [String: Any]) -> RequestArguments<(Any, Any)> {
let reply = deserializeWatchKitRequestReply(data)
let args = deserializeWatchKitRequestArgs(data)
return RequestArguments(reply: reply, tuple: (args[0], args[1]))
}
func deserializeWatchKitRequestEventArgs3(_ data: [String: Any]) -> RequestArguments<(Any, Any, Any)> {
let reply = deserializeWatchKitRequestReply(data)
let args = deserializeWatchKitRequestArgs(data)
return RequestArguments(reply: reply, tuple: (args[0], args[1], args[2]))
}
| mit | 3ca73be558e051ce51fd47ecd153523b | 29.02459 | 164 | 0.701611 | 4.016447 | false | false | false | false |
billdonner/sheetcheats9 | sc9/SettingsViewController.swift | 1 | 4982 | // SettingsViewController
//
//
import UIKit
final class SettingsViewController: UIViewController {
@IBOutlet weak var versioninfo: UILabel!
func versionInfo() -> String {
var out = ""
if let iDict = Bundle.main.infoDictionary {
if let w = iDict["CFBundleIdentifier"] as? String {
if w != "" {
out.append("'\(w) ")
}
}
if let w = iDict["CFBundleShortVersionString"] as? String {
if w != "" {
out.append("\(w).")
}
}
if let w = iDict["CFBundleVersion"] as? String {
if w != "" {
out.append("\(w)'")
}
}
}
return out
}
@IBOutlet weak var editGigButton: UIButton!
@IBOutlet weak var importButton: UIButton!
@IBOutlet weak var area1Label: UILabel!
@IBOutlet weak var phone1ImageView: UIImageView!
@IBOutlet weak var paperSwitch1: RAMPaperSwitch!
@IBOutlet weak var area2Label: UILabel!
@IBOutlet weak var phone2ImageView: UIImageView!
@IBOutlet weak var paperSwitch2: RAMPaperSwitch!
@IBAction func paperSwitch1Changed(_ sender: RAMPaperSwitch) {
if paperSwitch1.isOn {
// in performance mode, must disable otther
paperSwitch2.isEnabled = false
editGigButton.isEnabled = false
importButton.isEnabled = false
performanceMode = true
} else {
// not in performance mode
paperSwitch2.isEnabled = true
editGigButton.isEnabled = true
importButton.isEnabled = true
performanceMode = false
}
resetNextRestart = false // force this off
paperSwitch2.isOn = false
Persistence.resetCorpusNextRestart = nil
Persistence.resetSurfaceNextRestart = nil
Persistence.performanceMode = performanceMode ? Persistence.Config.modeKey : nil
editGigButton.isHidden = performanceMode
importButton.isHidden = performanceMode
}
@IBAction func paperSwitch2Changed(_ sender: RAMPaperSwitch) {
resetNextRestart = paperSwitch2.isOn
Persistence.resetCorpusNextRestart = resetNextRestart ?
Persistence.Config.corpusKey : nil
Persistence.resetSurfaceNextRestart = resetNextRestart ?
Persistence.Config.surfaceKey : nil
editGigButton.isHidden = paperSwitch2.isOn && !paperSwitch1.isOn
importButton.isHidden = paperSwitch2.isOn && !paperSwitch1.isOn
}
@IBAction func backAction(_ sender: AnyObject) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
editGigButton.backgroundColor = Col.r(.settingsBackground)
importButton.backgroundColor = Col.r(.settingsBackground)
area1Label.backgroundColor = Col.r(.settingsBackground)
area2Label.backgroundColor = Col.r(.settingsBackground)
view.backgroundColor = Col.r(.settingsBackground)
versioninfo.text = versionInfo()
setupPaperSwitch()
paperSwitch1.isOn = performanceMode // load from global
paperSwitch2.isOn = resetNextRestart
paperSwitch1Changed(paperSwitch1)
paperSwitch2Changed(paperSwitch2) }
fileprivate func setupPaperSwitch() {
self.paperSwitch1.animationDidStartClosure = {(onAnimation: Bool) in
self.animateLabel(self.area1Label, onAnimation: onAnimation, duration: self.paperSwitch1.duration)
self.animateImageView(self.phone1ImageView, onAnimation: onAnimation, duration: self.paperSwitch1.duration)
}
self.paperSwitch2.animationDidStartClosure = {(onAnimation: Bool) in
self.animateLabel(self.self.area2Label, onAnimation: onAnimation, duration: self.paperSwitch2.duration)
self.animateImageView(self.phone2ImageView, onAnimation: onAnimation, duration: self.paperSwitch2.duration)
}
}
fileprivate func animateLabel(_ label: UILabel, onAnimation: Bool, duration: TimeInterval) {
UIView.transition(with: label, duration: duration, options: UIViewAnimationOptions.transitionCrossDissolve, animations: {
label.textColor = onAnimation ? Col.r(.settingsText) :Col.r(.settingsButton)
}, completion:nil)
}
fileprivate func animateImageView(_ imageView: UIImageView, onAnimation: Bool, duration: TimeInterval) {
UIView.transition(with: imageView, duration: duration, options: UIViewAnimationOptions.transitionCrossDissolve, animations: {
imageView.image = UIImage(named: onAnimation ? "img_phone_on" : "img_phone_off")
}, completion:nil)
}
}
| apache-2.0 | a76fedb65a637de3df5395314884f925 | 37.921875 | 133 | 0.629868 | 5.052738 | false | false | false | false |
cyrilwei/Tabby2D | Tabby2D-TiledMap/Tiles/TBTiledLayer.swift | 1 | 1851 | //
// TBTiledLayer.swift
// Tabby2D
//
// Created by Cyril Wei on 1/15/16.
// Copyright © 2016 Cyril Wei. All rights reserved.
//
import SpriteKit
import SwiftyJSON
public struct TBTiledLayer {
public var name: String
public var width: Int
public var height: Int
public var baseWorldLayer: WorldLayer
public var zPosition: CGFloat
public var xOffset: Int
public var yOffset: Int
public var data: [Int]
}
extension TBTiledLayer {
public static func parse(json: JSON) -> TBTiledLayer {
let name = json["name"].stringValue
let width = json["width"].intValue
let height = json["height"].intValue
let baseWorldLayer = WorldLayer.layerFromString(json["nodeName"].stringValue)
let zPosition = CGFloat(json["zPosition"].doubleValue)
let xOffset = json["xOffset"].intValue
let yOffset = json["yOffset"].intValue
let data = json["data"].arrayObject as? [Int] ?? [Int]()
return TBTiledLayer(name: name
, width: width
, height: height
, baseWorldLayer: baseWorldLayer
, zPosition: zPosition
, xOffset: xOffset
, yOffset: yOffset
, data: data)
}
}
extension TBTiledLayer: CustomDebugStringConvertible {
public var debugDescription: String {
return "LAYER \(name) - size: \(width)*\(height); data: \(data)"
}
}
extension WorldLayer {
public static func layerFromString(layerName: String) -> WorldLayer {
switch layerName {
case "dynamicbg": return .DynamicBackground
case "characters": return .Characters
case "foreground": return .Foreground
case "camera": return .Camera
case "HUD": return .HUD
default:return .StaticBackground
}
}
} | mit | 85a82183e0f1523e5fafdf161ed972ed | 27.476923 | 85 | 0.620541 | 4.534314 | false | false | false | false |
KTMarc/Marvel-Heroes | Marvel Heroes/Controllers/MasterViewController.swift | 1 | 9050 | //
// MasterViewController.swift
// Marvel Heroes
//
// Created by Marc Humet on 10/4/16.
// Copyright © 2016 SPM. All rights reserved.
//
import UIKit
/**
Collection View with Hero objects
*/
enum toggle {
case enabled
case disabled
}
class MasterViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UISearchResultsUpdating, UISearchControllerDelegate, ModelUpdaterDelegate, UICollectionViewDataSourcePrefetching {
//MARK: - Types
typealias Model = MasterViewControllerModel
//MARK: - Outlets
@IBOutlet weak var collection: UICollectionView!
@IBOutlet weak var containerView: UIView!
//MARK: - Properties
private var searchController: UISearchController!
private var _model = Model()
private var _searchTimer: Timer?
private var _keystrokes = ""
private var _blurEffect : UIBlurEffect?
private var _blurEffectView : UIVisualEffectView?
private var _blurToggle : toggle = .disabled
//MARK: For testing purposes
var countItems : Int {return collection.numberOfItems(inSection: 0)}
//weak var testingDelegate : ModelUpdaterDelegate?
//MARK: - View LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
//Initialization
_model = Model(theDelegate: self)
_model.tearUp()
configureSearchController()
listenToNotifications()
collection.delegate = self
collection.dataSource = self
collection.prefetchDataSource = self
//collection.isPrefetchingEnabled = true
//UI
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 38, height: 38))
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: "navBarLogo.png")
navigationItem.titleView = imageView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collection.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - Notifications 📡
func listenToNotifications(){
NotificationCenter.default.addObserver(self, selector: #selector(MasterViewController.rotationDetected), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
NotificationCenter.default.addObserver(
forName: NSNotification.Name(rawValue: Consts.Notifications.modal_heroDetail_dismissed.rawValue), object: nil, queue: nil) { (_) in
self.searchController.searchBar.becomeFirstResponder()
}
}
//MARK: - Delegate methods
func updateModel(){
DispatchQueue.main.async(execute: {
self.collection.reloadData()
})
}
/**
Adjust Search Bar size when rotating devices
*/
@objc func rotationDetected(){
searchController.searchBar.sizeToFit()
}
// MARK: - Search Results Controller 🔍
func configureSearchController() {
searchController = UISearchController(searchResultsController: SuggestionsVC())
searchController.definesPresentationContext = false
searchController.searchResultsUpdater = self
searchController.searchBar.placeholder = "Search more Heroes, i.e. X-Men"
searchController.searchBar.delegate = self
searchController.delegate = self
searchController.searchBar.sizeToFit()
collection.superview!.addSubview(searchController.searchBar)
self.definesPresentationContext = true
searchController.obscuresBackgroundDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
}
//MARK: - UI Search Controller Delegate
func didPresentSearchController(_ searchController: UISearchController) {
searchController.searchBar.becomeFirstResponder()
}
func willPresentSearchController(_ searchController: UISearchController) {
toggleBackgroundBlur()
//Tap on the search bar
}
func didDismissSearchController(_ searchController: UISearchController) {
//cancel button press
}
func willDismissSearchController(_ searchController: UISearchController) {
toggleBackgroundBlur()
//cancel button press
}
//MARK: - Search Bar Delegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//view.endEditing(true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
_model.resetHeroSuggestions()
(searchController.searchResultsController as! SuggestionsVC).resetHeroSuggestions()
collection.reloadData()
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
_model.resetHeroSuggestions()
(searchController.searchResultsController as! SuggestionsVC).resetHeroSuggestions()
collection.reloadData()
}
///Blurred image background
func toggleBackgroundBlur () {
switch _blurToggle{
case .disabled:
_blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
_blurEffectView = UIVisualEffectView(effect: _blurEffect)
_blurEffectView?.frame = view.bounds
_blurEffectView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(_blurEffectView!)
UIView.animate(withDuration: 0.5) {
self._blurEffectView?.effect = UIBlurEffect(style: .light)
}
_blurToggle = .enabled
case .enabled:
guard let blurEffectToRemove = _blurEffectView else { break }
UIView.animate(withDuration: 0.5, animations: {
blurEffectToRemove.effect = nil
}, completion: { (finished: Bool) -> Void in
blurEffectToRemove.removeFromSuperview()
})
_blurToggle = .disabled
}
}
// MARK: - API request to get suggestions 📡
func updateSearchResults(for searchController: UISearchController) {
if let keystrokes = searchController.searchBar.text , keystrokes != "" {
if let searchTimer = _searchTimer {
searchTimer.invalidate()
}
_keystrokes = keystrokes
_searchTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(MasterViewController.launchNetworkQuery),userInfo: nil, repeats: false)
}
}
@objc func launchNetworkQuery(){
(searchController.searchResultsController as! SuggestionsVC).search(keystrokes: _keystrokes)
}
//MARK: - Collection View Data Soure
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Consts.StoryboardIds.HERO_CELL, for: indexPath) as! HeroCell
let cellViewModel = HeroCellModel(hero: _model[indexPath])
cell.presentCell(cellViewModel)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _model.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 105, height: 105)
}
//MARK: - CollectionView Datasource Prefetching
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
//ImagePreloader.preloadImagesForIndexPaths(indexPaths) // happens on a background queue
_model.prefetch(moreIndexPaths: [indexPaths].count)
}
func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
//ImagePreloader.cancelPreloadImagesForIndexPaths(indexPaths) // again, happens on a background queue
}
//MARK: - Collection View Delegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: Consts.Segues.TO_HERO_DETAIL_VC, sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Consts.Segues.TO_HERO_DETAIL_VC {
if let detailsVC = segue.destination as? HeroDetailVC {
if let selectedHeroIndex = collection.indexPathsForSelectedItems , selectedHeroIndex.count == 1{
let selectedHeroIndex = (selectedHeroIndex[0] as NSIndexPath).row
let hero = _model[heroAt: selectedHeroIndex]
detailsVC.setModelWith(hero)
}
}
}
}
}
| mit | 1e6700fdc6eeab7a7c09dfd82a956802 | 35.897959 | 271 | 0.669912 | 5.642946 | false | false | false | false |
Dwarfartisan/sparsec | sparsec/parsec.playground/section-1.swift | 1 | 487 | // Playground - noun: a place where people can play
import Cocoa
var range: [Int] = [0, 1 ,2, 3, 4, 5, 6, 7, 8, 9]
for idx in range {
print(idx)
}
for idx in 0...10 {
print(idx)
}
var ustr = "abcdef".unicodeScalars
ustr.startIndex.successor()
ustr.endIndex
enum Result<T, E>{
case Success(T)
case Failed(E)
}
typealias Status = Result<String?, String>
let success:Status = Status.Success("Yes")
let failed = Status.Failed("Failed")
let eof = Status.Success(nil)
| mit | 03a4bc49f506251c8f1e37dfb414b256 | 15.793103 | 51 | 0.659138 | 2.933735 | false | false | false | false |
edwinveger/vapor-cloud-test1 | Sources/App/Routes.swift | 1 | 1770 | 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, world!"
}
// response to requests to /info domain
// with a description of the request
get("info") { req in
return req.description
}
post("custom") { req in
let log = self.log
guard let json = req.json else { throw Abort(.badRequest, reason: "Missing JSON payload.") }
guard let query = json["query"]?.string else { throw Abort(.badRequest, reason: "Missing query parameter.") }
let parameters = query.components(separatedBy: " ")
guard !parameters.isEmpty else { throw Abort(.badRequest, reason: "Empty query parameter.") }
if parameters.count == 1 {
guard let parameter = parameters.first else { throw Abort.badRequest }
print("single argument")
log.info("single argument")
return Post(content: String(parameter))
} else {
print("multiple arguments")
log.info("multiple arguments")
var postArray: [Post] = []
for parameter in parameters {
postArray.append(Post(content: String(parameter)))
}
return try postArray.makeJSON()
}
}
try resource("posts", PostController.self)
}
}
| mit | 678406e8c6ee05b96213d13aeae7166f | 31.777778 | 121 | 0.477966 | 5.654952 | false | false | false | false |
lorentey/swift | test/decl/protocol/special/coding/enum_coding_key.swift | 14 | 4020 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Enums with no raw type conforming to CodingKey should get implicit derived
// conformance of methods.
enum NoRawTypeKey : CodingKey {
case a, b, c
}
let _ = NoRawTypeKey.a.stringValue
let _ = NoRawTypeKey(stringValue: "a")
let _ = NoRawTypeKey.a.intValue
let _ = NoRawTypeKey(intValue: 0)
// Enums with raw type of String conforming to CodingKey should get implicit
// derived conformance of methods.
enum StringKey : String, CodingKey {
case a = "A", b, c = "Foo"
}
let _ = StringKey.a.stringValue
let _ = StringKey(stringValue: "A")
let _ = StringKey.a.intValue
let _ = StringKey(intValue: 0)
// Enums with raw type of Int conforming to CodingKey should get implicit
// derived conformance of methods.
enum IntKey : Int, CodingKey {
case a = 3, b, c = 1
}
let _ = IntKey.a.stringValue
let _ = IntKey(stringValue: "a")
let _ = IntKey.a.intValue
let _ = IntKey(intValue: 3)
// Enums with a different raw value conforming to CodingKey should not get
// implicit derived conformance.
enum Int8Key : Int8, CodingKey { // expected-error {{type 'Int8Key' does not conform to protocol 'CodingKey'}}
case a = -1, b = 0, c = 1
}
// Structs conforming to CodingKey should not get implicit derived conformance.
struct StructKey : CodingKey { // expected-error {{type 'StructKey' does not conform to protocol 'CodingKey'}}
}
// Classes conforming to CodingKey should not get implict derived conformance.
class ClassKey : CodingKey { //expected-error {{type 'ClassKey' does not conform to protocol 'CodingKey'}}
}
// Types which are valid for CodingKey derived conformance should not get that
// derivation unless they explicitly conform to CodingKey.
enum X { case a }
enum Y : String { case a } // expected-note {{property 'rawValue' is implicitly declared}}
enum Z : Int { case a } // expected-note {{property 'rawValue' is implicitly declared}}
let _ = X.a.stringValue // expected-error {{value of type 'X' has no member 'stringValue'}}
let _ = Y.a.stringValue // expected-error {{value of type 'Y' has no member 'stringValue'}}
let _ = Z.a.stringValue // expected-error {{value of type 'Z' has no member 'stringValue'}}
let _ = X(stringValue: "a") // expected-error {{'X' cannot be constructed because it has no accessible initializers}}
let _ = Y(stringValue: "a") // expected-error {{incorrect argument label in call (have 'stringValue:', expected 'rawValue:')}}
let _ = Z(stringValue: "a") // expected-error {{incorrect argument label in call (have 'stringValue:', expected 'rawValue:')}}
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'Int'}}
let _ = X.a.intValue // expected-error {{value of type 'X' has no member 'intValue'}}
let _ = Y.a.intValue // expected-error {{value of type 'Y' has no member 'intValue'; did you mean 'rawValue'?}}
let _ = Z.a.intValue // expected-error {{value of type 'Z' has no member 'intValue'; did you mean 'rawValue'?}}
let _ = X(intValue: 0) // expected-error {{'X' cannot be constructed because it has no accessible initializers}}
let _ = Y(intValue: 0) // expected-error {{incorrect argument label in call (have 'intValue:', expected 'rawValue:')}}
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}}
let _ = Z(intValue: 0) // expected-error {{incorrect argument label in call (have 'intValue:', expected 'rawValue:')}}
// Types which are valid for CodingKey derived conformance should get derivation
// through extensions.
enum X2 { case a }
enum Y2 : String { case a }
enum Z2 : Int { case a }
extension X2 : CodingKey {}
extension Y2 : CodingKey {}
extension Z2 : CodingKey {}
let _ = X2.a.stringValue
let _ = Y2.a.stringValue
let _ = Z2.a.stringValue
let _ = X2(stringValue: "a")
let _ = Y2(stringValue: "a")
let _ = Z2(stringValue: "a")
let _ = X2.a.intValue
let _ = Y2.a.intValue
let _ = Z2.a.intValue
let _ = X2(intValue: 0)
let _ = Y2(intValue: 0)
let _ = Z2(intValue: 0)
| apache-2.0 | 0e29afe983fa3b575d7b14fc76917953 | 40.443299 | 126 | 0.698756 | 3.63472 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift | Sources/Tree/110_BalancedBinaryTree.swift | 1 | 1048 | //
// 110_BalancedBinaryTree.swift
// HRSwift
//
// Created by yansong li on 2016-08-05.
// Copyright © 2016 yansong li. All rights reserved.
//
import Foundation
/**
Title:110 Balanced Binary Tree
URL: https://leetcode.com/problems/balanced-binary-tree/
Space: O(n)
Time: O(n)
*/
class BalancedBinaryTree_Solution {
func isBalanced(_ root: TreeNode?) -> Bool {
let(ans, _) = balancedAt(root)
return ans
}
/// Detect whether a treenode is balanced, return the detection result and
/// Depth of the treenode
/// - parameter root: the root treenode.
fileprivate func balancedAt(_ root: TreeNode?) -> (Bool, Int) {
guard let root = root else {
return (true, 0)
}
let (leftBalanced, leftDepth) = balancedAt(root.left)
let (rightBalanced, rightDepth) = balancedAt(root.right)
let subTreeBalanced = leftBalanced && rightBalanced
let noMoreThanOne = abs(leftDepth - rightDepth) <= 1
let depth = max(leftDepth, rightDepth)
return (subTreeBalanced && noMoreThanOne, depth + 1)
}
}
| mit | 01ed5dbdd21dcd7dd01f1beb9bfc7e06 | 26.552632 | 76 | 0.677173 | 3.525253 | false | false | false | false |
JacquesCarette/literate-scientific-software | code/stable/glassbr/src/swift/InputFormat.swift | 1 | 11187 | /** InputFormat.swift
Provides the function for reading inputs
- Authors: Nikitha Krithnan and W. Spencer Smith
*/
import Foundation
/** Reads input from a file with the given file name
- Parameter filename: name of the input file
- Parameter inParams: structure holding the input values
*/
func get_input(_ filename: String, _ inParams: InputParameters) throws -> Void {
var outfile: FileHandle
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("function get_input called with inputs: {".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" filename = ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(filename.utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(", ".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" inParams = ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data("Instance of InputParameters object".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" }".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
var infile: URL
infile = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(filename)
var goolContents: [[String]]
do {
goolContents = try String(contentsOf: infile).components(separatedBy: "\n").map({(l: String) -> [String] in l.components(separatedBy: " ")})
} catch {
throw "Error reading from file."
}
inParams.a = Double(goolContents[1][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.a' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.a).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.b = Double(goolContents[2][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.b' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.b).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.w = Double(goolContents[3][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.w' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.w).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.P_btol = Double(goolContents[4][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.P_btol' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.P_btol).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.TNT = Double(goolContents[5][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.TNT' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.TNT).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.g = goolContents[6][0]
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.g' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(inParams.g.utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.t = Double(goolContents[7][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.t' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.t).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.SD_x = Double(goolContents[8][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.SD_x' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.SD_x).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.SD_y = Double(goolContents[9][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.SD_y' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.SD_y).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
inParams.SD_z = Double(goolContents[10][0])!
do {
outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt"))
try outfile.seekToEnd()
} catch {
throw "Error opening file."
}
do {
try outfile.write(contentsOf: Data("var 'inParams.SD_z' assigned ".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(String(inParams.SD_z).utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.write(contentsOf: Data(" in module InputFormat".utf8))
try outfile.write(contentsOf: Data("\n".utf8))
} catch {
throw "Error printing to file."
}
do {
try outfile.close()
} catch {
throw "Error closing file."
}
}
| bsd-2-clause | a2c0c8a23132f9de61787d8bcf84034c | 30.78125 | 159 | 0.598641 | 4.063567 | false | false | false | false |
haifengkao/ReactiveCache | Example/Pods/HanekeObjc/Pod/Classes/StringCache.swift | 1 | 2897 | import AltHaneke
@objc public class StringCache : NSObject {
public typealias T = String
public typealias FetchType = StringFetch
let cache : AltCache<T>
public override init(){
assert(false, "please specify the cache name")
self.cache = AltCache<T>(name: "default")
}
public init(name: String) {
self.cache = AltCache<T>(name: name)
}
public func size(formatName: String) -> NSNumber{
let diskCache = self.diskCache(formatName: formatName)
if let diskCache = diskCache {
return NSNumber(value: diskCache.size)
}
return NSNumber(value: 0.0)
}
public func cachePath(_ formatName: String) -> String{
let diskCache = self.diskCache(formatName: formatName)
if let diskCache = diskCache {
return diskCache.path
}
return ""
}
public func pathForKey(_ key: String, formatName: String) -> String {
let diskCache = self.diskCache(formatName: formatName)
if let diskCache = diskCache {
return diskCache.path(forKey: key)
}
return ""
}
public func diskCache(formatName: String) -> AltDiskCache? {
if let (_, _, diskCache) = self.cache.formats[formatName] {
return diskCache
}
return nil
}
public func addFormat(name: String, diskCapacity : UInt64 = UINT64_MAX, transform: ((T) -> (T))? = nil) {
let format = Format<T>(name: name, diskCapacity: diskCapacity, transform: transform)
return self.cache.addFormat(format)
}
public func set(value: T, key: String, formatName: String, success succeed: ((T) -> ())? = nil) {
self.cache.set(value: value, key: key, formatName: formatName, success: succeed)
}
public func remove(key: String, formatName: String) {
self.cache.remove(key: key, formatName: formatName)
}
public func removeAll(_ completion: (() -> ())? = nil) {
self.cache.removeAll(completion)
}
public func fetch(key: String, formatName: String, failure fail : FetchType.Failer? = nil, success succeed : FetchType.Succeeder? = nil) -> FetchType {
let fetch = self.cache.fetch(key: key, formatName: formatName, failure: fail, success: succeed)
return FetchType(fetch: fetch);
}
}
@objc public class StringFetch : NSObject {
public typealias T = String
public typealias Succeeder = (T) -> ()
public typealias Failer = (Error?) -> ()
let fetch : Fetch<T>
public init(fetch: Fetch<T>){
self.fetch = fetch
}
@discardableResult open func onSuccess(_ onSuccess: @escaping Succeeder) -> Self {
self.fetch.onSuccess(onSuccess)
return self
}
@discardableResult open func onFailure(_ onFailure: @escaping Failer) -> Self {
self.fetch.onFailure(onFailure)
return self
}
}
| mit | 5788aa9a7dc11e553b70bd8511459409 | 31.550562 | 155 | 0.623749 | 4.198551 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/PledgeCTAContainerViewViewModel.swift | 1 | 6511 | import KsApi
import Prelude
import ReactiveExtensions
import ReactiveSwift
public enum PledgeCTAContainerViewContext {
case projectPamphlet
case projectDescription
}
public typealias PledgeCTAContainerViewData = (
projectOrError: Either<(Project, RefTag?), ErrorEnvelope>,
isLoading: Bool,
context: PledgeCTAContainerViewContext
)
public protocol PledgeCTAContainerViewViewModelInputs {
func configureWith(value: PledgeCTAContainerViewData)
func pledgeCTAButtonTapped()
}
public protocol PledgeCTAContainerViewViewModelOutputs {
var activityIndicatorIsHidden: Signal<Bool, Never> { get }
var buttonStyleType: Signal<ButtonStyleType, Never> { get }
var buttonTitleText: Signal<String, Never> { get }
var notifyDelegateCTATapped: Signal<PledgeStateCTAType, Never> { get }
var pledgeCTAButtonIsHidden: Signal<Bool, Never> { get }
var retryStackViewIsHidden: Signal<Bool, Never> { get }
var spacerIsHidden: Signal<Bool, Never> { get }
var stackViewIsHidden: Signal<Bool, Never> { get }
var subtitleText: Signal<String, Never> { get }
var titleText: Signal<String, Never> { get }
}
public protocol PledgeCTAContainerViewViewModelType {
var inputs: PledgeCTAContainerViewViewModelInputs { get }
var outputs: PledgeCTAContainerViewViewModelOutputs { get }
}
public final class PledgeCTAContainerViewViewModel: PledgeCTAContainerViewViewModelType,
PledgeCTAContainerViewViewModelInputs, PledgeCTAContainerViewViewModelOutputs {
public init() {
let projectOrError = self.configData.signal
.skipNil()
.filter(second >>> isFalse)
.map(first)
let isLoading = self.configData.signal
.skipNil()
.map(second)
let project = projectOrError
.map(Either.left)
.skipNil()
.map(first)
let projectError = projectOrError
.map(Either.right)
.skipNil()
self.activityIndicatorIsHidden = isLoading
.negate()
let backing = project.map { $0.personalization.backing }
let pledgeState = Signal.combineLatest(project, backing)
.map(pledgeCTA(project:backing:))
let inError = Signal.merge(
projectError.ignoreValues().mapConst(true),
project.ignoreValues().mapConst(false)
)
let updateButtonStates = Signal.merge(
projectOrError.ignoreValues(),
isLoading.filter(isFalse).ignoreValues()
)
self.notifyDelegateCTATapped = pledgeState
.takeWhen(self.pledgeCTAButtonTappedProperty.signal)
self.retryStackViewIsHidden = inError
.map(isFalse)
.takeWhen(updateButtonStates)
.merge(with: isLoading.filter(isTrue).mapConst(true))
.skipRepeats()
self.pledgeCTAButtonIsHidden = inError
.map(isTrue)
.takeWhen(updateButtonStates)
.merge(with: isLoading.filter(isTrue).mapConst(true))
.skipRepeats()
self.buttonStyleType = pledgeState.map { $0.buttonStyle }
self.buttonTitleText = pledgeState.map { $0.buttonTitle }
let stackViewAndSpacerAreHidden = pledgeState.map { $0.stackViewAndSpacerAreHidden }
self.spacerIsHidden = stackViewAndSpacerAreHidden
self.stackViewIsHidden = stackViewAndSpacerAreHidden
self.titleText = pledgeState.map { $0.titleLabel }.skipNil()
self.subtitleText = Signal.combineLatest(project, pledgeState)
.map(subtitle(project:pledgeState:))
let pledgeTypeAndProject = Signal.combineLatest(pledgeState, project)
// Tracking
pledgeTypeAndProject
.takeWhen(self.pledgeCTAButtonTappedProperty.signal)
.observeValues { state, project in
let optimizelyProps = optimizelyProperties() ?? [:]
AppEnvironment.current.ksrAnalytics.trackPledgeCTAButtonClicked(
stateType: state,
project: project,
optimizelyProperties: optimizelyProps
)
}
}
fileprivate let configData = MutableProperty<PledgeCTAContainerViewData?>(nil)
public func configureWith(value: PledgeCTAContainerViewData) {
self.configData.value = value
}
fileprivate let pledgeCTAButtonTappedProperty = MutableProperty(())
public func pledgeCTAButtonTapped() {
self.pledgeCTAButtonTappedProperty.value = ()
}
public var inputs: PledgeCTAContainerViewViewModelInputs { return self }
public var outputs: PledgeCTAContainerViewViewModelOutputs { return self }
public let activityIndicatorIsHidden: Signal<Bool, Never>
public let buttonStyleType: Signal<ButtonStyleType, Never>
public let buttonTitleText: Signal<String, Never>
public let notifyDelegateCTATapped: Signal<PledgeStateCTAType, Never>
public let pledgeCTAButtonIsHidden: Signal<Bool, Never>
public let retryStackViewIsHidden: Signal<Bool, Never>
public let spacerIsHidden: Signal<Bool, Never>
public let stackViewIsHidden: Signal<Bool, Never>
public let subtitleText: Signal<String, Never>
public let titleText: Signal<String, Never>
}
// MARK: - Functions
private func pledgeCTA(project: Project, backing: Backing?) -> PledgeStateCTAType {
guard let projectBacking = backing, project.personalization.isBacking == .some(true) else {
if currentUserIsCreator(of: project) {
return PledgeStateCTAType.viewYourRewards
}
return project.state == .live ? PledgeStateCTAType.pledge : PledgeStateCTAType.viewRewards
}
// NB: Add error case back once correctly returned
switch (project.state, projectBacking.status) {
case (.live, _):
return .manage
case (.successful, .errored):
return .fix
case (_, _):
return .viewBacking
}
}
private func subtitle(project: Project, pledgeState: PledgeStateCTAType) -> String {
guard let backing = project.personalization.backing else { return "" }
if pledgeState == .fix { return pledgeState.subtitleLabel ?? "" }
let amount = formattedPledge(amount: backing.amount, project: project)
let reward = backing.reward
?? project.rewards.first { $0.id == backing.rewardId }
?? Reward.noReward
guard let rewardTitle = reward.title else { return "\(amount)" }
return "\(amount) • \(rewardTitle)"
}
private func formattedPledge(amount: Double, project: Project) -> String {
let numberOfDecimalPlaces = amount.truncatingRemainder(dividingBy: 1) == 0 ? 0 : 2
let formattedAmount = String(format: "%.\(numberOfDecimalPlaces)f", amount)
let projectCurrencyCountry = projectCountry(forCurrency: project.stats.currency) ?? project.country
return Format.formattedCurrency(
formattedAmount,
country: projectCurrencyCountry,
omitCurrencyCode: project.stats.omitUSCurrencyCode
)
}
| apache-2.0 | 0cc950b89f5a1865c85f245aa24fc899 | 33.078534 | 101 | 0.741281 | 4.501383 | false | false | false | false |
spweau/Test_DYZB | Test_DYZB/Test_DYZB/Classes/Tool/Extention/UIBarButtonItem-Extention.swift | 1 | 1733 | //
// UIBarButtonItem-Extention.swift
// Test_DYZB
//
// Created by Spweau on 2017/2/22.
// Copyright © 2017年 sp. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
// // 1. 扩充 类方法
// class func createItem(imageName: String , hightImageName : String , size: CGSize) -> UIBarButtonItem {
//
// let btn = UIButton()
// btn.setImage(UIImage(named:imageName), for: .normal)
// btn.setImage(UIImage(named:hightImageName), for: .highlighted)
// btn.frame = CGRect(origin: CGPoint(x:0,y:0), size: size)
// btn.backgroundColor = UIColor.red
// return UIBarButtonItem(customView: btn)
// }
// 2. 扩充 构造方法
// 便利构造函数
// 1. convenience 开头
// 2. 在构造函数中必须明确为调用一个设计的构造函数(并且这个设计的构造函数是使用self来调用的)
convenience init(imageName: String , hightImageName : String = "" , size:CGSize = CGSize(width: 0, height: 0)) {
// 1. 创建UIButton
let btn = UIButton()
// 2. btn 的图片
btn.setImage(UIImage(named:imageName), for: .normal)
if hightImageName != "" {
btn.setImage(UIImage(named:hightImageName), for: .highlighted)
}
// 3. 设置 frame
if size == CGSize(width: 0, height: 0) {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint(x:0,y:0), size: size)
}
btn.backgroundColor = UIColor.red
// 4. 创建 UIBarButtonItem
self.init(customView: btn)
}
}
| mit | f667b3cc5c82c563ebbb71bc7c5ee165 | 24.645161 | 118 | 0.545283 | 3.945409 | false | false | false | false |
jvesala/teknappi | teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift | 30 | 1426 | //
// Do.swift
// Rx
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DoSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = Do<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
do {
try parent.eventHandler(event)
observer?.on(event)
if event.isStopEvent {
self.dispose()
}
}
catch let error {
observer?.on(.Error(error))
self.dispose()
}
}
}
class Do<Element> : Producer<Element> {
typealias EventHandler = Event<Element> throws -> Void
let source: Observable<Element>
let eventHandler: EventHandler
init(source: Observable<Element>, eventHandler: EventHandler) {
self.source = source
self.eventHandler = eventHandler
}
override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = DoSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return self.source.subscribeSafe(sink)
}
} | gpl-3.0 | dc5da349f14f151166ac2e28cbb0bfe4 | 24.945455 | 139 | 0.591865 | 4.347561 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCap/Utils/Notify.swift | 1 | 1148 | //
// Notify.swift
// BlueCap
//
// Created by Troy Stribling on 9/24/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import UIKit
class Notify {
class func resetEventCount() {
eventCount = 0;
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}
class func withMessage(message:String) {
if UIApplication.sharedApplication().applicationState != .Active && self.getEnabled(){
eventCount += 1
let localNotification = UILocalNotification()
localNotification.alertBody = message
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = eventCount
UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
}
}
class func setEnable(enabled:Bool = true) {
NSUserDefaults.standardUserDefaults().setBool(enabled, forKey:"notifications")
}
class func getEnabled() -> Bool {
return NSUserDefaults.standardUserDefaults().boolForKey("notifications")
}
}
var eventCount = 0
| mit | 36a5eb841a5afe611de3d574b80cb5f5 | 27.7 | 94 | 0.670732 | 5.572816 | false | false | false | false |
timmystephani/monopoly | ios/Monopoly/Monopoly/Http.swift | 1 | 4715 | //
// Http.swift
// Monopoly
//
// Created by Tim Stephani on 7/18/15.
// Copyright (c) 2015 Tim Stephani. All rights reserved.
//
import UIKit
class Http {
static func post(params : AnyObject, url : String, postCompleted : (succeeded: Bool, response: NSDictionary) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
println("Url: " + url)
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Token " + Globals.auth_token, forHTTPHeaderField: "Authorization")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
//postCompleted(succeeded: false, msg: "Error")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
postCompleted(succeeded: true, response: parseJSON)
return
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
//postCompleted(succeeded: false, msg: "Error")
}
}
})
task.resume()
}
static func get(url : String, postCompleted : (succeeded: Bool, response: NSArray) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
//println("Url: " + url)
var err: NSError?
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Token " + Globals.auth_token, forHTTPHeaderField: "Authorization")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body:")
println(strData)
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSArray
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
println("Error could not parse JSON: '\(strData)'")
//postCompleted(succeeded: false, msg: "Error")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
postCompleted(succeeded: true, response: parseJSON)
return
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
//postCompleted(succeeded: false, msg: "Error")
}
}
})
task.resume()
}
}
| mit | 6de3ea865ef3f5db88d24dc147d98c6f | 44.776699 | 122 | 0.576882 | 5.238889 | false | false | false | false |
kiavashfaisali/KFWatchKitAnimations | Example/KFWatchKitAnimations/View Controllers/AnimationsViewController.swift | 1 | 6992 | //
// Created by Kiavash Faisali on 2015-02-17.
// Copyright (c) 2016 Kiavash Faisali. All rights reserved.
//
import UIKit
import KFWatchKitAnimations
final class AnimationsViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var watchView: UIView!
@IBOutlet weak var countdownLabel: UILabel!
@IBOutlet weak var heroImageView: UIImageView!
@IBOutlet weak var visualEffectView: UIVisualEffectView!
@IBOutlet weak var heroCenterYAlignmentConstraint: NSLayoutConstraint!
@IBOutlet weak var heroWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var watchKitAnimationsCenterYAlignmentConstraint: NSLayoutConstraint!
@IBOutlet weak var watchKitAnimationsLabel: UILabel!
@IBOutlet weak var watchViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var watchViewHeightConstraint: NSLayoutConstraint!
var circle: CAShapeLayer!
var animation: CABasicAnimation!
var counter = 5
var shouldFadeOut = false
let attributedString = NSMutableAttributedString(string: "KFWatchKitAnimations")
var currentCharacterLocation = 0
// MARK: - Memory Warning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Status Bar Methods
override var prefersStatusBarHidden : Bool {
return true
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Always make sure the background of the view you're recording is set to clearColor, unless you really intend to keep the background with it.
self.watchView.backgroundColor = UIColor.clear
// If your background color is clearColor, you should set opaque to false for better performance during recording.
self.watchView.isOpaque = false
self.visualEffectView.layer.cornerRadius = self.heroWidthConstraint.constant / 2
self.heroImageView.layer.cornerRadius = self.heroWidthConstraint.constant / 2
self.circle = CAShapeLayer()
self.circle.path = UIBezierPath(arcCenter: CGPoint(x: self.watchViewWidthConstraint.constant/2, y: self.watchViewHeightConstraint.constant/2), radius: 50, startAngle: CGFloat(-M_PI_2), endAngle: CGFloat(3.0 * M_PI_2), clockwise: true).cgPath
self.circle.fillColor = nil
self.circle.strokeColor = UIColor(red: 180/255.0, green: 1.0, blue: 167/255.0, alpha: 1.0).cgColor
self.circle.lineWidth = 2
self.animation = CABasicAnimation(keyPath: "strokeEnd")
self.animation.duration = 2
self.animation.fromValue = 0
self.animation.toValue = 1
self.animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
/* BEGIN ANIMATION CHAIN PHASE 1: DRAW GREEN CIRCLE */
self.watchView.snapshots(duration: self.animation.duration, imageName: "drawGreenCircle", animations: {
self.circle.add(self.animation, forKey: "circleAnimation")
self.watchView.layer.addSublayer(self.circle)
/* END ANIMATION CHAIN PHASE 1 */
}) { success in
/* BEGIN ANIMATION CHAIN PHASE 2: COUNTDOWN FROM 5 AND FADE OUT BLUR */
self.watchView.snapshots(duration: 7.7, imageName: "countdownAndRemoveBlur", animations: {
let sequenceDuration = 0.7
self.countdownAnimation(sequenceDuration: sequenceDuration) {
UIView.animate(withDuration: sequenceDuration, animations: {
self.visualEffectView.alpha = 0.0
self.circle.removeFromSuperlayer()
self.heroImageView.layer.borderWidth = 1.0
self.heroImageView.layer.borderColor = UIColor(red: 170/255.0, green: 211/255.0, blue: 1.0, alpha: 1.0).cgColor
}) { _ in
self.visualEffectView.removeFromSuperview()
}
}
/* END ANIMATION CHAIN PHASE 2 */
}) { _ in
/* BEGIN ANIMATION CHAIN PHASE 3: PLACE IMAGE AT THE TOP AND SLIDE IN TITLE FROM UNDERNEATH WHILE FADING IN */
self.watchView.snapshots(duration: 1.0, imageName: "verticalShiftAndFadeIn", animations: {
self.heroCenterYAlignmentConstraint.constant = 30
self.watchKitAnimationsCenterYAlignmentConstraint.constant = -35
UIView.animate(withDuration: 1.0, animations: {
self.watchView.layoutIfNeeded()
self.watchKitAnimationsLabel.alpha = 1.0
})
}) { _ in
// Kick off the text refresh beforehand and simply record the view without passing in any animations to the closure.
Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(AnimationsViewController.refreshText), userInfo: nil, repeats: true)
// ANIMATION CHAIN PHASE 4: INFINITE YELLOW CHARACTER JUMP
self.watchView.snapshots(duration: 3.0, imageName: "yellowCharacterJump")
}
/* END ANIMATION CHAIN PHASE 3 */
}
}
}
// MARK: - Miscellaneous Methods
func countdownAnimation(sequenceDuration: TimeInterval, completion: (() -> Void)? = nil) {
UIView.animate(withDuration: sequenceDuration, animations: {
if self.shouldFadeOut {
self.countdownLabel.alpha = 0.1
}
else {
self.countdownLabel.alpha = 1.0
self.countdownLabel.text = "\(self.counter)"
}
}) { _ in
self.shouldFadeOut = !self.shouldFadeOut
if !self.shouldFadeOut {
self.counter -= 1
}
if self.counter > 0 {
self.countdownAnimation(sequenceDuration: sequenceDuration, completion: completion)
}
else {
completion?()
}
}
}
func refreshText() {
let previousCharacterLocation = (self.currentCharacterLocation - 1 + self.attributedString.length) % self.attributedString.length
self.attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow, range: NSMakeRange(self.currentCharacterLocation, 1))
self.attributedString.removeAttribute(NSForegroundColorAttributeName, range: NSMakeRange(previousCharacterLocation, 1))
self.watchKitAnimationsLabel.attributedText = self.attributedString
self.currentCharacterLocation = (self.currentCharacterLocation + 1) % self.attributedString.length
}
}
| mit | 2752d30d0f211c86478284f1feb8387f | 46.890411 | 249 | 0.636299 | 5.129861 | false | false | false | false |
polkahq/PLKSwift | Sources/polka/network/PLKFormMultipart.swift | 1 | 6874 | //
// PLKFormMultipart.swift
//
// Created by Alvaro Talavera on 5/12/16.
// Copyright © 2016 Polka. All rights reserved.
//
import UIKit
import SwiftyJSON
public class PLKFormMultipart {
public var task:URLSessionDataTask?
let url:URL?
let session:URLSession
private var _formdata:Dictionary<String,Any>
private var _header:Dictionary<String,String>?
public init(url:String) {
self.url = URL(string: url)
let configuration = URLSessionConfiguration.default
self.session = URLSession(configuration: configuration)
_formdata = Dictionary<String,Any>()
}
// -----------
private func getRequest() -> URLRequest? {
guard let url = self.url else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = "post"
if let header = _header {
for (key, value) in header {
request.addValue(value, forHTTPHeaderField: key)
}
}
let boundary:String = PLKHash.uuid()
request.addValue("multipart/form-data; boundary=" + boundary, forHTTPHeaderField: "Content-Type")
let body:NSMutableData = NSMutableData()
for (key, value) in _formdata {
if(value is String) {
body.append(NSString(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "%@\r\n", value as! String).data(using: String.Encoding.utf8.rawValue)!)
}
if(value is Int) {
body.append(NSString(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "%i\r\n", value as! Int).data(using: String.Encoding.utf8.rawValue)!)
}
if(value is Float) {
body.append(NSString(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "%f\r\n", value as! Float).data(using: String.Encoding.utf8.rawValue)!)
}
if(value is UIImage) {
let imageData:Data = UIImageJPEGRepresentation(value as! UIImage, 0.8)!
body.append(NSString(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n", key, PLKHash.uuid()).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(string: "Content-Type: image/jpeg\r\n\r\n").data(using: String.Encoding.utf8.rawValue)!)
body.append(imageData)
body.append(NSString(string: "\r\n").data(using: String.Encoding.utf8.rawValue)!)
}
if(value is NSData) {
let tData:NSData = value as! NSData
body.append(NSString(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(format: "Content-Disposition: form-data; name=\"%@\"; filename=\"%@.bin\"\r\n", key, PLKHash.uuid()).data(using: String.Encoding.utf8.rawValue)!)
body.append(NSString(string: "Content-Type: application/octet-stream\r\n\r\n").data(using: String.Encoding.utf8.rawValue)!)
body.append(tData as Data)
body.append(NSString(string: "\r\n").data(using: String.Encoding.utf8.rawValue)!)
}
}
body.append(NSString(format: "--%@--\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
request.httpBody = body as Data
return request
}
public func setHeader(params:Dictionary<String,String>) -> PLKFormMultipart {
_header = params
return self
}
public func addFormDataString(name:String, data string:String) -> PLKFormMultipart {
_formdata[name] = string
return self
}
public func addFormDataInt(name:String, data number:Int) -> PLKFormMultipart {
_formdata[name] = number
return self
}
public func addFormDataFloat(name:String, data number:Float) -> PLKFormMultipart {
_formdata[name] = number
return self
}
public func addFormDataUIImage(name:String, data image:UIImage) -> PLKFormMultipart {
_formdata[name] = image
return self
}
public func addFormData(name:String, data image:NSData) -> PLKFormMultipart {
_formdata[name] = image
return self
}
public func executeWithData(completion:@escaping (_ data: Data?, _ response: URLResponse?, _ error:Error?) -> Void) {
guard let request = self.getRequest() else {
DispatchQueue.main.sync {
completion(nil, nil, nil)
}
return
}
task = session.dataTask(with: request, completionHandler: {(data, response, error) in
DispatchQueue.main.sync {
completion(data, response, error)
}
});
task?.resume()
}
public func executeWithJSON(completion:@escaping (_ data: JSON?, _ response: URLResponse?, _ error:Error?) -> Void) {
guard let request = self.getRequest() else {
DispatchQueue.main.sync {
completion(nil, nil, nil)
}
return
}
task = session.dataTask(with: request, completionHandler: {(data, response, error) in
if(error != nil) {
DispatchQueue.main.sync {
completion(nil, response, error)
}
return
}
if let data = data, let json = PLKJSON.decode(data: data) {
DispatchQueue.main.sync {
completion(json, response, error)
}
return
}
DispatchQueue.main.sync {
completion(nil, response, error)
}
});
task?.resume()
}
}
| mit | 7c3162aa8258b6e4c6aa2a98e24df852 | 34.427835 | 182 | 0.545904 | 4.442793 | false | false | false | false |
Restofire/Restofire-Gloss | Tests/Models/Person.swift | 1 | 661 | //
// Person.swift
// Restofire-Gloss
//
// Created by Rahul Katariya on 24/04/16.
// Copyright © 2016 Rahul Katariya. All rights reserved.
//
import Gloss
struct Person: Decodable {
var id: Int
var name: String
init(id: Int, name: String) {
self.id = id
self.name = name
}
init?(json: JSON) {
guard let id: Int = "id" <~~ json,
let name: String = "name" <~~ json else { return nil }
self.id = id
self.name = name
}
}
extension Person: Equatable { }
func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.id == rhs.id && lhs.name == rhs.name
} | mit | 1b95615053193f518b34a2a8902b11ac | 17.885714 | 66 | 0.537879 | 3.529412 | false | false | false | false |
Josscii/iOS-Demos | CoreAnimationDemo/CoreAnimationDemo/ViewController.swift | 1 | 1799 | //
// ViewController.swift
// CoreAnimationDemo
//
// Created by Josscii on 2018/9/2.
// Copyright © 2018 Josscii. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var layer1: CALayer!
var layer2: CALayer!
var layer3: CALayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
layer1 = CALayer()
layer1.frame = CGRect(x: 50, y: 500, width: 100, height: 200)
layer1.backgroundColor = UIColor.red.cgColor
view.layer.addSublayer(layer1)
layer2 = CALayer()
layer2.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
layer2.backgroundColor = UIColor.green.cgColor
layer1.addSublayer(layer2)
layer3 = CALayer()
layer3.frame = CGRect(x: 50, y: 0, width: 50, height: 50)
layer3.backgroundColor = UIColor.yellow.cgColor
layer1.addSublayer(layer3)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
/*
CATransaction.begin()
CATransaction.setAnimationDuration(5)
let c = CACurrentMediaTime()
let time1 = layer1.convertTime(c, from: nil)
layer1.beginTime = time1
layer1.fillMode = kCAFillModeBackwards
layer1.frame.origin.y = 50
// let time = layer3.convertTime(CACurrentMediaTime(), from: nil)
layer3.beginTime = 2
layer3.fillMode = kCAFillModeBackwards
layer3.frame.origin.y = 50
layer1.autoreverses = true
layer1.repeatCount = 20
CATransaction.commit()
*/
let g = CAAnimationGroup()
g.animations = [
}
}
| mit | 944529e253f9ba313c114219115ed6a7 | 26.661538 | 80 | 0.599555 | 4.322115 | false | false | false | false |
zixun/CocoaChinaPlus | Code/CocoaChinaPlus/Application/Business/Util/Helper/HTMLModel/Parser/CCHTMLParser+OptionPage.swift | 1 | 3252 | //
// CCHTMLParser+OptionPage.swift
// CocoaChinaPlus
//
// Created by user on 15/10/31.
// Copyright © 2015年 zixun. All rights reserved.
//
import Foundation
import Ji
extension CCHTMLParser {
func parsePage(_ urlString:String,result:@escaping (_ model:[CCArticleModel],_ nextURL:String?)->Void) {
weak var weakSelf = self
_ = CCRequest(.get, urlString).responseJi { (ji, error) -> Void in
let nextPageURL = weakSelf!.parseNextPageURL(ji!, currentURL: urlString)
let article = weakSelf!.parseArticle(ji!)
result(article, nextPageURL)
}
}
fileprivate func parseNextPageURL(_ ji:Ji,currentURL:String) -> String? {
guard let nodes = ji.xPath("//div[@id='page']/a") else {
return nil
}
var find = false
var urlString:String?
for node in nodes {
//如果上一次循环已经发现当前页面,说明这一次循环就是下一页
if find {
//如果是末页,说明这是最后一页,没有下一页
if node.content != "末页" {
urlString = node["href"]
}
break
}
//判断是否当前页
if node["class"] == "thisclass" {
find = true
}
}
guard urlString != nil else {
return nil
}
return self.optionPathOfURL(currentURL) + urlString!
}
fileprivate func optionPathOfURL(_ urlString:String) -> String {
let str = urlString as NSString
var count = 0
for i in 0 ..< str.length {
let temp = str.substring(with: NSMakeRange(i, 1))
if temp == "/" {
count += 1
if count >= 4 {
return str.substring(with: NSMakeRange(0,i+1))
}
}
}
return urlString
}
fileprivate func parseArticle(_ ji: Ji) -> [CCArticleModel] {
guard let nodes = ji.xPath("//div[@class='clearfix']") else {
return [CCArticleModel]()
}
var models = [CCArticleModel]()
for node in nodes {
let model = CCArticleModel()
var inner = node.xPath(".//a[@class='pic float-l']").first!
let href = "http://www.cocoachina.com" + inner["href"]!
let title = inner["title"]!
inner = inner.xPath(".//img").first!
let imageURL = inner["src"]!
let addtion = node.xPath("//div[@class='clearfix zx_manage']/div[@class='float-l']/span")
let postTime = addtion[0].content!
let viewed = addtion[1].content!
model.linkURL = href
model.title = title
model.postTime = postTime
model.viewed = viewed
model.imageURL = imageURL
models.append(model)
}
return models
}
}
| mit | 597a913360d9896fa9116f818636b34a | 26.5 | 108 | 0.470494 | 4.764438 | false | false | false | false |
Avtolic/ACAlertController | ACAlertController/ACAlertAction.swift | 1 | 2330 | //
// ACAlertAction.swift
// ACAlertControllerDemo
//
// Created by Yury on 21/09/16.
// Copyright © 2016 Avtolic. All rights reserved.
//
import UIKit
public protocol ACAlertActionProtocolBase {
var alertView: UIView { get }
var enabled: Bool { get }
func highlight(_ isHighlited: Bool)
func call() -> Void
}
extension ACAlertActionProtocolBase {
public var enabled: Bool { return true }
public func highlight(_ isHighlited: Bool) { }
}
public protocol ACAlertActionProtocol: ACAlertActionProtocolBase {
func alertView(_ tintColor: UIColor) -> UIView
}
extension ACAlertActionProtocol {
func alertView(_ tintColor: UIColor) -> UIView {
return self.alertView
}
}
// MARK: -
open class ACAlertAction: ACAlertActionProtocolBase {
open let alertView: UIView
open let handler: ((ACAlertAction) -> Void)?
public init(view: UIView, handler: ((ACAlertAction) -> Void)?) {
self.alertView = view
self.handler = handler
}
// open func alertView(_ tintColor: UIColor) -> UIView {
// return alertView
// }
open func call() {
handler?(self)
}
}
open class ACAlertActionNative: ACAlertActionProtocolBase {
open let handler: ((ACAlertActionNative) -> Void)?
open let title: String?
open let style: UIAlertActionStyle
open var enabled: Bool = true
public init(title: String?, style: UIAlertActionStyle, handler: ((ACAlertActionNative) -> Void)?) {
self.title = title
self.style = style
self.handler = handler
}
lazy open var alertView: UIView = {
let label = UILabel()
let blueColor = UIColor(red:0.31, green:0.75, blue:0.87, alpha:1.0)
let redColor = UIColor(red:0.82, green:0.01, blue:0.11, alpha:1.0)
let fontSize: CGFloat = 17
label.font = self.style == .cancel ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
label.minimumScaleFactor = 0.5
let normalColor = self.enabled ? blueColor : UIColor.gray
label.textColor = self.style == .destructive ? redColor : normalColor
label.text = self.title
return label
}()
open func call() {
handler?(self)
}
}
| mit | 07e2a466816692c2959e3a7db550275c | 24.877778 | 123 | 0.626449 | 4.219203 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Frontend/Home/RemoteTabsPanel.swift | 2 | 25580 | /* 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
import Account
import Shared
import SnapKit
import Storage
import Sync
import XCGLogger
private let log = Logger.browserLogger
private struct RemoteTabsPanelUX {
static let HeaderHeight = SiteTableViewControllerUX.RowHeight // Not HeaderHeight!
static let RowHeight = SiteTableViewControllerUX.RowHeight
static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8)
static let EmptyStateTitleTextColor = UIColor.darkGray
static let EmptyStateInstructionsTextColor = UIColor.gray
static let EmptyStateInstructionsWidth = 170
static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 // UX TODO I set this to 8 so that it all fits on landscape
static let EmptyStateSignInButtonColor = UIColor(red:0.3, green:0.62, blue:1, alpha:1)
static let EmptyStateSignInButtonTitleColor = UIColor.white
static let EmptyStateSignInButtonCornerRadius: CGFloat = 4
static let EmptyStateSignInButtonHeight = 44
static let EmptyStateSignInButtonWidth = 200
// Backup and active strings added in Bug 1205294.
static let EmptyStateInstructionsSyncTabsPasswordsBookmarksString = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.")
static let EmptyStateInstructionsSyncTabsPasswordsString = NSLocalizedString("Sync your tabs, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.")
static let EmptyStateInstructionsGetTabsBookmarksPasswordsString = NSLocalizedString("Get your open tabs, bookmarks, and passwords from your other devices.", comment: "A re-worded offer about Sync, displayed when the Sync home panel is empty, that emphasizes one-way data transfer, not syncing.")
static let HistoryTableViewHeaderChevronInset: CGFloat = 10
static let HistoryTableViewHeaderChevronSize: CGFloat = 20
static let HistoryTableViewHeaderChevronLineWidth: CGFloat = 3.0
}
private let RemoteClientIdentifier = "RemoteClient"
private let RemoteTabIdentifier = "RemoteTab"
class RemoteTabsPanel: UIViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
fileprivate lazy var tableViewController: RemoteTabsTableViewController = RemoteTabsTableViewController()
fileprivate lazy var historyBackButton: HistoryBackButton = {
let button = HistoryBackButton()
button.addTarget(self, action: #selector(RemoteTabsPanel.historyBackButtonWasTapped), for: .touchUpInside)
return button
}()
var profile: Profile!
init() {
super.init(nibName: nil, bundle: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RemoteTabsPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RemoteTabsPanel.notificationReceived(_:)), name: NotificationProfileDidFinishSyncing, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableViewController.profile = profile
tableViewController.remoteTabsPanel = self
view.backgroundColor = UIConstants.PanelBackgroundColor
addChildViewController(tableViewController)
self.view.addSubview(tableViewController.view)
self.view.addSubview(historyBackButton)
historyBackButton.snp_makeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(50)
make.bottom.equalTo(tableViewController.view.snp_top)
}
tableViewController.view.snp_makeConstraints { make in
make.top.equalTo(historyBackButton.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
tableViewController.didMove(toParentViewController: self)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
}
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing:
tableViewController.refreshTabs()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
@objc fileprivate func historyBackButtonWasTapped(_ gestureRecognizer: UITapGestureRecognizer) {
self.navigationController?.popViewController(animated: true)
}
}
enum RemoteTabsError {
case notLoggedIn
case noClients
case noTabs
case failedToSync
func localizedString() -> String {
switch self {
case .notLoggedIn:
return "" // This does not have a localized string because we have a whole specific screen for it.
case .noClients:
return Strings.EmptySyncedTabsPanelNullStateDescription
case .noTabs:
return NSLocalizedString("You don't have any tabs open in Cliqz on your other devices.", comment: "Error message in the remote tabs panel")
case .failedToSync:
return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel")
}
}
}
protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate {
}
class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
fileprivate var clientAndTabs: [ClientAndTabs]
init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) {
self.homePanel = homePanel
self.clientAndTabs = clientAndTabs
}
func numberOfSections(in tableView: UITableView) -> Int {
return self.clientAndTabs.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.clientAndTabs[section].tabs.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return RemoteTabsPanelUX.HeaderHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let clientTabs = self.clientAndTabs[section]
let client = clientTabs.client
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: RemoteClientIdentifier) as! TwoLineHeaderFooterView
view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight)
view.textLabel?.text = client.name
view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor
/*
* A note on timestamps.
* We have access to two timestamps here: the timestamp of the remote client record,
* and the set of timestamps of the client's tabs.
* Neither is "last synced". The client record timestamp changes whenever the remote
* client uploads its record (i.e., infrequently), but also whenever another device
* sends a command to that client -- which can be much later than when that client
* last synced.
* The client's tabs haven't necessarily changed, but it can still have synced.
* Ideally, we should save and use the modified time of the tabs record itself.
* This will be the real time that the other client uploaded tabs.
*/
let timestamp = clientTabs.approximateLastSyncTime()
let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.")
view.detailTextLabel?.text = String(format: label, Date.fromTimestamp(timestamp).toRelativeTimeString())
let image: UIImage?
if client.type == "desktop" {
image = UIImage(named: "deviceTypeDesktop")
image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list")
} else {
image = UIImage(named: "deviceTypeMobile")
image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list")
}
view.imageView.image = image
view.mergeAccessibilityLabels()
return view
}
fileprivate func tabAtIndexPath(_ indexPath: IndexPath) -> RemoteTab {
return clientAndTabs[indexPath.section].tabs[indexPath.item]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: RemoteTabIdentifier, for: indexPath) as! TwoLineTableViewCell
let tab = tabAtIndexPath(indexPath as IndexPath)
cell.setLines(tab.title, detailText: tab.URL.absoluteString)
// TODO: Bug 1144765 - Populate image with cached favicons.
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let tab = tabAtIndexPath(indexPath)
if let homePanel = self.homePanel {
// It's not a bookmark, so let's call it Typed (which means History, too).
homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.Typed)
}
}
}
// MARK: -
class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
var error: RemoteTabsError
var notLoggedCell: UITableViewCell?
init(homePanel: HomePanel, error: RemoteTabsError) {
self.homePanel = homePanel
self.error = error
self.notLoggedCell = nil
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let cell = self.notLoggedCell {
cell.updateConstraints()
}
return tableView.bounds.height
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// Making the footer height as small as possible because it will disable button tappability if too high.
return 1
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch error {
case .notLoggedIn:
let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel)
self.notLoggedCell = cell
return cell
default:
let cell = RemoteTabsErrorCell(error: self.error)
self.notLoggedCell = nil
return cell
}
}
}
// MARK: -
class RemoteTabsErrorCell: UITableViewCell {
static let Identifier = "RemoteTabsErrorCell"
init(error: RemoteTabsError) {
super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0)
let containerView = UIView()
contentView.addSubview(containerView)
let imageView = UIImageView()
imageView.image = UIImage(named: "emptySync")
containerView.addSubview(imageView)
imageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(containerView)
make.centerX.equalTo(containerView)
}
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont
titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor
containerView.addSubview(titleLabel)
let instructionsLabel = UILabel()
instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
instructionsLabel.text = error.localizedString()
instructionsLabel.textAlignment = NSTextAlignment.center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
containerView.addSubview(instructionsLabel)
titleLabel.snp_makeConstraints { make in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(imageView)
}
instructionsLabel.snp_makeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems / 2)
make.centerX.equalTo(containerView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
}
containerView.snp_makeConstraints { make in
// Let the container wrap around the content
make.top.equalTo(imageView.snp_top)
make.left.bottom.right.equalTo(instructionsLabel)
// And then center it in the overlay view that sits on top of the UITableView
make.centerX.equalTo(contentView)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(contentView.snp_centerY).offset(HomePanelUX.EmptyTabContentOffset).priorityMedium()
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(contentView.snp_top).offset(20).priorityHigh()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: -
class RemoteTabsNotLoggedInCell: UITableViewCell {
static let Identifier = "RemoteTabsNotLoggedInCell"
var homePanel: HomePanel?
var instructionsLabel: UILabel
var signInButton: UIButton
var titleLabel: UILabel
var emptyStateImageView: UIImageView
init(homePanel: HomePanel?) {
let titleLabel = UILabel()
let instructionsLabel = UILabel()
let signInButton = UIButton()
let imageView = UIImageView()
self.instructionsLabel = instructionsLabel
self.signInButton = signInButton
self.titleLabel = titleLabel
self.emptyStateImageView = imageView
super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
self.homePanel = homePanel
let createAnAccountButton = UIButton(type: .system)
imageView.image = UIImage(named: "emptySync")
contentView.addSubview(imageView)
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont
titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor
contentView.addSubview(titleLabel)
instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
instructionsLabel.text = Strings.EmptySyncedTabsPanelStateDescription
instructionsLabel.textAlignment = NSTextAlignment.center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
contentView.addSubview(instructionsLabel)
signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor
signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), for: UIControlState())
signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, for: UIControlState())
signInButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline)
signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius
signInButton.clipsToBounds = true
signInButton.addTarget(self, action: #selector(RemoteTabsNotLoggedInCell.SELsignIn), for: UIControlEvents.touchUpInside)
contentView.addSubview(signInButton)
createAnAccountButton.setTitle(NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j"), for: UIControlState())
createAnAccountButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1)
createAnAccountButton.addTarget(self, action: #selector(RemoteTabsNotLoggedInCell.SELcreateAnAccount), for: UIControlEvents.touchUpInside)
contentView.addSubview(createAnAccountButton)
imageView.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(instructionsLabel)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(contentView).offset(HomePanelUX.EmptyTabContentOffset + 30).priorityMedium()
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(contentView.snp_top).priorityHigh()
}
titleLabel.snp_makeConstraints { make in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(imageView)
}
createAnAccountButton.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(signInButton)
make.top.equalTo(signInButton.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc fileprivate func SELsignIn() {
if let homePanel = self.homePanel {
homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel)
}
}
@objc fileprivate func SELcreateAnAccount() {
if let homePanel = self.homePanel {
homePanel.homePanelDelegate?.homePanelDidRequestToCreateAccount(homePanel)
}
}
override func updateConstraints() {
if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) && !(DeviceInfo.deviceModel().range(of: "iPad") != nil) {
instructionsLabel.snp_remakeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
// Sets proper landscape layout for bigger phones: iPhone 6 and on.
make.left.lessThanOrEqualTo(contentView.snp_left).offset(80).priorityMedium()
// Sets proper landscape layout for smaller phones: iPhone 4 & 5.
make.right.lessThanOrEqualTo(contentView.snp_centerX).offset(-30).priorityHigh()
}
signInButton.snp_remakeConstraints { make in
make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth)
make.centerY.equalTo(emptyStateImageView).offset(2*RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
// Sets proper landscape layout for bigger phones: iPhone 6 and on.
make.right.greaterThanOrEqualTo(contentView.snp_right).offset(-70).priorityMedium()
// Sets proper landscape layout for smaller phones: iPhone 4 & 5.
make.left.greaterThanOrEqualTo(contentView.snp_centerX).offset(10).priorityHigh()
}
} else {
instructionsLabel.snp_remakeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(contentView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
}
signInButton.snp_remakeConstraints { make in
make.centerX.equalTo(contentView)
make.top.equalTo(instructionsLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth)
}
}
super.updateConstraints()
}
}
fileprivate class RemoteTabsTableViewController : UITableViewController {
weak var remoteTabsPanel: RemoteTabsPanel?
var profile: Profile!
var tableViewDelegate: RemoteTabsPanelDataSource? {
didSet {
tableView.dataSource = tableViewDelegate
tableView.delegate = tableViewDelegate
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier)
tableView.register(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier)
tableView.rowHeight = RemoteTabsPanelUX.RowHeight
tableView.separatorInset = UIEdgeInsets.zero
tableView.delegate = nil
tableView.dataSource = nil
refreshControl = UIRefreshControl()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshControl?.addTarget(self, action: #selector(RemoteTabsTableViewController.refreshTabs), for: .valueChanged)
refreshTabs()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
refreshControl?.removeTarget(self, action: #selector(RemoteTabsTableViewController.refreshTabs), for: .valueChanged)
}
fileprivate func startRefreshing() {
if let refreshControl = self.refreshControl {
let height = -refreshControl.bounds.size.height
tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true)
refreshControl.beginRefreshing()
}
}
func endRefreshing() {
if self.refreshControl?.isRefreshing ?? false {
self.refreshControl?.endRefreshing()
}
self.tableView.isScrollEnabled = true
self.tableView.reloadData()
}
func updateDelegateClientAndTabData(_ clientAndTabs: [ClientAndTabs]) {
guard let remoteTabsPanel = remoteTabsPanel else { return }
if clientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .noClients)
} else {
let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 }
if nonEmptyClientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .noTabs)
} else {
self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: remoteTabsPanel, clientAndTabs: nonEmptyClientAndTabs)
tableView.allowsSelection = true
}
}
}
@objc fileprivate func refreshTabs() {
guard let remoteTabsPanel = remoteTabsPanel else { return }
tableView.isScrollEnabled = false
tableView.allowsSelection = false
tableView.tableFooterView = UIView(frame: CGRect.zero)
// Short circuit if the user is not logged in
if !profile.hasSyncableAccount() {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .notLoggedIn)
self.endRefreshing()
return
}
self.profile.getCachedClientsAndTabs().uponQueue(DispatchQueue.main) { result in
if let clientAndTabs = result.successValue {
self.updateDelegateClientAndTabData(clientAndTabs)
}
// Otherwise, fetch the tabs cloud if its been more than 1 minute since last sync
let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
if Date.now() - (lastSyncTime ?? 0) > OneMinuteInMilliseconds && !(self.refreshControl?.isRefreshing ?? false) {
self.startRefreshing()
self.profile.getClientsAndTabs().uponQueue(DispatchQueue.main) { result in
if let clientAndTabs = result.successValue {
self.profile.prefs.setTimestamp(Date.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime)
self.updateDelegateClientAndTabData(clientAndTabs)
}
self.endRefreshing()
}
} else {
// If we failed before and didn't sync, show the failure delegate
if let _ = result.failureValue {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .failedToSync)
}
self.endRefreshing()
}
}
}
}
| mpl-2.0 | 513586604e116e4fa67f646e3871b592 | 43.103448 | 300 | 0.700117 | 5.35819 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.