repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kevinsumios/KSiShuHui | Project/Controller/BaseTableController.swift | 1 | 3352 | //
// BaseTableController.swift
// Project
//
// Created by Kevin Sum on 11/7/2017.
// Copyright © 2017 Kevin iShuHui. All rights reserved.
//
import UIKit
import Alamofire
import MJRefresh
import SDWebImage
import SwiftyJSON
class BaseTableController: BaseViewController {
var data: [JSON] = []
var index = 0
var api: ApiHelper.Name?
var parameter = Parameters()
var didFinishLoad: (() -> ())?
override func loadView() {
api = nil
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
// Layout
initLayout()
// Initial api data
loadData()
// MJRefresh
let refreshFooter = MJRefreshBackNormalFooter {
self.loadData()
}
refreshFooter?.setTitle("拼命向上", for: .idle)
refreshFooter?.setTitle("拼命向上", for: .pulling)
refreshFooter?.setTitle("夠了", for: .willRefresh)
refreshFooter?.setTitle("瘋狂旋轉中", for: .refreshing)
refreshFooter?.setTitle("不要再拉了", for: .noMoreData)
tableView.mj_footer = refreshFooter
}
func initLayout() {
}
func loadData() {
if let name = api {
ApiHelper.shared.request(
name: name,
parameters: parameter,
success: { (json, response) in
if let result = json.dictionary?["Return"]?.dictionary {
if let array = result["List"]?.array {
self.data.append(contentsOf: array)
self.didFinishLoad?()
self.tableView.reloadData()
if let count = result["ListCount"]?.int, let size = result["PageSize"]?.int {
if (self.index+1)*size > count {
self.tableView.mj_footer?.endRefreshingWithNoMoreData()
return
} else {
self.index += 1
}
}
}
} else if let number = json.int {
self.alert(message: "\(number)")
}
self.tableView.mj_header?.endRefreshing()
self.tableView.mj_footer?.endRefreshing()
},
failure: { (error, response) in
self.alert(message: error.localizedDescription)
self.tableView.mj_header?.endRefreshing()
self.tableView.mj_footer?.endRefreshing()
})
}
}
func alert(message: String = "未知錯誤") {
let alert = UIAlertController(title: "注意", message: message, preferredStyle: .alert)
let okButton = UIAlertAction(title: "好的", style: .cancel, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
}
| mit | dcd5535ed464cd4c880ea301b9611575 | 31.623762 | 105 | 0.511988 | 5.045942 | false | false | false | false |
iitjee/SteppinsSwift | 03 Tuples.swift | 1 | 2130 | /* So the tuple, in other words is a list of two or more things, they don't have to be the same types, surrounding by parentheses.
The tuple is treated as a single variable or constant, so in this case http404Error is going to point at the single tuple, not at either of the components of the tuple.
It's as if I had a struct that had two fields in it,
but the struct is effectively created implicitly by the compiler.
Now having initialized the variable, I can access the fields if I want to.
*/
let http404Error = (404, "Not Found")
http404Error.0 //404
http404Error.1 //"Not Found"
let (status, desc) = http404Error
status //404
desc //Not Found
//Note: Both status and desc are now constants
let http404Error = (status: 404, desc: "Not Found")
http404Error.status //404
http404Error.desc //"Not Found"
/* Ignoring some fields */
let (status, _) = (404, "Not Found")
//Here we use the wildcard character _ to ignore few fields
/* Tuples as Return types of Functions */
func fetch() -> (code: Int, desc: String) {
return (200, "Okay")
}
//using default names for decomposing tuple (which were given in the function declaration
let status = fetch()
status.code //(or) status.0
status.desc //(or) status.1
//If you want to provide your own names for the fields inside the tuple
let (error, description) = fetch()
error //
description //
//Another way
let tempstatus = fetch()
let status = (errorCode: tempstatus.0, descrip: tempstatus.1)
//(or) let status = (errorCode: fetch().0, descrip: fetch().1) //if function calls are not too expensive
status.errorCode
status.descrip
/* Tuple Types */
var someTuple = (top: 10, bottom: 12) // someTuple is of type (top: Int, bottom: Int)
someTuple = (top: 4, bottom: 42) // OK: names match
someTuple = (9, 99) // OK: names are inferred
someTuple = (left: 5, right: 5) // Error: names don't match
//Note: A single parenthesized type is the same as that type without parentheses. For example, (Int) is equivalent to Int.
/* Tuples are equivalent to a Class */
//once watch video
| apache-2.0 | a0ab4b78d1ac50c9d9a9b6aeb6370d47 | 27.4 | 168 | 0.687793 | 3.634812 | false | false | false | false |
frankcjw/CJWUtilsS | CJWUtilsS/QPLib/Utils/QPAlertUtils.swift | 1 | 990 | //
// QPAlertUtils.swift
// CJWUtilsS
//
// Created by Frank on 2/27/16.
// Copyright © 2016 cen. All rights reserved.
//
import UIKit
public class QPAlertUtils: NSObject {
public typealias QPAlertUtilsBlock = (index: Int) -> ()
public class func showSelection(viewcontroller: UIViewController, title: String, message: String, titles: [String], block: QPAlertUtilsBlock) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.ActionSheet)
for actionTitle in titles {
let alertAction = UIAlertAction(title: actionTitle, style: UIAlertActionStyle.Default) { (action) -> Void in
if let index = titles.indexOf(actionTitle) {
block(index: index)
}
}
alert.addAction(alertAction)
}
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel) { (action) -> Void in
}
alert.addAction(cancel)
viewcontroller.presentViewController(alert, animated: true) { () -> Void in
//
}
}
}
| mit | b118c550747492907393e303066a319a | 27.970588 | 144 | 0.713706 | 3.731061 | false | false | false | false |
Nick11/SwiftGen | Sources/Assets/SwiftGenAssetsEnumBuilder.swift | 2 | 1951 | import Foundation
//@import SwiftIdentifier
//@import SwiftGenIndentation
public final class SwiftGenAssetsEnumBuilder {
private var assetNames = [String]()
public init() {}
public func addAssetName(name: String) -> Bool {
if assetNames.contains(name) {
return false
}
else {
assetNames.append(name)
return true
}
}
public func parseDirectory(path: String) {
if let dirEnum = NSFileManager.defaultManager().enumeratorAtPath(path) {
while let path = dirEnum.nextObject() as? NSString {
if path.pathExtension == "imageset" {
let assetName = (path.lastPathComponent as NSString).stringByDeletingPathExtension
self.addAssetName(assetName)
}
}
}
}
public func build(enumName enumName : String = "Asset", indentation indent : SwiftGenIndentation = .Spaces(4)) -> String {
var text = "// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen\n\n"
let t = indent.string
text += "import Foundation\n"
text += "import UIKit\n"
text += "\n"
text += "extension UIImage {\n"
text += "\(t)enum \(enumName) : String {\n"
for name in assetNames {
let caseName = name.asSwiftIdentifier(forbiddenChars: "_")
text += "\(t)\(t)case \(caseName) = \"\(name)\"\n"
}
text += "\n"
text += "\(t)\(t)var image: UIImage {\n"
text += "\(t)\(t)\(t)return UIImage(asset: self)\n"
text += "\(t)\(t)}\n"
text += "\(t)}\n\n"
text += "\(t)convenience init(asset: \(enumName)) {\n"
text += "\(t)\(t)self.init(named: asset.rawValue)!\n"
text += "\(t)}\n"
text += "}\n"
return text
}
}
| mit | 3af41fa9cf8e86ccb79f5dfd09215eea | 30.435484 | 126 | 0.521293 | 4.501155 | false | false | false | false |
stripe/stripe-ios | StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/Inputs/Card/STPCardCVCInputTextFieldValidator.swift | 1 | 1443 | //
// STPCardCVCInputTextFieldValidator.swift
// StripePaymentsUI
//
// Created by Cameron Sabol on 10/22/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
@_spi(STP) import StripePayments
import UIKit
class STPCardCVCInputTextFieldValidator: STPInputTextFieldValidator {
override var defaultErrorMessage: String? {
return STPLocalizedString(
"Your card's security code is invalid.",
"Error message for card entry form when CVC/CVV is invalid"
)
}
var cardBrand: STPCardBrand = .unknown {
didSet {
checkInputValidity()
}
}
override public var inputValue: String? {
didSet {
checkInputValidity()
}
}
private func checkInputValidity() {
guard let inputValue = inputValue else {
validationState = .incomplete(description: nil)
return
}
switch STPCardValidator.validationState(forCVC: inputValue, cardBrand: cardBrand) {
case .valid:
validationState = .valid(message: nil)
case .invalid:
validationState = .invalid(errorMessage: defaultErrorMessage)
case .incomplete:
validationState = .incomplete(
description: !inputValue.isEmpty
? String.Localized.your_cards_security_code_is_incomplete : nil
)
}
}
}
| mit | dce1c67838652c6d02df8709a2c0741e | 27.27451 | 91 | 0.618585 | 5.077465 | false | false | false | false |
argent-os/argent-ios | app-ios/PlansListDetailViewController.swift | 1 | 15771 | //
// PlansListDetailViewController.swift
// app-ios
//
// Created by Sinan Ulkuatam on 8/7/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import UIKit
import Former
import CWStatusBarNotification
final class PlansListDetailViewController: FormViewController, UINavigationBarDelegate, UITextFieldDelegate {
var dic: Dictionary<String, AnyObject> = [:]
var planId:String?
let amountInputView = UITextField()
let perIntervalLabel = UILabel()
let currencyFormatter = NSNumberFormatter()
// MARK: Public
override func viewDidLoad() {
super.viewDidLoad()
configure()
setupNav()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .Default
}
// MARK: Private
private func setupNav() {
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 60)) // Offset by 20 pixels vertically to take the status bar into account
navigationBar.backgroundColor = UIColor.clearColor()
navigationBar.tintColor = UIColor.mediumBlue()
navigationBar.delegate = self
// Create a navigation item with a title
let navigationItem = UINavigationItem()
navigationItem.title = ""
navigationItem.titleView?.tintColor = UIColor.mediumBlue()
self.navigationController?.navigationItem.title = "Create a Billing Plan"
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.mediumBlue()]
// Create left and right button for navigation item
let leftButton = UIBarButtonItem(image: UIImage(named: "IconClose"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.returnToMenu(_:)))
let font = UIFont.systemFontOfSize(14)
leftButton.setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.mediumBlue()], forState: UIControlState.Normal)
// Create two buttons for the navigation item
navigationItem.leftBarButtonItem = leftButton
// Assign the navigation item to the navigation bar
navigationBar.titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.mediumBlue()]
navigationBar.items = [navigationItem]
// Make the navigation bar a subview of the current view controller
addSubviewWithFade(navigationBar, parentView: self, duration: 0.5)
}
//Calls this function when the tap is recognized.
func dismissKeyboard(sender: AnyObject) {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func viewDidAppear(animated: Bool) {
UIToolbar().tintColor = UIColor.iosBlue()
}
// toolbar buttons
private lazy var formerInputAccessoryView: FormerInputAccessoryView = FormerInputAccessoryView(former: self.former)
private func configure() {
// screen width and height:
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
UIToolbar().barTintColor = UIColor.iosBlue()
tableView.backgroundColor = UIColor.globalBackground()
tableView.contentInset.top = 60
tableView.contentInset.bottom = 90
tableView.contentOffset.y = 0
tableView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
let updatePlanButton = UIButton()
updatePlanButton.frame = CGRect(x: 15, y: screenHeight-125, width: screenWidth-30, height: 50)
updatePlanButton.setBackgroundColor(UIColor.pastelBlue(), forState: .Normal)
updatePlanButton.setBackgroundColor(UIColor.pastelBlue().lighterColor(), forState: .Highlighted)
updatePlanButton.tintColor = UIColor.whiteColor()
updatePlanButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
updatePlanButton.setTitleColor(UIColor.whiteColor().colorWithAlphaComponent(0.5), forState: .Highlighted)
updatePlanButton.titleLabel?.font = UIFont(name: "SFUIText-Regular", size: 16)
updatePlanButton.setAttributedTitle(adjustAttributedStringNoLineSpacing("UPDATE PLAN", spacing: 1, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.whiteColor()), forState: .Normal)
updatePlanButton.layer.cornerRadius = 3
updatePlanButton.layer.masksToBounds = true
updatePlanButton.clipsToBounds = true
updatePlanButton.addTarget(self, action: #selector(self.updatePlanButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
let _ = Timeout(0.5) {
addSubviewWithFade(updatePlanButton, parentView: self, duration: 0.3)
}
let deletePlanButton = UIButton()
deletePlanButton.frame = CGRect(x: 15, y: screenHeight-65, width: screenWidth-30, height: 50)
deletePlanButton.setBackgroundColor(UIColor.clearColor(), forState: .Normal)
deletePlanButton.setBackgroundColor(UIColor.brandRed(), forState: .Highlighted)
deletePlanButton.tintColor = UIColor.whiteColor()
deletePlanButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
deletePlanButton.setTitleColor(UIColor.whiteColor().colorWithAlphaComponent(0.5), forState: .Highlighted)
deletePlanButton.titleLabel?.font = UIFont(name: "SFUIText-Regular", size: 16)
deletePlanButton.setAttributedTitle(adjustAttributedStringNoLineSpacing("DELETE PLAN", spacing: 1, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.brandRed()), forState: .Normal)
deletePlanButton.setAttributedTitle(adjustAttributedStringNoLineSpacing("DELETE PLAN", spacing: 1, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.whiteColor()), forState: .Highlighted)
deletePlanButton.layer.cornerRadius = 3
deletePlanButton.layer.masksToBounds = true
deletePlanButton.layer.borderColor = UIColor.brandRed().CGColor
deletePlanButton.layer.borderWidth = 1
deletePlanButton.clipsToBounds = true
deletePlanButton.addTarget(self, action: #selector(self.deletePlanButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
let _ = Timeout(0.5) {
addSubviewWithFade(deletePlanButton, parentView: self, duration: 0.3)
}
let statementDescriptionCharacterCountLabel = UITextField()
statementDescriptionCharacterCountLabel.frame = CGRect(x: -20, y: 10, width: screenWidth, height: 60)
statementDescriptionCharacterCountLabel.layer.borderWidth = 0
statementDescriptionCharacterCountLabel.textColor = UIColor.lightBlue()
statementDescriptionCharacterCountLabel.textAlignment = .Right
self.view.addSubview(statementDescriptionCharacterCountLabel)
Plan.getPlan(planId!) { (plan, err) in
// Create RowFomers
let planAmountRow = SegmentedRowFormer<FormSegmentedCell>() {
$0.titleLabel.text = "Amount"
$0.titleLabel.font = UIFont(name: "SFUIText-Regular", size: 15)!
$0.titleLabel.textColor = UIColor.mediumBlue()
}.configure {
let amountNum: Float = Float(plan!["amount"].stringValue)!/100
let nf: NSNumberFormatter = NSNumberFormatter()
nf.numberStyle = NSNumberFormatterStyle.CurrencyStyle
let convertedString: String = nf.stringFromNumber(amountNum)!
$0.segmentTitles = [convertedString]
$0.rowHeight = 60
$0.cell.tintColor = UIColor.pastelBlue()
$0.selectedIndex = 0
self.dic["amount"] = plan!["amount"].stringValue
}
let planNameRow = SegmentedRowFormer<FormSegmentedCell>() {
$0.titleLabel.text = "Name"
$0.titleLabel.font = UIFont(name: "SFUIText-Regular", size: 15)!
$0.titleLabel.textColor = UIColor.mediumBlue()
}.configure {
$0.segmentTitles = [plan!["name"].stringValue]
$0.rowHeight = 60
$0.selectedIndex = 0
$0.cell.tintColor = UIColor.pastelBlue()
}
let planCurrencyRow = SegmentedRowFormer<FormSegmentedCell>() {
$0.titleLabel.text = "Currency"
$0.titleLabel.font = UIFont(name: "SFUIText-Regular", size: 15)!
$0.titleLabel.textColor = UIColor.mediumBlue()
}.configure {
$0.segmentTitles = ["USD"]
self.dic["currency"] = plan!["currency"].stringValue
$0.rowHeight = 60
$0.cell.tintColor = UIColor.pastelBlue()
$0.selectedIndex = 0
}
let planIntervalRow = SegmentedRowFormer<FormSegmentedCell>() {
$0.titleLabel.text = "Interval"
$0.titleLabel.font = UIFont(name: "SFUIText-Regular", size: 15)!
$0.titleLabel.textColor = UIColor.mediumBlue()
}.configure {
$0.segmentTitles = [plan!["interval"].stringValue]
self.dic["interval"] = plan!["interval"].stringValue
$0.rowHeight = 60
$0.cell.tintColor = UIColor.pastelBlue()
$0.selectedIndex = 0
}
let planTrialPeriodRow = SegmentedRowFormer<FormSegmentedCell>() {
$0.titleLabel.text = "Trial"
$0.titleLabel.font = UIFont(name: "SFUIText-Regular", size: 15)!
$0.titleLabel.textColor = UIColor.mediumBlue()
}.configure {
if plan!["trial_period_days"].stringValue == "" {
$0.segmentTitles = ["0 days"]
} else {
$0.segmentTitles = [plan!["trial_period_days"].stringValue + " days"]
}
$0.rowHeight = 60
$0.cell.tintColor = UIColor.pastelBlue()
$0.selectedIndex = 0
}
let planStatementDescriptionRow = TextFieldRowFormer<ProfileFieldCell>(instantiateType: .Nib(nibName: "ProfileFieldCell")) { [weak self] in
$0.titleLabel.text = "Desc"
$0.titleLabel.font = UIFont(name: "SFUIText-Regular", size: 15)!
$0.titleLabel.textColor = UIColor.mediumBlue()
$0.textField.font = .systemFontOfSize(15)
$0.textField.autocorrectionType = .No
$0.textField.autocapitalizationType = .None
$0.textField.returnKeyType = .Done
$0.textField.inputAccessoryView = self?.formerInputAccessoryView
}.configure {
if plan!["statement_descriptor"].stringValue == "" {
$0.placeholder = "(22 characters) Statement Descriptor"
} else {
$0.placeholder = plan!["statement_descriptor"].stringValue
}
$0.rowHeight = 60
self.dic["statement_descriptor"] = $0.text ?? ""
}.onTextChanged { [weak self] in
self?.dic["statement_descriptor"] = $0 ?? ""
statementDescriptionCharacterCountLabel.text = String($0.characters.count) + "/22"
if $0.characters.count > 22 {
statementDescriptionCharacterCountLabel.textColor = UIColor.brandRed()
} else {
statementDescriptionCharacterCountLabel.textColor = UIColor.lightBlue()
}
}
let planIntervalCountRow = SegmentedRowFormer<FormSegmentedCell>() {
$0.titleLabel.text = "Interval"
$0.titleLabel.font = UIFont(name: "SFUIText-Regular", size: 15)!
$0.titleLabel.textColor = UIColor.mediumBlue()
}.configure {
$0.segmentTitles = [plan!["interval_count"].stringValue]
self.dic["interval_count"] = plan!["interval_count"].stringValue
$0.rowHeight = 60
$0.cell.tintColor = UIColor.pastelBlue()
$0.selectedIndex = 0
}.onSegmentSelected { (segment, str) in
self.dic["interval_count"] = str.lowercaseString
}
// Create Headers
let createHeader: (() -> ViewFormer) = {
return CustomViewFormer<FormHeaderFooterView>()
.configure {
$0.viewHeight = 0
}
}
// Create SectionFormers
let titleSection = SectionFormer(rowFormer: planAmountRow, planNameRow, planCurrencyRow, planIntervalRow, planIntervalCountRow, planTrialPeriodRow, planStatementDescriptionRow)
.set(headerViewFormer: createHeader())
self.former.append(sectionFormer: titleSection)
.onCellSelected { [weak self] _ in
self?.formerInputAccessoryView.update()
}
}
}
func deletePlanButtonTapped(sender: AnyObject) {
if let id = planId {
let alertController = UIAlertController(title: "Confirm deletion", message: "Are you sure? This action cannot be undone.", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Continue", style: .Default) { (action) in
Plan.deletePlan(id, completionHandler: { (bool, err) in
if bool == true {
self.dismissViewControllerAnimated(true, completion: {
showGlobalNotification("Plan deleted, pull down to refresh.", duration: 4.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.brandGreen())
})
} else {
showAlert(.Error, title: "Error", msg: "Error deleting plan")
}
})
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
func updatePlanButtonTapped(sender: AnyObject) {
Plan.updatePlan(planId!, dic: dic) { (bool, err) in
if bool == true {
showAlert(.Success, title: "Success", msg: "Plan updated")
} else {
showAlert(.Error, title: "Error", msg: (err?.localizedDescription)!)
}
}
}
func returnToMenu(sender: AnyObject) {
self.dismissViewControllerAnimated(true) { }
}
func endEditing(sender: AnyObject) {
dismissKeyboard()
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
} | mit | e9c53785dec48e537d365d7233b5d04d | 47.377301 | 282 | 0.605136 | 5.288397 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/XCTEurofurenceModel/Entity Test Doubles/FakeDealer.swift | 1 | 2347 | import EurofurenceModel
import Foundation
import TestUtilities
public final class FakeDealer: Dealer {
public var identifier: DealerIdentifier
public var preferredName: String
public var alternateName: String?
public var isAttendingOnThursday: Bool
public var isAttendingOnFriday: Bool
public var isAttendingOnSaturday: Bool
public var isAfterDark: Bool
public var extendedData: ExtendedDealerData?
public var iconPNGData: Data?
public init(identifier: DealerIdentifier,
preferredName: String,
alternateName: String?,
isAttendingOnThursday: Bool,
isAttendingOnFriday: Bool,
isAttendingOnSaturday: Bool,
isAfterDark: Bool) {
self.identifier = identifier
self.preferredName = preferredName
self.alternateName = alternateName
self.isAttendingOnThursday = isAttendingOnThursday
self.isAttendingOnFriday = isAttendingOnFriday
self.isAttendingOnSaturday = isAttendingOnSaturday
self.isAfterDark = isAfterDark
}
public private(set) var websiteOpened = false
public func openWebsite() {
websiteOpened = true
}
public private(set) var twitterOpened = false
public func openTwitter() {
twitterOpened = true
}
public private(set) var telegramOpened = false
public func openTelegram() {
telegramOpened = true
}
public func fetchExtendedDealerData(completionHandler: @escaping (ExtendedDealerData) -> Void) {
extendedData.map(completionHandler)
}
public func fetchIconPNGData(completionHandler: @escaping (Data?) -> Void) {
completionHandler(iconPNGData)
}
public let shareableURL = URL.random
public var contentURL: URL {
return shareableURL
}
}
extension FakeDealer: RandomValueProviding {
public static var random: FakeDealer {
return FakeDealer(identifier: .random,
preferredName: .random,
alternateName: .random,
isAttendingOnThursday: .random,
isAttendingOnFriday: .random,
isAttendingOnSaturday: .random,
isAfterDark: .random)
}
}
| mit | 41b80ed1d159aaf989df91c7f83d5d52 | 29.881579 | 100 | 0.64167 | 5.047312 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/Instrumentation/SDKResourceExtension/DataSource/DeviceDataSource.swift | 1 | 2186 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
#if os(watchOS)
import WatchKit
#elseif os(macOS)
import AppKit
#else
import UIKit
#endif
public class DeviceDataSource: IDeviceDataSource {
public init() {}
public var model: String? {
#if os(watchOS)
return WKInterfaceDevice.current().localizedModel
#else
let hwName = UnsafeMutablePointer<Int32>.allocate(capacity: 2)
hwName[0] = CTL_HW
#if os(macOS)
hwName[1] = HW_MODEL
#else
hwName[1] = HW_MACHINE
#endif
// Returned 'error #12: Optional("Cannot allocate memory")' because len was not initialized properly.
let desiredLen = UnsafeMutablePointer<Int>.allocate(capacity: 1)
let lenRequestError = sysctl(hwName, 2, nil, desiredLen, nil, 0)
if lenRequestError != 0 {
// TODO: better error log
print("error #\(errno): \(String(describing: String(utf8String: strerror(errno))))")
return nil
}
let machine = UnsafeMutablePointer<CChar>.allocate(capacity: desiredLen[0])
let len: UnsafeMutablePointer<Int>! = UnsafeMutablePointer<Int>.allocate(capacity: 1)
len[0] = desiredLen[0]
let modelRequestError = sysctl(hwName, 2, machine, len, nil, 0)
if modelRequestError != 0 {
// TODO: better error log
print("error #\(errno): \(String(describing: String(utf8String: strerror(errno))))")
return nil
}
let machineName = String(cString: machine)
return machineName
#endif
}
public var identifier: String? {
#if os(watchOS)
if #available(watchOS 6.3, *) {
return WKInterfaceDevice.current().identifierForVendor?.uuidString
} else {
return nil
}
#elseif os(macOS)
return nil
#else
return UIDevice.current.identifierForVendor?.uuidString
#endif
}
}
| apache-2.0 | 4939b58792810ce4cf6169203f2c3af9 | 30.228571 | 113 | 0.567246 | 4.741866 | false | false | false | false |
ZhipingYang/UUChatSwift | UUChatTableViewSwift/RootViewController.swift | 1 | 1177 | //
// RootViewController.swift
// UUChatTableViewSwift
//
// Created by 杨志平 on 11/8/15.
// Copyright © 2015 XcodeYang. All rights reserved.
//
import UIKit
class RootViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let showBtn = UIButton(type: .Custom)
showBtn.setTitle("Creat Chat Room", forState: .Normal)
showBtn.setTitleColor(UIColor.purpleColor(), forState: .Normal)
showBtn.addTarget(self, action: Selector("showChatRoom"), forControlEvents: .TouchUpInside)
showBtn.center = view.center
view.addSubview(showBtn)
showBtn.snp_makeConstraints { (make) -> Void in
make.center.equalTo(view)
}
showBtn.contentEdgeInsets = UIEdgeInsetsMake(8, 20, 8, 20)
showBtn.layer.borderColor = UIColor.purpleColor().CGColor
showBtn.layer.borderWidth = 1
showBtn.layer.cornerRadius = 10
}
internal func showChatRoom() {
let nvc = UINavigationController.init(rootViewController: ChatTableViewController())
self.presentViewController(nvc, animated: true, completion: nil)
}
}
| mit | d4f3bb9e4f88ad1ba6938be4483db320 | 31.5 | 99 | 0.667521 | 4.5 | false | false | false | false |
tndatacommons/Compass-iOS | Compass/src/UI/CircleProgressView.swift | 1 | 6598 | //
// CircleProgressView.swift
//
//
// Created by Eric Rolf on 8/11/14.
// Copyright (c) 2014 Eric Rolf, Cardinal Solutions Group. All rights reserved.
//
import UIKit
@objc @IBDesignable public class CircleProgressView: UIView {
private struct Constants {
let circleDegress = 360.0
let minimumValue = 0.000001
let maximumValue = 0.999999
let ninetyDegrees = 90.0
let twoSeventyDegrees = 270.0
var contentView:UIView = UIView()
}
private let constants = Constants()
private var internalProgress:Double = 0.0
private var displayLink: CADisplayLink?
private var destinationProgress: Double = 0.0
@IBInspectable public var progress: Double = 0.000001 {
didSet {
internalProgress = progress
setNeedsDisplay()
}
}
@IBInspectable public var refreshRate: Double = 0.0 {
didSet { setNeedsDisplay() }
}
@IBInspectable public var clockwise: Bool = true {
didSet { setNeedsDisplay() }
}
@IBInspectable public var trackWidth: CGFloat = 10 {
didSet { setNeedsDisplay() }
}
@IBInspectable public var trackImage: UIImage? {
didSet { setNeedsDisplay() }
}
@IBInspectable public var trackBackgroundColor: UIColor = UIColor.grayColor() {
didSet { setNeedsDisplay() }
}
@IBInspectable public var trackFillColor: UIColor = UIColor.blueColor() {
didSet { setNeedsDisplay() }
}
@IBInspectable public var trackBorderColor:UIColor = UIColor.clearColor() {
didSet { setNeedsDisplay() }
}
@IBInspectable public var trackBorderWidth: CGFloat = 0 {
didSet { setNeedsDisplay() }
}
@IBInspectable public var centerFillColor: UIColor = UIColor.whiteColor() {
didSet { setNeedsDisplay() }
}
@IBInspectable public var centerImage: UIImage? {
didSet { setNeedsDisplay() }
}
@IBInspectable public var contentView: UIView {
return self.constants.contentView
}
required override public init(frame: CGRect) {
super.init(frame: frame)
internalInit()
self.addSubview(contentView)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
internalInit()
self.addSubview(contentView)
}
func internalInit() {
displayLink = CADisplayLink(target: self, selector: #selector(CircleProgressView.displayLinkTick))
displayLink?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
displayLink?.paused = true
}
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
let innerRect = CGRectInset(rect, trackBorderWidth, trackBorderWidth)
internalProgress = (internalProgress/1.0) == 0.0 ? constants.minimumValue : progress
internalProgress = (internalProgress/1.0) == 1.0 ? constants.maximumValue : internalProgress
internalProgress = clockwise ?
(-constants.twoSeventyDegrees + ((1.0 - internalProgress) * constants.circleDegress)) :
(constants.ninetyDegrees - ((1.0 - internalProgress) * constants.circleDegress))
let context = UIGraphicsGetCurrentContext()
// background Drawing
trackBackgroundColor.setFill()
let circlePath = UIBezierPath(ovalInRect: CGRectMake(innerRect.minX, innerRect.minY, CGRectGetWidth(innerRect), CGRectGetHeight(innerRect)))
circlePath.fill();
if trackBorderWidth > 0 {
circlePath.lineWidth = trackBorderWidth
trackBorderColor.setStroke()
circlePath.stroke()
}
// progress Drawing
let progressPath = UIBezierPath()
let progressRect: CGRect = CGRectMake(innerRect.minX, innerRect.minY, CGRectGetWidth(innerRect), CGRectGetHeight(innerRect))
let center = CGPointMake(progressRect.midX, progressRect.midY)
let radius = progressRect.width / 2.0
let startAngle:CGFloat = clockwise ? CGFloat(-internalProgress * M_PI / 180.0) : CGFloat(constants.twoSeventyDegrees * M_PI / 180)
let endAngle:CGFloat = clockwise ? CGFloat(constants.twoSeventyDegrees * M_PI / 180) : CGFloat(-internalProgress * M_PI / 180.0)
progressPath.addArcWithCenter(center, radius:radius, startAngle:startAngle, endAngle:endAngle, clockwise:!clockwise)
progressPath.addLineToPoint(CGPointMake(progressRect.midX, progressRect.midY))
progressPath.closePath()
CGContextSaveGState(context!)
progressPath.addClip()
if trackImage != nil {
trackImage!.drawInRect(innerRect)
} else {
trackFillColor.setFill()
circlePath.fill()
}
CGContextRestoreGState(context!)
// center Drawing
let centerPath = UIBezierPath(ovalInRect: CGRectMake(innerRect.minX + trackWidth, innerRect.minY + trackWidth, CGRectGetWidth(innerRect) - (2 * trackWidth), CGRectGetHeight(innerRect) - (2 * trackWidth)))
centerFillColor.setFill()
centerPath.fill()
if let centerImage = centerImage {
CGContextSaveGState(context!)
centerPath.addClip()
centerImage.drawInRect(rect)
CGContextRestoreGState(context!)
} else {
let layer = CAShapeLayer()
layer.path = centerPath.CGPath
contentView.layer.mask = layer
}
}
//MARK: - Progress Update
public func setProgress(newProgress: Double, animated: Bool) {
if animated {
destinationProgress = newProgress
displayLink?.paused = false
} else {
progress = newProgress
}
}
//MARK: - CADisplayLink Tick
internal func displayLinkTick() {
let renderTime = refreshRate.isZero ? displayLink!.duration : refreshRate
if destinationProgress > progress {
progress += renderTime
if progress >= destinationProgress {
progress = destinationProgress
}
}
else if destinationProgress < progress {
progress -= renderTime
if progress <= destinationProgress {
progress = destinationProgress
}
} else {
displayLink?.paused = true
}
}
}
| mit | 7c0c92915fcb3b483dbc055d35febd9f | 32.155779 | 212 | 0.618218 | 5.355519 | false | false | false | false |
leoneparise/iLog | iLogUI/CloseButton.swift | 1 | 1051 | //
// CloseButton.swift
// Pods
//
// Created by Leone Parise Vieira da Silva on 09/05/17.
//
//
import UIKit
@IBDesignable
class CloseButton: UIButton {
@IBInspectable var padding:CGFloat = 0
@IBInspectable var lineWidth:CGFloat = 0
override func draw(_ rect: CGRect) {
var bounds = rect.insetBy(dx: padding, dy: padding)
let minSize = min(bounds.width, bounds.height)
bounds = bounds.insetBy(dx: (bounds.width - minSize) / 2, dy: (bounds.height - minSize) / 2)
guard let ctx = UIGraphicsGetCurrentContext() else { return }
drawLine(ctx, from: CGPoint(x: bounds.minX, y: bounds.minY),
to: CGPoint(x: bounds.maxX, y: bounds.maxY),
lineWidth: lineWidth,
color: self.tintColor)
drawLine(ctx,
from: CGPoint(x: bounds.maxX, y: bounds.minY),
to: CGPoint(x: bounds.minX, y: bounds.maxY),
lineWidth: lineWidth,
color: self.tintColor)
}
}
| mit | bab282eec0beded5397dd91856b56754 | 29.911765 | 100 | 0.574691 | 4.105469 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | App_VolksWagenFinal-/App_VolksWagenFinal-/VWConcesionariosModel.swift | 1 | 1202 | //
// VWConcesionariosModel.swift
// App_VolksWagenFinal_CICE
//
// Created by Formador on 5/10/16.
// Copyright © 2016 icologic. All rights reserved.
//
import UIKit
class VWConcesionariosModel: NSObject {
var Contacto : String?
var CoreoContacto : String?
var Horario : String?
var Nombre : String?
var Provincia_Nombre : String?
var Responsable : String?
var telefono : Int?
var Ubicacion : String?
var Imagen : String?
var Longitud : Double?
var Latitud : Double?
init(pContacto : String, pCoreoContacto : String, pHorario : String, pNombre : String, pProvincia_Nombre : String, pResponsable : String, pTelefono : Int, pUbicacion : String, pImagen : String, pLongitud : Double, pLatitud : Double) {
self.Contacto = pContacto
self.CoreoContacto = pCoreoContacto
self.Horario = pHorario
self.Nombre = pNombre
self.Provincia_Nombre = pProvincia_Nombre
self.Responsable = pResponsable
self.telefono = pTelefono
self.Ubicacion = pUbicacion
self.Imagen = pImagen
self.Longitud = pLongitud
self.Latitud = pLatitud
super.init()
}
} | apache-2.0 | f338998abf5f834611447428a1367805 | 28.317073 | 238 | 0.653622 | 3.345404 | false | false | false | false |
liuCodeBoy/Ant | Ant/Ant/LunTan/Detials/Controller/CarBusinessDVC.swift | 1 | 9868 | //
// CarBusinessDVC.swift
// Ant
//
// Created by Weslie on 2017/8/4.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class CarBusinessDVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var modelInfo: LunTanDetialModel?
var menuView = Menu()
override func viewDidLoad() {
super.viewDidLoad()
loadCellData(index: 1)
loadDetialTableView()
self.tabBarController?.tabBar.isHidden = true
menuView.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60)
self.view.addSubview(menuView)
}
func loadDetialTableView() {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60)
self.tableView = UITableView(frame: frame, style: .grouped)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.tableView?.separatorStyle = .singleLine
tableView?.register(UINib(nibName: "CarBusinessBasicInfo", bundle: nil), forCellReuseIdentifier: "carBusinessBasicInfo")
tableView?.register(UINib(nibName: "CarBusinessDetial", bundle: nil), forCellReuseIdentifier: "carBusinessDetial")
tableView?.register(UINib(nibName: "LocationInfo", bundle: nil), forCellReuseIdentifier: "locationInfo")
tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction")
tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions")
tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader")
tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell")
tableView?.separatorStyle = .singleLine
self.view.addSubview(tableView!)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 3
case 2: return 5
case 4: return 10
default: return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 0.6)
let urls = [
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVHOV0AI20009.jpg",
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVIJ30AI20009.png",
"http://img5.cache.netease.com/photo/0009/2016-05-27/BO1HVLIM0AI20009.jpg",
"http://img6.cache.netease.com/photo/0009/2016-05-27/BO1HVJCD0AI20009.jpg",
"http://img2.cache.netease.com/photo/0009/2016-05-27/BO1HVPUT0AI20009.png"
]
var urlArray: [URL] = [URL]()
for str in urls {
let url = URL(string: str)
urlArray.append(url!)
}
return LoopView(images: urlArray, frame: frame, isAutoScroll: true) case 1:
let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
detialHeader?.DetialHeaderLabel.text = "详情介绍"
return detialHeader
case 2:
let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
connactHeader?.DetialHeaderLabel.text = "联系人方式"
return connactHeader
default:
return nil
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 2 {
return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView
} else {
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return UIScreen.main.bounds.width * 0.6
case 1:
return 30
case 2:
return 30
case 3:
return 10
case 4:
return 0.00001
default:
return 0.00001
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 {
return 140
} else {
return 0.00001
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell = tableView.dequeueReusableCell(withIdentifier: "carBusinessBasicInfo")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "carBusinessDetial")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 2: cell = tableView.dequeueReusableCell(withIdentifier: "locationInfo")
default: break
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "detialControduction")
case 2:
let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions
// guard modelInfo.con else {
// <#statements#>
// }
if let contact = modelInfo?.connactDict[indexPath.row] {
if let key = contact.first?.key{
connactoptions.con_Ways.text = key
}
}
if let value = modelInfo?.connactDict[indexPath.row].first?.value {
connactoptions.con_Detial.text = value
}
switch modelInfo?.connactDict[indexPath.row].first?.key {
case "联系人"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile")
case "电话"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone")
menuView.phoneURL = (modelInfo?.connactDict[indexPath.row].first?.value)!
case "微信"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat")
UIPasteboard.general.string = (modelInfo?.connactDict[indexPath.row].first?.value)!
case "QQ"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq")
case "邮箱"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email")
default:
break
}
cell = connactoptions
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
}
case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader")
case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell")
default: break
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return 60
case 1: return 120
case 2: return 40
default: return 20
}
case 1:
return detialHeight + 10
case 2:
return 50
case 3:
return 40
case 4:
return 120
default:
return 20
}
}
}
extension CarBusinessDVC {
// MARK:- load data
fileprivate func loadCellData(index: Int) {
let group = DispatchGroup()
//将当前的下载操作添加到组中
group.enter()
NetWorkTool.shareInstance.infoDetial(VCType: .car, id: index + 1) { [weak self](result, error) in
//在这里异步加载任务
if error != nil {
print(error ?? "load house info list failed")
return
}
guard let resultDict = result!["result"] else {
return
}
let basic = LunTanDetialModel(dict: resultDict as! [String : AnyObject])
self?.modelInfo = basic
//离开当前组
group.leave()
}
group.notify(queue: DispatchQueue.main) {
//在这里告诉调用者,下完完毕,执行下一步操作
self.tableView?.reloadData()
}
}
}
| apache-2.0 | 4f6e5c57685fe157f44ad7d8cce5d959 | 35.062963 | 130 | 0.564034 | 4.927632 | false | false | false | false |
iphone4peru/ejercicios_videos_youtube | EjemploTableViewExtensions/EjemploTableView/ViewController.swift | 1 | 1971 | //
// ViewController.swift
// EjemploTableView
//
// Created by Christian Quicano on 9/6/15.
// Copyright (c) 2015 iphone4peru.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController{
let items = [["title":"IPHONE4PERU", "rutaImagen":"http://www.iphone4peru.com/view/images/logo.png"]]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let imagen = cell.viewWithTag(1) as! UIImageView
let titulo = cell.viewWithTag(2) as! UILabel
titulo.text = items[indexPath.row]["title"]
imagen.imageFromUrl(items[indexPath.row]["rutaImagen"]!, completed: {
println("termino la descarga")
})
return cell
}
}
extension UIImageView {
public func imageFromUrl(urlS: String, completed:()->()) {
if let url = NSURL(string: urlS) {
NSOperationQueue().addOperationWithBlock{
[unowned self] ()->() in
if let data = NSData(contentsOfURL: url) {
if let image = UIImage(data: data){
NSOperationQueue.mainQueue().addOperationWithBlock({
self.image = image
completed()
})
}
}
}
}
}
}
| gpl-2.0 | 8bebe81d6af944e67cf8808c72271950 | 26.375 | 115 | 0.589548 | 5.053846 | false | false | false | false |
AsyncNinja/AsyncNinja | Sources/AsyncNinjaReactiveUI/appleOS_ReactiveProperties.swift | 1 | 15897 | //
// Copyright (c) 2016-2019 Anton Mironov
//
// 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 AsyncNinja
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// `ReactiveProperties` is an adaptor for reactive properties.
public struct ReactiveProperties<Object: NSObject&Retainer> {
/// a getter that could be provided as customization point
public typealias CustomGetter<T> = (Object) -> T?
/// a setter that could be provided as customization point
public typealias CustomSetter<T> = (Object, T) -> Void
/// object that hosts reactive properties
public var object: Object
/// executor to update object on
public var executor: Executor
/// original exectutor this instance was created on
public var originalExecutor: Executor?
/// observation session used by this instance
public var observationSession: ObservationSession?
/// designated initalizer
public init(
object: Object,
executor: Executor,
originalExecutor: Executor?,
observationSession: ObservationSession?) {
self.object = object
self.executor = executor
self.originalExecutor = originalExecutor
self.observationSession = observationSession
}
func reactiveProperties<O: NSObject&Retainer>(with object: O) -> ReactiveProperties<O> {
return ReactiveProperties<O>(object: object,
executor: executor,
originalExecutor: originalExecutor,
observationSession: observationSession)
}
}
public extension ReactiveProperties {
/// makes an `UpdatableProperty<T?>` for specified key path.
///
/// `UpdatableProperty` is a kind of `Producer` so you can:
/// * subscribe for updates
/// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ...
/// * update manually with `update()` method
/// * bind `Channel` to an `UpdatableProperty` using `Channel.bind`
///
/// - Parameter keyPath: to observe.
///
/// **Make sure that keyPath refers to KVO-compliant property**.
/// * Make sure that properties defined in swift have dynamic attribute.
/// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>`
/// return correct values for read-only properties
/// - Parameter allowSettingSameValue: set to true if you want
/// to set a new value event if it is equal to an old one
/// - Parameter channelBufferSize: size of the buffer within returned channel
/// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call
/// - Parameter customSetter: provides a custom getter to use instead of setValue(_: forKeyPath:) call
/// - Returns: an `UpdatableProperty<T?>` bound to observe and update specified keyPath
func updatable<T>(
forKeyPath keyPath: String,
allowSettingSameValue: Bool = false,
channelBufferSize: Int = 1,
customGetter: CustomGetter<T?>? = nil,
customSetter: CustomSetter<T?>? = nil
) -> ProducerProxy<T?, Void> {
return object.updatable(forKeyPath: keyPath,
executor: executor,
from: originalExecutor,
observationSession: observationSession,
allowSettingSameValue: allowSettingSameValue,
channelBufferSize: channelBufferSize,
customGetter: customGetter,
customSetter: customSetter)
}
/// makes an `UpdatableProperty<T>` for specified key path.
///
/// `UpdatableProperty` is a kind of `Producer` so you can:
/// * subscribe for updates
/// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ...
/// * update manually with `update()` method
/// * bind `Channel` to an `UpdatableProperty` using `Channel.bind`
///
/// - Parameter keyPath: to observe.
///
/// **Make sure that keyPath refers to KVO-compliant property**.
/// * Make sure that properties defined in swift have dynamic attribute.
/// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>`
/// return correct values for read-only properties
/// - Parameter onNone: is a policy of handling `None` (or `nil`) value
/// that can arrive from Key-Value observation.
/// - Parameter allowSettingSameValue: set to true if you want
/// to set a new value event if it is equal to an old one
/// - Parameter channelBufferSize: size of the buffer within returned channel
/// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call
/// - Parameter customSetter: provides a custom getter to use instead of setValue(_: forKeyPath:) call
/// - Returns: an `UpdatableProperty<T>` bound to observe and update specified keyPath
func updatable<T>(
forKeyPath keyPath: String,
onNone: UpdateWithNoneHandlingPolicy<T>,
allowSettingSameValue: Bool = false,
channelBufferSize: Int = 1,
customGetter: CustomGetter<T>? = nil,
customSetter: CustomSetter<T>? = nil
) -> ProducerProxy<T, Void> {
return object.updatable(forKeyPath: keyPath,
onNone: onNone,
executor: executor,
from: originalExecutor,
observationSession: observationSession,
allowSettingSameValue: allowSettingSameValue,
channelBufferSize: channelBufferSize,
customGetter: customGetter,
customSetter: customSetter)
}
/// makes an `Updating<T?>` for specified key path.
///
/// `Updating` is a kind of `Channel` so you can:
/// * subscribe for updates
/// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ...
///
/// - Parameter keyPath: to observe.
///
/// **Make sure that keyPath refers to KVO-compliant property**.
/// * Make sure that properties defined in swift have dynamic attribute.
/// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>`
/// return correct values for read-only properties
/// - Parameter channelBufferSize: size of the buffer within returned channel
/// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call
/// - Returns: an `Updating<T?>` bound to observe and update specified keyPath
func updating<T>(
forKeyPath keyPath: String,
channelBufferSize: Int = 1,
customGetter: CustomGetter<T>? = nil
) -> Channel<T?, Void> {
return object.updating(forKeyPath: keyPath,
executor: executor,
from: originalExecutor,
observationSession: observationSession,
channelBufferSize: channelBufferSize,
customGetter: customGetter)
}
/// makes an `Updating<T>` for specified key path.
///
/// `Updating` is a kind of `Channel` so you can:
/// * subscribe for updates
/// * transform using `map`, `flatMap`, `filter`, `debounce`, `distinct`, ...
///
/// - Parameter keyPath: to observe.
///
/// **Make sure that keyPath refers to KVO-compliant property**.
/// * Make sure that properties defined in swift have dynamic attribute.
/// * Make sure that methods `class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>`
/// return correct values for read-only properties
/// - Parameter onNone: is a policy of handling `None` (or `nil`) value
/// that can arrive from Key-Value observation.
/// - Parameter channelBufferSize: size of the buffer within returned channel
/// - Parameter customGetter: provides a custom getter to use instead of value(forKeyPath:) call
/// - Returns: an `Updating<T>` bound to observe and update specified keyPath
func updating<T>(
forKeyPath keyPath: String,
onNone: UpdateWithNoneHandlingPolicy<T>,
channelBufferSize: Int = 1,
customGetter: CustomGetter<T>? = nil
) -> Channel<T, Void> {
return object.updating(forKeyPath: keyPath,
onNone: onNone,
executor: executor,
from: originalExecutor,
observationSession: observationSession,
channelBufferSize: channelBufferSize,
customGetter: customGetter)
}
/// Makes a sink that wraps specified setter
///
/// - Parameter setter: to use with sink
/// - Returns: constructed sink
func sink<T>(setter: @escaping CustomSetter<T>) -> Sink<T, Void> {
return object.sink(executor: executor, setter: setter)
}
}
public extension Retainer where Self: NSObject {
/// Makes a `ReactiveProperties` bount to `self` that captures specified values
///
/// - Parameter executor: to subscribe and update value on
/// - Parameter originalExecutor: `Executor` you calling this method on.
/// Specifying this argument will allow to perform syncronous executions
/// on `strictAsync: false` `Executor`s.
/// Use default value or nil if you are not sure about an `Executor`
/// you calling this method on.
/// - Parameter observationSession: is an object that helps to control observation
/// - Returns: `ReactiveProperties` that capture specified values
func reactiveProperties(
executor: Executor,
from originalExecutor: Executor? = nil,
observationSession: ObservationSession? = nil
) -> ReactiveProperties<Self> {
return ReactiveProperties(object: self,
executor: executor,
originalExecutor: originalExecutor,
observationSession: observationSession)
}
}
public extension ExecutionContext where Self: NSObject {
/// Makes a `ReactiveProperties` bount to `self` that captures specified values
///
/// - Parameter originalExecutor: `Executor` you calling this method on.
/// Specifying this argument will allow to perform syncronous executions
/// on `strictAsync: false` `Executor`s.
/// Use default value or nil if you are not sure about an `Executor`
/// you calling this method on.
/// - Parameter observationSession: is an object that helps to control observation
/// - Returns: `ReactiveProperties` that capture specified values
func reactiveProperties(
from originalExecutor: Executor? = .immediate,
observationSession: ObservationSession? = nil
) -> ReactiveProperties<Self> {
return reactiveProperties(executor: executor,
from: originalExecutor,
observationSession: observationSession)
}
/// Short and useful property that returns `ReactiveProperties` and covers `99%` of use cases
var rp: ReactiveProperties<Self> { return reactiveProperties(from: executor) }
}
#endif
#if os(macOS)
import AppKit
public extension ReactiveProperties {
func anyUpdatable(
forBindingName bindingName: NSBindingName,
initialValue: Any?) -> ProducerProxy<Any?, Void> {
return object.updatable(
forBindingName: bindingName,
executor: executor,
from: originalExecutor,
observationSession: observationSession,
initialValue: initialValue
)
}
func updatable<T>(
forBindingName bindingName: NSBindingName,
channelBufferSize: Int = 1,
initialValue: T?,
transformer: @escaping (Any?) -> T? = { $0 as? T },
reveseTransformer: @escaping (T?) -> Any? = { $0 }
) -> ProducerProxy<T?, Void> {
let typeerasedProducerProxy = object.updatable(forBindingName: bindingName,
executor: executor,
from: originalExecutor,
observationSession: observationSession,
initialValue: initialValue)
var isTypesafeProxyUpdatingEnabled = true
let typesafeProducerProxy = ProducerProxy<T?, Void>(
updateExecutor: executor,
bufferSize: channelBufferSize
) { [weak typeerasedProducerProxy] (_, event, originalExecutor) in
isTypesafeProxyUpdatingEnabled = false
guard let typeerasedProducerProxy = typeerasedProducerProxy else { return }
switch event {
case .update(let update):
let transformedUpdate = reveseTransformer(update)
typeerasedProducerProxy.update(transformedUpdate, from: originalExecutor)
case .completion(let completion):
typeerasedProducerProxy.complete(completion, from: originalExecutor)
}
isTypesafeProxyUpdatingEnabled = true
}
let handler = typeerasedProducerProxy.makeUpdateHandler(
executor: .immediate
) { [weak typesafeProducerProxy] (update, originalExecutor) in
guard
isTypesafeProxyUpdatingEnabled,
let typesafeProducerProxy = typesafeProducerProxy
else { return }
_ = typesafeProducerProxy.tryUpdateWithoutHandling(transformer(update), from: originalExecutor)
}
typesafeProducerProxy._asyncNinja_retainHandlerUntilFinalization(handler)
return typesafeProducerProxy
}
}
#endif
// MARK: -
#if os(macOS) || os(iOS)
import WebKit
// MARK: - reactive properties for WKWebView
public extension ReactiveProperties where Object: WKWebView {
/// `Sink` that refers to write-only `WKWebView.load(_:)`
var loadRequest: Sink<URLRequest, Void> {
func setter(webView: WKWebView, request: URLRequest) {
webView.load(request)
}
return sink(setter: setter)
}
/// `Sink` that refers to write-only `WKWebView.loadFileURL(_:, allowingReadAccessTo:)`
@available(OSX 10.11, iOS 9, *)
var loadFileURL: Sink<(url: URL, readAccessURL: URL), Void> {
func setter(webView: WKWebView, values: (url: URL, readAccessURL: URL)) {
webView.loadFileURL(values.url, allowingReadAccessTo: values.readAccessURL)
}
return sink(setter: setter)
}
/// `Sink` that refers to write-only `WKWebView.loadHTMLString(_:, baseURL:)`
var loadHTMLString: Sink<(string: String, baseURL: URL?), Void> {
func setter(webView: WKWebView, values: (string: String, baseURL: URL?)) {
webView.loadHTMLString(values.string, baseURL: values.baseURL)
}
return sink(setter: setter)
}
/// `Sink` that refers to write-only `load(_:, mimeType:, characterEncodingName:, baseURL:)`
@available(OSX 10.11, iOS 9, *)
var loadData: Sink<(data: Data, mimeType: String, characterEncodingName: String, baseURL: URL), Void> {
return sink {
$0.load($1.data, mimeType: $1.mimeType, characterEncodingName: $1.characterEncodingName, baseURL: $1.baseURL)
}
}
}
#endif
| mit | 449acdbdf533536876866ea1d89cc618 | 42.19837 | 115 | 0.665409 | 4.752466 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00235-swift-genericparamlist-print.swift | 1 | 1951 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
)
func t<v>() -> (v, v -> v) -> v {
var d: ((v, v -> v) -> v)!
q d
}
protocol t {
}
protocol d : t {
}
protocol g : t {
}
s
q l
})
}
d(t(u, t(w, y)))
protocol e {
r j
}
struct m<v : e> {
k x: v
k x: v.j
}
protocol n {
g == o>(n: m<v>) {
}
}
struct e<v> {
k t: [(v, () -> ())] = [](m)
}
struct d<x> : e {
func d(d: d.p) {
}
}
class e<v : e> {
}
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
func i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
protocol a : a {
}
func f<m>() -> (m, m -> m) -> m {
e c e.i = { j func l()q c() ->
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
{
class func i()
}
class d: f{ class func i {}
functh): \(g())" }
}
protocol a : a {
}
func j(d: h) -> <k>(() -> k) -> h {
return { n n "\(}
c i<k : i> {
}
c i: i {
}
c e : l {
}
f = e
protocol m : o h = h
}
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g k{ class func q {}
func r<e: t, s where j<s> == e.m { func g
k q<n : t> {
q g: n
}
func p<n>() -> [q<n>] {
o : g.l) {
}
}
class p {
typealias g = g
o
class w<r>: c {
init(g: r) {
n.g = g
s.init()
(t: o
struct t : o {
p v = t
}
q t<where n.v == t<v : o u m : v {
}
strass l: j{ k() -> ())
}
({})
func j<o E == F>(f: B<T>)
}
struct }
}
| apache-2.0 | eefd30ff0519277d056b19fe7062c3c3 | 14.362205 | 79 | 0.474628 | 2.367718 | false | false | false | false |
mzyy94/TesSoMe | TesSoMe/IntroSignIn.swift | 1 | 3365 | //
// IntroSignIn.swift
// TesSoMe
//
// Created by Yuki Mizuno on 2014/10/08.
// Copyright (c) 2014年 Yuki Mizuno. All rights reserved.
//
import UIKit
class IntroSignIn: UIView, UITextFieldDelegate {
let apiManager = TessoApiManager()
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var signInBtn: UIButton!
@IBAction func signInBtnPressed() {
signIn()
}
override func awakeFromNib() {
super.awakeFromNib()
self.signInBtn.layer.borderColor = UIColor.whiteColor().CGColor
self.signInBtn.layer.borderWidth = 1.0
self.signInBtn.layer.cornerRadius = 4.0
self.signInBtn.clipsToBounds = true
changePlaceholderTextColor(self.usernameField)
changePlaceholderTextColor(self.passwordField)
self.usernameField.delegate = self
self.passwordField.delegate = self
}
func signIn() {
let username = usernameField.text
let password = passwordField.text
apiManager.signIn(username: username, password: password, onSuccess:
{
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.usernameOfTesSoMe = username
appDelegate.passwordOfTesSoMe = password
let serviceName = "TesSoMe"
SSKeychain.setPassword(password, forService: serviceName, account: username)
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("goNextPage"), userInfo: nil, repeats: false)
}
, onFailure:
{ err in
var alertController = UIAlertController(title: NSLocalizedString("Error", comment: "Error on AlertView"), message: err.localizedDescription, preferredStyle: .Alert)
let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: "OK on AlertView"), style: .Default, handler: nil)
alertController.addAction(okAction)
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
)
usernameField.resignFirstResponder()
passwordField.resignFirstResponder()
}
func goNextPage() {
let introView = self.superview?.superview?.superview as EAIntroView
introView.setCurrentPageIndex(introView.currentPageIndex + 1, animated: true)
}
override func layoutSubviews() {
super.layoutSubviews()
drawUnderline(self.usernameField.frame)
drawUnderline(self.passwordField.frame)
}
func changePlaceholderTextColor(textField: UITextField) {
let placeholderText = textField.placeholder
textField.attributedPlaceholder = NSAttributedString(string: placeholderText!, attributes: [NSForegroundColorAttributeName: UIColor(white: 0.9, alpha: 1.0)])
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
if (textField == usernameField) {
passwordField.becomeFirstResponder()
} else if (textField == passwordField) {
passwordField.resignFirstResponder()
signIn()
}
return true
}
func drawUnderline(frame: CGRect) {
let line = CAShapeLayer()
let path = UIBezierPath()
let start = CGPoint(x: frame.origin.x, y: frame.origin.y + frame.height)
let end = CGPoint(x: start.x + frame.width, y: start.y)
path.moveToPoint(start)
path.addLineToPoint(end)
line.path = path.CGPath
line.strokeColor = UIColor.whiteColor().CGColor
line.fillColor = nil
line.lineWidth = 1.0
self.layer.addSublayer(line)
}
}
| gpl-3.0 | 87326a9c090214029b6aaaecd3a94eae | 27.991379 | 168 | 0.739221 | 4.076364 | false | false | false | false |
ParsePlatform/Parse-SDK-iOS-OSX | ParseStarterProject/iOS/ParseStarterProject-Swift/ParseStarterProject/AppDelegate.swift | 1 | 6728 | /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import UserNotifications
import Parse
// If you want to use any of the UI components, uncomment this line
// import ParseUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// ****************************************************************************
// Initialize Parse SDK
// ****************************************************************************
let configuration = ParseClientConfiguration {
// Add your Parse applicationId:
$0.applicationId = "your_application_id"
// Uncomment and add your clientKey (it's not required if you are using Parse Server):
$0.clientKey = "your_client_key"
// Uncomment the following line and change to your Parse Server address;
$0.server = "https://YOUR_PARSE_SERVER/parse"
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
$0.isLocalDatastoreEnabled = true
}
Parse.initialize(with: configuration)
// ****************************************************************************
// If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
// described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
// Uncomment the line inside ParseStartProject-Bridging-Header and the following line here:
// PFFacebookUtils.initializeFacebook()
// ****************************************************************************
PFUser.enableAutomaticUser()
let defaultACL = PFACL()
// If you would like all objects to be private by default, remove this line.
defaultACL.getPublicReadAccess = true
PFACL.setDefault(defaultACL, withAccessForCurrentUser: true)
if application.applicationState != UIApplicationState.background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let oldPushHandlerOnly = !responds(to: #selector(UIApplicationDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:)))
var noPushPayload = false
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsKey.remoteNotification] == nil
}
if oldPushHandlerOnly || noPushPayload {
PFAnalytics.trackAppOpened(launchOptions: launchOptions)
}
}
if #available(iOS 10.0, *) {
// iOS 10+
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
print("Notifications access granted: \(granted.description)")
}
application.registerForRemoteNotifications()
} else {
// iOS 8, 9
let types: UIUserNotificationType = [.alert, .badge, .sound]
let settings = UIUserNotificationSettings(types: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
return true
}
//--------------------------------------
// MARK: Push Notifications
//--------------------------------------
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let installation = PFInstallation.current()
installation?.setDeviceTokenFrom(deviceToken)
installation?.saveInBackground()
PFPush.subscribeToChannel(inBackground: "") { succeeded, error in
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n")
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error!)
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
if error._code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", error)
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
PFPush.handle(userInfo)
if application.applicationState == UIApplicationState.inactive {
PFAnalytics.trackAppOpened(withRemoteNotificationPayload: userInfo)
}
}
///////////////////////////////////////////////////////////
// Uncomment this method if you want to use Push Notifications with Background App Refresh
///////////////////////////////////////////////////////////
// func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// if application.applicationState == UIApplicationState.Inactive {
// PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
// }
// }
//--------------------------------------
// MARK: Facebook SDK Integration
//--------------------------------------
///////////////////////////////////////////////////////////
// Uncomment this method if you are using Facebook
///////////////////////////////////////////////////////////
// func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
// return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session())
// }
}
| bsd-3-clause | ff9b9d98cba4fec26223f48c085f3971 | 44.768707 | 193 | 0.592449 | 6.110808 | false | false | false | false |
SlimGinz/HomeworkHelper | Pods/CocoaLumberjack/Classes/CocoaLumberjack.swift | 12 | 4805 | // Software License Agreement (BSD License)
//
// Copyright (c) 2014, 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.
import Foundation
import CocoaLumberjack
extension DDLogFlag {
public static func fromLogLevel(logLevel: DDLogLevel) -> DDLogFlag {
return DDLogFlag(logLevel.rawValue)
}
/**
* returns the log level, or the lowest equivalant.
*/
public func toLogLevel() -> DDLogLevel {
if let ourValid = DDLogLevel(rawValue: self.rawValue) {
return ourValid
} else {
let logFlag = self
if logFlag & .Verbose == .Verbose {
return .Error
} else if logFlag & .Debug == .Debug {
return .Debug
} else if logFlag & .Info == .Info {
return .Info
} else if logFlag & .Warning == .Warning {
return .Warning
} else if logFlag & .Error == .Error {
return .Verbose
} else {
return .Off
}
}
}
}
extension DDMultiFormatter {
public var formatterArray: [DDLogFormatter] {
return self.formatters as [DDLogFormatter]
}
}
public var defaultDebugLevel = DDLogLevel.Warning
public func resetDefaultDebugLevel() {
defaultDebugLevel = DDLogLevel.Warning
}
public func SwiftLogMacro(async: Bool, level: DDLogLevel, flag flg: DDLogFlag, context: UInt = 0, file: String = __FILE__, function: String = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, #format: String, #args: CVaListPointer) {
let string = NSString(format: format, arguments: args) as String
SwiftLogMacro(async, level, flag: flg, context: context, file: file, function: function, line: line, tag: tag, string)
}
public func SwiftLogMacro(isAsynchronous: Bool, level: DDLogLevel, flag flg: DDLogFlag, context: UInt = 0, file: String = __FILE__, function: String = __FUNCTION__, line: UInt = __LINE__, tag: AnyObject? = nil, string: String) {
// Tell the DDLogMessage constructor to copy the C strings that get passed to it.
let logMessage = DDLogMessage(message: string, level: level, flag: flg, context: context, file: file, function: function, line: line, tag: tag, options: .CopyFile | .CopyFunction, timestamp: nil)
DDLog.log(isAsynchronous, message: logMessage)
}
public func DDLogDebug(logText: String, level: DDLogLevel = defaultDebugLevel, file: String = __FILE__, function: String = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true, #args: CVarArgType...) {
SwiftLogMacro(async, level, flag: .Debug, file: file, function: function, line: line, format: logText, args: getVaList(args))
}
public func DDLogInfo(logText: String, level: DDLogLevel = defaultDebugLevel, file: String = __FILE__, function: String = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true, #args: CVarArgType...) {
SwiftLogMacro(async, level, flag: .Info, file: file, function: function, line: line, format: logText, args: getVaList(args))
}
public func DDLogWarn(logText: String, level: DDLogLevel = defaultDebugLevel, file: String = __FILE__, function: String = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true, #args: CVarArgType...) {
SwiftLogMacro(async, level, flag: .Warning, file: file, function: function, line: line, format: logText, args: getVaList(args))
}
public func DDLogVerbose(logText: String, level: DDLogLevel = defaultDebugLevel, file: String = __FILE__, function: String = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true, #args: CVarArgType...) {
SwiftLogMacro(async, level, flag: .Verbose, file: file, function: function, line: line, format: logText, args: getVaList(args))
}
public func DDLogError(logText: String, level: DDLogLevel = defaultDebugLevel, file: String = __FILE__, function: String = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = false, #args: CVarArgType...) {
SwiftLogMacro(async, level, flag: .Error, file: file, function: function, line: line, format: logText, args: getVaList(args))
}
/*!
* Analogous to the C preprocessor macro \c THIS_FILE
*/
public func CurrentFileName(fileName: String = __FILE__) -> String {
return fileName.lastPathComponent.stringByDeletingPathExtension
}
| gpl-2.0 | e1972c3de97dc54dfae42d980b1c4cb7 | 49.052083 | 244 | 0.677836 | 4.171007 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Utility/SharedState.swift | 2 | 1033 | //
// SharedState.swift
// Neocom
//
// Created by Artem Shimanski on 4/14/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import CoreData
import Expressible
import EVEAPI
import Combine
class SharedState: ObservableObject {
@Published var account: Account? {
willSet {
objectWillChange.send()
}
didSet {
accountID = account?.uuid
_esi = account.map{ESI(token: $0.oAuth2Token!)} ?? ESI()
}
}
private var _esi: ESI?
var esi: ESI {
return _esi!
}
let objectWillChange = ObjectWillChangePublisher()
@UserDefault(key: .activeAccountID) private var accountID: String? = nil
init(managedObjectContext: NSManagedObjectContext) {
self.account = try? managedObjectContext.from(Account.self).filter(/\Account.uuid == accountID).first()
_esi = account.map{ESI(token: $0.oAuth2Token!)} ?? ESI()
}
@Published var userActivity: NSUserActivity?
}
| lgpl-2.1 | 6d3ecd890fe8e70799f3f3a317c1e9cb | 23.571429 | 111 | 0.626938 | 4.336134 | false | false | false | false |
daher-alfawares/model | Model/Model/ViewModel.swift | 1 | 995 | //
// ViewModel.swift
// Model
//
// Created by Daher Alfawares on 5/13/16.
// Copyright © 2016 Brandon Chow, 2016 Daher Alfawares. All rights reserved.
//
import Foundation
public protocol ViewModelDelegate : class {
func viewModelUpdated()
}
protocol ViewModelProtocol : ListenerDelegate {
var delegate : ViewModelDelegate? { get }
func newModel(model: Model)
}
class ViewModel : ViewModelProtocol {
private(set) var delegate : ViewModelDelegate?
private(set) var listeners : [String : Listener]
private(set) var models : [String : Model]
init(viewModelDelegate: ViewModelDelegate, modelTypes: [Model.Type]){
delegate = viewModelDelegate
self.listeners = [:]
self.models = [:]
for model in modelTypes {
listeners[model.key()] = Listener(interested: self, forModel: model)
}
}
func newModel(model: Model) {
models[model.key()] = model
delegate?.viewModelUpdated()
}
} | apache-2.0 | d7a88dc052bd0f5caf620603528c913e | 25.184211 | 80 | 0.65493 | 4.194093 | false | false | false | false |
lbkchen/cvicu-app | complicationsapp/Pods/CVCalendar/CVCalendar/CVCalendarContentViewController.swift | 1 | 8025 | //
// CVCalendarContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public typealias Identifier = String
public class CVCalendarContentViewController: UIViewController {
// MARK: - Constants
public let Previous = "Previous"
public let Presented = "Presented"
public let Following = "Following"
// MARK: - Public Properties
public let calendarView: CalendarView
public let scrollView: UIScrollView
public var presentedMonthView: MonthView
public var bounds: CGRect {
return scrollView.bounds
}
public var currentPage = 1
public var pageChanged: Bool {
get {
return currentPage == 1 ? false : true
}
}
public var pageLoadingEnabled = true
public var presentationEnabled = true
public var lastContentOffset: CGFloat = 0
public var direction: CVScrollDirection = .None
public init(calendarView: CalendarView, frame: CGRect) {
self.calendarView = calendarView
scrollView = UIScrollView(frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: NSDate())
presentedMonthView.updateAppearance(frame)
super.init(nibName: nil, bundle: nil)
scrollView.contentSize = CGSizeMake(frame.width * 3, frame.height)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.layer.masksToBounds = true
scrollView.pagingEnabled = true
scrollView.delegate = self
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI Refresh
extension CVCalendarContentViewController {
public func updateFrames(frame: CGRect) {
if frame != CGRectZero {
scrollView.frame = frame
scrollView.removeAllSubviews()
scrollView.contentSize = CGSizeMake(frame.size.width * 3, frame.size.height)
}
calendarView.hidden = false
}
}
//MARK: - Month Refresh
extension CVCalendarContentViewController {
public func refreshPresentedMonth() {
for weekV in presentedMonthView.weekViews {
for dayView in weekV.dayViews {
removeCircleLabel(dayView)
dayView.setupDotMarker()
dayView.preliminarySetup()
dayView.supplementarySetup()
dayView.topMarkerSetup()
}
}
}
}
// MARK: Delete circle views (in effect refreshing the dayView circle)
extension CVCalendarContentViewController {
func removeCircleLabel(dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is UILabel {
continue
}
else if each is CVAuxiliaryView {
continue
}
else {
each.removeFromSuperview()
}
}
}
}
//MARK: Delete dot views (in effect refreshing the dayView dots)
extension CVCalendarContentViewController {
func removeDotViews(dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is CVAuxiliaryView && each.frame.height == 13 {
each.removeFromSuperview()
}
}
}
}
// MARK: - Abstract methods
/// UIScrollViewDelegate
extension CVCalendarContentViewController: UIScrollViewDelegate { }
/// Convenience API.
extension CVCalendarContentViewController {
public func performedDayViewSelection(dayView: DayView) { }
public func togglePresentedDate(date: NSDate) { }
public func presentNextView(view: UIView?) { }
public func presentPreviousView(view: UIView?) { }
public func updateDayViews(hidden: Bool) { }
}
// MARK: - Contsant conversion
extension CVCalendarContentViewController {
public func indexOfIdentifier(identifier: Identifier) -> Int {
let index: Int
switch identifier {
case Previous: index = 0
case Presented: index = 1
case Following: index = 2
default: index = -1
}
return index
}
}
// MARK: - Date management
extension CVCalendarContentViewController {
public func dateBeforeDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
let calendar = NSCalendar.currentCalendar()
components.month -= 1
let dateBefore = calendar.dateFromComponents(components)!
return dateBefore
}
public func dateAfterDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
let calendar = NSCalendar.currentCalendar()
components.month += 1
let dateAfter = calendar.dateFromComponents(components)!
return dateAfter
}
public func matchedMonths(lhs: Date, _ rhs: Date) -> Bool {
return lhs.year == rhs.year && lhs.month == rhs.month
}
public func matchedWeeks(lhs: Date, _ rhs: Date) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week)
}
public func matchedDays(lhs: Date, _ rhs: Date) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day)
}
}
// MARK: - AutoLayout Management
extension CVCalendarContentViewController {
private func layoutViews(views: [UIView], toHeight height: CGFloat) {
scrollView.frame.size.height = height
var superStack = [UIView]()
var currentView: UIView = calendarView
while let currentSuperview = currentView.superview where !(currentSuperview is UIWindow) {
superStack += [currentSuperview]
currentView = currentSuperview
}
for view in views + superStack {
view.layoutIfNeeded()
}
}
public func updateHeight(height: CGFloat, animated: Bool) {
if calendarView.shouldAnimateResizing {
var viewsToLayout = [UIView]()
if let calendarSuperview = calendarView.superview {
for constraintIn in calendarSuperview.constraints {
if let firstItem = constraintIn.firstItem as? UIView, let _ = constraintIn.secondItem as? CalendarView {
viewsToLayout.append(firstItem)
}
}
}
for constraintIn in calendarView.constraints where constraintIn.firstAttribute == NSLayoutAttribute.Height {
constraintIn.constant = height
if animated {
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.layoutViews(viewsToLayout, toHeight: height)
}) { _ in
self.presentedMonthView.frame.size = self.presentedMonthView.potentialSize
self.presentedMonthView.updateInteractiveView()
}
} else {
layoutViews(viewsToLayout, toHeight: height)
presentedMonthView.updateInteractiveView()
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
break
}
}
}
public func updateLayoutIfNeeded() {
if presentedMonthView.potentialSize.height != scrollView.bounds.height {
updateHeight(presentedMonthView.potentialSize.height, animated: true)
} else if presentedMonthView.frame.size != scrollView.frame.size {
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
}
}
extension UIView {
public func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
}
| mit | ec4019031b92d241d7b5a2efc10224b1 | 29.513308 | 124 | 0.631651 | 5.485304 | false | false | false | false |
alblue/swift | stdlib/public/core/FloatingPoint.swift | 2 | 98667 | //===--- FloatingPoint.swift ----------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
/// A floating-point numeric type.
///
/// Floating-point types are used to represent fractional numbers, like 5.5,
/// 100.0, or 3.14159274. Each floating-point type has its own possible range
/// and precision. The floating-point types in the standard library are
/// `Float`, `Double`, and `Float80` where available.
///
/// Create new instances of floating-point types using integer or
/// floating-point literals. For example:
///
/// let temperature = 33.2
/// let recordHigh = 37.5
///
/// The `FloatingPoint` protocol declares common arithmetic operations, so you
/// can write functions and algorithms that work on any floating-point type.
/// The following example declares a function that calculates the length of
/// the hypotenuse of a right triangle given its two perpendicular sides.
/// Because the `hypotenuse(_:_:)` function uses a generic parameter
/// constrained to the `FloatingPoint` protocol, you can call it using any
/// floating-point type.
///
/// func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T {
/// return (a * a + b * b).squareRoot()
/// }
///
/// let (dx, dy) = (3.0, 4.0)
/// let distance = hypotenuse(dx, dy)
/// // distance == 5.0
///
/// Floating-point values are represented as a *sign* and a *magnitude*, where
/// the magnitude is calculated using the type's *radix* and the instance's
/// *significand* and *exponent*. This magnitude calculation takes the
/// following form for a floating-point value `x` of type `F`, where `**` is
/// exponentiation:
///
/// x.significand * F.radix ** x.exponent
///
/// Here's an example of the number -8.5 represented as an instance of the
/// `Double` type, which defines a radix of 2.
///
/// let y = -8.5
/// // y.sign == .minus
/// // y.significand == 1.0625
/// // y.exponent == 3
///
/// let magnitude = 1.0625 * Double(2 ** 3)
/// // magnitude == 8.5
///
/// Types that conform to the `FloatingPoint` protocol provide most basic
/// (clause 5) operations of the [IEEE 754 specification][spec]. The base,
/// precision, and exponent range are not fixed in any way by this protocol,
/// but it enforces the basic requirements of any IEEE 754 floating-point
/// type.
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// Additional Considerations
/// =========================
///
/// In addition to representing specific numbers, floating-point types also
/// have special values for working with overflow and nonnumeric results of
/// calculation.
///
/// Infinity
/// --------
///
/// Any value whose magnitude is so great that it would round to a value
/// outside the range of representable numbers is rounded to *infinity*. For a
/// type `F`, positive and negative infinity are represented as `F.infinity`
/// and `-F.infinity`, respectively. Positive infinity compares greater than
/// every finite value and negative infinity, while negative infinity compares
/// less than every finite value and positive infinity. Infinite values with
/// the same sign are equal to each other.
///
/// let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity]
/// print(values.sorted())
/// // Prints "[-inf, -10.0, 10.0, 25.0, inf]"
///
/// Operations with infinite values follow real arithmetic as much as possible:
/// Adding or subtracting a finite value, or multiplying or dividing infinity
/// by a nonzero finite value, results in infinity.
///
/// NaN ("not a number")
/// --------------------
///
/// Floating-point types represent values that are neither finite numbers nor
/// infinity as NaN, an abbreviation for "not a number." Comparing a NaN with
/// any value, including another NaN, results in `false`.
///
/// let myNaN = Double.nan
/// print(myNaN > 0)
/// // Prints "false"
/// print(myNaN < 0)
/// // Prints "false"
/// print(myNaN == .nan)
/// // Prints "false"
///
/// Because testing whether one NaN is equal to another NaN results in `false`,
/// use the `isNaN` property to test whether a value is NaN.
///
/// print(myNaN.isNaN)
/// // Prints "true"
///
/// NaN propagates through many arithmetic operations. When you are operating
/// on many values, this behavior is valuable because operations on NaN simply
/// forward the value and don't cause runtime errors. The following example
/// shows how NaN values operate in different contexts.
///
/// Imagine you have a set of temperature data for which you need to report
/// some general statistics: the total number of observations, the number of
/// valid observations, and the average temperature. First, a set of
/// observations in Celsius is parsed from strings to `Double` values:
///
/// let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"]
/// let tempsCelsius = temperatureData.map { Double($0) ?? .nan }
/// // tempsCelsius == [21.5, 19.25, 27, nan, 28.25, nan, 23.0]
///
/// Note that some elements in the `temperatureData ` array are not valid
/// numbers. When these invalid strings are parsed by the `Double` failable
/// initializer, the example uses the nil-coalescing operator (`??`) to
/// provide NaN as a fallback value.
///
/// Next, the observations in Celsius are converted to Fahrenheit:
///
/// let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 }
/// // tempsFahrenheit == [70.7, 66.65, 80.6, nan, 82.85, nan, 73.4]
///
/// The NaN values in the `tempsCelsius` array are propagated through the
/// conversion and remain NaN in `tempsFahrenheit`.
///
/// Because calculating the average of the observations involves combining
/// every value of the `tempsFahrenheit` array, any NaN values cause the
/// result to also be NaN, as seen in this example:
///
/// let badAverage = tempsFahrenheit.reduce(0.0, combine: +) / Double(tempsFahrenheit.count)
/// // badAverage.isNaN == true
///
/// Instead, when you need an operation to have a specific numeric result,
/// filter out any NaN values using the `isNaN` property.
///
/// let validTemps = tempsFahrenheit.filter { !$0.isNaN }
/// let average = validTemps.reduce(0.0, combine: +) / Double(validTemps.count)
///
/// Finally, report the average temperature and observation counts:
///
/// print("Average: \(average)°F in \(validTemps.count) " +
/// "out of \(tempsFahrenheit.count) observations.")
/// // Prints "Average: 74.84°F in 5 out of 7 observations."
public protocol FloatingPoint : SignedNumeric, Strideable, Hashable
where Magnitude == Self {
/// A type that can represent any written exponent.
associatedtype Exponent: SignedInteger
/// Creates a new value from the given sign, exponent, and significand.
///
/// The following example uses this initializer to create a new `Double`
/// instance. `Double` is a binary floating-point type that has a radix of
/// `2`.
///
/// let x = Double(sign: .plus, exponent: -2, significand: 1.5)
/// // x == 0.375
///
/// This initializer is equivalent to the following calculation, where `**`
/// is exponentiation, computed as if by a single, correctly rounded,
/// floating-point operation:
///
/// let sign: FloatingPointSign = .plus
/// let exponent = -2
/// let significand = 1.5
/// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent
/// // y == 0.375
///
/// As with any basic operation, if this value is outside the representable
/// range of the type, overflow or underflow occurs, and zero, a subnormal
/// value, or infinity may result. In addition, there are two other edge
/// cases:
///
/// - If the value you pass to `significand` is zero or infinite, the result
/// is zero or infinite, regardless of the value of `exponent`.
/// - If the value you pass to `significand` is NaN, the result is NaN.
///
/// For any floating-point value `x` of type `F`, the result of the following
/// is equal to `x`, with the distinction that the result is canonicalized
/// if `x` is in a noncanonical encoding:
///
/// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand)
///
/// This initializer implements the `scaleB` operation defined by the [IEEE
/// 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - sign: The sign to use for the new value.
/// - exponent: The new value's exponent.
/// - significand: The new value's significand.
init(sign: FloatingPointSign, exponent: Exponent, significand: Self)
/// Creates a new floating-point value using the sign of one value and the
/// magnitude of another.
///
/// The following example uses this initializer to create a new `Double`
/// instance with the sign of `a` and the magnitude of `b`:
///
/// let a = -21.5
/// let b = 305.15
/// let c = Double(signOf: a, magnitudeOf: b)
/// print(c)
/// // Prints "-305.15"
///
/// This initializer implements the IEEE 754 `copysign` operation.
///
/// - Parameters:
/// - signOf: A value from which to use the sign. The result of the
/// initializer has the same sign as `signOf`.
/// - magnitudeOf: A value from which to use the magnitude. The result of
/// the initializer has the same magnitude as `magnitudeOf`.
init(signOf: Self, magnitudeOf: Self)
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
init(_ value: Int)
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
init<Source : BinaryInteger>(_ value: Source)
/// Creates a new value, if the given integer can be represented exactly.
///
/// If the given integer cannot be represented exactly, the result is `nil`.
///
/// - Parameter value: The integer to convert to a floating-point value.
init?<Source : BinaryInteger>(exactly value: Source)
/// The radix, or base of exponentiation, for a floating-point type.
///
/// The magnitude of a floating-point value `x` of type `F` can be calculated
/// by using the following formula, where `**` is exponentiation:
///
/// let magnitude = x.significand * F.radix ** x.exponent
///
/// A conforming type may use any integer radix, but values other than 2 (for
/// binary floating-point types) or 10 (for decimal floating-point types)
/// are extraordinarily rare in practice.
static var radix: Int { get }
/// A quiet NaN ("not a number").
///
/// A NaN compares not equal, not greater than, and not less than every
/// value, including itself. Passing a NaN to an operation generally results
/// in NaN.
///
/// let x = 1.21
/// // x > Double.nan == false
/// // x < Double.nan == false
/// // x == Double.nan == false
///
/// Because a NaN always compares not equal to itself, to test whether a
/// floating-point value is NaN, use its `isNaN` property instead of the
/// equal-to operator (`==`). In the following example, `y` is NaN.
///
/// let y = x + Double.nan
/// print(y == Double.nan)
/// // Prints "false"
/// print(y.isNaN)
/// // Prints "true"
static var nan: Self { get }
/// A signaling NaN ("not a number").
///
/// The default IEEE 754 behavior of operations involving a signaling NaN is
/// to raise the Invalid flag in the floating-point environment and return a
/// quiet NaN.
///
/// Operations on types conforming to the `FloatingPoint` protocol should
/// support this behavior, but they might also support other options. For
/// example, it would be reasonable to implement alternative operations in
/// which operating on a signaling NaN triggers a runtime error or results
/// in a diagnostic for debugging purposes. Types that implement alternative
/// behaviors for a signaling NaN must document the departure.
///
/// Other than these signaling operations, a signaling NaN behaves in the
/// same manner as a quiet NaN.
static var signalingNaN: Self { get }
/// Positive infinity.
///
/// Infinity compares greater than all finite numbers and equal to other
/// infinite values.
///
/// let x = Double.greatestFiniteMagnitude
/// let y = x * 2
/// // y == Double.infinity
/// // y > x
static var infinity: Self { get }
/// The greatest finite number representable by this type.
///
/// This value compares greater than or equal to all finite numbers, but less
/// than `infinity`.
///
/// This value corresponds to type-specific C macros such as `FLT_MAX` and
/// `DBL_MAX`. The naming of those macros is slightly misleading, because
/// `infinity` is greater than this value.
static var greatestFiniteMagnitude: Self { get }
/// The mathematical constant pi.
///
/// This value should be rounded toward zero to keep user computations with
/// angles from inadvertently ending up in the wrong quadrant. A type that
/// conforms to the `FloatingPoint` protocol provides the value for `pi` at
/// its best possible precision.
///
/// print(Double.pi)
/// // Prints "3.14159265358979"
static var pi: Self { get }
// NOTE: Rationale for "ulp" instead of "epsilon":
// We do not use that name because it is ambiguous at best and misleading
// at worst:
//
// - Historically several definitions of "machine epsilon" have commonly
// been used, which differ by up to a factor of two or so. By contrast
// "ulp" is a term with a specific unambiguous definition.
//
// - Some languages have used "epsilon" to refer to wildly different values,
// such as `leastNonzeroMagnitude`.
//
// - Inexperienced users often believe that "epsilon" should be used as a
// tolerance for floating-point comparisons, because of the name. It is
// nearly always the wrong value to use for this purpose.
/// The unit in the last place of this value.
///
/// This is the unit of the least significant digit in this value's
/// significand. For most numbers `x`, this is the difference between `x`
/// and the next greater (in magnitude) representable number. There are some
/// edge cases to be aware of:
///
/// - If `x` is not a finite number, then `x.ulp` is NaN.
/// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal
/// number. If a type does not support subnormals, `x.ulp` may be rounded
/// to zero.
/// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next
/// greater representable value is `infinity`.
///
/// This quantity, or a related quantity, is sometimes called *epsilon* or
/// *machine epsilon.* Avoid that name because it has different meanings in
/// different languages, which can lead to confusion, and because it
/// suggests that it is a good tolerance to use for comparisons, which it
/// almost never is.
var ulp: Self { get }
/// The unit in the last place of 1.0.
///
/// The positive difference between 1.0 and the next greater representable
/// number. The `ulpOfOne` constant corresponds to the C macros
/// `FLT_EPSILON`, `DBL_EPSILON`, and others with a similar purpose.
static var ulpOfOne: Self { get }
/// The least positive normal number.
///
/// This value compares less than or equal to all positive normal numbers.
/// There may be smaller positive numbers, but they are *subnormal*, meaning
/// that they are represented with less precision than normal numbers.
///
/// This value corresponds to type-specific C macros such as `FLT_MIN` and
/// `DBL_MIN`. The naming of those macros is slightly misleading, because
/// subnormals, zeros, and negative numbers are smaller than this value.
static var leastNormalMagnitude: Self { get }
/// The least positive number.
///
/// This value compares less than or equal to all positive numbers, but
/// greater than zero. If the type supports subnormal values,
/// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`;
/// otherwise they are equal.
static var leastNonzeroMagnitude: Self { get }
/// The sign of the floating-point value.
///
/// The `sign` property is `.minus` if the value's signbit is set, and
/// `.plus` otherwise. For example:
///
/// let x = -33.375
/// // x.sign == .minus
///
/// Do not use this property to check whether a floating point value is
/// negative. For a value `x`, the comparison `x.sign == .minus` is not
/// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if
/// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign`
/// could be either `.plus` or `.minus`.
var sign: FloatingPointSign { get }
/// The exponent of the floating-point value.
///
/// The *exponent* of a floating-point value is the integer part of the
/// logarithm of the value's magnitude. For a value `x` of a floating-point
/// type `F`, the magnitude can be calculated as the following, where `**`
/// is exponentiation:
///
/// let magnitude = x.significand * F.radix ** x.exponent
///
/// In the next example, `y` has a value of `21.5`, which is encoded as
/// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375.
///
/// let y: Double = 21.5
/// // y.significand == 1.34375
/// // y.exponent == 4
/// // Double.radix == 2
///
/// The `exponent` property has the following edge cases:
///
/// - If `x` is zero, then `x.exponent` is `Int.min`.
/// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max`
///
/// This property implements the `logB` operation defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
var exponent: Exponent { get }
/// The significand of the floating-point value.
///
/// The magnitude of a floating-point value `x` of type `F` can be calculated
/// by using the following formula, where `**` is exponentiation:
///
/// let magnitude = x.significand * F.radix ** x.exponent
///
/// In the next example, `y` has a value of `21.5`, which is encoded as
/// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375.
///
/// let y: Double = 21.5
/// // y.significand == 1.34375
/// // y.exponent == 4
/// // Double.radix == 2
///
/// If a type's radix is 2, then for finite nonzero numbers, the significand
/// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand`
/// is defined as follows:
///
/// - If `x` is zero, then `x.significand` is 0.0.
/// - If `x` is infinity, then `x.significand` is 1.0.
/// - If `x` is NaN, then `x.significand` is NaN.
/// - Note: The significand is frequently also called the *mantissa*, but
/// significand is the preferred terminology in the [IEEE 754
/// specification][spec], to allay confusion with the use of mantissa for
/// the fractional part of a logarithm.
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
var significand: Self { get }
/// Adds two values and produces their sum, rounded to a
/// representable value.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// let x = 1.5
/// let y = x + 2.25
/// // y == 3.75
///
/// The `+` operator implements the addition operation defined by the
/// [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +(lhs: Self, rhs: Self) -> Self
/// Adds two values and stores the result in the left-hand-side variable,
/// rounded to a representable value.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +=(lhs: inout Self, rhs: Self)
/// Calculates the additive inverse of a value.
///
/// The unary minus operator (prefix `-`) calculates the negation of its
/// operand. The result is always exact.
///
/// let x = 21.5
/// let y = -x
/// // y == -21.5
///
/// - Parameter operand: The value to negate.
override static prefix func - (_ operand: Self) -> Self
/// Replaces this value with its additive inverse.
///
/// The result is always exact. This example uses the `negate()` method to
/// negate the value of the variable `x`:
///
/// var x = 21.5
/// x.negate()
/// // x == -21.5
override mutating func negate()
/// Subtracts one value from another and produces their difference, rounded
/// to a representable value.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// let x = 7.5
/// let y = x - 2.25
/// // y == 5.25
///
/// The `-` operator implements the subtraction operation defined by the
/// [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -(lhs: Self, rhs: Self) -> Self
/// Subtracts the second value from the first and stores the difference in
/// the left-hand-side variable, rounding to a representable value.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -=(lhs: inout Self, rhs: Self)
/// Multiplies two values and produces their product, rounding to a
/// representable value.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// let x = 7.5
/// let y = x * 2.25
/// // y == 16.875
///
/// The `*` operator implements the multiplication operation defined by the
/// [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and stores the result in the left-hand-side
/// variable, rounding to a representable value.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *=(lhs: inout Self, rhs: Self)
/// Returns the quotient of dividing the first value by the second, rounded
/// to a representable value.
///
/// The division operator (`/`) calculates the quotient of the division if
/// `rhs` is nonzero. If `rhs` is zero, the result of the division is
/// infinity, with the sign of the result matching the sign of `lhs`.
///
/// let x = 16.875
/// let y = x / 2.25
/// // y == 7.5
///
/// let z = x / 0
/// // z.isInfinite == true
///
/// The `/` operator implements the division operation defined by the [IEEE
/// 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by.
static func /(lhs: Self, rhs: Self) -> Self
/// Divides the first value by the second and stores the quotient in the
/// left-hand-side variable, rounding to a representable value.
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by.
static func /=(lhs: inout Self, rhs: Self)
/// Returns the remainder of this value divided by the given value.
///
/// For two finite values `x` and `y`, the remainder `r` of dividing `x` by
/// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to
/// `x / y`. If `x / y` is exactly halfway between two integers, `q` is
/// chosen to be even. Note that `q` is *not* `x / y` computed in
/// floating-point arithmetic, and that `q` may not be representable in any
/// available integer type.
///
/// The following example calculates the remainder of dividing 8.625 by 0.75:
///
/// let x = 8.625
/// print(x / 0.75)
/// // Prints "11.5"
///
/// let q = (x / 0.75).rounded(.toNearestOrEven)
/// // q == 12.0
/// let r = x.remainder(dividingBy: 0.75)
/// // r == -0.375
///
/// let x1 = 0.75 * q + r
/// // x1 == 8.625
///
/// If this value and `other` are finite numbers, the remainder is in the
/// closed range `-abs(other / 2)...abs(other / 2)`. The
/// `remainder(dividingBy:)` method is always exact. This method implements
/// the remainder operation defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameter other: The value to use when dividing this value.
/// - Returns: The remainder of this value divided by `other`.
func remainder(dividingBy other: Self) -> Self
/// Replaces this value with the remainder of itself divided by the given
/// value.
///
/// For two finite values `x` and `y`, the remainder `r` of dividing `x` by
/// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to
/// `x / y`. If `x / y` is exactly halfway between two integers, `q` is
/// chosen to be even. Note that `q` is *not* `x / y` computed in
/// floating-point arithmetic, and that `q` may not be representable in any
/// available integer type.
///
/// The following example calculates the remainder of dividing 8.625 by 0.75:
///
/// var x = 8.625
/// print(x / 0.75)
/// // Prints "11.5"
///
/// let q = (x / 0.75).rounded(.toNearestOrEven)
/// // q == 12.0
/// x.formRemainder(dividingBy: 0.75)
/// // x == -0.375
///
/// let x1 = 0.75 * q + x
/// // x1 == 8.625
///
/// If this value and `other` are finite numbers, the remainder is in the
/// closed range `-abs(other / 2)...abs(other / 2)`. The
/// `formRemainder(dividingBy:)` method is always exact.
///
/// - Parameter other: The value to use when dividing this value.
mutating func formRemainder(dividingBy other: Self)
/// Returns the remainder of this value divided by the given value using
/// truncating division.
///
/// Performing truncating division with floating-point values results in a
/// truncated integer quotient and a remainder. For values `x` and `y` and
/// their truncated integer quotient `q`, the remainder `r` satisfies
/// `x == y * q + r`.
///
/// The following example calculates the truncating remainder of dividing
/// 8.625 by 0.75:
///
/// let x = 8.625
/// print(x / 0.75)
/// // Prints "11.5"
///
/// let q = (x / 0.75).rounded(.towardZero)
/// // q == 11.0
/// let r = x.truncatingRemainder(dividingBy: 0.75)
/// // r == 0.375
///
/// let x1 = 0.75 * q + r
/// // x1 == 8.625
///
/// If this value and `other` are both finite numbers, the truncating
/// remainder has the same sign as this value and is strictly smaller in
/// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method
/// is always exact.
///
/// - Parameter other: The value to use when dividing this value.
/// - Returns: The remainder of this value divided by `other` using
/// truncating division.
func truncatingRemainder(dividingBy other: Self) -> Self
/// Replaces this value with the remainder of itself divided by the given
/// value using truncating division.
///
/// Performing truncating division with floating-point values results in a
/// truncated integer quotient and a remainder. For values `x` and `y` and
/// their truncated integer quotient `q`, the remainder `r` satisfies
/// `x == y * q + r`.
///
/// The following example calculates the truncating remainder of dividing
/// 8.625 by 0.75:
///
/// var x = 8.625
/// print(x / 0.75)
/// // Prints "11.5"
///
/// let q = (x / 0.75).rounded(.towardZero)
/// // q == 11.0
/// x.formTruncatingRemainder(dividingBy: 0.75)
/// // x == 0.375
///
/// let x1 = 0.75 * q + x
/// // x1 == 8.625
///
/// If this value and `other` are both finite numbers, the truncating
/// remainder has the same sign as this value and is strictly smaller in
/// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)`
/// method is always exact.
///
/// - Parameter other: The value to use when dividing this value.
mutating func formTruncatingRemainder(dividingBy other: Self)
/// Returns the square root of the value, rounded to a representable value.
///
/// The following example declares a function that calculates the length of
/// the hypotenuse of a right triangle given its two perpendicular sides.
///
/// func hypotenuse(_ a: Double, _ b: Double) -> Double {
/// return (a * a + b * b).squareRoot()
/// }
///
/// let (dx, dy) = (3.0, 4.0)
/// let distance = hypotenuse(dx, dy)
/// // distance == 5.0
///
/// - Returns: The square root of the value.
func squareRoot() -> Self
/// Replaces this value with its square root, rounded to a representable
/// value.
mutating func formSquareRoot()
/// Returns the result of adding the product of the two given values to this
/// value, computed without intermediate rounding.
///
/// This method is equivalent to the C `fma` function and implements the
/// `fusedMultiplyAdd` operation defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - lhs: One of the values to multiply before adding to this value.
/// - rhs: The other value to multiply.
/// - Returns: The product of `lhs` and `rhs`, added to this value.
func addingProduct(_ lhs: Self, _ rhs: Self) -> Self
/// Adds the product of the two given values to this value in place, computed
/// without intermediate rounding.
///
/// - Parameters:
/// - lhs: One of the values to multiply before adding to this value.
/// - rhs: The other value to multiply.
mutating func addProduct(_ lhs: Self, _ rhs: Self)
/// Returns the lesser of the two given values.
///
/// This method returns the minimum of two values, preserving order and
/// eliminating NaN when possible. For two values `x` and `y`, the result of
/// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x`
/// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are
/// NaN, or either `x` or `y` is a signaling NaN, the result is NaN.
///
/// Double.minimum(10.0, -25.0)
/// // -25.0
/// Double.minimum(10.0, .nan)
/// // 10.0
/// Double.minimum(.nan, -25.0)
/// // -25.0
/// Double.minimum(.nan, .nan)
/// // nan
///
/// The `minimum` method implements the `minNum` operation defined by the
/// [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: The minimum of `x` and `y`, or whichever is a number if the
/// other is NaN.
static func minimum(_ x: Self, _ y: Self) -> Self
/// Returns the greater of the two given values.
///
/// This method returns the maximum of two values, preserving order and
/// eliminating NaN when possible. For two values `x` and `y`, the result of
/// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x`
/// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are
/// NaN, or either `x` or `y` is a signaling NaN, the result is NaN.
///
/// Double.maximum(10.0, -25.0)
/// // 10.0
/// Double.maximum(10.0, .nan)
/// // 10.0
/// Double.maximum(.nan, -25.0)
/// // -25.0
/// Double.maximum(.nan, .nan)
/// // nan
///
/// The `maximum` method implements the `maxNum` operation defined by the
/// [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: The greater of `x` and `y`, or whichever is a number if the
/// other is NaN.
static func maximum(_ x: Self, _ y: Self) -> Self
/// Returns the value with lesser magnitude.
///
/// This method returns the value with lesser magnitude of the two given
/// values, preserving order and eliminating NaN when possible. For two
/// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if
/// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or
/// whichever of `x` or `y` is a number if the other is a quiet NaN. If both
/// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result
/// is NaN.
///
/// Double.minimumMagnitude(10.0, -25.0)
/// // 10.0
/// Double.minimumMagnitude(10.0, .nan)
/// // 10.0
/// Double.minimumMagnitude(.nan, -25.0)
/// // -25.0
/// Double.minimumMagnitude(.nan, .nan)
/// // nan
///
/// The `minimumMagnitude` method implements the `minNumMag` operation
/// defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is
/// a number if the other is NaN.
static func minimumMagnitude(_ x: Self, _ y: Self) -> Self
/// Returns the value with greater magnitude.
///
/// This method returns the value with greater magnitude of the two given
/// values, preserving order and eliminating NaN when possible. For two
/// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if
/// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or
/// whichever of `x` or `y` is a number if the other is a quiet NaN. If both
/// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result
/// is NaN.
///
/// Double.maximumMagnitude(10.0, -25.0)
/// // -25.0
/// Double.maximumMagnitude(10.0, .nan)
/// // 10.0
/// Double.maximumMagnitude(.nan, -25.0)
/// // -25.0
/// Double.maximumMagnitude(.nan, .nan)
/// // nan
///
/// The `maximumMagnitude` method implements the `maxNumMag` operation
/// defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is
/// a number if the other is NaN.
static func maximumMagnitude(_ x: Self, _ y: Self) -> Self
/// Returns this value rounded to an integral value using the specified
/// rounding rule.
///
/// The following example rounds a value using four different rounding rules:
///
/// let x = 6.5
///
/// // Equivalent to the C 'round' function:
/// print(x.rounded(.toNearestOrAwayFromZero))
/// // Prints "7.0"
///
/// // Equivalent to the C 'trunc' function:
/// print(x.rounded(.towardZero))
/// // Prints "6.0"
///
/// // Equivalent to the C 'ceil' function:
/// print(x.rounded(.up))
/// // Prints "7.0"
///
/// // Equivalent to the C 'floor' function:
/// print(x.rounded(.down))
/// // Prints "6.0"
///
/// For more information about the available rounding rules, see the
/// `FloatingPointRoundingRule` enumeration. To round a value using the
/// default "schoolbook rounding", you can use the shorter `rounded()`
/// method instead.
///
/// print(x.rounded())
/// // Prints "7.0"
///
/// - Parameter rule: The rounding rule to use.
/// - Returns: The integral value found by rounding using `rule`.
func rounded(_ rule: FloatingPointRoundingRule) -> Self
/// Rounds the value to an integral value using the specified rounding rule.
///
/// The following example rounds a value using four different rounding rules:
///
/// // Equivalent to the C 'round' function:
/// var w = 6.5
/// w.round(.toNearestOrAwayFromZero)
/// // w == 7.0
///
/// // Equivalent to the C 'trunc' function:
/// var x = 6.5
/// x.round(.towardZero)
/// // x == 6.0
///
/// // Equivalent to the C 'ceil' function:
/// var y = 6.5
/// y.round(.up)
/// // y == 7.0
///
/// // Equivalent to the C 'floor' function:
/// var z = 6.5
/// z.round(.down)
/// // z == 6.0
///
/// For more information about the available rounding rules, see the
/// `FloatingPointRoundingRule` enumeration. To round a value using the
/// default "schoolbook rounding", you can use the shorter `round()` method
/// instead.
///
/// var w1 = 6.5
/// w1.round()
/// // w1 == 7.0
///
/// - Parameter rule: The rounding rule to use.
mutating func round(_ rule: FloatingPointRoundingRule)
/// The least representable value that compares greater than this value.
///
/// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or
/// `infinity`, `x.nextUp` is `x` itself. The following special cases also
/// apply:
///
/// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`.
/// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`.
/// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`.
/// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`.
var nextUp: Self { get }
/// The greatest representable value that compares less than this value.
///
/// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or
/// `-infinity`, `x.nextDown` is `x` itself. The following special cases
/// also apply:
///
/// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`.
/// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`.
/// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`.
/// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`.
var nextDown: Self { get }
/// Returns a Boolean value indicating whether this instance is equal to the
/// given value.
///
/// This method serves as the basis for the equal-to operator (`==`) for
/// floating-point values. When comparing two values with this method, `-0`
/// is equal to `+0`. NaN is not equal to any value, including itself. For
/// example:
///
/// let x = 15.0
/// x.isEqual(to: 15.0)
/// // true
/// x.isEqual(to: .nan)
/// // false
/// Double.nan.isEqual(to: .nan)
/// // false
///
/// The `isEqual(to:)` method implements the equality predicate defined by
/// the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameter other: The value to compare with this value.
/// - Returns: `true` if `other` has the same value as this instance;
/// otherwise, `false`. If either this value or `other` is NaN, the result
/// of this method is `false`.
func isEqual(to other: Self) -> Bool
/// Returns a Boolean value indicating whether this instance is less than the
/// given value.
///
/// This method serves as the basis for the less-than operator (`<`) for
/// floating-point values. Some special cases apply:
///
/// - Because NaN compares not less than nor greater than any value, this
/// method returns `false` when called on NaN or when NaN is passed as
/// `other`.
/// - `-infinity` compares less than all values except for itself and NaN.
/// - Every value except for NaN and `+infinity` compares less than
/// `+infinity`.
///
/// let x = 15.0
/// x.isLess(than: 20.0)
/// // true
/// x.isLess(than: .nan)
/// // false
/// Double.nan.isLess(than: x)
/// // false
///
/// The `isLess(than:)` method implements the less-than predicate defined by
/// the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameter other: The value to compare with this value.
/// - Returns: `true` if this value is less than `other`; otherwise, `false`.
/// If either this value or `other` is NaN, the result of this method is
/// `false`.
func isLess(than other: Self) -> Bool
/// Returns a Boolean value indicating whether this instance is less than or
/// equal to the given value.
///
/// This method serves as the basis for the less-than-or-equal-to operator
/// (`<=`) for floating-point values. Some special cases apply:
///
/// - Because NaN is incomparable with any value, this method returns `false`
/// when called on NaN or when NaN is passed as `other`.
/// - `-infinity` compares less than or equal to all values except NaN.
/// - Every value except NaN compares less than or equal to `+infinity`.
///
/// let x = 15.0
/// x.isLessThanOrEqualTo(20.0)
/// // true
/// x.isLessThanOrEqualTo(.nan)
/// // false
/// Double.nan.isLessThanOrEqualTo(x)
/// // false
///
/// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal
/// predicate defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameter other: The value to compare with this value.
/// - Returns: `true` if `other` is greater than this value; otherwise,
/// `false`. If either this value or `other` is NaN, the result of this
/// method is `false`.
func isLessThanOrEqualTo(_ other: Self) -> Bool
/// Returns a Boolean value indicating whether this instance should precede
/// or tie positions with the given value in an ascending sort.
///
/// This relation is a refinement of the less-than-or-equal-to operator
/// (`<=`) that provides a total order on all values of the type, including
/// signed zeros and NaNs.
///
/// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an
/// array of floating-point values, including some that are NaN:
///
/// var numbers = [2.5, 21.25, 3.0, .nan, -9.5]
/// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) }
/// // numbers == [-9.5, 2.5, 3.0, 21.25, NaN]
///
/// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order
/// relation as defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameter other: A floating-point value to compare to this value.
/// - Returns: `true` if this value is ordered below or the same as `other`
/// in a total ordering of the floating-point type; otherwise, `false`.
func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool
/// A Boolean value indicating whether this instance is normal.
///
/// A *normal* value is a finite number that uses the full precision
/// available to values of a type. Zero is neither a normal nor a subnormal
/// number.
var isNormal: Bool { get }
/// A Boolean value indicating whether this instance is finite.
///
/// All values other than NaN and infinity are considered finite, whether
/// normal or subnormal.
var isFinite: Bool { get }
/// A Boolean value indicating whether the instance is equal to zero.
///
/// The `isZero` property of a value `x` is `true` when `x` represents either
/// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison:
/// `x == 0.0`.
///
/// let x = -0.0
/// x.isZero // true
/// x == 0.0 // true
var isZero: Bool { get }
/// A Boolean value indicating whether the instance is subnormal.
///
/// A *subnormal* value is a nonzero number that has a lesser magnitude than
/// the smallest normal number. Subnormal values do not use the full
/// precision available to values of a type.
///
/// Zero is neither a normal nor a subnormal number. Subnormal numbers are
/// often called *denormal* or *denormalized*---these are different names
/// for the same concept.
var isSubnormal: Bool { get }
/// A Boolean value indicating whether the instance is infinite.
///
/// Note that `isFinite` and `isInfinite` do not form a dichotomy, because
/// they are not total: If `x` is `NaN`, then both properties are `false`.
var isInfinite: Bool { get }
/// A Boolean value indicating whether the instance is NaN ("not a number").
///
/// Because NaN is not equal to any value, including NaN, use this property
/// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`)
/// to test whether a value is or is not NaN. For example:
///
/// let x = 0.0
/// let y = x * .infinity
/// // y is a NaN
///
/// // Comparing with the equal-to operator never returns 'true'
/// print(x == Double.nan)
/// // Prints "false"
/// print(y == Double.nan)
/// // Prints "false"
///
/// // Test with the 'isNaN' property instead
/// print(x.isNaN)
/// // Prints "false"
/// print(y.isNaN)
/// // Prints "true"
///
/// This property is `true` for both quiet and signaling NaNs.
var isNaN: Bool { get }
/// A Boolean value indicating whether the instance is a signaling NaN.
///
/// Signaling NaNs typically raise the Invalid flag when used in general
/// computing operations.
var isSignalingNaN: Bool { get }
/// The classification of this value.
///
/// A value's `floatingPointClass` property describes its "class" as
/// described by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
var floatingPointClass: FloatingPointClassification { get }
/// A Boolean value indicating whether the instance's representation is in
/// the canonical form.
///
/// The [IEEE 754 specification][spec] defines a *canonical*, or preferred,
/// encoding of a floating-point value's representation. Every `Float` or
/// `Double` value is canonical, but noncanonical values of the `Float80`
/// type exist, and noncanonical values may exist for other types that
/// conform to the `FloatingPoint` protocol.
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
var isCanonical: Bool { get }
}
/// The sign of a floating-point value.
@_frozen // FIXME(sil-serialize-all)
public enum FloatingPointSign: Int {
/// The sign for a positive value.
case plus
/// The sign for a negative value.
case minus
// Explicit declarations of otherwise-synthesized members to make them
// @inlinable, promising that we will never change the implementation.
@inlinable
public init?(rawValue: Int) {
switch rawValue {
case 0: self = .plus
case 1: self = .minus
default: return nil
}
}
@inlinable
public var rawValue: Int {
switch self {
case .plus: return 0
case .minus: return 1
}
}
@_transparent
@inlinable
public static func ==(a: FloatingPointSign, b: FloatingPointSign) -> Bool {
return a.rawValue == b.rawValue
}
}
/// The IEEE 754 floating-point classes.
@_frozen // FIXME(sil-serialize-all)
public enum FloatingPointClassification {
/// A signaling NaN ("not a number").
///
/// A signaling NaN sets the floating-point exception status when used in
/// many floating-point operations.
case signalingNaN
/// A silent NaN ("not a number") value.
case quietNaN
/// A value equal to `-infinity`.
case negativeInfinity
/// A negative value that uses the full precision of the floating-point type.
case negativeNormal
/// A negative, nonzero number that does not use the full precision of the
/// floating-point type.
case negativeSubnormal
/// A value equal to zero with a negative sign.
case negativeZero
/// A value equal to zero with a positive sign.
case positiveZero
/// A positive, nonzero number that does not use the full precision of the
/// floating-point type.
case positiveSubnormal
/// A positive value that uses the full precision of the floating-point type.
case positiveNormal
/// A value equal to `+infinity`.
case positiveInfinity
}
/// A rule for rounding a floating-point number.
public enum FloatingPointRoundingRule {
/// Round to the closest allowed value; if two values are equally close, the
/// one with greater magnitude is chosen.
///
/// This rounding rule is also known as "schoolbook rounding." The following
/// example shows the results of rounding numbers using this rule:
///
/// (5.2).rounded(.toNearestOrAwayFromZero)
/// // 5.0
/// (5.5).rounded(.toNearestOrAwayFromZero)
/// // 6.0
/// (-5.2).rounded(.toNearestOrAwayFromZero)
/// // -5.0
/// (-5.5).rounded(.toNearestOrAwayFromZero)
/// // -6.0
///
/// This rule is equivalent to the C `round` function and implements the
/// `roundToIntegralTiesToAway` operation defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
case toNearestOrAwayFromZero
/// Round to the closest allowed value; if two values are equally close, the
/// even one is chosen.
///
/// This rounding rule is also known as "bankers rounding," and is the
/// default IEEE 754 rounding mode for arithmetic. The following example
/// shows the results of rounding numbers using this rule:
///
/// (5.2).rounded(.toNearestOrEven)
/// // 5.0
/// (5.5).rounded(.toNearestOrEven)
/// // 6.0
/// (4.5).rounded(.toNearestOrEven)
/// // 4.0
///
/// This rule implements the `roundToIntegralTiesToEven` operation defined by
/// the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
case toNearestOrEven
/// Round to the closest allowed value that is greater than or equal to the
/// source.
///
/// The following example shows the results of rounding numbers using this
/// rule:
///
/// (5.2).rounded(.up)
/// // 6.0
/// (5.5).rounded(.up)
/// // 6.0
/// (-5.2).rounded(.up)
/// // -5.0
/// (-5.5).rounded(.up)
/// // -5.0
///
/// This rule is equivalent to the C `ceil` function and implements the
/// `roundToIntegralTowardPositive` operation defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
case up
/// Round to the closest allowed value that is less than or equal to the
/// source.
///
/// The following example shows the results of rounding numbers using this
/// rule:
///
/// (5.2).rounded(.down)
/// // 5.0
/// (5.5).rounded(.down)
/// // 5.0
/// (-5.2).rounded(.down)
/// // -6.0
/// (-5.5).rounded(.down)
/// // -6.0
///
/// This rule is equivalent to the C `floor` function and implements the
/// `roundToIntegralTowardNegative` operation defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
case down
/// Round to the closest allowed value whose magnitude is less than or equal
/// to that of the source.
///
/// The following example shows the results of rounding numbers using this
/// rule:
///
/// (5.2).rounded(.towardZero)
/// // 5.0
/// (5.5).rounded(.towardZero)
/// // 5.0
/// (-5.2).rounded(.towardZero)
/// // -5.0
/// (-5.5).rounded(.towardZero)
/// // -5.0
///
/// This rule is equivalent to the C `trunc` function and implements the
/// `roundToIntegralTowardZero` operation defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
case towardZero
/// Round to the closest allowed value whose magnitude is greater than or
/// equal to that of the source.
///
/// The following example shows the results of rounding numbers using this
/// rule:
///
/// (5.2).rounded(.awayFromZero)
/// // 6.0
/// (5.5).rounded(.awayFromZero)
/// // 6.0
/// (-5.2).rounded(.awayFromZero)
/// // -6.0
/// (-5.5).rounded(.awayFromZero)
/// // -6.0
case awayFromZero
}
extension FloatingPoint {
@_transparent
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.isEqual(to: rhs)
}
@_transparent
public static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.isLess(than: rhs)
}
@_transparent
public static func <= (lhs: Self, rhs: Self) -> Bool {
return lhs.isLessThanOrEqualTo(rhs)
}
@_transparent
public static func > (lhs: Self, rhs: Self) -> Bool {
return rhs.isLess(than: lhs)
}
@_transparent
public static func >= (lhs: Self, rhs: Self) -> Bool {
return rhs.isLessThanOrEqualTo(lhs)
}
}
/// A radix-2 (binary) floating-point type.
///
/// The `BinaryFloatingPoint` protocol extends the `FloatingPoint` protocol
/// with operations specific to floating-point binary types, as defined by the
/// [IEEE 754 specification][spec]. `BinaryFloatingPoint` is implemented in
/// the standard library by `Float`, `Double`, and `Float80` where available.
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
public protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral {
/// A type that represents the encoded significand of a value.
associatedtype RawSignificand: UnsignedInteger
/// A type that represents the encoded exponent of a value.
associatedtype RawExponent: UnsignedInteger
/// Creates a new instance from the specified sign and bit patterns.
///
/// The values passed as `exponentBitPattern` and `significandBitPattern` are
/// interpreted in the binary interchange format defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - sign: The sign of the new value.
/// - exponentBitPattern: The bit pattern to use for the exponent field of
/// the new value.
/// - significandBitPattern: The bit pattern to use for the significand
/// field of the new value.
init(sign: FloatingPointSign,
exponentBitPattern: RawExponent,
significandBitPattern: RawSignificand)
/// Creates a new instance from the given value, rounded to the closest
/// possible representation.
///
/// - Parameter value: A floating-point value to be converted.
init(_ value: Float)
/// Creates a new instance from the given value, rounded to the closest
/// possible representation.
///
/// - Parameter value: A floating-point value to be converted.
init(_ value: Double)
#if !os(Windows) && (arch(i386) || arch(x86_64))
/// Creates a new instance from the given value, rounded to the closest
/// possible representation.
///
/// - Parameter value: A floating-point value to be converted.
init(_ value: Float80)
#endif
/// Creates a new instance from the given value, rounded to the closest
/// possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: A floating-point value to be converted.
init<Source : BinaryFloatingPoint>(_ value: Source)
/// Creates a new instance from the given value, if it can be represented
/// exactly.
///
/// If the given floating-point value cannot be represented exactly, the
/// result is `nil`. A value that is NaN ("not a number") cannot be
/// represented exactly if its payload cannot be encoded exactly.
///
/// - Parameter value: A floating-point value to be converted.
init?<Source : BinaryFloatingPoint>(exactly value: Source)
/// The number of bits used to represent the type's exponent.
///
/// A binary floating-point type's `exponentBitCount` imposes a limit on the
/// range of the exponent for normal, finite values. The *exponent bias* of
/// a type `F` can be calculated as the following, where `**` is
/// exponentiation:
///
/// let bias = 2 ** (F.exponentBitCount - 1) - 1
///
/// The least normal exponent for values of the type `F` is `1 - bias`, and
/// the largest finite exponent is `bias`. An all-zeros exponent is reserved
/// for subnormals and zeros, and an all-ones exponent is reserved for
/// infinity and NaN.
///
/// For example, the `Float` type has an `exponentBitCount` of 8, which gives
/// an exponent bias of `127` by the calculation above.
///
/// let bias = 2 ** (Float.exponentBitCount - 1) - 1
/// // bias == 127
/// print(Float.greatestFiniteMagnitude.exponent)
/// // Prints "127"
/// print(Float.leastNormalMagnitude.exponent)
/// // Prints "-126"
static var exponentBitCount: Int { get }
/// The available number of fractional significand bits.
///
/// For fixed-width floating-point types, this is the actual number of
/// fractional significand bits.
///
/// For extensible floating-point types, `significandBitCount` should be the
/// maximum allowed significand width (without counting any leading integral
/// bit of the significand). If there is no upper limit, then
/// `significandBitCount` should be `Int.max`.
///
/// Note that `Float80.significandBitCount` is 63, even though 64 bits are
/// used to store the significand in the memory representation of a
/// `Float80` (unlike other floating-point types, `Float80` explicitly
/// stores the leading integral significand bit, but the
/// `BinaryFloatingPoint` APIs provide an abstraction so that users don't
/// need to be aware of this detail).
static var significandBitCount: Int { get }
/// The raw encoding of the value's exponent field.
///
/// This value is unadjusted by the type's exponent bias.
var exponentBitPattern: RawExponent { get }
/// The raw encoding of the value's significand field.
///
/// The `significandBitPattern` property does not include the leading
/// integral bit of the significand, even for types like `Float80` that
/// store it explicitly.
var significandBitPattern: RawSignificand { get }
/// The floating-point value with the same sign and exponent as this value,
/// but with a significand of 1.0.
///
/// A *binade* is a set of binary floating-point values that all have the
/// same sign and exponent. The `binade` property is a member of the same
/// binade as this value, but with a unit significand.
///
/// In this example, `x` has a value of `21.5`, which is stored as
/// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is
/// equal to `1.0 * 2**4`, or `16.0`.
///
/// let x = 21.5
/// // x.significand == 1.34375
/// // x.exponent == 4
///
/// let y = x.binade
/// // y == 16.0
/// // y.significand == 1.0
/// // y.exponent == 4
var binade: Self { get }
/// The number of bits required to represent the value's significand.
///
/// If this value is a finite nonzero number, `significandWidth` is the
/// number of fractional bits required to represent the value of
/// `significand`; otherwise, `significandWidth` is -1. The value of
/// `significandWidth` is always -1 or between zero and
/// `significandBitCount`. For example:
///
/// - For any representable power of two, `significandWidth` is zero, because
/// `significand` is `1.0`.
/// - If `x` is 10, `x.significand` is `1.01` in binary, so
/// `x.significandWidth` is 2.
/// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in
/// binary, and `x.significandWidth` is 23.
var significandWidth: Int { get }
/* TODO: Implement these once it becomes possible to do so. (Requires
* revised Integer protocol).
func isEqual<Other: BinaryFloatingPoint>(to other: Other) -> Bool
func isLess<Other: BinaryFloatingPoint>(than other: Other) -> Bool
func isLessThanOrEqualTo<Other: BinaryFloatingPoint>(other: Other) -> Bool
func isTotallyOrdered<Other: BinaryFloatingPoint>(belowOrEqualTo other: Other) -> Bool
*/
}
extension FloatingPoint {
/// The unit in the last place of 1.0.
///
/// The positive difference between 1.0 and the next greater representable
/// number. The `ulpOfOne` constant corresponds to the C macros
/// `FLT_EPSILON`, `DBL_EPSILON`, and others with a similar purpose.
@inlinable // FIXME(sil-serialize-all)
public static var ulpOfOne: Self {
return (1 as Self).ulp
}
/// Returns this value rounded to an integral value using the specified
/// rounding rule.
///
/// The following example rounds a value using four different rounding rules:
///
/// let x = 6.5
///
/// // Equivalent to the C 'round' function:
/// print(x.rounded(.toNearestOrAwayFromZero))
/// // Prints "7.0"
///
/// // Equivalent to the C 'trunc' function:
/// print(x.rounded(.towardZero))
/// // Prints "6.0"
///
/// // Equivalent to the C 'ceil' function:
/// print(x.rounded(.up))
/// // Prints "7.0"
///
/// // Equivalent to the C 'floor' function:
/// print(x.rounded(.down))
/// // Prints "6.0"
///
/// For more information about the available rounding rules, see the
/// `FloatingPointRoundingRule` enumeration. To round a value using the
/// default "schoolbook rounding", you can use the shorter `rounded()`
/// method instead.
///
/// print(x.rounded())
/// // Prints "7.0"
///
/// - Parameter rule: The rounding rule to use.
/// - Returns: The integral value found by rounding using `rule`.
@_transparent
public func rounded(_ rule: FloatingPointRoundingRule) -> Self {
var lhs = self
lhs.round(rule)
return lhs
}
/// Returns this value rounded to an integral value using "schoolbook
/// rounding."
///
/// The `rounded()` method uses the `.toNearestOrAwayFromZero` rounding rule,
/// where a value halfway between two integral values is rounded to the one
/// with greater magnitude. The following example rounds several values
/// using this default rule:
///
/// (5.2).rounded()
/// // 5.0
/// (5.5).rounded()
/// // 6.0
/// (-5.2).rounded()
/// // -5.0
/// (-5.5).rounded()
/// // -6.0
///
/// To specify an alternative rule for rounding, use the `rounded(_:)` method
/// instead.
///
/// - Returns: The nearest integral value, or, if two integral values are
/// equally close, the integral value with greater magnitude.
@_transparent
public func rounded() -> Self {
return rounded(.toNearestOrAwayFromZero)
}
/// Rounds this value to an integral value using "schoolbook rounding."
///
/// The `round()` method uses the `.toNearestOrAwayFromZero` rounding rule,
/// where a value halfway between two integral values is rounded to the one
/// with greater magnitude. The following example rounds several values
/// using this default rule:
///
/// var x = 5.2
/// x.round()
/// // x == 5.0
/// var y = 5.5
/// y.round()
/// // y == 6.0
/// var z = -5.5
/// z.round()
/// // z == -6.0
///
/// To specify an alternative rule for rounding, use the `round(_:)` method
/// instead.
@_transparent
public mutating func round() {
round(.toNearestOrAwayFromZero)
}
/// The greatest representable value that compares less than this value.
///
/// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or
/// `-infinity`, `x.nextDown` is `x` itself. The following special cases
/// also apply:
///
/// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`.
/// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`.
/// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`.
/// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`.
public var nextDown: Self {
@inline(__always)
get {
return -(-self).nextUp
}
}
/// Returns the remainder of this value divided by the given value using
/// truncating division.
///
/// Performing truncating division with floating-point values results in a
/// truncated integer quotient and a remainder. For values `x` and `y` and
/// their truncated integer quotient `q`, the remainder `r` satisfies
/// `x == y * q + r`.
///
/// The following example calculates the truncating remainder of dividing
/// 8.625 by 0.75:
///
/// let x = 8.625
/// print(x / 0.75)
/// // Prints "11.5"
///
/// let q = (x / 0.75).rounded(.towardZero)
/// // q == 11.0
/// let r = x.truncatingRemainder(dividingBy: 0.75)
/// // r == 0.375
///
/// let x1 = 0.75 * q + r
/// // x1 == 8.625
///
/// If this value and `other` are both finite numbers, the truncating
/// remainder has the same sign as this value and is strictly smaller in
/// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method
/// is always exact.
///
/// - Parameter other: The value to use when dividing this value.
/// - Returns: The remainder of this value divided by `other` using
/// truncating division.
@inline(__always)
public func truncatingRemainder(dividingBy other: Self) -> Self {
var lhs = self
lhs.formTruncatingRemainder(dividingBy: other)
return lhs
}
/// Returns the remainder of this value divided by the given value.
///
/// For two finite values `x` and `y`, the remainder `r` of dividing `x` by
/// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to
/// `x / y`. If `x / y` is exactly halfway between two integers, `q` is
/// chosen to be even. Note that `q` is *not* `x / y` computed in
/// floating-point arithmetic, and that `q` may not be representable in any
/// available integer type.
///
/// The following example calculates the remainder of dividing 8.625 by 0.75:
///
/// let x = 8.625
/// print(x / 0.75)
/// // Prints "11.5"
///
/// let q = (x / 0.75).rounded(.toNearestOrEven)
/// // q == 12.0
/// let r = x.remainder(dividingBy: 0.75)
/// // r == -0.375
///
/// let x1 = 0.75 * q + r
/// // x1 == 8.625
///
/// If this value and `other` are finite numbers, the remainder is in the
/// closed range `-abs(other / 2)...abs(other / 2)`. The
/// `remainder(dividingBy:)` method is always exact. This method implements
/// the remainder operation defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameter other: The value to use when dividing this value.
/// - Returns: The remainder of this value divided by `other`.
@inline(__always)
public func remainder(dividingBy other: Self) -> Self {
var lhs = self
lhs.formRemainder(dividingBy: other)
return lhs
}
/// Returns the square root of the value, rounded to a representable value.
///
/// The following example declares a function that calculates the length of
/// the hypotenuse of a right triangle given its two perpendicular sides.
///
/// func hypotenuse(_ a: Double, _ b: Double) -> Double {
/// return (a * a + b * b).squareRoot()
/// }
///
/// let (dx, dy) = (3.0, 4.0)
/// let distance = hypotenuse(dx, dy)
/// // distance == 5.0
///
/// - Returns: The square root of the value.
@_transparent
public func squareRoot( ) -> Self {
var lhs = self
lhs.formSquareRoot( )
return lhs
}
/// Returns the result of adding the product of the two given values to this
/// value, computed without intermediate rounding.
///
/// This method is equivalent to the C `fma` function and implements the
/// `fusedMultiplyAdd` operation defined by the [IEEE 754
/// specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - lhs: One of the values to multiply before adding to this value.
/// - rhs: The other value to multiply.
/// - Returns: The product of `lhs` and `rhs`, added to this value.
@_transparent
public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self {
var addend = self
addend.addProduct(lhs, rhs)
return addend
}
/// Returns the lesser of the two given values.
///
/// This method returns the minimum of two values, preserving order and
/// eliminating NaN when possible. For two values `x` and `y`, the result of
/// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x`
/// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are
/// NaN, or either `x` or `y` is a signaling NaN, the result is NaN.
///
/// Double.minimum(10.0, -25.0)
/// // -25.0
/// Double.minimum(10.0, .nan)
/// // 10.0
/// Double.minimum(.nan, -25.0)
/// // -25.0
/// Double.minimum(.nan, .nan)
/// // nan
///
/// The `minimum` method implements the `minNum` operation defined by the
/// [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: The minimum of `x` and `y`, or whichever is a number if the
/// other is NaN.
@inlinable
public static func minimum(_ x: Self, _ y: Self) -> Self {
if x.isSignalingNaN || y.isSignalingNaN {
// Produce a quiet NaN matching platform arithmetic behavior.
return x + y
}
if x <= y || y.isNaN { return x }
return y
}
/// Returns the greater of the two given values.
///
/// This method returns the maximum of two values, preserving order and
/// eliminating NaN when possible. For two values `x` and `y`, the result of
/// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x`
/// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are
/// NaN, or either `x` or `y` is a signaling NaN, the result is NaN.
///
/// Double.maximum(10.0, -25.0)
/// // 10.0
/// Double.maximum(10.0, .nan)
/// // 10.0
/// Double.maximum(.nan, -25.0)
/// // -25.0
/// Double.maximum(.nan, .nan)
/// // nan
///
/// The `maximum` method implements the `maxNum` operation defined by the
/// [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: The greater of `x` and `y`, or whichever is a number if the
/// other is NaN.
@inlinable
public static func maximum(_ x: Self, _ y: Self) -> Self {
if x.isSignalingNaN || y.isSignalingNaN {
// Produce a quiet NaN matching platform arithmetic behavior.
return x + y
}
if x > y || y.isNaN { return x }
return y
}
/// Returns the value with lesser magnitude.
///
/// This method returns the value with lesser magnitude of the two given
/// values, preserving order and eliminating NaN when possible. For two
/// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if
/// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or
/// whichever of `x` or `y` is a number if the other is a quiet NaN. If both
/// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result
/// is NaN.
///
/// Double.minimumMagnitude(10.0, -25.0)
/// // 10.0
/// Double.minimumMagnitude(10.0, .nan)
/// // 10.0
/// Double.minimumMagnitude(.nan, -25.0)
/// // -25.0
/// Double.minimumMagnitude(.nan, .nan)
/// // nan
///
/// The `minimumMagnitude` method implements the `minNumMag` operation
/// defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is
/// a number if the other is NaN.
@inlinable
public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self {
if x.isSignalingNaN || y.isSignalingNaN {
// Produce a quiet NaN matching platform arithmetic behavior.
return x + y
}
if x.magnitude <= y.magnitude || y.isNaN { return x }
return y
}
/// Returns the value with greater magnitude.
///
/// This method returns the value with greater magnitude of the two given
/// values, preserving order and eliminating NaN when possible. For two
/// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if
/// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or
/// whichever of `x` or `y` is a number if the other is a quiet NaN. If both
/// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result
/// is NaN.
///
/// Double.maximumMagnitude(10.0, -25.0)
/// // -25.0
/// Double.maximumMagnitude(10.0, .nan)
/// // 10.0
/// Double.maximumMagnitude(.nan, -25.0)
/// // -25.0
/// Double.maximumMagnitude(.nan, .nan)
/// // nan
///
/// The `maximumMagnitude` method implements the `maxNumMag` operation
/// defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameters:
/// - x: A floating-point value.
/// - y: Another floating-point value.
/// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is
/// a number if the other is NaN.
@inlinable
public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self {
if x.isSignalingNaN || y.isSignalingNaN {
// Produce a quiet NaN matching platform arithmetic behavior.
return x + y
}
if x.magnitude > y.magnitude || y.isNaN { return x }
return y
}
/// The classification of this value.
///
/// A value's `floatingPointClass` property describes its "class" as
/// described by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
@inlinable
public var floatingPointClass: FloatingPointClassification {
if isSignalingNaN { return .signalingNaN }
if isNaN { return .quietNaN }
if isInfinite { return sign == .minus ? .negativeInfinity : .positiveInfinity }
if isNormal { return sign == .minus ? .negativeNormal : .positiveNormal }
if isSubnormal { return sign == .minus ? .negativeSubnormal : .positiveSubnormal }
return sign == .minus ? .negativeZero : .positiveZero
}
}
extension BinaryFloatingPoint {
/// The radix, or base of exponentiation, for this floating-point type.
///
/// All binary floating-point types have a radix of 2. The magnitude of a
/// floating-point value `x` of type `F` can be calculated by using the
/// following formula, where `**` is exponentiation:
///
/// let magnitude = x.significand * F.radix ** x.exponent
public static var radix: Int { return 2 }
/// Creates a new floating-point value using the sign of one value and the
/// magnitude of another.
///
/// The following example uses this initializer to create a new `Double`
/// instance with the sign of `a` and the magnitude of `b`:
///
/// let a = -21.5
/// let b = 305.15
/// let c = Double(signOf: a, magnitudeOf: b)
/// print(c)
/// // Prints "-305.15"
///
/// This initializer implements the IEEE 754 `copysign` operation.
///
/// - Parameters:
/// - signOf: A value from which to use the sign. The result of the
/// initializer has the same sign as `signOf`.
/// - magnitudeOf: A value from which to use the magnitude. The result of
/// the initializer has the same magnitude as `magnitudeOf`.
@inlinable
public init(signOf: Self, magnitudeOf: Self) {
self.init(sign: signOf.sign,
exponentBitPattern: magnitudeOf.exponentBitPattern,
significandBitPattern: magnitudeOf.significandBitPattern)
}
@inlinable
public // @testable
static func _convert<Source : BinaryFloatingPoint>(
from source: Source
) -> (value: Self, exact: Bool) {
guard _fastPath(!source.isZero) else {
return (source.sign == .minus ? -0.0 : 0, true)
}
guard _fastPath(source.isFinite) else {
if source.isInfinite {
return (source.sign == .minus ? -.infinity : .infinity, true)
}
// IEEE 754 requires that any NaN payload be propagated, if possible.
let payload_ =
source.significandBitPattern &
~(Source.nan.significandBitPattern |
Source.signalingNaN.significandBitPattern)
let mask =
Self.greatestFiniteMagnitude.significandBitPattern &
~(Self.nan.significandBitPattern |
Self.signalingNaN.significandBitPattern)
let payload = Self.RawSignificand(truncatingIfNeeded: payload_) & mask
// Although .signalingNaN.exponentBitPattern == .nan.exponentBitPattern,
// we do not *need* to rely on this relation, and therefore we do not.
let value = source.isSignalingNaN
? Self(
sign: source.sign,
exponentBitPattern: Self.signalingNaN.exponentBitPattern,
significandBitPattern: payload |
Self.signalingNaN.significandBitPattern)
: Self(
sign: source.sign,
exponentBitPattern: Self.nan.exponentBitPattern,
significandBitPattern: payload | Self.nan.significandBitPattern)
// We define exactness by equality after roundtripping; since NaN is never
// equal to itself, it can never be converted exactly.
return (value, false)
}
let exponent = source.exponent
var exemplar = Self.leastNormalMagnitude
let exponentBitPattern: Self.RawExponent
let leadingBitIndex: Int
let shift: Int
let significandBitPattern: Self.RawSignificand
if exponent < exemplar.exponent {
// The floating-point result is either zero or subnormal.
exemplar = Self.leastNonzeroMagnitude
let minExponent = exemplar.exponent
if exponent + 1 < minExponent {
return (source.sign == .minus ? -0.0 : 0, false)
}
if _slowPath(exponent + 1 == minExponent) {
// Although the most significant bit (MSB) of a subnormal source
// significand is explicit, Swift BinaryFloatingPoint APIs actually
// omit any explicit MSB from the count represented in
// significandWidth. For instance:
//
// Double.leastNonzeroMagnitude.significandWidth == 0
//
// Therefore, we do not need to adjust our work here for a subnormal
// source.
return source.significandWidth == 0
? (source.sign == .minus ? -0.0 : 0, false)
: (source.sign == .minus ? -exemplar : exemplar, false)
}
exponentBitPattern = 0 as Self.RawExponent
leadingBitIndex = Int(Self.Exponent(exponent) - minExponent)
shift =
leadingBitIndex &-
(source.significandWidth &+
source.significandBitPattern.trailingZeroBitCount)
let leadingBit = source.isNormal
? (1 as Self.RawSignificand) << leadingBitIndex
: 0
significandBitPattern = leadingBit | (shift >= 0
? Self.RawSignificand(source.significandBitPattern) << shift
: Self.RawSignificand(source.significandBitPattern >> -shift))
} else {
// The floating-point result is either normal or infinite.
exemplar = Self.greatestFiniteMagnitude
if exponent > exemplar.exponent {
return (source.sign == .minus ? -.infinity : .infinity, false)
}
exponentBitPattern = exponent < 0
? (1 as Self).exponentBitPattern - Self.RawExponent(-exponent)
: (1 as Self).exponentBitPattern + Self.RawExponent(exponent)
leadingBitIndex = exemplar.significandWidth
shift =
leadingBitIndex &-
(source.significandWidth &+
source.significandBitPattern.trailingZeroBitCount)
let sourceLeadingBit = source.isSubnormal
? (1 as Source.RawSignificand) <<
(source.significandWidth &+
source.significandBitPattern.trailingZeroBitCount)
: 0
significandBitPattern = shift >= 0
? Self.RawSignificand(
sourceLeadingBit ^ source.significandBitPattern) << shift
: Self.RawSignificand(
(sourceLeadingBit ^ source.significandBitPattern) >> -shift)
}
let value = Self(
sign: source.sign,
exponentBitPattern: exponentBitPattern,
significandBitPattern: significandBitPattern)
if source.significandWidth <= leadingBitIndex {
return (value, true)
}
// We promise to round to the closest representation, and if two
// representable values are equally close, the value with more trailing
// zeros in its significand bit pattern. Therefore, we must take a look at
// the bits that we've just truncated.
let ulp = (1 as Source.RawSignificand) << -shift
let truncatedBits = source.significandBitPattern & (ulp - 1)
if truncatedBits < ulp / 2 {
return (value, false)
}
let rounded = source.sign == .minus ? value.nextDown : value.nextUp
guard _fastPath(
truncatedBits != ulp / 2 ||
exponentBitPattern.trailingZeroBitCount <
rounded.exponentBitPattern.trailingZeroBitCount) else {
return (value, false)
}
return (rounded, false)
}
/// Creates a new instance from the given value, rounded to the closest
/// possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: A floating-point value to be converted.
@inlinable
public init<Source : BinaryFloatingPoint>(_ value: Source) {
self = Self._convert(from: value).value
}
/// Creates a new instance from the given value, if it can be represented
/// exactly.
///
/// If the given floating-point value cannot be represented exactly, the
/// result is `nil`.
///
/// - Parameter value: A floating-point value to be converted.
@inlinable
public init?<Source : BinaryFloatingPoint>(exactly value: Source) {
let (value_, exact) = Self._convert(from: value)
guard exact else { return nil }
self = value_
}
/// Returns a Boolean value indicating whether this instance should precede
/// or tie positions with the given value in an ascending sort.
///
/// This relation is a refinement of the less-than-or-equal-to operator
/// (`<=`) that provides a total order on all values of the type, including
/// signed zeros and NaNs.
///
/// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an
/// array of floating-point values, including some that are NaN:
///
/// var numbers = [2.5, 21.25, 3.0, .nan, -9.5]
/// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) }
/// // numbers == [-9.5, 2.5, 3.0, 21.25, NaN]
///
/// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order
/// relation as defined by the [IEEE 754 specification][spec].
///
/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
///
/// - Parameter other: A floating-point value to compare to this value.
/// - Returns: `true` if this value is ordered below or the same as `other`
/// in a total ordering of the floating-point type; otherwise, `false`.
@inlinable
public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool {
// Quick return when possible.
if self < other { return true }
if other > self { return false }
// Self and other are either equal or unordered.
// Every negative-signed value (even NaN) is less than every positive-
// signed value, so if the signs do not match, we simply return the
// sign bit of self.
if sign != other.sign { return sign == .minus }
// Sign bits match; look at exponents.
if exponentBitPattern > other.exponentBitPattern { return sign == .minus }
if exponentBitPattern < other.exponentBitPattern { return sign == .plus }
// Signs and exponents match, look at significands.
if significandBitPattern > other.significandBitPattern {
return sign == .minus
}
if significandBitPattern < other.significandBitPattern {
return sign == .plus
}
// Sign, exponent, and significand all match.
return true
}
}
extension BinaryFloatingPoint where Self.RawSignificand : FixedWidthInteger {
@inlinable
public // @testable
static func _convert<Source : BinaryInteger>(
from source: Source
) -> (value: Self, exact: Bool) {
// Useful constants:
let exponentBias = (1 as Self).exponentBitPattern
let significandMask = ((1 as RawSignificand) << Self.significandBitCount) &- 1
// Zero is really extra simple, and saves us from trying to normalize a
// value that cannot be normalized.
if _fastPath(source == 0) { return (0, true) }
// We now have a non-zero value; convert it to a strictly positive value
// by taking the magnitude.
let magnitude = source.magnitude
var exponent = magnitude._binaryLogarithm()
// If the exponent would be larger than the largest representable
// exponent, the result is just an infinity of the appropriate sign.
guard exponent <= Self.greatestFiniteMagnitude.exponent else {
return (Source.isSigned && source < 0 ? -.infinity : .infinity, false)
}
// If exponent <= significandBitCount, we don't need to round it to
// construct the significand; we just need to left-shift it into place;
// the result is always exact as we've accounted for exponent-too-large
// already and no rounding can occur.
if exponent <= Self.significandBitCount {
let shift = Self.significandBitCount &- exponent
let significand = RawSignificand(magnitude) &<< shift
let value = Self(
sign: Source.isSigned && source < 0 ? .minus : .plus,
exponentBitPattern: exponentBias + RawExponent(exponent),
significandBitPattern: significand
)
return (value, true)
}
// exponent > significandBitCount, so we need to do a rounding right
// shift, and adjust exponent if needed
let shift = exponent &- Self.significandBitCount
let halfway = (1 as Source.Magnitude) << (shift - 1)
let mask = 2 * halfway - 1
let fraction = magnitude & mask
var significand = RawSignificand(truncatingIfNeeded: magnitude >> shift) & significandMask
if fraction > halfway || (fraction == halfway && significand & 1 == 1) {
var carry = false
(significand, carry) = significand.addingReportingOverflow(1)
if carry || significand > significandMask {
exponent += 1
guard exponent <= Self.greatestFiniteMagnitude.exponent else {
return (Source.isSigned && source < 0 ? -.infinity : .infinity, false)
}
}
}
return (Self(
sign: Source.isSigned && source < 0 ? .minus : .plus,
exponentBitPattern: exponentBias + RawExponent(exponent),
significandBitPattern: significand
), fraction == 0)
}
/// Creates a new value, rounded to the closest possible representation.
///
/// If two representable values are equally close, the result is the value
/// with more trailing zeros in its significand bit pattern.
///
/// - Parameter value: The integer to convert to a floating-point value.
@inlinable
public init<Source : BinaryInteger>(_ value: Source) {
self = Self._convert(from: value).value
}
/// Creates a new value, if the given integer can be represented exactly.
///
/// If the given integer cannot be represented exactly, the result is `nil`.
///
/// - Parameter value: The integer to convert to a floating-point value.
@inlinable
public init?<Source : BinaryInteger>(exactly value: Source) {
let (value_, exact) = Self._convert(from: value)
guard exact else { return nil }
self = value_
}
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate a floating-point value within a specific
/// range when you are using a custom random number generator. This example
/// creates three new values in the range `10.0 ..< 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ..< 20.0, using: &myGenerator))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random(in:using:)` static method chooses a random value from a
/// continuous uniform distribution in `range`, and then converts that value
/// to the nearest representable value in this type. Depending on the size
/// and span of `range`, some concrete values may be represented more
/// frequently than others.
///
/// - Note: The algorithm used to create random values may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same sequence of floating-point values each time you run your program,
/// that sequence may change when your program is compiled using a
/// different version of Swift.
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// `range` must be finite and non-empty.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: Range<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
let delta = range.upperBound - range.lowerBound
// TODO: this still isn't quite right, because the computation of delta
// can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and
// .lowerBound = -.upperBound); this should be re-written with an
// algorithm that handles that case correctly, but this precondition
// is an acceptable short-term fix.
_precondition(
delta.isFinite,
"There is no uniform distribution on an infinite range"
)
let rand: Self.RawSignificand
if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 {
rand = generator.next()
} else {
let significandCount = Self.significandBitCount + 1
let maxSignificand: Self.RawSignificand = 1 << significandCount
// Rather than use .next(upperBound:), which has to work with arbitrary
// upper bounds, and therefore does extra work to avoid bias, we can take
// a shortcut because we know that maxSignificand is a power of two.
rand = generator.next() & (maxSignificand - 1)
}
let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2)
let randFloat = delta * unitRandom + range.lowerBound
if randFloat == range.upperBound {
return Self.random(in: range, using: &generator)
}
return randFloat
}
/// Returns a random value within the specified range.
///
/// Use this method to generate a floating-point value within a specific
/// range. This example creates three new values in the range
/// `10.0 ..< 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ..< 20.0))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random()` static method chooses a random value from a continuous
/// uniform distribution in `range`, and then converts that value to the
/// nearest representable value in this type. Depending on the size and span
/// of `range`, some concrete values may be represented more frequently than
/// others.
///
/// This method is equivalent to calling `random(in:using:)`, passing in the
/// system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// `range` must be finite and non-empty.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: Range<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate a floating-point value within a specific
/// range when you are using a custom random number generator. This example
/// creates three new values in the range `10.0 ... 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ... 20.0, using: &myGenerator))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random(in:using:)` static method chooses a random value from a
/// continuous uniform distribution in `range`, and then converts that value
/// to the nearest representable value in this type. Depending on the size
/// and span of `range`, some concrete values may be represented more
/// frequently than others.
///
/// - Note: The algorithm used to create random values may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same sequence of floating-point values each time you run your program,
/// that sequence may change when your program is compiled using a
/// different version of Swift.
///
/// - Parameters:
/// - range: The range in which to create a random value. Must be finite.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: ClosedRange<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
let delta = range.upperBound - range.lowerBound
// TODO: this still isn't quite right, because the computation of delta
// can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and
// .lowerBound = -.upperBound); this should be re-written with an
// algorithm that handles that case correctly, but this precondition
// is an acceptable short-term fix.
_precondition(
delta.isFinite,
"There is no uniform distribution on an infinite range"
)
let rand: Self.RawSignificand
if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 {
rand = generator.next()
let tmp: UInt8 = generator.next() & 1
if rand == Self.RawSignificand.max && tmp == 1 {
return range.upperBound
}
} else {
let significandCount = Self.significandBitCount + 1
let maxSignificand: Self.RawSignificand = 1 << significandCount
rand = generator.next(upperBound: maxSignificand + 1)
if rand == maxSignificand {
return range.upperBound
}
}
let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2)
let randFloat = delta * unitRandom + range.lowerBound
return randFloat
}
/// Returns a random value within the specified range.
///
/// Use this method to generate a floating-point value within a specific
/// range. This example creates three new values in the range
/// `10.0 ... 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ... 20.0))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random()` static method chooses a random value from a continuous
/// uniform distribution in `range`, and then converts that value to the
/// nearest representable value in this type. Depending on the size and span
/// of `range`, some concrete values may be represented more frequently than
/// others.
///
/// This method is equivalent to calling `random(in:using:)`, passing in the
/// system's default random generator.
///
/// - Parameter range: The range in which to create a random value. Must be finite.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: ClosedRange<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
}
| apache-2.0 | a90a8ef9db33120ec3ceb18336ea06ae | 37.737731 | 96 | 0.635879 | 4.047961 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/CocoaLumberjack/CSCocoaLumberjack.swift | 1 | 2143 | //
// Created by Rene Dohan on 2019-01-17.
//
import CocoaLumberjack
public class CocoaLumberjackCSLogger: NSObject, CSLoggerProtocol {
var isDisabled: Bool = false
var isToast: Bool = false
public init(disabled: Bool = false) {
isDisabled = disabled
}
public init(toast: Bool = false) {
isToast = toast
}
public func logDebug(_ value: String) {
if !isDisabled {
DDLogDebug(value)
if isToast { CSNotification().title(value).time(5).show() }
}
}
public func logInfo(_ value: String) {
if !isDisabled {
DDLogInfo(value)
if isToast { CSNotification().title(value).time(5).show() }
}
}
public func logWarn(_ value: String) {
if !isDisabled {
DDLogWarn(value)
if isToast { CSNotification().title(value).time(5).show() }
}
}
public func logError(_ value: String) {
if !isDisabled {
DDLogError(value)
if isToast { CSNotification().title(value).time(5).show() }
}
}
}
public class CSCocoaLumberjackFormatter: NSObject, DDLogFormatter {
var loggerCount = 0
let threadUnsafeDateFormatter = DateFormatter().also {
$0.formatterBehavior = .behavior10_4
$0.dateFormat = "HH:mm:ss:SSS"
}
public func format(message: DDLogMessage) -> String? {
var logLevel: String
switch message.flag {
case DDLogFlag.debug: logLevel = "Debug"
case DDLogFlag.error: logLevel = "Error"
case DDLogFlag.warning: logLevel = "Warning"
case DDLogFlag.info: logLevel = "Info"
default: logLevel = "Verbose"
}
var dateAndTime = threadUnsafeDateFormatter.string(from: message.timestamp)
return "\(dateAndTime) \(logLevel) \(message.fileName ?? "") \(message.function) \(message.line) = \(message.message)"
}
public func didAdd(to logger: DDLogger) {
loggerCount += 1
assert(loggerCount <= 1, "This logger isn't thread-safe")
}
public func willRemove(from logger: DDLogger) { loggerCount -= 1 }
}
| mit | cf498645f3b8c5cb0b4bbe87009ccc6c | 27.573333 | 126 | 0.601493 | 4.268924 | false | false | false | false |
nakau1/NerobluCore | NerobluCore/NBKeyboard.swift | 1 | 4370 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
/// NBKeyboardEventのデリゲートプロトコル
@objc public protocol NBKeyboardEventDelegate {
/// キーボードの座標変更が始まる時に呼ばれる
///
/// このメソッド内でキーボードに隠れてしまう要素を退避させます
/// NSLayoutConstraintによる位置変更は、self.view.layoutIfNeeded()を呼ぶことでアニメーションが綺麗に行われます
///
/// - parameter event: NBKeyboardEventオブジェクトの参照
/// - parameter y: 座標変更後のキーボードのY座標
/// - parameter height: 座標変更後のキーボードの高さ
/// - parameter diff: 座標変更後のY座標の変化量
optional func keyboard(willChangeKeyboardFrame event: NBKeyboardEvent, y: CGFloat, height: CGFloat, diff: CGFloat)
}
/// キーボードイベントに関するイベントの汎用処理を行うクラス
public class NBKeyboardEvent : NSObject {
/// デリゲート
public weak var delegate: NBKeyboardEventDelegate?
private var keyboardHeight: CGFloat = CGFloat.min
private var keyboardY: CGFloat = CGFloat.min
/// キーボードイベントの監視を開始または終了する
/// - parameter start: 開始/終了
public func observeKeyboardEvents(start: Bool) {
let nc = NSNotificationCenter.defaultCenter()
let notifications = [
UIKeyboardWillShowNotification,
UIKeyboardWillChangeFrameNotification,
UIKeyboardWillHideNotification,
]
for notification in notifications {
if start {
self.keyboardHeight = CGFloat.min
self.keyboardY = CGFloat.min
nc.addObserver(self, selector: Selector("willChangeKeyboardFrame:"), name: notification, object: nil)
} else {
nc.removeObserver(self, name: notification, object: nil)
}
}
}
// イベントハンドラ
func willChangeKeyboardFrame(notify: NSNotification) {
guard
let userInfo = notify.userInfo,
let beginFrame = userInfo[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue,
let endFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue,
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval
else {
return
}
// 初回のみ
if self.keyboardHeight == CGFloat.min && self.keyboardY == CGFloat.min {
self.keyboardHeight = crH(beginFrame)
self.keyboardY = crY(beginFrame)
}
let height = crH(endFrame)
let beginY = crY(beginFrame)
let endY = crY(endFrame)
// 別画面でキーボードを表示すると変数yに大きな整数が入ってしまうため
if endY > App.Dimen.Screen.Height * 2 { return }
// 高さもY座標も変化していない場合は処理抜け
if self.keyboardHeight == height && self.keyboardY == endY { return }
self.keyboardHeight = height
self.keyboardY = endY
let options = UIViewAnimationOptions(rawValue: UInt(curve))
UIView.animateWithDuration(duration, delay: 0, options: options,
animations: {
let diff = endY - beginY
self.delegate?.keyboard?(willChangeKeyboardFrame: self, y: endY, height: height, diff: diff)
},
completion: { finished in }
)
}
}
// MARK: - ビューコントローラ拡張 -
public extension NBViewController {
/// キーボードイベント監視オブジェクト
public var keyboardEvent: NBKeyboardEvent {
let key = "NBKeyboardEvent"
if self.externalComponents[key] == nil {
self.externalComponents[key] = NBKeyboardEvent()
}
return self.externalComponents[key] as! NBKeyboardEvent
}
}
| apache-2.0 | 48e7fc9dfbfc912df5d19e5c99e24dd5 | 34.735849 | 118 | 0.595037 | 4.752823 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Registration/Company/CompanyLoginRequestDetector.swift | 1 | 4812 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
/**
* An object that detects company login request wihtin the pasteboard.
*
* A session request is a string formatted as `wire-[UUID]`.
*/
public final class CompanyLoginRequestDetector: NSObject {
/**
* A struct that describes the result of a login code detection operation..
*/
public struct DetectorResult: Equatable {
public let code: String // The detected shared identity login code.
public let isNew: Bool // Weather or not the code changed since the last check.
}
/// An enum describing the parsing result of a presumed SSO code / email
///
/// - ssoCode: SSO code
/// - domain: Domain extracted from the email
/// - unknown: Not matching an email or SSO code
public enum ParserResult {
case ssoCode(UUID)
case domain(String)
case unknown
}
private let pasteboard: Pasteboard
private let processQueue = DispatchQueue(label: "WireSyncEngine.SharedIdentitySessionRequestDetector")
private var previouslyDetectedSSOCode: String?
// MARK: - Initialization
/// Returns the detector that uses the system pasteboard to detect session requests.
public static let shared = CompanyLoginRequestDetector(pasteboard: UIPasteboard.general)
/// Creates a detector that uses the specified pasteboard to detect session requests.
public init(pasteboard: Pasteboard) {
self.pasteboard = pasteboard
}
// MARK: - Detection
/**
* Tries to extract the session request code from the current pasteboard.
*
* The processing will be done on a background queue, and the completion
* handler will be called on the main thread with the result.
*/
public func detectCopiedRequestCode(_ completionHandler: @escaping (DetectorResult?) -> Void) {
func complete(_ result: DetectorResult?) {
previouslyDetectedSSOCode = result?.code
DispatchQueue.main.async {
completionHandler(result)
}
}
processQueue.async { [pasteboard, previouslyDetectedSSOCode] in
guard let text = pasteboard.text else { return complete(nil) }
guard let code = CompanyLoginRequestDetector.requestCode(in: text) else { return complete(nil) }
let validSSOCode = "wire-" + code.uuidString
let isNew = validSSOCode != previouslyDetectedSSOCode
complete(.init(code: validSSOCode, isNew: isNew))
}
}
/// Parses the input and returns its type (.ssoCode, .domain or .unknown)
///
/// - Parameter input: to be parsed
/// - Returns: type of input with its eventual associated value
public static func parse(input: String) -> ParserResult {
if let domain = domain(from: input) {
return .domain(domain)
} else if let code = requestCode(in: input) {
return .ssoCode(code)
} else {
return .unknown
}
}
/// Tries to extract the domain from a given email
///
/// - Parameter email: the email to extract the domain from. e.g. [email protected]
/// - Returns: domain. e.g. domain.com
private static func domain(from email: String) -> String? {
guard ZMEmailAddressValidator.isValidEmailAddress(email) else { return nil }
return email.components(separatedBy: "@").last
}
/**
* Tries to extract the request ID from the contents of the text.
*/
public static func requestCode(in string: String) -> UUID? {
guard let prefixRange = string.range(of: "wire-") else {
return nil
}
guard let endIndex = string.index(prefixRange.upperBound, offsetBy: 36, limitedBy: string.endIndex) else {
return nil
}
let codeString = string[prefixRange.upperBound ..< endIndex]
return UUID(uuidString: String(codeString))
}
/**
* Validates the session request code from the user input.
*/
public static func isValidRequestCode(in string: String) -> Bool {
return requestCode(in: string) != nil
}
}
| gpl-3.0 | 0c84385fd5a23f17cbb5ab8e0c1f74d0 | 33.869565 | 114 | 0.661471 | 4.676385 | false | false | false | false |
qinting513/SwiftNote | youtube/YouTube/Supporting views/TabBar.swift | 1 | 4170 | //
// TabBar.swift
// YouTube
//
// Created by Haik Aslanyan on 6/26/16.
// Copyright © 2016 Haik Aslanyan. All rights reserved.
//
protocol TabBarDelegate {
func didSelectItem(atIndex: Int)
}
import UIKit
class TabBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
//MARK: Properties
let identifier = "cell"
let darkItems = ["homeDark", "trendingDark", "subscriptionsDark", "accountDark"]
let items = ["home", "trending", "subscriptions", "account"]
lazy var whiteView: UIView = {
let wv = UIView.init(frame: CGRect.init(x: 0, y: self.frame.height - 5, width: self.frame.width / 4, height: 5))
wv.backgroundColor = UIColor.rbg(r: 245, g: 245, b: 245)
return wv
}()
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView.init(frame: CGRect.init(x: 0, y: 20, width: self.frame.width, height: (self.frame.height - 20)), collectionViewLayout: layout)
cv.delegate = self
cv.dataSource = self
cv.backgroundColor = UIColor.clear
cv.isScrollEnabled = false
return cv
}()
var delegate: TabBarDelegate?
//MARK: CollectionView DataSources
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! TabBarCellCollectionViewCell
cell.icon.image = UIImage.init(named: darkItems[indexPath.row])
if indexPath.row == 0 {
cell.icon.image = UIImage.init(named: items[0])
}
return cell
}
//MARK: CollectionView Delegates
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: self.frame.width / 4, height: (self.frame.height - 20))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.didSelectItem(atIndex: indexPath.row)
}
//MARK: Methods
func highlightItem(atIndex: Int) {
for index in 0...3 {
let cell = collectionView.cellForItem(at: IndexPath.init(row: index, section: 0)) as! TabBarCellCollectionViewCell
cell.icon.image = UIImage.init(named: darkItems[index])
}
let cell = collectionView.cellForItem(at: IndexPath.init(row: atIndex, section: 0)) as! TabBarCellCollectionViewCell
cell.icon.image = UIImage.init(named: items[atIndex])
}
//MARK: - Inits
override init(frame: CGRect) {
super.init(frame: frame)
collectionView.register(TabBarCellCollectionViewCell.self, forCellWithReuseIdentifier: identifier)
self.backgroundColor = UIColor.rbg(r: 228, g: 34, b: 24)
addSubview(self.collectionView)
addSubview(self.whiteView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//TabBarCell Class
class TabBarCellCollectionViewCell: UICollectionViewCell {
let icon = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
let width = (self.contentView.bounds.width - 30) / 2
icon.frame = CGRect.init(x: width, y: 2, width: 30, height: 30)
let image = UIImage.init(named: "home")
icon.image = image?.withRenderingMode(.alwaysTemplate)
self.contentView.addSubview(icon)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 1e908112372311d6e1ca75688308988a | 37.962617 | 175 | 0.673543 | 4.616833 | false | false | false | false |
royhsu/tiny-core | Tests/Reducer/CombinedReducersTests+Counter.swift | 1 | 528 | //
// CombinedReducersTests+Counter.swift
// TinyCoreTests
//
// Created by Roy Hsu on 2019/3/14.
// Copyright © 2019 TinyWorld. All rights reserved.
//
// MARK: - Counter
extension CombinedReducersTests {
struct Counter: Equatable {
var currentNumber: Int
init(initialNumber: Int = 0) { self.currentNumber = initialNumber }
// MARK: - Equatable
static func == (lhs: Counter, rhs: Counter) -> Bool {
return lhs.currentNumber == rhs.currentNumber
}
}
}
| mit | 685bbef7f47644a91e028ce08ff3716b | 17.172414 | 75 | 0.620493 | 4.053846 | false | true | false | false |
AV8R-/SwiftUtils | ComplexButton.swift | 1 | 5082 | //
// ComplexButton.swift
// UltimateGuitar
//
// Created by Bogdan Manshilin on 3/18/17.
//
//
import UIKit
open class ComplexButton: UIControl {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initOverlayButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
initOverlayButton()
}
public var onPress: (()->Void)? {
didSet {
if let _ = onPress {
overlay.addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
} else {
overlay.removeTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
}
}
}
public var shouldMakeTranclucentOnHiglhlight = true
lazy var nestedButtons: [UIButton] = {
var buttons = [UIButton]()
let count = self.subviews.count - 1
guard count > 0 else {
return []
}
let sbviews = Array(self.subviews[0..<1])
self.recursive(subviews: sbviews) {
if let button = $0 as? UIButton {
buttons.append(button)
}
}
return buttons
}()
private weak var overlay: UIButton!
private func initOverlayButton() {
let overlay = UIButton()
overlay.translatesAutoresizingMaskIntoConstraints = false
addSubview(overlay)
overlay.addConstraintsToSuperviewBounds()
overlay.addObserver(self, forKeyPath: "highlighted", options: .new, context: nil)
overlay.addObserver(self, forKeyPath: "selected", options: .new, context: nil)
overlay.addObserver(self, forKeyPath: "enabled", options: .new, context: nil)
self.overlay = overlay
}
override open var isEnabled: Bool { didSet {
self.nestedButtons.forEach { $0.isEnabled = isEnabled }
}}
override open var isSelected: Bool { didSet {
self.nestedButtons.forEach { $0.isSelected = isSelected }
}}
override open var isHighlighted: Bool { didSet {
guard shouldMakeTranclucentOnHiglhlight else {
return
}
let count = subviews.count - 1 > 0 ? subviews.count - 1 : 0
let alpha: CGFloat = isHighlighted ? 0.3 : 1
for subview in subviews[0..<count] {
subview.alpha = alpha
}
}}
override open func layoutIfNeeded() {
super.layoutIfNeeded()
self.bringSubview(toFront: overlay)
}
override open func addSubview(_ view: UIView) {
if let overlay = overlay {
insertSubview(view, belowSubview: overlay)
} else {
super.addSubview(view)
}
}
override open var contentVerticalAlignment: UIControlContentVerticalAlignment { didSet {
self.nestedButtons.forEach { $0.contentVerticalAlignment = contentVerticalAlignment }
}}
override open var contentHorizontalAlignment: UIControlContentHorizontalAlignment{ didSet {
self.nestedButtons.forEach { $0.contentHorizontalAlignment = contentHorizontalAlignment }
}}
override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
self.nestedButtons.forEach { $0.beginTracking(touch, with: event) }
return super.beginTracking(touch, with: event)
}
override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
self.nestedButtons.forEach { $0.continueTracking(touch, with: event) }
return super.continueTracking(touch, with: event)
}
override open func endTracking(_ touch: UITouch?, with event: UIEvent?) {
self.nestedButtons.forEach { $0.endTracking(touch, with: event) }
return super.endTracking(touch, with: event)
}
override open func cancelTracking(with event: UIEvent?) {
self.nestedButtons.forEach { $0.cancelTracking(with: event) }
super.cancelTracking(with: event)
}
override open func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) {
overlay.addTarget(target, action: action, for: controlEvents)
}
override open func removeTarget(_ target: Any?, action: Selector?, for controlEvents: UIControlEvents) {
overlay.removeTarget(target, action: action, for: controlEvents)
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let newValue = change![.newKey] as! Bool
switch keyPath {
case "highlighted"?: isHighlighted = newValue
case "selected"?: isSelected = newValue
case "enabled"?: isEnabled = newValue
default:()
}
}
deinit {
overlay.removeObserver(self, forKeyPath: "highlighted")
overlay.removeObserver(self, forKeyPath: "selected")
overlay.removeObserver(self, forKeyPath: "enabled")
}
@objc func touchUpInside(_ sender: Any) {
onPress?()
}
}
| mit | a232f73f963c194205359e7c900aeb06 | 32.434211 | 156 | 0.625344 | 4.84 | false | false | false | false |
thachpv91/loafwallet | BreadWallet/BRHTTPRouter.swift | 3 | 7658 | //
// BRHTTPRouter.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet LLC
// Copyright © 2016 Litecoin Association <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public typealias BRHTTPRouteMatch = [String: [String]]
public typealias BRHTTPRoute = (_ request: BRHTTPRequest, _ match: BRHTTPRouteMatch) throws -> BRHTTPResponse
@objc public protocol BRHTTPRouterPlugin {
func hook(_ router: BRHTTPRouter)
}
@objc open class BRHTTPRoutePair: NSObject {
open var method: String = "GET"
open var path: String = "/"
open var regex: NSRegularExpression!
var captureGroups: [Int: String]!
override open var hashValue: Int {
return method.hashValue ^ path.hashValue
}
init(method m: String, path p: String) {
method = m.uppercased()
path = p
super.init()
parse()
}
fileprivate func parse() {
if !path.hasPrefix("/") {
path = "/" + path
}
if path.hasSuffix("/") {
path = path.substring(to: path.characters.index(path.endIndex, offsetBy: -1))
}
let parts = path.components(separatedBy: "/")
captureGroups = [Int: String]()
var reParts = [String]()
var i = 0
for part in parts {
if part.hasPrefix("(") && part.hasSuffix(")") {
let w1 = part.characters.index(part.endIndex, offsetBy: -2)
let w2 = part.characters.index(part.endIndex, offsetBy: -1)
if part.substring(with: w1..<w2) == "*" { // a wild card capture (part*)
let i1 = part.characters.index(part.startIndex, offsetBy: 1)
let i2 = part.characters.index(part.endIndex, offsetBy: -2)
captureGroups[i] = part.substring(with: i1..<i2)
reParts.append("(.*)")
} else {
let i1 = part.characters.index(part.startIndex, offsetBy: 1)
let i2 = part.characters.index(part.endIndex, offsetBy: -1)
captureGroups[i] = part.substring(with: i1..<i2)
reParts.append("([^/]+)") // a capture (part)
}
i += 1
} else {
reParts.append(part) // a non-captured component
}
}
let re = "^" + reParts.joined(separator: "/") + "$"
//print("\n\nroute: \n\n method: \(method)\n path: \(path)\n regex: \(re)\n captures: \(captureGroups)\n\n")
regex = try! NSRegularExpression(pattern: re, options: [])
}
open func match(_ request: BRHTTPRequest) -> BRHTTPRouteMatch? {
if request.method.uppercased() != method {
return nil
}
var p = request.path // strip trailing slash
if p.hasSuffix("/") {
p = request.path.substring(to: request.path.characters.index(request.path.endIndex, offsetBy: -1))
}
if let m = regex.firstMatch(in: request.path, options: [], range: NSMakeRange(0, p.characters.count))
, m.numberOfRanges - 1 == captureGroups.count {
var match = BRHTTPRouteMatch()
for i in 1..<m.numberOfRanges {
let key = captureGroups[i-1]!
let captured = (p as NSString).substring(with: m.rangeAt(i))
if match[key] == nil {
match[key] = [captured]
} else {
match[key]?.append(captured)
}
//print("capture range: '\(key)' = '\(captured)'\n\n")
}
return match
}
return nil
}
}
@objc open class BRHTTPRouter: NSObject, BRHTTPMiddleware {
var routes = [(BRHTTPRoutePair, BRHTTPRoute)]()
var plugins = [BRHTTPRouterPlugin]()
fileprivate var wsServer = BRWebSocketServer()
open func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void) {
var response: BRHTTPResponse? = nil
for (routePair, route) in routes {
if let match = routePair.match(request) {
do {
response = try route(request, match)
} catch let e {
print("[BRHTTPRouter] route \(routePair.method) \(routePair.path) threw an exception \(e)")
response = BRHTTPResponse(request: request, code: 500)
}
break
}
}
return next(BRHTTPMiddlewareResponse(request: request, response: response))
}
open func get(_ pattern: String, route: @escaping BRHTTPRoute) {
routes.append((BRHTTPRoutePair(method: "GET", path: pattern), route))
}
open func post(_ pattern: String, route: @escaping BRHTTPRoute) {
routes.append((BRHTTPRoutePair(method: "POST", path: pattern), route))
}
open func put(_ pattern: String, route: @escaping BRHTTPRoute) {
routes.append((BRHTTPRoutePair(method: "PUT", path: pattern), route))
}
open func patch(_ pattern: String, route: @escaping BRHTTPRoute) {
routes.append((BRHTTPRoutePair(method: "PATCH", path: pattern), route))
}
open func delete(_ pattern: String, route: @escaping BRHTTPRoute) {
routes.append((BRHTTPRoutePair(method: "DELETE", path: pattern), route))
}
open func any(_ pattern: String, route: @escaping BRHTTPRoute) {
for m in ["GET", "POST", "PUT", "PATCH", "DELETE"] {
routes.append((BRHTTPRoutePair(method: m, path: pattern), route))
}
}
open func websocket(_ pattern: String, client: BRWebSocketClient) {
self.get(pattern) { (request, match) -> BRHTTPResponse in
self.wsServer.serveForever()
let resp = BRHTTPResponse(async: request)
let ws = BRWebSocketImpl(request: request, response: resp, match: match, client: client)
if !ws.handshake() {
print("[BRHTTPRouter] websocket - invalid handshake")
resp.provide(400, json: ["error": "invalid handshake"])
} else {
self.wsServer.add(ws)
}
return resp
}
}
open func plugin(_ plugin: BRHTTPRouterPlugin) {
plugin.hook(self)
plugins.append(plugin)
}
open func printDebug() {
for (r, _) in routes {
print("[BRHTTPRouter] \(r.method) \(r.path)")
}
}
}
| mit | 55c2dd8bca943bcd1e9648d6ceb9e808 | 38.673575 | 116 | 0.579992 | 4.355518 | false | false | false | false |
nsagora/validation-toolkit | Sources/Constraints/Standard/BlockConstraint.swift | 1 | 2792 | import Foundation
/**
A `Constraint` that links a custom validation closure to an `Error` that describes why the evaluation has failed.
```swift
enum Failure: Error {
case notEven
}
```
```swift
let constraint = BlockConstraint<Int, Failure> {
$0 % 2 == 0
} errorBuilder: {
.notEven
}
let result = constraint.evaluate(with: 2)
```
*/
public struct BlockConstraint<T, E: Error>: Constraint {
public typealias InputType = T
public typealias ErrorType = E
private let predicate: BlockPredicate<T>
private let errorBuilder: (T) -> E
/**
Returns a new `BlockConstraint` instance.
```swift
enum Failure: Error {
case notEven
}
```
```swift
let constraint = BlockConstraint<Int, Failure> {
$0 % 2 == 0
} errorBuilder: {
.notEven
}
let result = constraint.evaluate(with: 2)
```
- parameter evaluationBlock: A closure describing a custom validation condition.
- parameter errorBuilder: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed.
*/
public init(_ evaluationBlock: @escaping (T) -> Bool, errorBuilder: @escaping () -> E) {
self.predicate = BlockPredicate(evaluationBlock: evaluationBlock)
self.errorBuilder = { _ in errorBuilder() }
}
/**
Create a new `BlockConstraint` instance.
```swift
enum Failure: Error {
case notEven(Int)
}
```
```swift
let constraint = BlockConstraint<Int, Failure> {
$0 % 2 == 0
} errorBuilder: { input in
.notEven(input)
}
let result = constraint.evaluate(with: 2)
```
- parameter evaluationBlock: A closure describing a custom validation condition.
- parameter errorBuilder: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed.
*/
public init(_ evaluationBlock: @escaping (T) -> Bool, errorBuilder: @escaping (T) -> E) {
predicate = BlockPredicate(evaluationBlock: evaluationBlock)
self.errorBuilder = errorBuilder
}
/**
Evaluates the input against the provided evaluation closure.
- parameter input: The input to be validated.
- returns: `.success` if the input is valid,`.failure` containing the `Summary` of the failing `Constraint`s otherwise.
*/
public func evaluate(with input: T) -> Result<Void, Summary<E>> {
let result = predicate.evaluate(with: input)
if result == true {
return .success(())
}
let error = errorBuilder(input)
let summary = Summary(errors: [error])
return .failure(summary)
}
}
| mit | a50e758a759e41ed7e411de8fefecb48 | 27.489796 | 126 | 0.610673 | 4.569558 | false | false | false | false |
society2012/PGDBK | PGDBK/PGDBK/Tool/Extension/Common.swift | 1 | 757 | //
// Common.swift
// HPZBTV
//
// Created by hupeng on 17/3/22.
// Copyright © 2017年 m.zintao. All rights reserved.
//
import UIKit
let kStatusBarH :CGFloat = 20
let kTabBarH :CGFloat = 49
let kNavigaitonBarH :CGFloat = 64
let kScreenW :CGFloat = UIScreen.main.bounds.width
let kScreenH :CGFloat = UIScreen.main.bounds.height
let kDelegate = UIApplication.shared.delegate as? AppDelegate
func kRGBColorFromHex(rgbValue: Int) -> (UIColor) {
return UIColor(
red: ((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255.0,
green: ((CGFloat)((rgbValue & 0xFF00) >> 8)) / 255.0,
blue: ((CGFloat)(rgbValue & 0xFF)) / 255.0,
alpha: 1.0)
}
| mit | 5398e2659b52d3e4ff8ebc409b889a0d | 17.85 | 70 | 0.584881 | 3.57346 | false | false | false | false |
TwoRingSoft/shared-utils | Sources/PippinCore/Environment/DefaultDefaults.swift | 1 | 2410 | //
// DefaultDefaults.swift
// Pippin
//
// Created by Andrew McKnight on 8/17/18.
//
import Foundation
import PippinLibrary
public enum DefaultDefaultsKey: String {
case debugLogging = "debug-logging"
case lastLaunchedSemanticVersion = "last-launched-semantic-version"
case lastLaunchedBuildNumber = "last-launched-build-number"
public func keyString() -> String {
return String(asRDNSForPippinSubpaths: ["user-defaults", "key", self.rawValue])
}
}
public struct DefaultDefaults: Defaults {
public var environment: Environment?
public init() {}
public var logLevel: LogLevel? {
get {
return LogLevel(debugDescription: UserDefaults.standard.string(forKey: DefaultDefaultsKey.debugLogging.keyString()))
}
set(newValue) {
let key = DefaultDefaultsKey.debugLogging.keyString()
guard let value = newValue else {
UserDefaults.setAndSynchronize(key: key, value: nil)
return
}
UserDefaults.setAndSynchronize(key: key, value: String(reflecting: value))
}
}
public var lastLaunchedBuild: Build? {
get {
guard let stringValue = UserDefaults.standard.string(forKey: DefaultDefaultsKey.lastLaunchedBuildNumber.keyString()) else { return nil }
return Build(stringValue)
}
set(newValue) {
let key = DefaultDefaultsKey.lastLaunchedBuildNumber.keyString()
guard let value = newValue else {
UserDefaults.setAndSynchronize(key: key, value: nil)
return
}
UserDefaults.setAndSynchronize(key: key, value: String(describing: value))
}
}
public var lastLaunchedVersion: SemanticVersion? {
get {
guard let stringValue = UserDefaults.standard.string(forKey: DefaultDefaultsKey.lastLaunchedSemanticVersion.keyString()) else { return nil }
return SemanticVersion(stringValue)
}
set(newValue) {
let key = DefaultDefaultsKey.lastLaunchedSemanticVersion.keyString()
guard let value = newValue else {
UserDefaults.setAndSynchronize(key: key, value: nil)
return
}
UserDefaults.setAndSynchronize(key: key, value: String(describing: value))
}
}
}
| mit | 4f0e0123c12b71f2e4b4fd616add59df | 32.943662 | 152 | 0.629876 | 4.938525 | false | false | false | false |
brentsimmons/Evergreen | Shared/Extensions/URL-Extensions.swift | 1 | 1923 | //
// URL-Extensions.swift
// NetNewsWire
//
// Created by Stuart Breckenridge on 03/05/2020.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
extension URL {
/// Extracts email address from a `URL` with a `mailto` scheme, otherwise `nil`.
var emailAddress: String? {
scheme == "mailto" ? URLComponents(url: self, resolvingAgainstBaseURL: false)?.path : nil
}
/// Percent encoded `mailto` URL for use with `canOpenUrl`. If the URL doesn't contain the `mailto` scheme, this is `nil`.
var percentEncodedEmailAddress: URL? {
scheme == "mailto" ? self.string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?.url : nil
}
/// URL pointing to current app version release notes.
static var releaseNotes: URL {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""
var gitHub = "https://github.com/Ranchero-Software/NetNewsWire/releases/tag/"
#if os(macOS)
gitHub += "mac-\(String(describing: appVersion))"
return URL(string: gitHub)!
#else
gitHub += "ios-\(String(describing: appVersion))"
return URL(string: gitHub)!
#endif
}
func valueFor(_ parameter: String) -> String? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false),
let queryItems = components.queryItems,
let value = queryItems.first(where: { $0.name == parameter })?.value else {
return nil
}
return value
}
static func reparingIfRequired(_ link: String?) -> URL? {
// If required, we replace any space characters to handle malformed links that are otherwise percent
// encoded but contain spaces. For performance reasons, only try this if initial URL init fails.
guard let link = link, !link.isEmpty else { return nil }
if let url = URL(string: link) {
return url
} else {
return URL(string: link.replacingOccurrences(of: " ", with: "%20"))
}
}
}
| mit | b94686c71a34e2beecc6ccb5676a0df4 | 32.719298 | 123 | 0.703954 | 3.844 | false | false | false | false |
sessionm/ios-smp-example | Rewards/OrdersTableViewController.swift | 1 | 3022 | //
// OrdersTableViewController.swift
// SMPExample
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMRewardsKit
import UIKit
class OrderCell: UITableViewCell {
@IBOutlet var logo: UIImageView!
@IBOutlet var orderID: UILabel!
@IBOutlet var name: UILabel!
@IBOutlet var quantity: UILabel!
@IBOutlet var points: UILabel!
@IBOutlet var status: UILabel!
@IBOutlet var details: UILabel!
@IBOutlet var createdAt: UILabel!
}
class OrdersTableViewController: UITableViewController {
private var rewardsManager = SMRewardsManager.instance()
private var orders: [SMOrder] = []
@IBAction private func onRefresh(_ sender: UIRefreshControl) {
fetchOrders()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fetchOrders()
}
private func fetchOrders() {
self.refreshControl?.beginRefreshing()
rewardsManager.fetchOrders(completionHandler: { (orders: [SMOrder]?, error: SMError?) in
if let err = error {
Util.failed(self, message: err.message)
} else if let newOrders = orders {
self.orders = newOrders
self.tableView.reloadData()
}
self.refreshControl?.endRefreshing()
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return orders.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let order = orders[indexPath.row]
if order.logoURL != nil {
return 240.0
} else {
return 96.0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let order = orders[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "OrderCell", for: indexPath) as? OrderCell
if let c = cell {
c.orderID.text = order.orderID
c.name.text = order.name
c.quantity.text = "\(order.quantity)"
c.points.text = "\(order.points) pts"
c.status.text = order.stringFromCurrentStatus()
c.details.text = order.details
c.createdAt.text = order.createdTime
c.tag = indexPath.row
if let img = order.logoURL {
Util.loadFrom(img, callback: { (image) in
c.logo.image = image
})
}
}
return cell!
}
@IBAction private func logout(_ sender: AnyObject) {
if let provider = SessionM.authenticationProvider() as? SessionMOAuthProvider {
provider.logOutUser { (authState, error) in
LoginViewController.loginIfNeeded(self.tabBarController!)
}
}
}
}
| mit | 2c52465dbc088554077c72109ce72b3d | 30.46875 | 109 | 0.614366 | 4.818182 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/ViewControllers/Config/LayoutConfigController.swift | 2 | 3221 | //
// ConfigController.swift
// SwiftNetworkImages
//
// Created by Arseniy on 7/6/16.
// Copyright © 2016 Arseniy Kuznetsov. All rights reserved.
//
import UIKit
import AKPFlowLayout
/// Visual configuration of AKPCollectionViewFlowLayout's LayoutConfigOptions
class LayoutConfigController: UITableViewController {
var configOptions: AKPLayoutConfigOptions?
var selectedOptions: AKPLayoutConfigOptions?
var height: CGFloat {
let numRows = tableView(tableView, numberOfRowsInSection: 0)
let headerHeight = tableView(tableView, heightForHeaderInSection: 0)
let footerHeight = tableView(tableView, heightForFooterInSection: 0)
return CGFloat(numRows) * tableView.rowHeight + CGFloat(headerHeight + footerHeight)
}
override init(style: UITableViewStyle) {
super.init(style: UITableViewStyle.grouped)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 40
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellReuseID")
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return configOptions?.descriptions.count ?? 0
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellReuseID",
for: indexPath) as UITableViewCell
if let configOptions = configOptions
, configOptions.descriptions.count > indexPath.row {
let optionDescription = configOptions.descriptions[indexPath.row]
cell.textLabel?.text = optionDescription
if let selectedOptions = selectedOptions {
let option = AKPLayoutConfigOptions(rawValue: 1 << indexPath.row)
cell.accessoryType = selectedOptions.contains(option) ?
UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.none
}
}
cell.textLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let selectedOptions = selectedOptions {
let option = AKPLayoutConfigOptions(rawValue: 1 << indexPath.row )
if selectedOptions.contains(option) {
_ = self.selectedOptions?.remove(option)
} else {
self.selectedOptions?.insert(option)
}
}
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.1
}
}
| mit | c09ea67810e7a50ca7b793df25ab9284 | 38.268293 | 105 | 0.651863 | 5.639229 | false | true | false | false |
s-aska/Toucan | Source/Toucan.swift | 2 | 26800 | // Toucan.swift
//
// Copyright (c) 2014 Gavin Bunney, Bunney Apps (http://bunney.net.au)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreGraphics
/**
Toucan - Fabulous Image Processing in Swift.
The Toucan class provides two methods of interaction - either through an instance, wrapping an single image,
or through the static functions, providing an image for each invocation.
This allows for some flexible usage. Using static methods when you need a single operation:
let resizedImage = Toucan.resize(myImage, size: CGSize(width: 100, height: 150))
Or create an instance for easy method chaining:
let resizedAndMaskedImage = Toucan(withImage: myImage).resize(CGSize(width: 100, height: 150)).maskWithEllipse().image
*/
public class Toucan : NSObject {
public var image : UIImage
public init(image withImage: UIImage) {
self.image = withImage
}
// MARK: - Resize
/**
Resize the contained image to the specified size. Depending on what fitMode is supplied, the image
may be clipped, cropped or scaled. @see documentation on FitMode.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- parameter fitMode: How to handle the image resizing process
- returns: Self, allowing method chaining
*/
public func resize(size: CGSize, fitMode: Toucan.Resize.FitMode = .Clip) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: fitMode)
return self
}
/**
Resize the contained image to the specified size by resizing the image to fit
within the width and height boundaries without cropping or scaling the image.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- returns: Self, allowing method chaining
*/
@objc
public func resizeByClipping(size: CGSize) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: .Clip)
return self
}
/**
Resize the contained image to the specified size by resizing the image to fill the
width and height boundaries and crops any excess image data.
The resulting image will match the width and height constraints without scaling the image.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- returns: Self, allowing method chaining
*/
@objc
public func resizeByCropping(size: CGSize) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: .Crop)
return self
}
/**
Resize the contained image to the specified size by scaling the image to fit the
constraining dimensions exactly.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- returns: Self, allowing method chaining
*/
@objc
public func resizeByScaling(size: CGSize) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: .Scale)
return self
}
/**
Container struct for all things Resize related
*/
public struct Resize {
/**
FitMode drives the resizing process to determine what to do with an image to
make it fit the given size bounds.
- Clip: Resizes the image to fit within the width and height boundaries without cropping or scaling the image.
- Crop: Resizes the image to fill the width and height boundaries and crops any excess image data.
- Scale: Scales the image to fit the constraining dimensions exactly.
*/
public enum FitMode {
/**
Resizes the image to fit within the width and height boundaries without cropping or scaling the image.
The resulting image is assured to match one of the constraining dimensions, while
the other dimension is altered to maintain the same aspect ratio of the input image.
*/
case Clip
/**
Resizes the image to fill the width and height boundaries and crops any excess image data.
The resulting image will match the width and height constraints without scaling the image.
*/
case Crop
/**
Scales the image to fit the constraining dimensions exactly.
*/
case Scale
}
/**
Resize an image to the specified size. Depending on what fitMode is supplied, the image
may be clipped, cropped or scaled. @see documentation on FitMode.
- parameter image: Image to Resize
- parameter size: Size to resize the image to
- parameter fitMode: How to handle the image resizing process
- returns: Resized image
*/
public static func resizeImage(image: UIImage, size: CGSize, fitMode: FitMode = .Clip) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let originalWidth = CGFloat(CGImageGetWidth(imgRef))
let originalHeight = CGFloat(CGImageGetHeight(imgRef))
let widthRatio = size.width / originalWidth
let heightRatio = size.height / originalHeight
let scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio
let resizedImageBounds = CGRect(x: 0, y: 0, width: round(originalWidth * scaleRatio), height: round(originalHeight * scaleRatio))
let resizedImage = Util.drawImageInBounds(image, bounds: resizedImageBounds)
switch (fitMode) {
case .Clip:
return resizedImage
case .Crop:
let croppedRect = CGRect(x: (resizedImage.size.width - size.width) / 2,
y: (resizedImage.size.height - size.height) / 2,
width: size.width, height: size.height)
return Util.croppedImageWithRect(resizedImage, rect: croppedRect)
case .Scale:
return Util.drawImageInBounds(resizedImage, bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
}
}
// MARK: - Mask
/**
Mask the contained image with another image mask.
Note that the areas in the original image that correspond to the black areas of the mask
show through in the resulting image. The areas that correspond to the white areas of
the mask aren’t painted. The areas that correspond to the gray areas in the mask are painted
using an intermediate alpha value that’s equal to 1 minus the image mask sample value.
- parameter maskImage: Image Mask to apply to the Image
- returns: Self, allowing method chaining
*/
public func maskWithImage(maskImage maskImage : UIImage) -> Toucan {
self.image = Toucan.Mask.maskImageWithImage(self.image, maskImage: maskImage)
return self
}
/**
Mask the contained image with an ellipse.
Allows specifying an additional border to draw on the clipped image.
For a circle, ensure the image width and height are equal!
- parameter borderWidth: Optional width of the border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Self, allowing method chaining
*/
public func maskWithEllipse(borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> Toucan {
self.image = Toucan.Mask.maskImageWithEllipse(self.image, borderWidth: borderWidth, borderColor: borderColor)
return self
}
/**
Mask the contained image with a path (UIBezierPath) that will be scaled to fit the image.
- parameter path: UIBezierPath to mask the image
- returns: Self, allowing method chaining
*/
public func maskWithPath(path path: UIBezierPath) -> Toucan {
self.image = Toucan.Mask.maskImageWithPath(self.image, path: path)
return self
}
/**
Mask the contained image with a path (UIBezierPath) which is provided via a closure.
- parameter path: closure that returns a UIBezierPath. Using a closure allows the user to provide the path after knowing the size of the image
- returns: Self, allowing method chaining
*/
public func maskWithPathClosure(path path: (rect: CGRect) -> (UIBezierPath)) -> Toucan {
self.image = Toucan.Mask.maskImageWithPathClosure(self.image, pathInRect: path)
return self
}
/**
Mask the contained image with a rounded rectangle border.
Allows specifying an additional border to draw on the clipped image.
- parameter cornerRadius: Radius of the rounded rect corners
- parameter borderWidth: Optional width of border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Self, allowing method chaining
*/
public func maskWithRoundedRect(cornerRadius cornerRadius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> Toucan {
self.image = Toucan.Mask.maskImageWithRoundedRect(self.image, cornerRadius: cornerRadius, borderWidth: borderWidth, borderColor: borderColor)
return self
}
/**
Container struct for all things Mask related
*/
public struct Mask {
/**
Mask the given image with another image mask.
Note that the areas in the original image that correspond to the black areas of the mask
show through in the resulting image. The areas that correspond to the white areas of
the mask aren’t painted. The areas that correspond to the gray areas in the mask are painted
using an intermediate alpha value that’s equal to 1 minus the image mask sample value.
- parameter image: Image to apply the mask to
- parameter maskImage: Image Mask to apply to the Image
- returns: Masked image
*/
public static func maskImageWithImage(image: UIImage, maskImage: UIImage) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let maskRef = maskImage.CGImage
let mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), nil, false);
let masked = CGImageCreateWithMask(imgRef, mask);
return Util.drawImageWithClosure(size: image.size) { (size: CGSize, context: CGContext) -> () in
// need to flip the transform matrix, CoreGraphics has (0,0) in lower left when drawing image
CGContextScaleCTM(context, 1, -1)
CGContextTranslateCTM(context, 0, -size.height)
CGContextDrawImage(context, CGRect(x: 0, y: 0, width: size.width, height: size.height), masked);
}
}
/**
Mask the given image with an ellipse.
Allows specifying an additional border to draw on the clipped image.
For a circle, ensure the image width and height are equal!
- parameter image: Image to apply the mask to
- parameter borderWidth: Optional width of the border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Masked image
*/
public static func maskImageWithEllipse(image: UIImage,
borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
CGContextAddEllipseInRect(context, rect)
CGContextClip(context)
image.drawInRect(rect)
if (borderWidth > 0) {
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextSetLineWidth(context, borderWidth);
CGContextAddEllipseInRect(context, CGRect(x: borderWidth / 2,
y: borderWidth / 2,
width: size.width - borderWidth,
height: size.height - borderWidth));
CGContextStrokePath(context);
}
}
}
/**
Mask the given image with a path(UIBezierPath) that will be scaled to fit the image.
- parameter image: Image to apply the mask to
- parameter path: UIBezierPath to make as the mask
- returns: Masked image
*/
public static func maskImageWithPath(image: UIImage,
path: UIBezierPath) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let boundSize = path.bounds.size
let pathRatio = boundSize.width / boundSize.height
let imageRatio = size.width / size.height
if pathRatio > imageRatio {
//scale based on width
let scale = size.width / boundSize.width
path.applyTransform(CGAffineTransformMakeScale(scale, scale))
path.applyTransform(CGAffineTransformMakeTranslation(0, (size.height - path.bounds.height) / 2.0))
} else {
//scale based on height
let scale = size.height / boundSize.height
path.applyTransform(CGAffineTransformMakeScale(scale, scale))
path.applyTransform(CGAffineTransformMakeTranslation((size.width - path.bounds.width) / 2.0, 0))
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
CGContextAddPath(context, path.CGPath)
CGContextClip(context)
image.drawInRect(rect)
}
}
/**
Mask the given image with a path(UIBezierPath) provided via a closure. This allows the user to get the size of the image before computing their path variable.
- parameter image: Image to apply the mask to
- parameter path: UIBezierPath to make as the mask
- returns: Masked image
*/
public static func maskImageWithPathClosure(image: UIImage,
pathInRect:(rect: CGRect) -> (UIBezierPath)) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return maskImageWithPath(image, path: pathInRect(rect: CGRectMake(0, 0, size.width, size.height)))
}
/**
Mask the given image with a rounded rectangle border.
Allows specifying an additional border to draw on the clipped image.
- parameter image: Image to apply the mask to
- parameter cornerRadius: Radius of the rounded rect corners
- parameter borderWidth: Optional width of border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Masked image
*/
public static func maskImageWithRoundedRect(image: UIImage, cornerRadius: CGFloat,
borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIBezierPath(roundedRect:rect, cornerRadius: cornerRadius).addClip()
image.drawInRect(rect)
if (borderWidth > 0) {
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextSetLineWidth(context, borderWidth);
let borderRect = CGRect(x: 0, y: 0,
width: size.width, height: size.height)
let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: cornerRadius)
borderPath.lineWidth = borderWidth * 2
borderPath.stroke()
}
}
}
}
// MARK: - Layer
/**
Overlay an image ontop of the current image.
- parameter image: Image to be on the bottom layer
- parameter overlayImage: Image to be on the top layer, i.e. drawn on top of image
- parameter overlayFrame: Frame of the overlay image
- returns: Self, allowing method chaining
*/
public func layerWithOverlayImage(overlayImage: UIImage, overlayFrame: CGRect) -> Toucan {
self.image = Toucan.Layer.overlayImage(self.image, overlayImage:overlayImage, overlayFrame:overlayFrame)
return self
}
/**
Container struct for all things Layer related
*/
public struct Layer {
/**
Overlay the given image into a new layout ontop of the image.
- parameter image: Image to be on the bottom layer
- parameter overlayImage: Image to be on the top layer, i.e. drawn on top of image
- parameter overlayFrame: Frame of the overlay image
- returns: Masked image
*/
public static func overlayImage(image: UIImage, overlayImage: UIImage, overlayFrame: CGRect) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
image.drawInRect(rect)
overlayImage.drawInRect(overlayFrame);
}
}
}
/**
Container struct for internally used utility functions.
*/
internal struct Util {
/**
Get the CGImage of the image with the orientation fixed up based on EXF data.
This helps to normalise input images to always be the correct orientation when performing
other core graphics tasks on the image.
- parameter image: Image to create CGImageRef for
- returns: CGImageRef with rotated/transformed image context
*/
static func CGImageWithCorrectOrientation(image : UIImage) -> CGImageRef {
if (image.imageOrientation == UIImageOrientation.Up) {
return image.CGImage!
}
var transform : CGAffineTransform = CGAffineTransformIdentity;
switch (image.imageOrientation) {
case UIImageOrientation.Right, UIImageOrientation.RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, image.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(-1.0 * M_PI_2))
break
case UIImageOrientation.Left, UIImageOrientation.LeftMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
break
case UIImageOrientation.Down, UIImageOrientation.DownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
break
default:
break
}
switch (image.imageOrientation) {
case UIImageOrientation.RightMirrored, UIImageOrientation.LeftMirrored:
transform = CGAffineTransformTranslate(transform, image.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break
case UIImageOrientation.DownMirrored, UIImageOrientation.UpMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break
default:
break
}
let context : CGContextRef = CGBitmapContextCreate(nil, CGImageGetWidth(image.CGImage), CGImageGetWidth(image.CGImage),
CGImageGetBitsPerComponent(image.CGImage),
CGImageGetBytesPerRow(image.CGImage),
CGImageGetColorSpace(image.CGImage),
CGImageGetBitmapInfo(image.CGImage).rawValue)!;
CGContextConcatCTM(context, transform);
switch (image.imageOrientation) {
case UIImageOrientation.Left, UIImageOrientation.LeftMirrored,
UIImageOrientation.Right, UIImageOrientation.RightMirrored:
CGContextDrawImage(context, CGRectMake(0, 0, image.size.height, image.size.width), image.CGImage);
break;
default:
CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
break;
}
let cgImage = CGBitmapContextCreateImage(context);
return cgImage!;
}
/**
Draw the image within the given bounds (i.e. resizes)
- parameter image: Image to draw within the given bounds
- parameter bounds: Bounds to draw the image within
- returns: Resized image within bounds
*/
static func drawImageInBounds(image: UIImage, bounds : CGRect) -> UIImage {
return drawImageWithClosure(size: bounds.size) { (size: CGSize, context: CGContext) -> () in
image.drawInRect(bounds)
};
}
/**
Crap the image within the given rect (i.e. resizes and crops)
- parameter image: Image to clip within the given rect bounds
- parameter rect: Bounds to draw the image within
- returns: Resized and cropped image
*/
static func croppedImageWithRect(image: UIImage, rect: CGRect) -> UIImage {
return drawImageWithClosure(size: rect.size) { (size: CGSize, context: CGContext) -> () in
let drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, image.size.width, image.size.height)
CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height))
image.drawInRect(drawRect)
};
}
/**
Closure wrapper around image context - setting up, ending and grabbing the image from the context.
- parameter size: Size of the graphics context to create
- parameter closure: Closure of magic to run in a new context
- returns: Image pulled from the end of the closure
*/
static func drawImageWithClosure(size size: CGSize!, closure: (size: CGSize, context: CGContext) -> ()) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
closure(size: size, context: UIGraphicsGetCurrentContext())
let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
} | mit | 87f87326ff1c591f037a1d0f74f56cba | 43.804348 | 166 | 0.610033 | 5.486791 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Tracks+ShareExtension.swift | 1 | 1469 | import Foundation
/// This extension implements helper tracking methods, meant for Share Extension Usage.
///
extension Tracks {
// MARK: - Public Methods
public func trackExtensionLaunched(_ wpcomAvailable: Bool) {
let properties = ["is_configured_dotcom": wpcomAvailable]
trackExtensionEvent(.Launched, properties: properties as [String: AnyObject]?)
}
public func trackExtensionPosted(_ status: String) {
let properties = ["post_status": status]
trackExtensionEvent(.Posted, properties: properties as [String: AnyObject]?)
}
public func trackExtensionError(_ error: NSError) {
let properties = ["error_code": String(error.code), "error_domain": error.domain, "error_description": error.description]
trackExtensionEvent(.Error, properties: properties as [String: AnyObject]?)
}
public func trackExtensionCancelled() {
trackExtensionEvent(.Canceled)
}
// MARK: - Private Helpers
fileprivate func trackExtensionEvent(_ event: ExtensionEvents, properties: [String: AnyObject]? = nil) {
track(event.rawValue, properties: properties)
}
// MARK: - Private Enums
fileprivate enum ExtensionEvents: String {
case Launched = "wpios_share_extension_launched"
case Posted = "wpios_share_extension_posted"
case Canceled = "wpios_share_extension_canceled"
case Error = "wpios_share_extension_error"
}
}
| gpl-2.0 | de8667a8c46af4c6d4ae9f871c9a9215 | 34.829268 | 129 | 0.680735 | 4.848185 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Amplify/Amplify_Shapes.swift | 1 | 120074 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension Amplify {
// MARK: Enums
public enum DomainStatus: String, CustomStringConvertible, Codable {
case available = "AVAILABLE"
case creating = "CREATING"
case failed = "FAILED"
case inProgress = "IN_PROGRESS"
case pendingDeployment = "PENDING_DEPLOYMENT"
case pendingVerification = "PENDING_VERIFICATION"
case requestingCertificate = "REQUESTING_CERTIFICATE"
case updating = "UPDATING"
public var description: String { return self.rawValue }
}
public enum JobStatus: String, CustomStringConvertible, Codable {
case cancelled = "CANCELLED"
case cancelling = "CANCELLING"
case failed = "FAILED"
case pending = "PENDING"
case provisioning = "PROVISIONING"
case running = "RUNNING"
case succeed = "SUCCEED"
public var description: String { return self.rawValue }
}
public enum JobType: String, CustomStringConvertible, Codable {
case manual = "MANUAL"
case release = "RELEASE"
case retry = "RETRY"
case webHook = "WEB_HOOK"
public var description: String { return self.rawValue }
}
public enum Platform: String, CustomStringConvertible, Codable {
case web = "WEB"
public var description: String { return self.rawValue }
}
public enum Stage: String, CustomStringConvertible, Codable {
case beta = "BETA"
case development = "DEVELOPMENT"
case experimental = "EXPERIMENTAL"
case production = "PRODUCTION"
case pullRequest = "PULL_REQUEST"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct App: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the Amplify app.
public let appArn: String
/// The unique ID of the Amplify app.
public let appId: String
/// Describes the automated branch creation configuration for the Amplify app.
public let autoBranchCreationConfig: AutoBranchCreationConfig?
/// Describes the automated branch creation glob patterns for the Amplify app.
public let autoBranchCreationPatterns: [String]?
/// The basic authorization credentials for branches for the Amplify app.
public let basicAuthCredentials: String?
/// Describes the content of the build specification (build spec) for the Amplify app.
public let buildSpec: String?
/// Creates a date and time for the Amplify app.
public let createTime: Date
/// Describes the custom redirect and rewrite rules for the Amplify app.
public let customRules: [CustomRule]?
/// The default domain for the Amplify app.
public let defaultDomain: String
/// The description for the Amplify app.
public let description: String
/// Enables automated branch creation for the Amplify app.
public let enableAutoBranchCreation: Bool?
/// Enables basic authorization for the Amplify app's branches.
public let enableBasicAuth: Bool
/// Enables the auto-building of branches for the Amplify app.
public let enableBranchAutoBuild: Bool
/// Automatically disconnect a branch in the Amplify Console when you delete a branch from your Git repository.
public let enableBranchAutoDeletion: Bool?
/// The environment variables for the Amplify app.
public let environmentVariables: [String: String]
/// The AWS Identity and Access Management (IAM) service role for the Amazon Resource Name (ARN) of the Amplify app.
public let iamServiceRoleArn: String?
/// The name for the Amplify app.
public let name: String
/// The platform for the Amplify app.
public let platform: Platform
/// Describes the information about a production branch of the Amplify app.
public let productionBranch: ProductionBranch?
/// The repository for the Amplify app.
public let repository: String
/// The tag for the Amplify app.
public let tags: [String: String]?
/// Updates the date and time for the Amplify app.
public let updateTime: Date
public init(appArn: String, appId: String, autoBranchCreationConfig: AutoBranchCreationConfig? = nil, autoBranchCreationPatterns: [String]? = nil, basicAuthCredentials: String? = nil, buildSpec: String? = nil, createTime: Date, customRules: [CustomRule]? = nil, defaultDomain: String, description: String, enableAutoBranchCreation: Bool? = nil, enableBasicAuth: Bool, enableBranchAutoBuild: Bool, enableBranchAutoDeletion: Bool? = nil, environmentVariables: [String: String], iamServiceRoleArn: String? = nil, name: String, platform: Platform, productionBranch: ProductionBranch? = nil, repository: String, tags: [String: String]? = nil, updateTime: Date) {
self.appArn = appArn
self.appId = appId
self.autoBranchCreationConfig = autoBranchCreationConfig
self.autoBranchCreationPatterns = autoBranchCreationPatterns
self.basicAuthCredentials = basicAuthCredentials
self.buildSpec = buildSpec
self.createTime = createTime
self.customRules = customRules
self.defaultDomain = defaultDomain
self.description = description
self.enableAutoBranchCreation = enableAutoBranchCreation
self.enableBasicAuth = enableBasicAuth
self.enableBranchAutoBuild = enableBranchAutoBuild
self.enableBranchAutoDeletion = enableBranchAutoDeletion
self.environmentVariables = environmentVariables
self.iamServiceRoleArn = iamServiceRoleArn
self.name = name
self.platform = platform
self.productionBranch = productionBranch
self.repository = repository
self.tags = tags
self.updateTime = updateTime
}
private enum CodingKeys: String, CodingKey {
case appArn
case appId
case autoBranchCreationConfig
case autoBranchCreationPatterns
case basicAuthCredentials
case buildSpec
case createTime
case customRules
case defaultDomain
case description
case enableAutoBranchCreation
case enableBasicAuth
case enableBranchAutoBuild
case enableBranchAutoDeletion
case environmentVariables
case iamServiceRoleArn
case name
case platform
case productionBranch
case repository
case tags
case updateTime
}
}
public struct Artifact: AWSDecodableShape {
/// The file name for the artifact.
public let artifactFileName: String
/// The unique ID for the artifact.
public let artifactId: String
public init(artifactFileName: String, artifactId: String) {
self.artifactFileName = artifactFileName
self.artifactId = artifactId
}
private enum CodingKeys: String, CodingKey {
case artifactFileName
case artifactId
}
}
public struct AutoBranchCreationConfig: AWSEncodableShape & AWSDecodableShape {
/// The basic authorization credentials for the autocreated branch.
public let basicAuthCredentials: String?
/// The build specification (build spec) for the autocreated branch.
public let buildSpec: String?
/// Enables auto building for the autocreated branch.
public let enableAutoBuild: Bool?
/// Enables basic authorization for the autocreated branch.
public let enableBasicAuth: Bool?
/// Performance mode optimizes for faster hosting performance by keeping content cached at the edge for a longer interval. Enabling performance mode will mean that hosting configuration or code changes can take up to 10 minutes to roll out.
public let enablePerformanceMode: Bool?
/// Enables pull request preview for the autocreated branch.
public let enablePullRequestPreview: Bool?
/// The environment variables for the autocreated branch.
public let environmentVariables: [String: String]?
/// The framework for the autocreated branch.
public let framework: String?
/// The Amplify environment name for the pull request.
public let pullRequestEnvironmentName: String?
/// Describes the current stage for the autocreated branch.
public let stage: Stage?
public init(basicAuthCredentials: String? = nil, buildSpec: String? = nil, enableAutoBuild: Bool? = nil, enableBasicAuth: Bool? = nil, enablePerformanceMode: Bool? = nil, enablePullRequestPreview: Bool? = nil, environmentVariables: [String: String]? = nil, framework: String? = nil, pullRequestEnvironmentName: String? = nil, stage: Stage? = nil) {
self.basicAuthCredentials = basicAuthCredentials
self.buildSpec = buildSpec
self.enableAutoBuild = enableAutoBuild
self.enableBasicAuth = enableBasicAuth
self.enablePerformanceMode = enablePerformanceMode
self.enablePullRequestPreview = enablePullRequestPreview
self.environmentVariables = environmentVariables
self.framework = framework
self.pullRequestEnvironmentName = pullRequestEnvironmentName
self.stage = stage
}
public func validate(name: String) throws {
try self.validate(self.basicAuthCredentials, name: "basicAuthCredentials", parent: name, max: 2000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, max: 25000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, min: 1)
try self.environmentVariables?.forEach {
try validate($0.key, name: "environmentVariables.key", parent: name, max: 255)
try validate($0.value, name: "environmentVariables[\"\($0.key)\"]", parent: name, max: 1000)
}
try self.validate(self.framework, name: "framework", parent: name, max: 255)
try self.validate(self.pullRequestEnvironmentName, name: "pullRequestEnvironmentName", parent: name, max: 20)
}
private enum CodingKeys: String, CodingKey {
case basicAuthCredentials
case buildSpec
case enableAutoBuild
case enableBasicAuth
case enablePerformanceMode
case enablePullRequestPreview
case environmentVariables
case framework
case pullRequestEnvironmentName
case stage
}
}
public struct BackendEnvironment: AWSDecodableShape {
/// The Amazon Resource Name (ARN) for a backend environment that is part of an Amplify app.
public let backendEnvironmentArn: String
/// The creation date and time for a backend environment that is part of an Amplify app.
public let createTime: Date
/// The name of deployment artifacts.
public let deploymentArtifacts: String?
/// The name for a backend environment that is part of an Amplify app.
public let environmentName: String
/// The AWS CloudFormation stack name of a backend environment.
public let stackName: String?
/// The last updated date and time for a backend environment that is part of an Amplify app.
public let updateTime: Date
public init(backendEnvironmentArn: String, createTime: Date, deploymentArtifacts: String? = nil, environmentName: String, stackName: String? = nil, updateTime: Date) {
self.backendEnvironmentArn = backendEnvironmentArn
self.createTime = createTime
self.deploymentArtifacts = deploymentArtifacts
self.environmentName = environmentName
self.stackName = stackName
self.updateTime = updateTime
}
private enum CodingKeys: String, CodingKey {
case backendEnvironmentArn
case createTime
case deploymentArtifacts
case environmentName
case stackName
case updateTime
}
}
public struct Branch: AWSDecodableShape {
/// The ID of the active job for a branch of an Amplify app.
public let activeJobId: String
/// A list of custom resources that are linked to this branch.
public let associatedResources: [String]?
/// The Amazon Resource Name (ARN) for a backend environment that is part of an Amplify app.
public let backendEnvironmentArn: String?
/// The basic authorization credentials for a branch of an Amplify app.
public let basicAuthCredentials: String?
/// The Amazon Resource Name (ARN) for a branch that is part of an Amplify app.
public let branchArn: String
/// The name for the branch that is part of an Amplify app.
public let branchName: String
/// The build specification (build spec) content for the branch of an Amplify app.
public let buildSpec: String?
/// The creation date and time for a branch that is part of an Amplify app.
public let createTime: Date
/// The custom domains for a branch of an Amplify app.
public let customDomains: [String]
/// The description for the branch that is part of an Amplify app.
public let description: String
/// The destination branch if the branch is a pull request branch.
public let destinationBranch: String?
/// The display name for the branch. This is used as the default domain prefix.
public let displayName: String
/// Enables auto-building on push for a branch of an Amplify app.
public let enableAutoBuild: Bool
/// Enables basic authorization for a branch of an Amplify app.
public let enableBasicAuth: Bool
/// Enables notifications for a branch that is part of an Amplify app.
public let enableNotification: Bool
/// Performance mode optimizes for faster hosting performance by keeping content cached at the edge for a longer interval. Enabling performance mode will mean that hosting configuration or code changes can take up to 10 minutes to roll out.
public let enablePerformanceMode: Bool?
/// Enables pull request preview for the branch.
public let enablePullRequestPreview: Bool
/// The environment variables specific to a branch of an Amplify app.
public let environmentVariables: [String: String]
/// The framework for a branch of an Amplify app.
public let framework: String
/// The Amplify environment name for the pull request.
public let pullRequestEnvironmentName: String?
/// The source branch if the branch is a pull request branch.
public let sourceBranch: String?
/// The current stage for the branch that is part of an Amplify app.
public let stage: Stage
/// The tag for the branch of an Amplify app.
public let tags: [String: String]?
/// The thumbnail URL for the branch of an Amplify app.
public let thumbnailUrl: String?
/// The total number of jobs that are part of an Amplify app.
public let totalNumberOfJobs: String
/// The content Time to Live (TTL) for the website in seconds.
public let ttl: String
/// The last updated date and time for a branch that is part of an Amplify app.
public let updateTime: Date
public init(activeJobId: String, associatedResources: [String]? = nil, backendEnvironmentArn: String? = nil, basicAuthCredentials: String? = nil, branchArn: String, branchName: String, buildSpec: String? = nil, createTime: Date, customDomains: [String], description: String, destinationBranch: String? = nil, displayName: String, enableAutoBuild: Bool, enableBasicAuth: Bool, enableNotification: Bool, enablePerformanceMode: Bool? = nil, enablePullRequestPreview: Bool, environmentVariables: [String: String], framework: String, pullRequestEnvironmentName: String? = nil, sourceBranch: String? = nil, stage: Stage, tags: [String: String]? = nil, thumbnailUrl: String? = nil, totalNumberOfJobs: String, ttl: String, updateTime: Date) {
self.activeJobId = activeJobId
self.associatedResources = associatedResources
self.backendEnvironmentArn = backendEnvironmentArn
self.basicAuthCredentials = basicAuthCredentials
self.branchArn = branchArn
self.branchName = branchName
self.buildSpec = buildSpec
self.createTime = createTime
self.customDomains = customDomains
self.description = description
self.destinationBranch = destinationBranch
self.displayName = displayName
self.enableAutoBuild = enableAutoBuild
self.enableBasicAuth = enableBasicAuth
self.enableNotification = enableNotification
self.enablePerformanceMode = enablePerformanceMode
self.enablePullRequestPreview = enablePullRequestPreview
self.environmentVariables = environmentVariables
self.framework = framework
self.pullRequestEnvironmentName = pullRequestEnvironmentName
self.sourceBranch = sourceBranch
self.stage = stage
self.tags = tags
self.thumbnailUrl = thumbnailUrl
self.totalNumberOfJobs = totalNumberOfJobs
self.ttl = ttl
self.updateTime = updateTime
}
private enum CodingKeys: String, CodingKey {
case activeJobId
case associatedResources
case backendEnvironmentArn
case basicAuthCredentials
case branchArn
case branchName
case buildSpec
case createTime
case customDomains
case description
case destinationBranch
case displayName
case enableAutoBuild
case enableBasicAuth
case enableNotification
case enablePerformanceMode
case enablePullRequestPreview
case environmentVariables
case framework
case pullRequestEnvironmentName
case sourceBranch
case stage
case tags
case thumbnailUrl
case totalNumberOfJobs
case ttl
case updateTime
}
}
public struct CreateAppRequest: AWSEncodableShape {
/// The personal access token for a third-party source control system for an Amplify app. The personal access token is used to create a webhook and a read-only deploy key. The token is not stored.
public let accessToken: String?
/// The automated branch creation configuration for the Amplify app.
public let autoBranchCreationConfig: AutoBranchCreationConfig?
/// The automated branch creation glob patterns for the Amplify app.
public let autoBranchCreationPatterns: [String]?
/// The credentials for basic authorization for an Amplify app.
public let basicAuthCredentials: String?
/// The build specification (build spec) for an Amplify app.
public let buildSpec: String?
/// The custom rewrite and redirect rules for an Amplify app.
public let customRules: [CustomRule]?
/// The description for an Amplify app.
public let description: String?
/// Enables automated branch creation for the Amplify app.
public let enableAutoBranchCreation: Bool?
/// Enables basic authorization for an Amplify app. This will apply to all branches that are part of this app.
public let enableBasicAuth: Bool?
/// Enables the auto building of branches for an Amplify app.
public let enableBranchAutoBuild: Bool?
/// Automatically disconnects a branch in the Amplify Console when you delete a branch from your Git repository.
public let enableBranchAutoDeletion: Bool?
/// The environment variables map for an Amplify app.
public let environmentVariables: [String: String]?
/// The AWS Identity and Access Management (IAM) service role for an Amplify app.
public let iamServiceRoleArn: String?
/// The name for the Amplify app.
public let name: String
/// The OAuth token for a third-party source control system for an Amplify app. The OAuth token is used to create a webhook and a read-only deploy key. The OAuth token is not stored.
public let oauthToken: String?
/// The platform or framework for an Amplify app.
public let platform: Platform?
/// The repository for an Amplify app.
public let repository: String?
/// The tag for an Amplify app.
public let tags: [String: String]?
public init(accessToken: String? = nil, autoBranchCreationConfig: AutoBranchCreationConfig? = nil, autoBranchCreationPatterns: [String]? = nil, basicAuthCredentials: String? = nil, buildSpec: String? = nil, customRules: [CustomRule]? = nil, description: String? = nil, enableAutoBranchCreation: Bool? = nil, enableBasicAuth: Bool? = nil, enableBranchAutoBuild: Bool? = nil, enableBranchAutoDeletion: Bool? = nil, environmentVariables: [String: String]? = nil, iamServiceRoleArn: String? = nil, name: String, oauthToken: String? = nil, platform: Platform? = nil, repository: String? = nil, tags: [String: String]? = nil) {
self.accessToken = accessToken
self.autoBranchCreationConfig = autoBranchCreationConfig
self.autoBranchCreationPatterns = autoBranchCreationPatterns
self.basicAuthCredentials = basicAuthCredentials
self.buildSpec = buildSpec
self.customRules = customRules
self.description = description
self.enableAutoBranchCreation = enableAutoBranchCreation
self.enableBasicAuth = enableBasicAuth
self.enableBranchAutoBuild = enableBranchAutoBuild
self.enableBranchAutoDeletion = enableBranchAutoDeletion
self.environmentVariables = environmentVariables
self.iamServiceRoleArn = iamServiceRoleArn
self.name = name
self.oauthToken = oauthToken
self.platform = platform
self.repository = repository
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.accessToken, name: "accessToken", parent: name, max: 255)
try self.validate(self.accessToken, name: "accessToken", parent: name, min: 1)
try self.autoBranchCreationConfig?.validate(name: "\(name).autoBranchCreationConfig")
try self.autoBranchCreationPatterns?.forEach {
try validate($0, name: "autoBranchCreationPatterns[]", parent: name, max: 2048)
try validate($0, name: "autoBranchCreationPatterns[]", parent: name, min: 1)
}
try self.validate(self.basicAuthCredentials, name: "basicAuthCredentials", parent: name, max: 2000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, max: 25000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, min: 1)
try self.customRules?.forEach {
try $0.validate(name: "\(name).customRules[]")
}
try self.validate(self.description, name: "description", parent: name, max: 1000)
try self.environmentVariables?.forEach {
try validate($0.key, name: "environmentVariables.key", parent: name, max: 255)
try validate($0.value, name: "environmentVariables[\"\($0.key)\"]", parent: name, max: 1000)
}
try self.validate(self.iamServiceRoleArn, name: "iamServiceRoleArn", parent: name, max: 1000)
try self.validate(self.iamServiceRoleArn, name: "iamServiceRoleArn", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, max: 255)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.oauthToken, name: "oauthToken", parent: name, max: 1000)
try self.validate(self.repository, name: "repository", parent: name, max: 1000)
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
}
}
private enum CodingKeys: String, CodingKey {
case accessToken
case autoBranchCreationConfig
case autoBranchCreationPatterns
case basicAuthCredentials
case buildSpec
case customRules
case description
case enableAutoBranchCreation
case enableBasicAuth
case enableBranchAutoBuild
case enableBranchAutoDeletion
case environmentVariables
case iamServiceRoleArn
case name
case oauthToken
case platform
case repository
case tags
}
}
public struct CreateAppResult: AWSDecodableShape {
public let app: App
public init(app: App) {
self.app = app
}
private enum CodingKeys: String, CodingKey {
case app
}
}
public struct CreateBackendEnvironmentRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name of deployment artifacts.
public let deploymentArtifacts: String?
/// The name for the backend environment.
public let environmentName: String
/// The AWS CloudFormation stack name of a backend environment.
public let stackName: String?
public init(appId: String, deploymentArtifacts: String? = nil, environmentName: String, stackName: String? = nil) {
self.appId = appId
self.deploymentArtifacts = deploymentArtifacts
self.environmentName = environmentName
self.stackName = stackName
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.deploymentArtifacts, name: "deploymentArtifacts", parent: name, max: 1000)
try self.validate(self.deploymentArtifacts, name: "deploymentArtifacts", parent: name, min: 1)
try self.validate(self.environmentName, name: "environmentName", parent: name, max: 255)
try self.validate(self.environmentName, name: "environmentName", parent: name, min: 1)
try self.validate(self.stackName, name: "stackName", parent: name, max: 255)
try self.validate(self.stackName, name: "stackName", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case deploymentArtifacts
case environmentName
case stackName
}
}
public struct CreateBackendEnvironmentResult: AWSDecodableShape {
/// Describes the backend environment for an Amplify app.
public let backendEnvironment: BackendEnvironment
public init(backendEnvironment: BackendEnvironment) {
self.backendEnvironment = backendEnvironment
}
private enum CodingKeys: String, CodingKey {
case backendEnvironment
}
}
public struct CreateBranchRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The Amazon Resource Name (ARN) for a backend environment that is part of an Amplify app.
public let backendEnvironmentArn: String?
/// The basic authorization credentials for the branch.
public let basicAuthCredentials: String?
/// The name for the branch.
public let branchName: String
/// The build specification (build spec) for the branch.
public let buildSpec: String?
/// The description for the branch.
public let description: String?
/// The display name for a branch. This is used as the default domain prefix.
public let displayName: String?
/// Enables auto building for the branch.
public let enableAutoBuild: Bool?
/// Enables basic authorization for the branch.
public let enableBasicAuth: Bool?
/// Enables notifications for the branch.
public let enableNotification: Bool?
/// Performance mode optimizes for faster hosting performance by keeping content cached at the edge for a longer interval. Enabling performance mode will mean that hosting configuration or code changes can take up to 10 minutes to roll out.
public let enablePerformanceMode: Bool?
/// Enables pull request preview for this branch.
public let enablePullRequestPreview: Bool?
/// The environment variables for the branch.
public let environmentVariables: [String: String]?
/// The framework for the branch.
public let framework: String?
/// The Amplify environment name for the pull request.
public let pullRequestEnvironmentName: String?
/// Describes the current stage for the branch.
public let stage: Stage?
/// The tag for the branch.
public let tags: [String: String]?
/// The content Time To Live (TTL) for the website in seconds.
public let ttl: String?
public init(appId: String, backendEnvironmentArn: String? = nil, basicAuthCredentials: String? = nil, branchName: String, buildSpec: String? = nil, description: String? = nil, displayName: String? = nil, enableAutoBuild: Bool? = nil, enableBasicAuth: Bool? = nil, enableNotification: Bool? = nil, enablePerformanceMode: Bool? = nil, enablePullRequestPreview: Bool? = nil, environmentVariables: [String: String]? = nil, framework: String? = nil, pullRequestEnvironmentName: String? = nil, stage: Stage? = nil, tags: [String: String]? = nil, ttl: String? = nil) {
self.appId = appId
self.backendEnvironmentArn = backendEnvironmentArn
self.basicAuthCredentials = basicAuthCredentials
self.branchName = branchName
self.buildSpec = buildSpec
self.description = description
self.displayName = displayName
self.enableAutoBuild = enableAutoBuild
self.enableBasicAuth = enableBasicAuth
self.enableNotification = enableNotification
self.enablePerformanceMode = enablePerformanceMode
self.enablePullRequestPreview = enablePullRequestPreview
self.environmentVariables = environmentVariables
self.framework = framework
self.pullRequestEnvironmentName = pullRequestEnvironmentName
self.stage = stage
self.tags = tags
self.ttl = ttl
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.backendEnvironmentArn, name: "backendEnvironmentArn", parent: name, max: 1000)
try self.validate(self.backendEnvironmentArn, name: "backendEnvironmentArn", parent: name, min: 1)
try self.validate(self.basicAuthCredentials, name: "basicAuthCredentials", parent: name, max: 2000)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, max: 25000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, min: 1)
try self.validate(self.description, name: "description", parent: name, max: 1000)
try self.validate(self.displayName, name: "displayName", parent: name, max: 255)
try self.environmentVariables?.forEach {
try validate($0.key, name: "environmentVariables.key", parent: name, max: 255)
try validate($0.value, name: "environmentVariables[\"\($0.key)\"]", parent: name, max: 1000)
}
try self.validate(self.framework, name: "framework", parent: name, max: 255)
try self.validate(self.pullRequestEnvironmentName, name: "pullRequestEnvironmentName", parent: name, max: 20)
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
}
}
private enum CodingKeys: String, CodingKey {
case backendEnvironmentArn
case basicAuthCredentials
case branchName
case buildSpec
case description
case displayName
case enableAutoBuild
case enableBasicAuth
case enableNotification
case enablePerformanceMode
case enablePullRequestPreview
case environmentVariables
case framework
case pullRequestEnvironmentName
case stage
case tags
case ttl
}
}
public struct CreateBranchResult: AWSDecodableShape {
/// Describes the branch for an Amplify app, which maps to a third-party repository branch.
public let branch: Branch
public init(branch: Branch) {
self.branch = branch
}
private enum CodingKeys: String, CodingKey {
case branch
}
}
public struct CreateDeploymentRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for the branch, for the job.
public let branchName: String
/// An optional file map that contains the file name as the key and the file content md5 hash as the value. If this argument is provided, the service will generate a unique upload URL per file. Otherwise, the service will only generate a single upload URL for the zipped files.
public let fileMap: [String: String]?
public init(appId: String, branchName: String, fileMap: [String: String]? = nil) {
self.appId = appId
self.branchName = branchName
self.fileMap = fileMap
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.fileMap?.forEach {
try validate($0.key, name: "fileMap.key", parent: name, max: 255)
try validate($0.value, name: "fileMap[\"\($0.key)\"]", parent: name, max: 32)
}
}
private enum CodingKeys: String, CodingKey {
case fileMap
}
}
public struct CreateDeploymentResult: AWSDecodableShape {
/// When the fileMap argument is provided in the request, fileUploadUrls will contain a map of file names to upload URLs.
public let fileUploadUrls: [String: String]
/// The job ID for this deployment. will supply to start deployment api.
public let jobId: String?
/// When the fileMap argument is not provided in the request, this zipUploadUrl is returned.
public let zipUploadUrl: String
public init(fileUploadUrls: [String: String], jobId: String? = nil, zipUploadUrl: String) {
self.fileUploadUrls = fileUploadUrls
self.jobId = jobId
self.zipUploadUrl = zipUploadUrl
}
private enum CodingKeys: String, CodingKey {
case fileUploadUrls
case jobId
case zipUploadUrl
}
}
public struct CreateDomainAssociationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// Sets the branch patterns for automatic subdomain creation.
public let autoSubDomainCreationPatterns: [String]?
/// The required AWS Identity and Access Management (IAM) service role for the Amazon Resource Name (ARN) for automatically creating subdomains.
public let autoSubDomainIAMRole: String?
/// The domain name for the domain association.
public let domainName: String
/// Enables the automated creation of subdomains for branches.
public let enableAutoSubDomain: Bool?
/// The setting for the subdomain.
public let subDomainSettings: [SubDomainSetting]
public init(appId: String, autoSubDomainCreationPatterns: [String]? = nil, autoSubDomainIAMRole: String? = nil, domainName: String, enableAutoSubDomain: Bool? = nil, subDomainSettings: [SubDomainSetting]) {
self.appId = appId
self.autoSubDomainCreationPatterns = autoSubDomainCreationPatterns
self.autoSubDomainIAMRole = autoSubDomainIAMRole
self.domainName = domainName
self.enableAutoSubDomain = enableAutoSubDomain
self.subDomainSettings = subDomainSettings
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.autoSubDomainCreationPatterns?.forEach {
try validate($0, name: "autoSubDomainCreationPatterns[]", parent: name, max: 2048)
try validate($0, name: "autoSubDomainCreationPatterns[]", parent: name, min: 1)
}
try self.validate(self.autoSubDomainIAMRole, name: "autoSubDomainIAMRole", parent: name, max: 1000)
try self.validate(self.autoSubDomainIAMRole, name: "autoSubDomainIAMRole", parent: name, pattern: "^$|^arn:aws:iam::\\d{12}:role.+")
try self.validate(self.domainName, name: "domainName", parent: name, max: 255)
try self.subDomainSettings.forEach {
try $0.validate(name: "\(name).subDomainSettings[]")
}
try self.validate(self.subDomainSettings, name: "subDomainSettings", parent: name, max: 255)
}
private enum CodingKeys: String, CodingKey {
case autoSubDomainCreationPatterns
case autoSubDomainIAMRole
case domainName
case enableAutoSubDomain
case subDomainSettings
}
}
public struct CreateDomainAssociationResult: AWSDecodableShape {
/// Describes the structure of a domain association, which associates a custom domain with an Amplify app.
public let domainAssociation: DomainAssociation
public init(domainAssociation: DomainAssociation) {
self.domainAssociation = domainAssociation
}
private enum CodingKeys: String, CodingKey {
case domainAssociation
}
}
public struct CreateWebhookRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for a branch that is part of an Amplify app.
public let branchName: String
/// The description for a webhook.
public let description: String?
public init(appId: String, branchName: String, description: String? = nil) {
self.appId = appId
self.branchName = branchName
self.description = description
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.description, name: "description", parent: name, max: 1000)
}
private enum CodingKeys: String, CodingKey {
case branchName
case description
}
}
public struct CreateWebhookResult: AWSDecodableShape {
/// Describes a webhook that connects repository events to an Amplify app.
public let webhook: Webhook
public init(webhook: Webhook) {
self.webhook = webhook
}
private enum CodingKeys: String, CodingKey {
case webhook
}
}
public struct CustomRule: AWSEncodableShape & AWSDecodableShape {
/// The condition for a URL rewrite or redirect rule, such as a country code.
public let condition: String?
/// The source pattern for a URL rewrite or redirect rule.
public let source: String
/// The status code for a URL rewrite or redirect rule. 200 Represents a 200 rewrite rule. 301 Represents a 301 (moved pemanently) redirect rule. This and all future requests should be directed to the target URL. 302 Represents a 302 temporary redirect rule. 404 Represents a 404 redirect rule. 404-200 Represents a 404 rewrite rule.
public let status: String?
/// The target pattern for a URL rewrite or redirect rule.
public let target: String
public init(condition: String? = nil, source: String, status: String? = nil, target: String) {
self.condition = condition
self.source = source
self.status = status
self.target = target
}
public func validate(name: String) throws {
try self.validate(self.condition, name: "condition", parent: name, max: 2048)
try self.validate(self.condition, name: "condition", parent: name, min: 1)
try self.validate(self.source, name: "source", parent: name, max: 2048)
try self.validate(self.source, name: "source", parent: name, min: 1)
try self.validate(self.status, name: "status", parent: name, max: 7)
try self.validate(self.status, name: "status", parent: name, min: 3)
try self.validate(self.target, name: "target", parent: name, max: 2048)
try self.validate(self.target, name: "target", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case condition
case source
case status
case target
}
}
public struct DeleteAppRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The unique ID for an Amplify app.
public let appId: String
public init(appId: String) {
self.appId = appId
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteAppResult: AWSDecodableShape {
public let app: App
public init(app: App) {
self.app = app
}
private enum CodingKeys: String, CodingKey {
case app
}
}
public struct DeleteBackendEnvironmentRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "environmentName", location: .uri(locationName: "environmentName"))
]
/// The unique ID of an Amplify app.
public let appId: String
/// The name of a backend environment of an Amplify app.
public let environmentName: String
public init(appId: String, environmentName: String) {
self.appId = appId
self.environmentName = environmentName
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.environmentName, name: "environmentName", parent: name, max: 255)
try self.validate(self.environmentName, name: "environmentName", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteBackendEnvironmentResult: AWSDecodableShape {
/// Describes the backend environment for an Amplify app.
public let backendEnvironment: BackendEnvironment
public init(backendEnvironment: BackendEnvironment) {
self.backendEnvironment = backendEnvironment
}
private enum CodingKeys: String, CodingKey {
case backendEnvironment
}
}
public struct DeleteBranchRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for the branch.
public let branchName: String
public init(appId: String, branchName: String) {
self.appId = appId
self.branchName = branchName
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteBranchResult: AWSDecodableShape {
/// The branch for an Amplify app, which maps to a third-party repository branch.
public let branch: Branch
public init(branch: Branch) {
self.branch = branch
}
private enum CodingKeys: String, CodingKey {
case branch
}
}
public struct DeleteDomainAssociationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "domainName", location: .uri(locationName: "domainName"))
]
/// The unique id for an Amplify app.
public let appId: String
/// The name of the domain.
public let domainName: String
public init(appId: String, domainName: String) {
self.appId = appId
self.domainName = domainName
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.domainName, name: "domainName", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteDomainAssociationResult: AWSDecodableShape {
public let domainAssociation: DomainAssociation
public init(domainAssociation: DomainAssociation) {
self.domainAssociation = domainAssociation
}
private enum CodingKeys: String, CodingKey {
case domainAssociation
}
}
public struct DeleteJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName")),
AWSMemberEncoding(label: "jobId", location: .uri(locationName: "jobId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for the branch, for the job.
public let branchName: String
/// The unique ID for the job.
public let jobId: String
public init(appId: String, branchName: String, jobId: String) {
self.appId = appId
self.branchName = branchName
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteJobResult: AWSDecodableShape {
public let jobSummary: JobSummary
public init(jobSummary: JobSummary) {
self.jobSummary = jobSummary
}
private enum CodingKeys: String, CodingKey {
case jobSummary
}
}
public struct DeleteWebhookRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "webhookId", location: .uri(locationName: "webhookId"))
]
/// The unique ID for a webhook.
public let webhookId: String
public init(webhookId: String) {
self.webhookId = webhookId
}
public func validate(name: String) throws {
try self.validate(self.webhookId, name: "webhookId", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteWebhookResult: AWSDecodableShape {
/// Describes a webhook that connects repository events to an Amplify app.
public let webhook: Webhook
public init(webhook: Webhook) {
self.webhook = webhook
}
private enum CodingKeys: String, CodingKey {
case webhook
}
}
public struct DomainAssociation: AWSDecodableShape {
/// Sets branch patterns for automatic subdomain creation.
public let autoSubDomainCreationPatterns: [String]?
/// The required AWS Identity and Access Management (IAM) service role for the Amazon Resource Name (ARN) for automatically creating subdomains.
public let autoSubDomainIAMRole: String?
/// The DNS record for certificate verification.
public let certificateVerificationDNSRecord: String?
/// The Amazon Resource Name (ARN) for the domain association.
public let domainAssociationArn: String
/// The name of the domain.
public let domainName: String
/// The current status of the domain association.
public let domainStatus: DomainStatus
/// Enables the automated creation of subdomains for branches.
public let enableAutoSubDomain: Bool
/// The reason for the current status of the domain association.
public let statusReason: String
/// The subdomains for the domain association.
public let subDomains: [SubDomain]
public init(autoSubDomainCreationPatterns: [String]? = nil, autoSubDomainIAMRole: String? = nil, certificateVerificationDNSRecord: String? = nil, domainAssociationArn: String, domainName: String, domainStatus: DomainStatus, enableAutoSubDomain: Bool, statusReason: String, subDomains: [SubDomain]) {
self.autoSubDomainCreationPatterns = autoSubDomainCreationPatterns
self.autoSubDomainIAMRole = autoSubDomainIAMRole
self.certificateVerificationDNSRecord = certificateVerificationDNSRecord
self.domainAssociationArn = domainAssociationArn
self.domainName = domainName
self.domainStatus = domainStatus
self.enableAutoSubDomain = enableAutoSubDomain
self.statusReason = statusReason
self.subDomains = subDomains
}
private enum CodingKeys: String, CodingKey {
case autoSubDomainCreationPatterns
case autoSubDomainIAMRole
case certificateVerificationDNSRecord
case domainAssociationArn
case domainName
case domainStatus
case enableAutoSubDomain
case statusReason
case subDomains
}
}
public struct GenerateAccessLogsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name of the domain.
public let domainName: String
/// The time at which the logs should end. The time range specified is inclusive of the end time.
public let endTime: Date?
/// The time at which the logs should start. The time range specified is inclusive of the start time.
public let startTime: Date?
public init(appId: String, domainName: String, endTime: Date? = nil, startTime: Date? = nil) {
self.appId = appId
self.domainName = domainName
self.endTime = endTime
self.startTime = startTime
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.domainName, name: "domainName", parent: name, max: 255)
}
private enum CodingKeys: String, CodingKey {
case domainName
case endTime
case startTime
}
}
public struct GenerateAccessLogsResult: AWSDecodableShape {
/// The pre-signed URL for the requested access logs.
public let logUrl: String?
public init(logUrl: String? = nil) {
self.logUrl = logUrl
}
private enum CodingKeys: String, CodingKey {
case logUrl
}
}
public struct GetAppRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The unique ID for an Amplify app.
public let appId: String
public init(appId: String) {
self.appId = appId
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct GetAppResult: AWSDecodableShape {
public let app: App
public init(app: App) {
self.app = app
}
private enum CodingKeys: String, CodingKey {
case app
}
}
public struct GetArtifactUrlRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "artifactId", location: .uri(locationName: "artifactId"))
]
/// The unique ID for an artifact.
public let artifactId: String
public init(artifactId: String) {
self.artifactId = artifactId
}
public func validate(name: String) throws {
try self.validate(self.artifactId, name: "artifactId", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct GetArtifactUrlResult: AWSDecodableShape {
/// The unique ID for an artifact.
public let artifactId: String
/// The presigned URL for the artifact.
public let artifactUrl: String
public init(artifactId: String, artifactUrl: String) {
self.artifactId = artifactId
self.artifactUrl = artifactUrl
}
private enum CodingKeys: String, CodingKey {
case artifactId
case artifactUrl
}
}
public struct GetBackendEnvironmentRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "environmentName", location: .uri(locationName: "environmentName"))
]
/// The unique id for an Amplify app.
public let appId: String
/// The name for the backend environment.
public let environmentName: String
public init(appId: String, environmentName: String) {
self.appId = appId
self.environmentName = environmentName
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.environmentName, name: "environmentName", parent: name, max: 255)
try self.validate(self.environmentName, name: "environmentName", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct GetBackendEnvironmentResult: AWSDecodableShape {
/// Describes the backend environment for an Amplify app.
public let backendEnvironment: BackendEnvironment
public init(backendEnvironment: BackendEnvironment) {
self.backendEnvironment = backendEnvironment
}
private enum CodingKeys: String, CodingKey {
case backendEnvironment
}
}
public struct GetBranchRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for the branch.
public let branchName: String
public init(appId: String, branchName: String) {
self.appId = appId
self.branchName = branchName
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct GetBranchResult: AWSDecodableShape {
public let branch: Branch
public init(branch: Branch) {
self.branch = branch
}
private enum CodingKeys: String, CodingKey {
case branch
}
}
public struct GetDomainAssociationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "domainName", location: .uri(locationName: "domainName"))
]
/// The unique id for an Amplify app.
public let appId: String
/// The name of the domain.
public let domainName: String
public init(appId: String, domainName: String) {
self.appId = appId
self.domainName = domainName
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.domainName, name: "domainName", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct GetDomainAssociationResult: AWSDecodableShape {
/// Describes the structure of a domain association, which associates a custom domain with an Amplify app.
public let domainAssociation: DomainAssociation
public init(domainAssociation: DomainAssociation) {
self.domainAssociation = domainAssociation
}
private enum CodingKeys: String, CodingKey {
case domainAssociation
}
}
public struct GetJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName")),
AWSMemberEncoding(label: "jobId", location: .uri(locationName: "jobId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The branch name for the job.
public let branchName: String
/// The unique ID for the job.
public let jobId: String
public init(appId: String, branchName: String, jobId: String) {
self.appId = appId
self.branchName = branchName
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct GetJobResult: AWSDecodableShape {
public let job: Job
public init(job: Job) {
self.job = job
}
private enum CodingKeys: String, CodingKey {
case job
}
}
public struct GetWebhookRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "webhookId", location: .uri(locationName: "webhookId"))
]
/// The unique ID for a webhook.
public let webhookId: String
public init(webhookId: String) {
self.webhookId = webhookId
}
public func validate(name: String) throws {
try self.validate(self.webhookId, name: "webhookId", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct GetWebhookResult: AWSDecodableShape {
/// Describes the structure of a webhook.
public let webhook: Webhook
public init(webhook: Webhook) {
self.webhook = webhook
}
private enum CodingKeys: String, CodingKey {
case webhook
}
}
public struct Job: AWSDecodableShape {
/// The execution steps for an execution job, for an Amplify app.
public let steps: [Step]
/// Describes the summary for an execution job for an Amplify app.
public let summary: JobSummary
public init(steps: [Step], summary: JobSummary) {
self.steps = steps
self.summary = summary
}
private enum CodingKeys: String, CodingKey {
case steps
case summary
}
}
public struct JobSummary: AWSDecodableShape {
/// The commit ID from a third-party repository provider for the job.
public let commitId: String
/// The commit message from a third-party repository provider for the job.
public let commitMessage: String
/// The commit date and time for the job.
public let commitTime: Date
/// The end date and time for the job.
public let endTime: Date?
/// The Amazon Resource Name (ARN) for the job.
public let jobArn: String
/// The unique ID for the job.
public let jobId: String
/// The type for the job. If the value is RELEASE, the job was manually released from its source by using the StartJob API. If the value is RETRY, the job was manually retried using the StartJob API. If the value is WEB_HOOK, the job was automatically triggered by webhooks.
public let jobType: JobType
/// The start date and time for the job.
public let startTime: Date
/// The current status for the job.
public let status: JobStatus
public init(commitId: String, commitMessage: String, commitTime: Date, endTime: Date? = nil, jobArn: String, jobId: String, jobType: JobType, startTime: Date, status: JobStatus) {
self.commitId = commitId
self.commitMessage = commitMessage
self.commitTime = commitTime
self.endTime = endTime
self.jobArn = jobArn
self.jobId = jobId
self.jobType = jobType
self.startTime = startTime
self.status = status
}
private enum CodingKeys: String, CodingKey {
case commitId
case commitMessage
case commitTime
case endTime
case jobArn
case jobId
case jobType
case startTime
case status
}
}
public struct ListAppsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
/// The maximum number of records to list in a single response.
public let maxResults: Int?
/// A pagination token. If non-null, the pagination token is returned in a result. Pass its value in another request to retrieve more entries.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListAppsResult: AWSDecodableShape {
/// A list of Amplify apps.
public let apps: [App]
/// A pagination token. Set to null to start listing apps from start. If non-null, the pagination token is returned in a result. Pass its value in here to list more projects.
public let nextToken: String?
public init(apps: [App], nextToken: String? = nil) {
self.apps = apps
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case apps
case nextToken
}
}
public struct ListArtifactsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName")),
AWSMemberEncoding(label: "jobId", location: .uri(locationName: "jobId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name of a branch that is part of an Amplify app.
public let branchName: String
/// The unique ID for a job.
public let jobId: String
/// The maximum number of records to list in a single response.
public let maxResults: Int?
/// A pagination token. Set to null to start listing artifacts from start. If a non-null pagination token is returned in a result, pass its value in here to list more artifacts.
public let nextToken: String?
public init(appId: String, branchName: String, jobId: String, maxResults: Int? = nil, nextToken: String? = nil) {
self.appId = appId
self.branchName = branchName
self.jobId = jobId
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, max: 255)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListArtifactsResult: AWSDecodableShape {
/// A list of artifacts.
public let artifacts: [Artifact]
/// A pagination token. If a non-null pagination token is returned in a result, pass its value in another request to retrieve more entries.
public let nextToken: String?
public init(artifacts: [Artifact], nextToken: String? = nil) {
self.artifacts = artifacts
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case artifacts
case nextToken
}
}
public struct ListBackendEnvironmentsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "environmentName", location: .querystring(locationName: "environmentName")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name of the backend environment
public let environmentName: String?
/// The maximum number of records to list in a single response.
public let maxResults: Int?
/// A pagination token. Set to null to start listing backend environments from the start. If a non-null pagination token is returned in a result, pass its value in here to list more backend environments.
public let nextToken: String?
public init(appId: String, environmentName: String? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.appId = appId
self.environmentName = environmentName
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.environmentName, name: "environmentName", parent: name, max: 255)
try self.validate(self.environmentName, name: "environmentName", parent: name, min: 1)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListBackendEnvironmentsResult: AWSDecodableShape {
/// The list of backend environments for an Amplify app.
public let backendEnvironments: [BackendEnvironment]
/// A pagination token. If a non-null pagination token is returned in a result, pass its value in another request to retrieve more entries.
public let nextToken: String?
public init(backendEnvironments: [BackendEnvironment], nextToken: String? = nil) {
self.backendEnvironments = backendEnvironments
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case backendEnvironments
case nextToken
}
}
public struct ListBranchesRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The maximum number of records to list in a single response.
public let maxResults: Int?
/// A pagination token. Set to null to start listing branches from the start. If a non-null pagination token is returned in a result, pass its value in here to list more branches.
public let nextToken: String?
public init(appId: String, maxResults: Int? = nil, nextToken: String? = nil) {
self.appId = appId
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListBranchesResult: AWSDecodableShape {
/// A list of branches for an Amplify app.
public let branches: [Branch]
/// A pagination token. If a non-null pagination token is returned in a result, pass its value in another request to retrieve more entries.
public let nextToken: String?
public init(branches: [Branch], nextToken: String? = nil) {
self.branches = branches
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case branches
case nextToken
}
}
public struct ListDomainAssociationsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The maximum number of records to list in a single response.
public let maxResults: Int?
/// A pagination token. Set to null to start listing apps from the start. If non-null, a pagination token is returned in a result. Pass its value in here to list more projects.
public let nextToken: String?
public init(appId: String, maxResults: Int? = nil, nextToken: String? = nil) {
self.appId = appId
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListDomainAssociationsResult: AWSDecodableShape {
/// A list of domain associations.
public let domainAssociations: [DomainAssociation]
/// A pagination token. If non-null, a pagination token is returned in a result. Pass its value in another request to retrieve more entries.
public let nextToken: String?
public init(domainAssociations: [DomainAssociation], nextToken: String? = nil) {
self.domainAssociations = domainAssociations
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case domainAssociations
case nextToken
}
}
public struct ListJobsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for a branch.
public let branchName: String
/// The maximum number of records to list in a single response.
public let maxResults: Int?
/// A pagination token. Set to null to start listing steps from the start. If a non-null pagination token is returned in a result, pass its value in here to list more steps.
public let nextToken: String?
public init(appId: String, branchName: String, maxResults: Int? = nil, nextToken: String? = nil) {
self.appId = appId
self.branchName = branchName
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListJobsResult: AWSDecodableShape {
/// The result structure for the list job result request.
public let jobSummaries: [JobSummary]
/// A pagination token. If non-null the pagination token is returned in a result. Pass its value in another request to retrieve more entries.
public let nextToken: String?
public init(jobSummaries: [JobSummary], nextToken: String? = nil) {
self.jobSummaries = jobSummaries
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case jobSummaries
case nextToken
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn"))
]
/// The Amazon Resource Name (ARN) to use to list tags.
public let resourceArn: String
public init(resourceArn: String) {
self.resourceArn = resourceArn
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws:amplify:.*")
}
private enum CodingKeys: CodingKey {}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
/// A list of tags for the specified The Amazon Resource Name (ARN).
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct ListWebhooksRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The maximum number of records to list in a single response.
public let maxResults: Int?
/// A pagination token. Set to null to start listing webhooks from the start. If non-null,the pagination token is returned in a result. Pass its value in here to list more webhooks.
public let nextToken: String?
public init(appId: String, maxResults: Int? = nil, nextToken: String? = nil) {
self.appId = appId
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListWebhooksResult: AWSDecodableShape {
/// A pagination token. If non-null, the pagination token is returned in a result. Pass its value in another request to retrieve more entries.
public let nextToken: String?
/// A list of webhooks.
public let webhooks: [Webhook]
public init(nextToken: String? = nil, webhooks: [Webhook]) {
self.nextToken = nextToken
self.webhooks = webhooks
}
private enum CodingKeys: String, CodingKey {
case nextToken
case webhooks
}
}
public struct ProductionBranch: AWSDecodableShape {
/// The branch name for the production branch.
public let branchName: String?
/// The last deploy time of the production branch.
public let lastDeployTime: Date?
/// The status of the production branch.
public let status: String?
/// The thumbnail URL for the production branch.
public let thumbnailUrl: String?
public init(branchName: String? = nil, lastDeployTime: Date? = nil, status: String? = nil, thumbnailUrl: String? = nil) {
self.branchName = branchName
self.lastDeployTime = lastDeployTime
self.status = status
self.thumbnailUrl = thumbnailUrl
}
private enum CodingKeys: String, CodingKey {
case branchName
case lastDeployTime
case status
case thumbnailUrl
}
}
public struct StartDeploymentRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for the branch, for the job.
public let branchName: String
/// The job ID for this deployment, generated by the create deployment request.
public let jobId: String?
/// The source URL for this deployment, used when calling start deployment without create deployment. The source URL can be any HTTP GET URL that is publicly accessible and downloads a single .zip file.
public let sourceUrl: String?
public init(appId: String, branchName: String, jobId: String? = nil, sourceUrl: String? = nil) {
self.appId = appId
self.branchName = branchName
self.jobId = jobId
self.sourceUrl = sourceUrl
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, max: 255)
try self.validate(self.sourceUrl, name: "sourceUrl", parent: name, max: 1000)
}
private enum CodingKeys: String, CodingKey {
case jobId
case sourceUrl
}
}
public struct StartDeploymentResult: AWSDecodableShape {
/// The summary for the job.
public let jobSummary: JobSummary
public init(jobSummary: JobSummary) {
self.jobSummary = jobSummary
}
private enum CodingKeys: String, CodingKey {
case jobSummary
}
}
public struct StartJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The branch name for the job.
public let branchName: String
/// The commit ID from a third-party repository provider for the job.
public let commitId: String?
/// The commit message from a third-party repository provider for the job.
public let commitMessage: String?
/// The commit date and time for the job.
public let commitTime: Date?
/// The unique ID for an existing job. This is required if the value of jobType is RETRY.
public let jobId: String?
/// A descriptive reason for starting this job.
public let jobReason: String?
/// Describes the type for the job. The job type RELEASE starts a new job with the latest change from the specified branch. This value is available only for apps that are connected to a repository. The job type RETRY retries an existing job. If the job type value is RETRY, the jobId is also required.
public let jobType: JobType
public init(appId: String, branchName: String, commitId: String? = nil, commitMessage: String? = nil, commitTime: Date? = nil, jobId: String? = nil, jobReason: String? = nil, jobType: JobType) {
self.appId = appId
self.branchName = branchName
self.commitId = commitId
self.commitMessage = commitMessage
self.commitTime = commitTime
self.jobId = jobId
self.jobReason = jobReason
self.jobType = jobType
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.commitId, name: "commitId", parent: name, max: 255)
try self.validate(self.commitMessage, name: "commitMessage", parent: name, max: 10000)
try self.validate(self.jobId, name: "jobId", parent: name, max: 255)
try self.validate(self.jobReason, name: "jobReason", parent: name, max: 255)
}
private enum CodingKeys: String, CodingKey {
case commitId
case commitMessage
case commitTime
case jobId
case jobReason
case jobType
}
}
public struct StartJobResult: AWSDecodableShape {
/// The summary for the job.
public let jobSummary: JobSummary
public init(jobSummary: JobSummary) {
self.jobSummary = jobSummary
}
private enum CodingKeys: String, CodingKey {
case jobSummary
}
}
public struct Step: AWSDecodableShape {
/// The URL to the artifact for the execution step.
public let artifactsUrl: String?
/// The context for the current step. Includes a build image if the step is build.
public let context: String?
/// The end date and time of the execution step.
public let endTime: Date
/// The URL to the logs for the execution step.
public let logUrl: String?
/// The list of screenshot URLs for the execution step, if relevant.
public let screenshots: [String: String]?
/// The start date and time of the execution step.
public let startTime: Date
/// The status of the execution step.
public let status: JobStatus
/// The reason for the current step status.
public let statusReason: String?
/// The name of the execution step.
public let stepName: String
/// The URL to the test artifact for the execution step.
public let testArtifactsUrl: String?
/// The URL to the test configuration for the execution step.
public let testConfigUrl: String?
public init(artifactsUrl: String? = nil, context: String? = nil, endTime: Date, logUrl: String? = nil, screenshots: [String: String]? = nil, startTime: Date, status: JobStatus, statusReason: String? = nil, stepName: String, testArtifactsUrl: String? = nil, testConfigUrl: String? = nil) {
self.artifactsUrl = artifactsUrl
self.context = context
self.endTime = endTime
self.logUrl = logUrl
self.screenshots = screenshots
self.startTime = startTime
self.status = status
self.statusReason = statusReason
self.stepName = stepName
self.testArtifactsUrl = testArtifactsUrl
self.testConfigUrl = testConfigUrl
}
private enum CodingKeys: String, CodingKey {
case artifactsUrl
case context
case endTime
case logUrl
case screenshots
case startTime
case status
case statusReason
case stepName
case testArtifactsUrl
case testConfigUrl
}
}
public struct StopJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName")),
AWSMemberEncoding(label: "jobId", location: .uri(locationName: "jobId"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The name for the branch, for the job.
public let branchName: String
/// The unique id for the job.
public let jobId: String
public init(appId: String, branchName: String, jobId: String) {
self.appId = appId
self.branchName = branchName
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, max: 255)
}
private enum CodingKeys: CodingKey {}
}
public struct StopJobResult: AWSDecodableShape {
/// The summary for the job.
public let jobSummary: JobSummary
public init(jobSummary: JobSummary) {
self.jobSummary = jobSummary
}
private enum CodingKeys: String, CodingKey {
case jobSummary
}
}
public struct SubDomain: AWSDecodableShape {
/// The DNS record for the subdomain.
public let dnsRecord: String
/// Describes the settings for the subdomain.
public let subDomainSetting: SubDomainSetting
/// The verified status of the subdomain
public let verified: Bool
public init(dnsRecord: String, subDomainSetting: SubDomainSetting, verified: Bool) {
self.dnsRecord = dnsRecord
self.subDomainSetting = subDomainSetting
self.verified = verified
}
private enum CodingKeys: String, CodingKey {
case dnsRecord
case subDomainSetting
case verified
}
}
public struct SubDomainSetting: AWSEncodableShape & AWSDecodableShape {
/// The branch name setting for the subdomain.
public let branchName: String
/// The prefix setting for the subdomain.
public let prefix: String
public init(branchName: String, prefix: String) {
self.branchName = branchName
self.prefix = prefix
}
public func validate(name: String) throws {
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.prefix, name: "prefix", parent: name, max: 255)
}
private enum CodingKeys: String, CodingKey {
case branchName
case prefix
}
}
public struct TagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn"))
]
/// The Amazon Resource Name (ARN) to use to tag a resource.
public let resourceArn: String
/// The tags used to tag the resource.
public let tags: [String: String]
public init(resourceArn: String, tags: [String: String]) {
self.resourceArn = resourceArn
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws:amplify:.*")
try self.tags.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
}
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct TagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UntagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")),
AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys"))
]
/// The Amazon Resource Name (ARN) to use to untag a resource.
public let resourceArn: String
/// The tag keys to use to untag a resource.
public let tagKeys: [String]
public init(resourceArn: String, tagKeys: [String]) {
self.resourceArn = resourceArn
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws:amplify:.*")
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
try validate($0, name: "tagKeys[]", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$")
}
try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 50)
try self.validate(self.tagKeys, name: "tagKeys", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct UntagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UpdateAppRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId"))
]
/// The personal access token for a third-party source control system for an Amplify app. The token is used to create webhook and a read-only deploy key. The token is not stored.
public let accessToken: String?
/// The unique ID for an Amplify app.
public let appId: String
/// The automated branch creation configuration for the Amplify app.
public let autoBranchCreationConfig: AutoBranchCreationConfig?
/// Describes the automated branch creation glob patterns for the Amplify app.
public let autoBranchCreationPatterns: [String]?
/// The basic authorization credentials for an Amplify app.
public let basicAuthCredentials: String?
/// The build specification (build spec) for an Amplify app.
public let buildSpec: String?
/// The custom redirect and rewrite rules for an Amplify app.
public let customRules: [CustomRule]?
/// The description for an Amplify app.
public let description: String?
/// Enables automated branch creation for the Amplify app.
public let enableAutoBranchCreation: Bool?
/// Enables basic authorization for an Amplify app.
public let enableBasicAuth: Bool?
/// Enables branch auto-building for an Amplify app.
public let enableBranchAutoBuild: Bool?
/// Automatically disconnects a branch in the Amplify Console when you delete a branch from your Git repository.
public let enableBranchAutoDeletion: Bool?
/// The environment variables for an Amplify app.
public let environmentVariables: [String: String]?
/// The AWS Identity and Access Management (IAM) service role for an Amplify app.
public let iamServiceRoleArn: String?
/// The name for an Amplify app.
public let name: String?
/// The OAuth token for a third-party source control system for an Amplify app. The token is used to create a webhook and a read-only deploy key. The OAuth token is not stored.
public let oauthToken: String?
/// The platform for an Amplify app.
public let platform: Platform?
/// The name of the repository for an Amplify app
public let repository: String?
public init(accessToken: String? = nil, appId: String, autoBranchCreationConfig: AutoBranchCreationConfig? = nil, autoBranchCreationPatterns: [String]? = nil, basicAuthCredentials: String? = nil, buildSpec: String? = nil, customRules: [CustomRule]? = nil, description: String? = nil, enableAutoBranchCreation: Bool? = nil, enableBasicAuth: Bool? = nil, enableBranchAutoBuild: Bool? = nil, enableBranchAutoDeletion: Bool? = nil, environmentVariables: [String: String]? = nil, iamServiceRoleArn: String? = nil, name: String? = nil, oauthToken: String? = nil, platform: Platform? = nil, repository: String? = nil) {
self.accessToken = accessToken
self.appId = appId
self.autoBranchCreationConfig = autoBranchCreationConfig
self.autoBranchCreationPatterns = autoBranchCreationPatterns
self.basicAuthCredentials = basicAuthCredentials
self.buildSpec = buildSpec
self.customRules = customRules
self.description = description
self.enableAutoBranchCreation = enableAutoBranchCreation
self.enableBasicAuth = enableBasicAuth
self.enableBranchAutoBuild = enableBranchAutoBuild
self.enableBranchAutoDeletion = enableBranchAutoDeletion
self.environmentVariables = environmentVariables
self.iamServiceRoleArn = iamServiceRoleArn
self.name = name
self.oauthToken = oauthToken
self.platform = platform
self.repository = repository
}
public func validate(name: String) throws {
try self.validate(self.accessToken, name: "accessToken", parent: name, max: 255)
try self.validate(self.accessToken, name: "accessToken", parent: name, min: 1)
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.autoBranchCreationConfig?.validate(name: "\(name).autoBranchCreationConfig")
try self.autoBranchCreationPatterns?.forEach {
try validate($0, name: "autoBranchCreationPatterns[]", parent: name, max: 2048)
try validate($0, name: "autoBranchCreationPatterns[]", parent: name, min: 1)
}
try self.validate(self.basicAuthCredentials, name: "basicAuthCredentials", parent: name, max: 2000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, max: 25000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, min: 1)
try self.customRules?.forEach {
try $0.validate(name: "\(name).customRules[]")
}
try self.validate(self.description, name: "description", parent: name, max: 1000)
try self.environmentVariables?.forEach {
try validate($0.key, name: "environmentVariables.key", parent: name, max: 255)
try validate($0.value, name: "environmentVariables[\"\($0.key)\"]", parent: name, max: 1000)
}
try self.validate(self.iamServiceRoleArn, name: "iamServiceRoleArn", parent: name, max: 1000)
try self.validate(self.iamServiceRoleArn, name: "iamServiceRoleArn", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, max: 255)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.oauthToken, name: "oauthToken", parent: name, max: 1000)
try self.validate(self.repository, name: "repository", parent: name, max: 1000)
}
private enum CodingKeys: String, CodingKey {
case accessToken
case autoBranchCreationConfig
case autoBranchCreationPatterns
case basicAuthCredentials
case buildSpec
case customRules
case description
case enableAutoBranchCreation
case enableBasicAuth
case enableBranchAutoBuild
case enableBranchAutoDeletion
case environmentVariables
case iamServiceRoleArn
case name
case oauthToken
case platform
case repository
}
}
public struct UpdateAppResult: AWSDecodableShape {
/// Represents the updated Amplify app.
public let app: App
public init(app: App) {
self.app = app
}
private enum CodingKeys: String, CodingKey {
case app
}
}
public struct UpdateBranchRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "branchName", location: .uri(locationName: "branchName"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// The Amazon Resource Name (ARN) for a backend environment that is part of an Amplify app.
public let backendEnvironmentArn: String?
/// The basic authorization credentials for the branch.
public let basicAuthCredentials: String?
/// The name for the branch.
public let branchName: String
/// The build specification (build spec) for the branch.
public let buildSpec: String?
/// The description for the branch.
public let description: String?
/// The display name for a branch. This is used as the default domain prefix.
public let displayName: String?
/// Enables auto building for the branch.
public let enableAutoBuild: Bool?
/// Enables basic authorization for the branch.
public let enableBasicAuth: Bool?
/// Enables notifications for the branch.
public let enableNotification: Bool?
/// Performance mode optimizes for faster hosting performance by keeping content cached at the edge for a longer interval. Enabling performance mode will mean that hosting configuration or code changes can take up to 10 minutes to roll out.
public let enablePerformanceMode: Bool?
/// Enables pull request preview for this branch.
public let enablePullRequestPreview: Bool?
/// The environment variables for the branch.
public let environmentVariables: [String: String]?
/// The framework for the branch.
public let framework: String?
/// The Amplify environment name for the pull request.
public let pullRequestEnvironmentName: String?
/// Describes the current stage for the branch.
public let stage: Stage?
/// The content Time to Live (TTL) for the website in seconds.
public let ttl: String?
public init(appId: String, backendEnvironmentArn: String? = nil, basicAuthCredentials: String? = nil, branchName: String, buildSpec: String? = nil, description: String? = nil, displayName: String? = nil, enableAutoBuild: Bool? = nil, enableBasicAuth: Bool? = nil, enableNotification: Bool? = nil, enablePerformanceMode: Bool? = nil, enablePullRequestPreview: Bool? = nil, environmentVariables: [String: String]? = nil, framework: String? = nil, pullRequestEnvironmentName: String? = nil, stage: Stage? = nil, ttl: String? = nil) {
self.appId = appId
self.backendEnvironmentArn = backendEnvironmentArn
self.basicAuthCredentials = basicAuthCredentials
self.branchName = branchName
self.buildSpec = buildSpec
self.description = description
self.displayName = displayName
self.enableAutoBuild = enableAutoBuild
self.enableBasicAuth = enableBasicAuth
self.enableNotification = enableNotification
self.enablePerformanceMode = enablePerformanceMode
self.enablePullRequestPreview = enablePullRequestPreview
self.environmentVariables = environmentVariables
self.framework = framework
self.pullRequestEnvironmentName = pullRequestEnvironmentName
self.stage = stage
self.ttl = ttl
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.validate(self.backendEnvironmentArn, name: "backendEnvironmentArn", parent: name, max: 1000)
try self.validate(self.backendEnvironmentArn, name: "backendEnvironmentArn", parent: name, min: 1)
try self.validate(self.basicAuthCredentials, name: "basicAuthCredentials", parent: name, max: 2000)
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, max: 25000)
try self.validate(self.buildSpec, name: "buildSpec", parent: name, min: 1)
try self.validate(self.description, name: "description", parent: name, max: 1000)
try self.validate(self.displayName, name: "displayName", parent: name, max: 255)
try self.environmentVariables?.forEach {
try validate($0.key, name: "environmentVariables.key", parent: name, max: 255)
try validate($0.value, name: "environmentVariables[\"\($0.key)\"]", parent: name, max: 1000)
}
try self.validate(self.framework, name: "framework", parent: name, max: 255)
try self.validate(self.pullRequestEnvironmentName, name: "pullRequestEnvironmentName", parent: name, max: 20)
}
private enum CodingKeys: String, CodingKey {
case backendEnvironmentArn
case basicAuthCredentials
case buildSpec
case description
case displayName
case enableAutoBuild
case enableBasicAuth
case enableNotification
case enablePerformanceMode
case enablePullRequestPreview
case environmentVariables
case framework
case pullRequestEnvironmentName
case stage
case ttl
}
}
public struct UpdateBranchResult: AWSDecodableShape {
/// The branch for an Amplify app, which maps to a third-party repository branch.
public let branch: Branch
public init(branch: Branch) {
self.branch = branch
}
private enum CodingKeys: String, CodingKey {
case branch
}
}
public struct UpdateDomainAssociationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")),
AWSMemberEncoding(label: "domainName", location: .uri(locationName: "domainName"))
]
/// The unique ID for an Amplify app.
public let appId: String
/// Sets the branch patterns for automatic subdomain creation.
public let autoSubDomainCreationPatterns: [String]?
/// The required AWS Identity and Access Management (IAM) service role for the Amazon Resource Name (ARN) for automatically creating subdomains.
public let autoSubDomainIAMRole: String?
/// The name of the domain.
public let domainName: String
/// Enables the automated creation of subdomains for branches.
public let enableAutoSubDomain: Bool?
/// Describes the settings for the subdomain.
public let subDomainSettings: [SubDomainSetting]
public init(appId: String, autoSubDomainCreationPatterns: [String]? = nil, autoSubDomainIAMRole: String? = nil, domainName: String, enableAutoSubDomain: Bool? = nil, subDomainSettings: [SubDomainSetting]) {
self.appId = appId
self.autoSubDomainCreationPatterns = autoSubDomainCreationPatterns
self.autoSubDomainIAMRole = autoSubDomainIAMRole
self.domainName = domainName
self.enableAutoSubDomain = enableAutoSubDomain
self.subDomainSettings = subDomainSettings
}
public func validate(name: String) throws {
try self.validate(self.appId, name: "appId", parent: name, max: 255)
try self.validate(self.appId, name: "appId", parent: name, min: 1)
try self.autoSubDomainCreationPatterns?.forEach {
try validate($0, name: "autoSubDomainCreationPatterns[]", parent: name, max: 2048)
try validate($0, name: "autoSubDomainCreationPatterns[]", parent: name, min: 1)
}
try self.validate(self.autoSubDomainIAMRole, name: "autoSubDomainIAMRole", parent: name, max: 1000)
try self.validate(self.autoSubDomainIAMRole, name: "autoSubDomainIAMRole", parent: name, pattern: "^$|^arn:aws:iam::\\d{12}:role.+")
try self.validate(self.domainName, name: "domainName", parent: name, max: 255)
try self.subDomainSettings.forEach {
try $0.validate(name: "\(name).subDomainSettings[]")
}
try self.validate(self.subDomainSettings, name: "subDomainSettings", parent: name, max: 255)
}
private enum CodingKeys: String, CodingKey {
case autoSubDomainCreationPatterns
case autoSubDomainIAMRole
case enableAutoSubDomain
case subDomainSettings
}
}
public struct UpdateDomainAssociationResult: AWSDecodableShape {
/// Describes a domain association, which associates a custom domain with an Amplify app.
public let domainAssociation: DomainAssociation
public init(domainAssociation: DomainAssociation) {
self.domainAssociation = domainAssociation
}
private enum CodingKeys: String, CodingKey {
case domainAssociation
}
}
public struct UpdateWebhookRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "webhookId", location: .uri(locationName: "webhookId"))
]
/// The name for a branch that is part of an Amplify app.
public let branchName: String?
/// The description for a webhook.
public let description: String?
/// The unique ID for a webhook.
public let webhookId: String
public init(branchName: String? = nil, description: String? = nil, webhookId: String) {
self.branchName = branchName
self.description = description
self.webhookId = webhookId
}
public func validate(name: String) throws {
try self.validate(self.branchName, name: "branchName", parent: name, max: 255)
try self.validate(self.branchName, name: "branchName", parent: name, min: 1)
try self.validate(self.description, name: "description", parent: name, max: 1000)
try self.validate(self.webhookId, name: "webhookId", parent: name, max: 255)
}
private enum CodingKeys: String, CodingKey {
case branchName
case description
}
}
public struct UpdateWebhookResult: AWSDecodableShape {
/// Describes a webhook that connects repository events to an Amplify app.
public let webhook: Webhook
public init(webhook: Webhook) {
self.webhook = webhook
}
private enum CodingKeys: String, CodingKey {
case webhook
}
}
public struct Webhook: AWSDecodableShape {
/// The name for a branch that is part of an Amplify app.
public let branchName: String
/// The create date and time for a webhook.
public let createTime: Date
/// The description for a webhook.
public let description: String
/// Updates the date and time for a webhook.
public let updateTime: Date
/// The Amazon Resource Name (ARN) for the webhook.
public let webhookArn: String
/// The ID of the webhook.
public let webhookId: String
/// The URL of the webhook.
public let webhookUrl: String
public init(branchName: String, createTime: Date, description: String, updateTime: Date, webhookArn: String, webhookId: String, webhookUrl: String) {
self.branchName = branchName
self.createTime = createTime
self.description = description
self.updateTime = updateTime
self.webhookArn = webhookArn
self.webhookId = webhookId
self.webhookUrl = webhookUrl
}
private enum CodingKeys: String, CodingKey {
case branchName
case createTime
case description
case updateTime
case webhookArn
case webhookId
case webhookUrl
}
}
}
| apache-2.0 | 71b44ce6987586b5b078cfad9b235a88 | 44.259706 | 742 | 0.633251 | 4.892194 | false | false | false | false |
marsal-silveira/iStackOS | iStackOS/src/Utils/Logger.swift | 1 | 783 | //
// Logger.swift
// iStackOS
//
// Created by Marsal on 13/03/16.
// Copyright © 2016 Marsal Silveira. All rights reserved.
//
import Foundation
class Logger
{
static func log(logMessage: String = "", file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__)
{
// __FILE__ : String - The name of the file in which it appears.
// __FUNCTION__ : String - The name of the declaration in which it appears.
// __LINE__ : Int - The line number on which it appears.
let fileURL = NSURL(fileURLWithPath: file)
let className = fileURL.lastPathComponent!.stringByReplacingOccurrencesOfString(fileURL.pathExtension!, withString: "")
print("[\(className)\(function)][\(line)] \(logMessage)")
}
} | mit | da94f45c79b1d55250c9f61aa7f1d4ff | 33.043478 | 127 | 0.629156 | 4.204301 | false | false | false | false |
kylef/fd | Sources/UNIXListener.swift | 1 | 1880 | #if os(Linux)
import Glibc
private let system_accept = Glibc.accept
private let system_listen = Glibc.listen
private let sock_stream = Int32(SOCK_STREAM.rawValue)
private let system_bind = Glibc.bind
#else
import Darwin
private let system_accept = Darwin.accept
private let system_listen = Darwin.listen
private let sock_stream = SOCK_STREAM
private let system_bind = Darwin.bind
#endif
public class UNIXListener : FileDescriptor {
public let fileNumber: FileNumber
public init(path: String) throws {
fileNumber = socket(AF_UNIX, sock_stream, 0)
if fileNumber == -1 {
throw FileDescriptorError()
}
do {
try bind(path)
} catch {
try close()
throw error
}
}
deinit {
let _ = try? close()
}
fileprivate func bind(_ path: String) throws {
var addr = sockaddr_un()
addr.sun_family = sa_family_t(AF_UNIX)
let lengthOfPath = path.withCString { Int(strlen($0)) }
guard lengthOfPath < MemoryLayout.size(ofValue: addr.sun_path) else {
throw FileDescriptorError()
}
_ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in
path.withCString {
strncpy(ptr, $0, lengthOfPath)
}
}
try withUnsafePointer(to: &addr) {
try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
guard system_bind(fileNumber, $0, UInt32(MemoryLayout<sockaddr_un>.stride)) != -1 else {
throw FileDescriptorError()
}
}
}
}
fileprivate func listen(backlog: Int32) throws {
if system_listen(fileNumber, backlog) == -1 {
throw FileDescriptorError()
}
}
/// Accepts a connection socket
public func accept() throws -> UNIXConnection {
let fileNumber = system_accept(self.fileNumber, nil, nil)
if fileNumber == -1 {
throw FileDescriptorError()
}
return UNIXConnection(fileNumber: fileNumber)
}
}
| bsd-2-clause | 4bd4ff54839a34dfa258b3caeafc9647 | 23.415584 | 96 | 0.658511 | 3.900415 | false | false | false | false |
bliker/ipython-osx | IPython/Document.swift | 1 | 1869 | //
// Document.swift
// IPython
//
// Created by Samuel Vasko on 17/12/14.
// Copyright (c) 2014 Samuel Vasko. All rights reserved.
//
import Cocoa
import WebKit
class Document: NSDocument {
@IBOutlet var webView: WebView!
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
let requesturl = NSURL(string: "http://localhost:8888/notebooks/Code/Python/Untitled1.ipynb")
let request = NSURLRequest(URL: requesturl!)
webView.mainFrame.loadRequest(request)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
}
override class func autosavesInPlace() -> Bool {
return false
}
override var windowNibName: String? {
return "Document"
}
override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
//
// outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return nil
}
override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
// outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return true
}
}
| mit | ee38c216a23d5dba21c9ae72452e4e55 | 34.264151 | 186 | 0.693954 | 4.547445 | false | false | false | false |
milseman/swift | benchmark/single-source/OpenClose.swift | 11 | 963 | //===--- OpenClose.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
// A micro benchmark for checking the speed of string-based enums.
enum MyState : String {
case Closed = "Closed"
case Opened = "Opened"
}
@inline(never)
func check_state(_ state : MyState) -> Int {
return state == .Opened ? 1 : 0
}
@inline(never)
public func run_OpenClose(_ N: Int) {
var c = 0
for _ in 1...N*10000 {
c += check_state(MyState.Closed)
}
CheckResults(c == 0)
}
| apache-2.0 | 9ce3ee59df276840e988a2573dfd9227 | 25.027027 | 80 | 0.58567 | 4.168831 | false | false | false | false |
mlibai/XZKit | XZKit/Code/NavigationController/XZNavigationController.AnimationController.swift | 1 | 32342 | //
// NavigationControllerGestureDrivenTransitionController.swift
// XZKit
//
// Created by Xezun on 2017/7/11.
//
//
import UIKit
extension NavigationController {
/// 动画控制器,处理了导航控制器的转场过程中的动画效果。
open class AnimationController: NSObject, UIViewControllerAnimatedTransitioning {
/// 导航控制器。
public unowned let navigationController: NavigationController
/// 导航行为。
public let operation: UINavigationController.Operation
/// 交互控制器。
public let interactionController: UIPercentDrivenInteractiveTransition?
/// 是否为交互性动画。
public var isInteractive: Bool {
return interactionController != nil
}
public init?(for navigationController: NavigationController, operation: UINavigationController.Operation, isInteractive: Bool) {
guard operation != .none else { return nil }
self.navigationController = navigationController
self.operation = operation
self.interactionController = (isInteractive ? UIPercentDrivenInteractiveTransition() : nil)
super.init()
}
}
}
extension NavigationController.AnimationController {
/// 系统默认转场动画时长为 0.3 秒,此处也一样。
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
/// 4. 配置转场动画。
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch operation {
case .push: animatePushTransition(using: transitionContext)
case .pop: animatePopTransition(using: transitionContext)
default: break
}
}
/// 6. 转场结束。
open func animationEnded(_ transitionCompleted: Bool) {
// 此方法在 UIViewControllerContextTransitioning.completeTransition(_:) 中被调用。
// 且调用后,系统内部处理了一些操作,致使在这里处理取消导航的恢复操作无法生效,所以取消导航的恢复操作放在了动画的 completion 回调中处理。
// navigationController.transitionController.navigationController(navigationController, animationController: self, animatedTransitionDidEnd: transitionCompleted)
// 在此取 navigationController.topViewController 可能并不准确,因为 viewDidAppear 比此方法先调用,
// 如果在 viewDidAppear 中 push 了新的控制器,那么这里的获取到的 topViewController 就是新的控制器。
// 因此在此方法中无法设置当前的自定义导航条。
}
open func animationOptions(forTransition operation: UINavigationController.Operation) -> UIView.AnimationOptions {
if interactionController == nil {
return .curveEaseInOut
}
return .curveLinear
}
/// 执行 Push 动画。
///
/// - Parameter transitionContext: 转场信息。
open func animatePushTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from) else { return }
guard let fromView = transitionContext.view(forKey: .from) else { return }
guard let toVC = transitionContext.viewController(forKey: .to) else { return }
guard let toView = transitionContext.view(forKey: .to) else { return }
let flag: CGFloat = transitionContext.containerView.userInterfaceLayoutDirection == .leftToRight ? 1.0 : -1.0
// 使用 transform 写动画效果,改变的也是视图的 frame 不能解决在专场开始时获取控制器视图 frame 不正常的问题。
// 配置旧视图。
let fromViewFrame1 = transitionContext.initialFrame(for: fromVC)
let fromViewFrame2 = fromViewFrame1.offsetBy(dx: flag * -fromViewFrame1.width / 3.0, dy: 0)
fromView.frame = fromViewFrame1
transitionContext.containerView.addSubview(fromView)
// 配置新视图。
let toViewFrame2 = transitionContext.finalFrame(for: toVC)
let toViewFrame1 = toViewFrame2.offsetBy(dx: flag * toViewFrame2.width, dy: 0)
toView.frame = toViewFrame1
transitionContext.containerView.addSubview(toView)
// 转场容器与导航条不在同一个层次上,坐标系需要转换。
let navigationBar = navigationController.navigationBar // 系统导航条。
// 获取自定义导航条,并配置导航条。
let fromNavigationBar = (fromVC as? NavigationBarCustomizable)?.navigationBarIfLoaded
let toNavigationBar = (toVC as? NavigationBarCustomizable)?.navigationBarIfLoaded
// 导航条当前坐标系(这里获取到的是转场之后的导航条状态),已转换到转场容器内。
// fromNavigationBar 在转场前已从导航条上移除,转换坐标系需使用系统导航条(需保持 fromNavigationBar.frame 不变)。
let navigationBarRect = navigationBar.convert(navigationBar.bounds, to: transitionContext.containerView)
// 根据导航条的变化来设置导航条。
let navigationBarTransition = TransitionType.init(forNavigationBarFrom: fromNavigationBar?.isHidden, to: toNavigationBar?.isHidden)
switch navigationBarTransition {
case .alwaysShow:
// 旧的导航条保持原样添加到动画视图上。
fromNavigationBar!.frame = navigationBar.convert(fromNavigationBar!.frame, to: transitionContext.containerView)
transitionContext.containerView.insertSubview(fromNavigationBar!, aboveSubview: fromView)
// 新的导航条与当前系统导航条一致。
toNavigationBar!.frame = navigationBarRect.offsetBy(dx: flag * navigationBarRect.width, dy: 0)
transitionContext.containerView.insertSubview(toNavigationBar!, aboveSubview: toView)
case .alwaysHide:
break // 始终隐藏,不需要做动画,自定义导航条(如果有)在转场之后添加到系统导航条上。
case .showToHide:
fromNavigationBar!.frame = navigationBar.convert(fromNavigationBar!.frame, to: transitionContext.containerView)
transitionContext.containerView.insertSubview(fromNavigationBar!, aboveSubview: fromView)
case .hideToShow:
toNavigationBar!.frame = navigationBarRect.offsetBy(dx: flag * navigationBarRect.width, dy: 0)
transitionContext.containerView.insertSubview(toNavigationBar!, aboveSubview: toView)
}
// 解决因为状态栏变化而造成的导航条布局问题。
fromNavigationBar?.setNeedsLayout()
toNavigationBar?.setNeedsLayout()
// 记录导航条当前位置,然后将导航条放到转场容器内执行动画。
let navigationBarLocation = (
superview: navigationBar.superview,
frame: navigationBar.frame,
index: navigationBar.superview?.subviews.firstIndex(of: navigationBar)
)
navigationBar.frame = navigationBarRect
transitionContext.containerView.insertSubview(navigationBar, belowSubview: fromView)
// 阴影
let containerBounds = transitionContext.containerView.bounds
let shadowView = ShadowView.init(frame: containerBounds.offsetBy(dx: flag * containerBounds.width, dy: 0))
transitionContext.containerView.insertSubview(shadowView, belowSubview: toView)
let tabBarAnimator = TabBarAnimator.init(
navigationController: navigationController,
operation: .push,
containerView: transitionContext.containerView,
from: (fromVC, fromViewFrame1, fromViewFrame2),
to: (toVC, toViewFrame1, toViewFrame2)
)
let duration = transitionDuration(using: transitionContext)
let options = animationOptions(forTransition: .push)
UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
fromView.frame = fromViewFrame2
toView.frame = toViewFrame2
shadowView.frame = containerBounds
tabBarAnimator?.commitAnimation()
switch navigationBarTransition {
case .alwaysShow:
let frame = fromNavigationBar!.frame
fromNavigationBar!.frame = frame.offsetBy(dx: flag * -frame.width / 3.0, dy: 0)
toNavigationBar!.frame = navigationBarRect
case .alwaysHide: break
case .showToHide:
let frame = fromNavigationBar!.frame
fromNavigationBar!.frame = frame.offsetBy(dx: flag * -frame.width / 3.0, dy: 0)
case .hideToShow:
toNavigationBar!.frame = navigationBarRect
}
}, completion: { (finished) in
// 删除阴影。
shadowView.removeFromSuperview()
// 恢复导航条原有位置。
if let superview = navigationBarLocation.superview, let index = navigationBarLocation.index {
navigationBar.frame = navigationBarLocation.frame
superview.insertSubview(navigationBar, at: min(index, superview.subviews.count))
}
// 恢复 TabBar 。
tabBarAnimator?.completeAnimation(finished)
// 自定义导航条在转场过程中,仅仅作为转场效果出现,将起放置到导航条上有导航控制器处理,所以这里要移除。
fromNavigationBar?.removeFromSuperview()
toNavigationBar?.removeFromSuperview()
// 恢复导航条状态。如果将恢复操作放在 animationEnded(_:) 方法中,在Demo中没有问题,但是在实际项目中却遇到了未知问题:
// 页面A导航条透明,页面B导航条不透明。从 B 返回(pop)到 A ,如果操作取消,那么最终 B 页面的导航条属性为不透明,但是从布局(控制器view)上看却是透明的。
// 由于 animationEnded(_:) 是在控制器 viewDidAppear 或 viewDidDisappear 之后被调用(见页面底部文档),此时再来恢复导航条样式已无济于事。
// 至于在Demo中放在前后都可以,可能是因为计算少速度快导致的,但是项目计算量达时,放后面就无法及时抓取正确的状态,从而导致问题。
if transitionContext.transitionWasCancelled {
if let fromNavigationBar = fromNavigationBar {
navigationBar.isTranslucent = fromNavigationBar.isTranslucent
navigationBar.tintColor = fromNavigationBar.tintColor
navigationBar.isHidden = fromNavigationBar.isHidden
if #available(iOS 11.0, *) {
navigationBar.prefersLargeTitles = fromNavigationBar.prefersLargeTitles
}
} else {
navigationBar.isTranslucent = true
navigationBar.tintColor = nil
navigationBar.isHidden = true
if #available(iOS 11.0, *) {
navigationBar.prefersLargeTitles = false
}
}
transitionContext.completeTransition(false)
navigationBar.customizedBar = fromNavigationBar;
} else {
transitionContext.completeTransition(true)
navigationBar.customizedBar = toNavigationBar;
}
})
}
/// 执行 pop 动画。
///
/// - Parameter transitionContext: 转场信息。
open func animatePopTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from) else { return }
guard let fromView = transitionContext.view(forKey: .from) else { return }
guard let toVC = transitionContext.viewController(forKey: .to) else { return }
guard let toView = transitionContext.view(forKey: .to) else { return }
let flag: CGFloat = transitionContext.containerView.userInterfaceLayoutDirection == .leftToRight ? 1.0 : -1.0
// 配置旧视图。
let fromViewFrame1 = transitionContext.initialFrame(for: fromVC)
let fromViewFrame2 = fromViewFrame1.offsetBy(dx: flag * fromViewFrame1.width, dy: 0)
fromView.frame = fromViewFrame1
transitionContext.containerView.addSubview(fromView)
// 配置新视图。
let toViewFrame2 = transitionContext.finalFrame(for: toVC)
let toViewFrame1 = toViewFrame2.offsetBy(dx: flag * -toViewFrame2.width / 3.0, dy: 0)
toView.frame = toViewFrame1
transitionContext.containerView.insertSubview(toView, belowSubview: fromView)
// 转场容器与导航条不在同一个层次上,坐标系需要转换。
let navigationBar = navigationController.navigationBar // 系统导航条。
// 获取自定义导航条,并配置导航条。
let fromNavigationBar = (fromVC as? NavigationBarCustomizable)?.navigationBarIfLoaded
let toNavigationBar = (toVC as? NavigationBarCustomizable)?.navigationBarIfLoaded
// 导航条当前坐标系(这里获取到的是转场之后的导航条状态),已转换到转场容器内。
let navigationBarRect = navigationBar.convert(navigationBar.bounds, to: transitionContext.containerView)
// 根据导航条的变化来设置导航条。
let navigationBarTransition = TransitionType.init(forNavigationBarFrom: fromNavigationBar?.isHidden, to: toNavigationBar?.isHidden)
switch navigationBarTransition {
case .alwaysShow:
// 旧的导航条保持原样添加到动画视图上。
fromNavigationBar!.frame = navigationBar.convert(fromNavigationBar!.frame, to: transitionContext.containerView)
transitionContext.containerView.insertSubview(fromNavigationBar!, aboveSubview: fromView)
// 新的导航条与当前系统导航条一致。
toNavigationBar!.frame = navigationBarRect.offsetBy(dx: flag * -navigationBarRect.width / 3.0, dy: 0)
transitionContext.containerView.insertSubview(toNavigationBar!, aboveSubview: toView)
case .alwaysHide:
break // 始终隐藏,不需要做动画,自定义导航条(如果有)在转场之后添加到系统导航条上。
case .showToHide:
fromNavigationBar!.frame = navigationBar.convert(fromNavigationBar!.frame, to: transitionContext.containerView)
transitionContext.containerView.insertSubview(fromNavigationBar!, aboveSubview: fromView)
case .hideToShow:
toNavigationBar!.frame = navigationBarRect.offsetBy(dx: flag * -navigationBarRect.width / 3.0, dy: 0)
transitionContext.containerView.insertSubview(toNavigationBar!, aboveSubview: toView)
}
// 解决因为状态栏变化而造成的导航条布局问题。
fromNavigationBar?.setNeedsLayout()
toNavigationBar?.setNeedsLayout()
// 记录导航条当前位置,然后将导航条放到转场容器最底层(作为自定义导航条的背景)执行动画。
let navigationBarLocation = (
superview: navigationBar.superview,
frame: navigationBar.frame,
index: navigationBar.superview?.subviews.firstIndex(of: navigationBar)
)
navigationBar.frame = navigationBarRect
transitionContext.containerView.insertSubview(navigationBar, belowSubview: toView)
let containerBounds = transitionContext.containerView.bounds
let shadowView = ShadowView.init(frame: containerBounds)
transitionContext.containerView.insertSubview(shadowView, belowSubview: fromView)
let tabBarAnimator = TabBarAnimator.init(
navigationController: navigationController,
operation: .pop,
containerView: transitionContext.containerView,
from: (fromVC, fromViewFrame1, fromViewFrame2),
to: (toVC, toViewFrame1, toViewFrame2)
)
let duration = transitionDuration(using: transitionContext)
let options = animationOptions(forTransition: .push)
UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
fromView.frame = fromViewFrame2
toView.frame = toViewFrame2
shadowView.frame = containerBounds.offsetBy(dx: flag * containerBounds.width, dy: 0)
tabBarAnimator?.commitAnimation()
switch navigationBarTransition {
case .alwaysShow:
let frame = fromNavigationBar!.frame
fromNavigationBar!.frame = frame.offsetBy(dx: flag * frame.width, dy: 0)
toNavigationBar!.frame = navigationBarRect
case .alwaysHide: break
case .showToHide:
let frame = fromNavigationBar!.frame
fromNavigationBar!.frame = frame.offsetBy(dx: flag * frame.width, dy: 0)
case .hideToShow:
toNavigationBar!.frame = navigationBarRect
}
}, completion: { (finished) in
shadowView.removeFromSuperview()
// 恢复导航条原有位置。
if let superview = navigationBarLocation.superview, let index = navigationBarLocation.index {
superview.insertSubview(navigationBar, at: min(index, superview.subviews.count))
}
// 恢复 TabBar 。
tabBarAnimator?.completeAnimation(finished)
// 自定义导航条在转场过程中,仅仅作为转场效果出现,将起放置到导航条上有导航控制器处理,所以这里要移除。
fromNavigationBar?.removeFromSuperview()
toNavigationBar?.removeFromSuperview()
// 恢复导航条状态。如果将恢复操作放在 animationEnded(_:) 方法中,在Demo中没有问题,但是在实际项目中却遇到了未知问题:
// 页面A导航条透明,页面B导航条不透明。从 B 返回(pop)到 A ,如果操作取消,那么最终 B 页面的导航条属性为不透明,但是从布局(控制器view)上看却是透明的。
// 由于 animationEnded(_:) 是在控制器 viewDidAppear 或 viewDidDisappear 之后被调用(见页面底部文档),此时再来恢复导航条样式已无济于事。
// 至于在Demo中放在前后都可以,可能是因为计算少速度快导致的,但是项目计算量达时,放后面就无法及时抓取正确的状态,从而导致问题。
if transitionContext.transitionWasCancelled {
if let fromNavigationBar = fromNavigationBar {
navigationBar.isTranslucent = fromNavigationBar.isTranslucent
navigationBar.tintColor = fromNavigationBar.tintColor
navigationBar.isHidden = fromNavigationBar.isHidden
if #available(iOS 11.0, *) {
navigationBar.prefersLargeTitles = fromNavigationBar.prefersLargeTitles
}
} else {
navigationBar.isTranslucent = true
navigationBar.tintColor = nil
navigationBar.isHidden = true
if #available(iOS 11.0, *) {
navigationBar.prefersLargeTitles = false
}
}
transitionContext.completeTransition(false)
navigationBar.customizedBar = fromNavigationBar
} else {
transitionContext.completeTransition(true)
navigationBar.customizedBar = toNavigationBar
}
})
}
/// 导航条、工具条视图的转场类型,在转场过程中显示/隐藏状态变化。
public enum TransitionType {
/// 转场中始终显示。
case alwaysShow
/// 转场中始终隐藏。
case alwaysHide
/// 转场中由显示到隐藏。
case showToHide
/// 转场中由隐藏到显示。
case hideToShow
/// 导航条的转场状态。
public init(forNavigationBarFrom hidden1: Bool?, to hidden2: Bool?) {
if let fromHidden = hidden1 {
if let toHidden = hidden2 {
if fromHidden {
self = toHidden ? .alwaysHide : .hideToShow
} else {
self = toHidden ? .showToHide : .alwaysShow
}
} else {
self = fromHidden ? .alwaysHide : .showToHide
}
} else if let toHidden = hidden2 {
self = toHidden ? .alwaysHide : .hideToShow
} else {
self = .alwaysHide
}
}
/// 导航控制器转场时,其所在的 tabBar 转场状态。
public init?(forTabBarEmbedded navigationController: UINavigationController, operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) {
let viewControllers = navigationController.viewControllers
if viewControllers.isEmpty {
return nil
}
// 导航控制器栈中,只有所有控制器 hidesBottomBarWhenPushed 都为 false 时,tabBar 才不隐藏。
// 当配置转场动画时,导航控制器栈内控制器已经确定。Push 已包含新控制器,Pop 已不包含站内控制器。
switch operation {
case .push:
let fromHidden = viewControllers[0 ..< viewControllers.count - 1].contains(where: { $0.hidesBottomBarWhenPushed })
if !fromHidden && toVC.hidesBottomBarWhenPushed {
self = .showToHide
} else {
return nil
}
case .pop:
let toHidden = viewControllers.contains(where: { $0.hidesBottomBarWhenPushed })
if !toHidden && fromVC.hidesBottomBarWhenPushed {
self = .hideToShow
} else {
return nil
}
case .none: fallthrough
default:
return nil
}
}
}
/// TabBar 的转场动画控制器。
public class TabBarAnimator {
let tabBar: UITabBar
/// tabBar 的原始父视图。
let tabBarSuperview: UIView
/// tabBar 在原始父视图中的层级。
let tabBarIndex: Int
private let tabBarToFrame: CGRect
private(set) var isCompleted: Bool
deinit {
// 最后尝试恢复 tabBar 。
completeAnimation(true)
}
/// 确认动画,配置动画。
public func commitAnimation() {
guard !isCompleted else {
return
}
tabBar.isFrameFrozen = false
tabBar.frame = tabBarToFrame
tabBar.isFrameFrozen = true
}
/// 动画执行完毕后。
public func completeAnimation(_ isFinished: Bool) {
guard !isCompleted else {
return
}
isCompleted = true
tabBar.isFrameFrozen = false
let bounds = tabBarSuperview.bounds
tabBar.frame = CGRect.init(
x: bounds.minX,
y: bounds.maxY - tabBarToFrame.height,
width: tabBarToFrame.width,
height: tabBarToFrame.height
)
tabBarSuperview.insertSubview(tabBar, at: min(tabBarIndex, tabBarSuperview.subviews.count))
// 根据 Apple 官方的说法 hidesBottomBarWhenPushed 是单向的,一旦设置隐藏,tabBar 就再也不会显示了(Issue 39277909)。
// 所以不需要控制 tabBar 的显示和隐藏,只控制器动画就行了。因为如果官方不显示 tabBar 的话,不透明时,控制器是没有下边距的。
}
public typealias AnimationContext = (viewController: UIViewController, fromFrame: CGRect, toFrame: CGRect)
public let transitionType: TransitionType
public init?(navigationController: UINavigationController, operation: UINavigationController.Operation, containerView: UIView, from fromContext: AnimationContext, to toContext: AnimationContext) {
guard let tabBar = navigationController.tabBarController?.tabBar else { return nil }
guard let transitionType = TransitionType(forTabBarEmbedded: navigationController, operation: operation, from: fromContext.viewController, to: toContext.viewController) else {
return nil
}
guard let superview = tabBar.superview else { return nil }
self.isCompleted = false
// TODO: 存在一个未知 BUG : TabBar 在某些情况下无法恢复,暂无法复现步骤。
switch transitionType {
case .alwaysHide: return nil
case .alwaysShow: return nil
case .showToHide:
self.tabBar = tabBar
self.tabBarIndex = superview.subviews.firstIndex(of: tabBar)!
self.tabBarSuperview = superview
self.transitionType = .showToHide
tabBar.isFrameFrozen = false
let tabBarFrame = tabBar.frame
tabBar.frame = CGRect.init(
x: fromContext.fromFrame.minX,
y: containerView.bounds.maxY - tabBarFrame.height,
width: tabBarFrame.width,
height: tabBarFrame.height
)
containerView.insertSubview(tabBar, aboveSubview: fromContext.viewController.view)
self.tabBarToFrame = CGRect.init(
x: fromContext.toFrame.minX,
y: containerView.bounds.maxY - tabBarFrame.height,
width: tabBarFrame.width,
height: tabBarFrame.height
)
tabBar.isFrameFrozen = true
case .hideToShow:
self.tabBar = tabBar
self.tabBarIndex = superview.subviews.firstIndex(of: tabBar)!
self.tabBarSuperview = superview
self.transitionType = .hideToShow
tabBar.isFrameFrozen = false
let tabBarFrame = tabBar.frame
tabBar.frame = CGRect.init(
x: toContext.fromFrame.minX,
y: containerView.bounds.maxY - tabBarFrame.height,
width: tabBarFrame.width,
height: tabBarFrame.height
)
containerView.insertSubview(tabBar, aboveSubview: toContext.viewController.view)
self.tabBarToFrame = CGRect.init(
x: toContext.toFrame.minX,
y: containerView.bounds.maxY - tabBarFrame.height,
width: tabBarFrame.width,
height: tabBarFrame.height
)
tabBar.isFrameFrozen = true
}
}
}
/// 转场过程中的阴影视图。
public class ShadowView: UIView {
public override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 5.0
self.layer.shadowOffset = .zero
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
// 转场过程中,各个函数先后执行顺序:
//Push:
//
//navigationController(_:animationControllerFor:from:to:)
//navigationController(_:interactionControllerFor:)
//<Example.SampleViewController: 0x7fa1a4434440> viewDidLoad()
//<Example.SampleViewController: 0x7fa1a6835bb0> viewWillDisappear
//<Example.SampleViewController: 0x7fa1a4434440> viewWillAppear
//navigationController(_:willShow:animated:)
//animateTransition(using:)
//animatePushTransition(using:) Config Animation.
//<Example.SampleViewController: 0x7fa1a4434440> viewWillLayoutSubviews()
//<Example.SampleViewController: 0x7fa1a4434440> viewDidLayoutSubviews()
//animatePushTransition(using:) Animation finished 1.
//<Example.SampleViewController: 0x7fa1a6835bb0> viewDidDisappear
//<Example.SampleViewController: 0x7fa1a4434440> viewDidAppear
//navigationController(_:didShow:animated:)
//animationEnded
//animationController(_:animatedTransitionDidEnd:)
//animatePushTransition(using:) Animation finished 2.
//
//Pop:
//
//navigationController(_:animationControllerFor:from:to:)
//navigationController(_:interactionControllerFor:)
//<Example.SampleViewController: 0x7fa1a4436850> viewWillDisappear
//<Example.SampleViewController: 0x7fa1a4434440> viewWillAppear
//navigationController(_:willShow:animated:)
//animateTransition(using:)
//animatePopTransition(using:) Config Animation.
//animatePopTransition(using:) Animation finished 1.
//<Example.SampleViewController: 0x7fa1a4436850> viewDidDisappear
//<Example.SampleViewController: 0x7fa1a4434440> viewDidAppear
//navigationController(_:didShow:animated:)
//animationEnded
//animationController(_:animatedTransitionDidEnd:)
//animatePopTransition(using:) Animation finished 2.
//
//
//Push Cancelled:
//
//navigationController(_:animationControllerFor:from:to:)
//navigationController(_:interactionControllerFor:)
//<Example.SampleViewController: 0x7fa1a683f830> viewDidLoad()
//<Example.SampleViewController: 0x7fa1a4436850> viewWillDisappear
//<Example.SampleViewController: 0x7fa1a683f830> viewWillAppear
//navigationController(_:willShow:animated:)
//animateTransition(using:)
//animatePushTransition(using:) Config Animation.
//<Example.SampleViewController: 0x7fa1a683f830> viewWillLayoutSubviews()
//<Example.SampleViewController: 0x7fa1a683f830> viewDidLayoutSubviews()
//animatePushTransition(using:) Animation finished 1.
//<Example.SampleViewController: 0x7fa1a683f830> viewWillDisappear
//<Example.SampleViewController: 0x7fa1a683f830> viewDidDisappear
//<Example.SampleViewController: 0x7fa1a4436850> viewWillAppear
//<Example.SampleViewController: 0x7fa1a4436850> viewDidAppear
//animationEnded
//animationController(_:animatedTransitionDidEnd:)
//animatePushTransition(using:) Animation finished 2.
//
//Pop Cancelled:
//
//navigationController(_:animationControllerFor:from:to:)
//navigationController(_:interactionControllerFor:)
//<Example.SampleViewController: 0x7fa1a4436850> viewWillDisappear
//<Example.SampleViewController: 0x7fa1a4434440> viewWillAppear
//navigationController(_:willShow:animated:)
//animateTransition(using:)
//animatePopTransition(using:) Config Animation.
//animatePopTransition(using:) Animation finished 1.
//<Example.SampleViewController: 0x7fa1a4434440> viewWillDisappear
//<Example.SampleViewController: 0x7fa1a4434440> viewDidDisappear
//<Example.SampleViewController: 0x7fa1a4436850> viewWillAppear
//<Example.SampleViewController: 0x7fa1a4436850> viewDidAppear
//animationEnded
//animationController(_:animatedTransitionDidEnd:)
//animatePopTransition(using:) Animation finished 2.
| mit | d0ae2e7ab3e2abfadc5b1f0895bf64ff | 44.366771 | 204 | 0.638198 | 5.03024 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | nRF Toolbox/Profiles/DeviceFirmwareUpdate/ViewConrollers/DFUFirmwareInfo/Sections/DFUDeviceInfoSection.swift | 1 | 2802 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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
class DFUDeviceInfoSection: DFUActionSection {
var peripheral: Peripheral
let action: () -> ()
init(peripheral: Peripheral, action: @escaping () -> ()) {
self.peripheral = peripheral
self.action = action
}
func dequeCell(for index: Int, from tableView: UITableView) -> UITableViewCell {
guard index != 2 else {
let cell = tableView.dequeueCell(ofType: NordicActionTableViewCell.self)
cell.textLabel?.text = "Choose another device"
return cell
}
let cell = tableView.dequeueCell(ofType: NordicRightDetailTableViewCell.self)
let title = index == 0 ? "Name" : "Status"
let details = index == 0 ? peripheral.name : peripheral.peripheral.state.description
cell.textLabel?.text = title
cell.detailTextLabel?.text = details
cell.selectionStyle = .none
return cell
}
func reset() {
}
var numberOfItems: Int {
3
}
var sectionTitle: String {
"Device Info"
}
var id: Identifier<Section> {
"DFUDeviceInfoSection"
}
var isHidden: Bool { false }
}
| bsd-3-clause | 85f60d7e72b4ef9883a9ef605970b702 | 33.592593 | 92 | 0.689151 | 4.822719 | false | false | false | false |
charmaex/weather-up | WeatherUp/ScrollingView.swift | 1 | 5099 | //
// ScrollingView.swift
// WeatherUp
//
// Created by Jan Dammshäuser on 26.03.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import UIKit
protocol ScrollingViewDelegate: NSObjectProtocol {
func scrollingView(leftAlpha left: CGFloat, MoveWithRightAlpha right: CGFloat, arrow: CGFloat)
}
class ScrollingView: UIView {
var delegate: ScrollingViewDelegate!
fileprivate var _tappable = false
fileprivate var _positionInView: CGPoint!
fileprivate var _fullDrag: CGFloat!
fileprivate var _dragStart: CGFloat!
fileprivate var _horizontalPosition: CGFloat!
fileprivate var _offset: CGFloat!
fileprivate var _left: CGFloat {
return UIScreen.main.bounds.width - bounds.width / 2
}
fileprivate var _right: CGFloat {
return bounds.width / 2
}
fileprivate var _damping: CGFloat {
return ((_left + _right) / 2) * 0.25
}
fileprivate enum Direction {
case left
case right
case none
var opposite: Direction {
if self == .left {
return .right
}
if self == .right {
return .left
}
return .none
}
}
func activate() {
_tappable = true
}
fileprivate func deactivate() {
_tappable = false
}
func reset() {
if let horizontalPosition = _horizontalPosition {
_positionInView = CGPoint(x: _right, y: horizontalPosition)
}
delegate.scrollingView(leftAlpha: 1, MoveWithRightAlpha: 0, arrow: 1)
positionView()
deactivate()
}
func positionView() {
if _positionInView != nil {
center = _positionInView
}
}
fileprivate func setHorizontalPosition() {
_horizontalPosition = center.y
}
fileprivate func dragPercent(_ pos: CGFloat) -> (Direction, CGFloat) {
let dragAct = _dragStart - pos
let percentFull = abs(dragAct / _fullDrag)
let dir: Direction
if dragAct > 0 {
dir = .left
} else if dragAct < 0 {
dir = .right
} else {
dir = .none
}
let percent = percentFull <= 1 ? percentFull : 1
return (dir, percent)
}
fileprivate func arrowPercent(point pos: CGFloat) -> CGFloat {
let distance = _right - _left
return (pos - _left) / distance
}
fileprivate func arrowPercent(position pos: CGFloat) -> CGFloat {
return arrowPercent(point: pos + _offset)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard _tappable, let position = getPosition(touches) else {
return
}
_fullDrag = bounds.width - UIScreen.main.bounds.width
setHorizontalPosition()
_dragStart = position.x
_offset = center.x - position.x
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard _tappable, let position = getPosition(touches) else {
return
}
let newCenter = position.x + _offset
guard newCenter >= _left - _damping && newCenter <= _right + _damping else {
return
}
center = CGPoint(x: newCenter, y: _horizontalPosition)
guard newCenter >= _left && newCenter <= _right else {
return
}
let (dir, percent) = dragPercent(position.x)
let arrow = arrowPercent(position: position.x)
let leftAlpha: CGFloat
let rightAlpha: CGFloat
switch dir {
case .left:
leftAlpha = 1 - percent
rightAlpha = percent
case .right:
leftAlpha = percent
rightAlpha = 1 - percent
case .none:
return
}
delegate.scrollingView(leftAlpha: leftAlpha, MoveWithRightAlpha: rightAlpha, arrow: arrow)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard _tappable, let position = getPosition(touches) else {
return
}
let dragPos = position.x + _offset
let (dir, percent) = dragPercent(position.x)
var direction: Direction
if dragPos < _left || dragPos > _right {
direction = dir
} else {
direction = percent >= 0.2 ? dir : dir.opposite
}
let newCenter: CGFloat
let leftAlpha: CGFloat
let rightAlpha: CGFloat
var delay = 0.0
if direction == .none {
let x = center.x
let off: CGFloat
switch x {
case _left:
off = -15
direction = .left
case _right:
off = 15
direction = .right
default:
return
}
let centerPoint = CGPoint(x: x - off, y: _horizontalPosition)
delay = 0.1
UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseIn, animations: {
self.center = centerPoint
}, completion: { _ in })
}
switch direction {
case .left:
newCenter = _left
leftAlpha = 0
rightAlpha = 1
case .right:
newCenter = _right
leftAlpha = 1
rightAlpha = 0
case .none:
_positionInView = center
return
}
let arrow = arrowPercent(point: newCenter)
let centerPoint = CGPoint(x: newCenter, y: _horizontalPosition)
_positionInView = centerPoint
UIView.animate(withDuration: 0.3, delay: delay, usingSpringWithDamping: 0.6, initialSpringVelocity: 3, options: .curveEaseOut, animations: {
self.center = centerPoint
self.delegate.scrollingView(leftAlpha: leftAlpha, MoveWithRightAlpha: rightAlpha, arrow: arrow)
}) { _ in }
}
fileprivate func getPosition(_ input: Set<UITouch>) -> CGPoint? {
guard let touch = input.first else {
return nil
}
return touch.location(in: super.superview)
}
}
| gpl-3.0 | 301e24521c7f519f726ce1fceab41751 | 20.322176 | 142 | 0.677786 | 3.41555 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/OptimizelyFeatureFlagToolsViewModel.swift | 1 | 5487 | import Foundation
import KsApi
import Prelude
import ReactiveSwift
public typealias OptimizelyFeatures = [(OptimizelyFeature, Bool)]
public protocol OptimizelyFeatureFlagToolsViewModelOutputs {
var reloadWithData: Signal<OptimizelyFeatures, Never> { get }
var updateUserDefaultsWithFeatures: Signal<OptimizelyFeatures, Never> { get }
}
public protocol OptimizelyFeatureFlagToolsViewModelInputs {
func didUpdateUserDefaults()
func setFeatureAtIndexEnabled(index: Int, isEnabled: Bool)
func viewDidLoad()
}
public protocol OptimizelyFeatureFlagToolsViewModelType {
var inputs: OptimizelyFeatureFlagToolsViewModelInputs { get }
var outputs: OptimizelyFeatureFlagToolsViewModelOutputs { get }
}
public final class OptimizelyFeatureFlagToolsViewModel: OptimizelyFeatureFlagToolsViewModelType,
OptimizelyFeatureFlagToolsViewModelInputs,
OptimizelyFeatureFlagToolsViewModelOutputs {
public init() {
let didUpdateUserDefaultsAndUI = self.didUpdateUserDefaultsProperty.signal
.ksr_debounce(.seconds(1), on: AppEnvironment.current.scheduler)
let features = Signal.merge(
self.viewDidLoadProperty.signal,
didUpdateUserDefaultsAndUI
)
.map { _ in AppEnvironment.current.optimizelyClient?.allFeatures() }
.skipNil()
let optimizelyFeatures = features
.map { features in
features.map { feature -> (OptimizelyFeature, Bool) in
let isEnabledFromServer = AppEnvironment.current.optimizelyClient?
.isFeatureEnabled(featureKey: feature.rawValue) ?? false
let isEnabledFromUserDefaults = getValueFromUserDefaults(for: feature)
return (feature, isEnabledFromUserDefaults ?? isEnabledFromServer)
}
}
self.reloadWithData = optimizelyFeatures
self.updateUserDefaultsWithFeatures = optimizelyFeatures
.takePairWhen(self.setFeatureEnabledAtIndexProperty.signal.skipNil())
.map(unpack)
.map { features, index, isEnabled -> OptimizelyFeatures? in
let (feature, _) = features[index]
var mutatedFeatures = features
setValueInUserDefaults(for: feature, and: isEnabled)
mutatedFeatures[index] = (feature, isEnabled)
return mutatedFeatures
}
.skipNil()
}
private let setFeatureEnabledAtIndexProperty = MutableProperty<(Int, Bool)?>(nil)
public func setFeatureAtIndexEnabled(index: Int, isEnabled: Bool) {
self.setFeatureEnabledAtIndexProperty.value = (index, isEnabled)
}
private let didUpdateUserDefaultsProperty = MutableProperty(())
public func didUpdateUserDefaults() {
self.didUpdateUserDefaultsProperty.value = ()
}
private let viewDidLoadProperty = MutableProperty(())
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
public let reloadWithData: Signal<OptimizelyFeatures, Never>
public let updateUserDefaultsWithFeatures: Signal<OptimizelyFeatures, Never>
public var inputs: OptimizelyFeatureFlagToolsViewModelInputs { return self }
public var outputs: OptimizelyFeatureFlagToolsViewModelOutputs { return self }
}
// MARK: - Private Helpers
/** Returns the value of the User Defaults key in the AppEnvironment.
*/
private func getValueFromUserDefaults(for feature: OptimizelyFeature) -> Bool? {
switch feature {
case .commentFlaggingEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.commentFlaggingEnabled.rawValue]
case .projectPageStoryTabEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.projectPageStoryTabEnabled.rawValue]
case .rewardLocalPickupEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.rewardLocalPickupEnabled.rawValue]
case .paymentSheetEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.paymentSheetEnabled.rawValue]
case .settingsPaymentSheetEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.settingsPaymentSheetEnabled.rawValue]
case .facebookLoginDeprecationEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.facebookLoginDeprecationEnabled.rawValue]
}
}
/** Sets the value for the UserDefaults key in the AppEnvironment.
*/
private func setValueInUserDefaults(for feature: OptimizelyFeature, and value: Bool) {
switch feature {
case .commentFlaggingEnabled:
AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.commentFlaggingEnabled.rawValue] = value
case .projectPageStoryTabEnabled:
AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.projectPageStoryTabEnabled.rawValue] = value
case .rewardLocalPickupEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.rewardLocalPickupEnabled.rawValue] = value
case .paymentSheetEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.paymentSheetEnabled.rawValue] = value
case .settingsPaymentSheetEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.settingsPaymentSheetEnabled.rawValue] = value
case .facebookLoginDeprecationEnabled:
return AppEnvironment.current.userDefaults
.optimizelyFeatureFlags[OptimizelyFeature.facebookLoginDeprecationEnabled.rawValue] = value
}
}
| apache-2.0 | e9313205ac79367b3909f9bc759e0f15 | 38.47482 | 97 | 0.787862 | 5.296332 | false | false | false | false |
chinlam91/edx-app-ios | Test/MockNetworkManager.swift | 2 | 6137 | //
// MockNetworkManager.swift
// edX
//
// Created by Akiva Leffert on 5/22/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import edX
struct MockSuccessResult<Out> {
let data : Out
}
class MockNetworkManager: NetworkManager {
private class Interceptor : NSObject {
// Storing these as Any types is kind of ridiculous, but getting swift to contain a list
// of values with different type parameters doesn't work. One would think you could wrap it
// with a protocol and associated type, but that doesn't compile. We should revisit this as Swift improves
let matcher : Any
let response : Any
let delay : NSTimeInterval
init<Out>(matcher : NetworkRequest<Out> -> Bool, delay : NSTimeInterval, response : NetworkRequest<Out> -> NetworkResult<Out>) {
self.matcher = matcher as Any
self.response = response as Any
self.delay = delay
}
}
private var interceptors : [Interceptor] = []
let responseCache = MockResponseCache()
init(authorizationHeaderProvider: AuthorizationHeaderProvider? = nil, baseURL: NSURL) {
super.init(authorizationHeaderProvider: authorizationHeaderProvider, baseURL: baseURL, cache: responseCache)
}
func interceptWhenMatching<Out>(matcher: NetworkRequest<Out> -> Bool, afterDelay delay : NSTimeInterval = 0, withResponse response : NetworkRequest<Out> -> NetworkResult<Out>) -> Removable {
let interceptor = Interceptor(
matcher : matcher,
delay : delay,
response : response
)
interceptors.append(interceptor)
return BlockRemovable(action: { () -> Void in
self.removeInterceptor(interceptor)
})
}
/// Returns success with the given value
func interceptWhenMatching<Out>(matcher : NetworkRequest<Out> -> Bool, afterDelay delay : NSTimeInterval = 0, successResponse : () -> (NSData?, Out)) -> Removable {
return interceptWhenMatching(matcher, afterDelay: delay, withResponse: {[weak self] request in
let URLRequest = self!.URLRequestWithRequest(request).value!
let (data, value) = successResponse()
let response = NSHTTPURLResponse(URL: URLRequest.URL!, statusCode: 200, HTTPVersion: nil, headerFields: [:])
return NetworkResult(request: URLRequest, response: response, data: value, baseData: data, error: nil)
})
}
/// Returns failure with the given value
func interceptWhenMatching<Out>(matcher : (NetworkRequest<Out> -> Bool), afterDelay delay : NSTimeInterval = 0, statusCode : Int = 400, error : NSError = NSError.oex_unknownError()) -> Removable {
return interceptWhenMatching(matcher, afterDelay: delay, withResponse: {[weak self] request in
let URLRequest = self!.URLRequestWithRequest(request).value!
let response = NSHTTPURLResponse(URL: URLRequest.URL!, statusCode: statusCode, HTTPVersion: nil, headerFields: [:])
return NetworkResult(request: URLRequest, response: response, data: nil, baseData: nil, error: error)
})
}
private func removeInterceptor(interceptor : Interceptor) {
if let index = interceptors.indexOf(interceptor) {
self.interceptors.removeAtIndex(index)
}
}
override func taskForRequest<Out>(request: NetworkRequest<Out>, handler: NetworkResult<Out> -> Void) -> Removable {
dispatch_async(dispatch_get_main_queue()) {
for interceptor in self.interceptors {
if let matcher = interceptor.matcher as? NetworkRequest<Out> -> Bool,
response = interceptor.response as? NetworkRequest<Out> -> NetworkResult<Out>
where matcher(request)
{
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(interceptor.delay * NSTimeInterval(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
handler(response(request))
}
return
}
}
let URLRequest = self.URLRequestWithRequest(request).value!
handler(NetworkResult(request: URLRequest, response: nil, data: nil, baseData: nil, error: NSError.oex_unknownError()))
}
return BlockRemovable {}
}
func reset() {
self.responseCache.clear()
self.interceptors.removeAll()
}
}
class MockNetworkManagerTests : XCTestCase {
func testInterception() {
let manager = MockNetworkManager(authorizationHeaderProvider: nil, baseURL: NSURL(string : "http://example.com")!)
manager.interceptWhenMatching({ _ in true}, withResponse: { _ -> NetworkResult<String> in
NetworkResult(request : nil, response : nil, data : "Success", baseData : nil, error : nil)
})
let expectation = expectationWithDescription("Request sent")
let request = NetworkRequest(method: HTTPMethod.GET, path: "/test", deserializer: .DataResponse({ _ -> Result<String> in
XCTFail("Should not get here")
return Failure(nil)
}))
manager.taskForRequest(request) {result in
XCTAssertEqual(result.data!, "Success")
expectation.fulfill()
}
self.waitForExpectations()
}
func testNoInterceptorsFails() {
let manager = MockNetworkManager(authorizationHeaderProvider: nil, baseURL: NSURL(string : "http://example.com")!)
let expectation = expectationWithDescription("Request sent")
let request = NetworkRequest(method: HTTPMethod.GET, path: "/test", deserializer: .DataResponse({ _ -> Result<String> in
XCTFail("Should not get here")
return Failure(nil)
}))
manager.taskForRequest(request) {result in
XCTAssertNotNil(result.error)
expectation.fulfill()
}
self.waitForExpectations()
}
}
| apache-2.0 | 5df9a76a6a795280a338f60bb1b76559 | 41.916084 | 200 | 0.628157 | 5.135565 | false | false | false | false |
Eddpt/Hackerrank-Submissions | Hackrank-Submissions/Operators/Operators.playground/Contents.swift | 1 | 2639 | /*:
# Operators
**Objective**
In this challenge, you'll work with arithmetic operators. Check out the [Tutorial](https://www.hackerrank.com/challenges/30-operators/tutorial) tab for learning materials and an instructional video!
**Task**
Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost.
**Note:** Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result!
**Input Format**
There are `3` lines of numeric input:
- The first line has a double, `mealCost` (the cost of the meal before tax and tip).
- The second line has an integer, `tipPercent` (the percentage of being added as tip).
- The third line has an integer, `taxPercent` (the percentage of being added as tax).
**Output Format**
Print `"The total meal cost is totalCost dollars."`, where `totalCost` is the rounded integer result of the entire bill (`mealCost` with added tax and tip).
**Sample Input**
```
12.00
20
8
```
**Sample Output**
```
The total meal cost is 15 dollars.
```
**Explanation**
Given:
`mealCost = 12`, `tipPercent = 20`, `taxPercent = 8`
Calculations:
- `tip = 12 * 20 / 100 = 2.4`
- `tax = 12 * 8 / 100 = 0.96`
- `totalCost = mealCost + tip + tax = 12 + 2.4 + 0.96 = 15.36`
- `round(totalCost) = 15`
We round `totalCost` to the nearest dollar (integer) and then print our result:
```
The total meal cost is 15 dollars.
```
**Source:** [Hackerrank - Operators](https://www.hackerrank.com/challenges/30-operators)
*/
import Foundation
func readData() -> NSData {
return NSFileHandle.fileHandleWithStandardInput().availableData
}
func readString() -> String {
return String(data: readData(), encoding:NSUTF8StringEncoding)!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
func readArrayOfStrings() -> Array<String> {
return readString().componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
func readArrayOfDoubles() -> Array<Double> {
return readArrayOfStrings().map {
(str: String) -> Double in
return Double(str)!
}
}
let input = [12.0, 20, 8] //readArrayOfDoubles()
let mealCost = input.first!
let tipPercent = input[1]
let taxPercent = input.last!
let tip = mealCost * (tipPercent / 100)
let tax = mealCost * (taxPercent / 100)
let totalMealCost = mealCost + tip + tax
print("The total meal cost is \(Int(round(totalMealCost))) dollars.")
| mit | 94eb3613bbd9925528de73c236094d62 | 26.778947 | 231 | 0.701402 | 3.927083 | false | false | false | false |
ivan-konov/SwiftQueues | SwiftQueues.swift | 1 | 4009 | //The MIT License (MIT)
//
//Copyright (c) 2015 Ivan Konov
//
//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.
//
struct SwiftQueue <T: Equatable> {
typealias ElementType = T
private var storage = [ElementType]()
// MARK: Queryng the Queue
var count: Int {
return storage.count
}
var isEmpty: Bool {
return storage.isEmpty
}
func front() -> ElementType? {
return storage.first
}
func back() -> ElementType? {
return storage.last
}
func findElement(element: ElementType) -> Int? {
return storage.indexOf(element)
}
// MARK: Adding and Removing Elements
mutating func pushBack(element: ElementType) {
storage.append(element)
}
mutating func popFront() -> ElementType? {
guard let _ = storage.first else {
return nil
}
return storage.removeAtIndex(0)
}
mutating func clear() {
storage.removeAll()
}
}
// MARK: Debug
extension SwiftQueue: CustomStringConvertible {
var description: String {
return storage.description
}
}
// MARK: Iteration
extension SwiftQueue: SequenceType {
//the backing storage is an Array so we can simply return IndexingGenerator
//no need of custom GeneratorType implementations
func generate() -> IndexingGenerator<[ElementType]> {
return storage.generate()
}
}
struct SwiftDequeue <T: Equatable> {
typealias ElementType = T
private var storage = [ElementType]()
// MARK: Queryng the Dequeue
var count: Int {
return storage.count
}
var isEmpty: Bool {
return storage.isEmpty
}
func front() -> ElementType? {
return storage.first
}
func back() -> ElementType? {
return storage.last
}
func findElement(element: ElementType) -> Int? {
return storage.indexOf(element)
}
// MARK: Adding and Removing Elements
mutating func pushBack(element: ElementType) {
storage.append(element)
}
mutating func pushFront(element: ElementType) {
storage.insert(element, atIndex: 0)
}
mutating func popFront() -> ElementType? {
guard let first = storage.first else {
return nil
}
storage.removeAtIndex(0)
return first
}
mutating func popBack() -> ElementType? {
guard let _ = storage.last else {
return nil
}
return storage.removeLast()
}
mutating func clear() {
storage.removeAll()
}
}
// MARK: Debug
extension SwiftDequeue: CustomStringConvertible {
var description: String {
return storage.description
}
}
// MARK: Iteration
extension SwiftDequeue: SequenceType {
//the backing storage is an Array so we can simply return IndexingGenerator
//no need of custom GeneratorType implementations
func generate() -> IndexingGenerator<[ElementType]> {
return storage.generate()
}
} | mit | 7031789a5bfd68d55e052ee035074e67 | 24.220126 | 80 | 0.661761 | 4.656214 | false | false | false | false |
keyeMyria/edx-app-ios | Source/DiscussionNewCommentViewController.swift | 1 | 8871 | //
// DiscussionNewCommentViewController.swift
// edX
//
// Created by Tang, Jeff on 6/5/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
protocol DiscussionNewCommentViewControllerDelegate : class {
func newCommentController(controller : DiscussionNewCommentViewController, addedItem item: DiscussionResponseItem)
}
public class DiscussionNewCommentViewController: UIViewController, UITextViewDelegate {
private let ANSWER_LABEL_VISIBLE_HEIGHT : CGFloat = 15
public class Environment {
private let courseDataManager : CourseDataManager?
private let networkManager : NetworkManager?
private weak var router: OEXRouter?
public init(courseDataManager : CourseDataManager, networkManager : NetworkManager?, router: OEXRouter?) {
self.courseDataManager = courseDataManager
self.networkManager = networkManager
self.router = router
}
}
private let minBodyTextHeight: CGFloat = 66 // height for 3 lines of text
private let environment: Environment
weak var delegate: DiscussionNewCommentViewControllerDelegate?
@IBOutlet private var scrollView: UIScrollView!
@IBOutlet private var newCommentView: UIView!
@IBOutlet private var responseTitle: UILabel!
@IBOutlet private var answerLabel: UILabel!
@IBOutlet private var responseBody: UILabel!
@IBOutlet private var personTimeLabel: UILabel!
@IBOutlet private var contentTextView: OEXPlaceholderTextView!
@IBOutlet private var addCommentButton: UIButton!
@IBOutlet private var contentTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private var answerLabelHeightConstraint: NSLayoutConstraint!
private let insetsController = ContentInsetsController()
private let growingTextController = GrowingTextViewController()
private let item: DiscussionItem
private let courseID : String
private var editingStyle : OEXTextStyle {
let style = OEXMutableTextStyle(weight: OEXTextWeight.Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark())
style.lineBreakMode = .ByWordWrapping
return style
}
private var isEndorsed : Bool = false {
didSet {
answerLabelHeightConstraint.constant = isEndorsed ? ANSWER_LABEL_VISIBLE_HEIGHT : 0
}
}
public init(environment: Environment, courseID : String, item: DiscussionItem) {
self.environment = environment
self.item = item
self.courseID = courseID
super.init(nibName: nil, bundle: nil)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBAction func addCommentTapped(sender: AnyObject) {
// TODO convert to a spinner
addCommentButton.enabled = false
// create new response or comment
let apiRequest = DiscussionAPI.createNewComment(item.threadID, text: contentTextView.text, parentID: item.responseID)
environment.networkManager?.taskForRequest(apiRequest) {[weak self] result in
if let comment = result.data,
threadID = comment.threadId,
courseID = self?.courseID {
let dataManager = self?.environment.courseDataManager?.discussionManagerForCourseWithID(courseID)
dataManager?.commentAddedStream.send((threadID: threadID, comment: comment))
self?.dismissViewControllerAnimated(true, completion: nil)
}
else {
// TODO: error handling
}
}
}
private var responseTitleStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size : .Base, color : OEXStyles.sharedStyles().neutralXDark())
}
private var answerLabelStyle : OEXTextStyle {
return OEXTextStyle(weight: .Normal, size: .XSmall, color: OEXStyles.sharedStyles().utilitySuccessBase())
}
private var responseBodyStyle : OEXTextStyle {
return OEXTextStyle(weight: .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark())
}
private var personTimeLabelStyle : OEXTextStyle {
return OEXTextStyle(weight: .Normal, size: .XXXSmall, color: OEXStyles.sharedStyles().neutralBase())
}
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
NSBundle.mainBundle().loadNibNamed("DiscussionNewCommentView", owner: self, options: nil)
view.addSubview(newCommentView)
newCommentView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
}
setupContextFromItem(item)
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets
contentTextView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes
contentTextView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight()
contentTextView.textColor = OEXStyles.sharedStyles().neutralBase()
contentTextView.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle)
contentTextView.delegate = self
let tapGesture = UIGestureRecognizer()
tapGesture.addAction {[weak self] _ in
self?.contentTextView.resignFirstResponder()
}
self.newCommentView.addGestureRecognizer(tapGesture)
let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: nil)
cancelItem.oex_setAction { [weak self]() -> Void in
self?.dismissViewControllerAnimated(true, completion: nil)
}
self.navigationItem.leftBarButtonItem = cancelItem
self.addCommentButton.enabled = false
self.insetsController.setupInController(self, scrollView: scrollView)
self.growingTextController.setupWithScrollView(scrollView, textView: contentTextView, bottomView: addCommentButton)
}
public func textViewDidChange(textView: UITextView) {
self.validateAddButton()
self.growingTextController.handleTextChange()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.insetsController.updateInsets()
self.growingTextController.scrollToVisible()
}
private func validateAddButton() {
addCommentButton.enabled = !contentTextView.text.isEmpty
}
// For determining the context of the screen and also manipulating the relevant elements on screen
private func setupContextFromItem(item : DiscussionItem) {
let buttonTitle : String
let placeholderText : String
let navigationItemTitle : String
let itemTitle : String?
switch item {
case let .Post(post):
itemTitle = item.title
buttonTitle = OEXLocalizedString("ADD_RESPONSE", nil)
placeholderText = OEXLocalizedString("ADD_YOUR_RESPONSE", nil)
navigationItemTitle = OEXLocalizedString("ADD_A_RESPONSE", nil)
case let .Response(response):
itemTitle = nil
buttonTitle = OEXLocalizedString("ADD_COMMENT", nil)
placeholderText = OEXLocalizedString("ADD_YOUR_COMMENT", nil)
navigationItemTitle = OEXLocalizedString("ADD_A_COMMENT", nil)
responseTitle.snp_makeConstraints({ (make) -> Void in
make.height.equalTo(0)
})
}
self.isEndorsed = item.isEndorsed
responseTitle.attributedText = responseTitleStyle.attributedStringWithText(item.title)
responseBody.attributedText = responseBodyStyle.attributedStringWithText(item.body)
addCommentButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle, withTitle: buttonTitle)
contentTextView.placeholder = placeholderText
self.navigationItem.title = navigationItemTitle
answerLabel.attributedText = NSAttributedString.joinInNaturalLayout([
Icon.Answered.attributedTextWithStyle(answerLabelStyle, inline : true),
answerLabelStyle.attributedStringWithText(OEXLocalizedString("ANSWER", nil))])
let authorAttributedString = personTimeLabelStyle.attributedStringWithText(item.author)
let timeAttributedString = personTimeLabelStyle.attributedStringWithText(item.createdAt.timeAgoSinceNow())
personTimeLabel.attributedText = NSAttributedString.joinInNaturalLayout([authorAttributedString,timeAttributedString])
}
}
| apache-2.0 | 737faaa6f1139756e72ded175d12fee4 | 40.453271 | 130 | 0.683914 | 5.752918 | false | false | false | false |
SunLiner/Floral | Floral/Floral/Classes/Malls/Malls/Model/MallsCategory.swift | 1 | 2961 | //
// MallsCategory.swift
// Floral
//
// Created by 孙林 on 16/5/9.
// Copyright © 2016年 ALin. All rights reserved.
// 商品分类
import UIKit
class MallsCategory: NSObject {
// 描述
var fnDesc : String?
// id
var fnId : String?
// 类型名称
var fnName : String?
// 子序列
var childrenList : [MallsCategory]?
init(dict: [String : AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
// 哎呀, 我去! 我天真的以为和OC一样, 调用forkeypath也是可以的, 坑死我了!!!问题是还不报错
override func setValue(value: AnyObject?, forKey key: String) {
if key == "childrenList" {
if let tempValue = value {
let temp = tempValue as! [[String : AnyObject]]
var childrenCategory = [MallsCategory]()
for dict in temp {
childrenCategory.append(MallsCategory(dict: dict))
}
childrenList = childrenCategory
return
}
}
super.setValue(value, forKey: key)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
// MARK: - 序列化和反序列化
private let fnDesc_Key = "fnDesc"
private let fnId_Key = "fnId"
private let fnName_Key = "fnName"
private let childrenList_Key = "childrenList"
// 序列化
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(fnDesc, forKey: fnDesc_Key)
aCoder.encodeObject(fnId, forKey: fnId_Key)
aCoder.encodeObject(fnName, forKey: fnName_Key)
aCoder.encodeObject(childrenList, forKey: childrenList_Key)
}
// 反序列化
required init?(coder aDecoder: NSCoder) {
fnDesc = aDecoder.decodeObjectForKey(fnDesc_Key) as? String
fnId = aDecoder.decodeObjectForKey(fnId_Key) as? String
fnName = aDecoder.decodeObjectForKey(fnName_Key) as? String
childrenList = aDecoder.decodeObjectForKey(childrenList_Key) as? [MallsCategory]
}
// MARK: - 保存和获取所有分类
static let CategoriesKey = "MallsKey"
/**
保存所有的分类
- parameter categories: 分类数组
*/
class func savaCategories(categories: [MallsCategory])
{
let data = NSKeyedArchiver.archivedDataWithRootObject(categories)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: MallsCategory.CategoriesKey)
}
/**
取出本地保存的分类
- returns: 分类数组或者nil
*/
class func loadLocalCategories() -> [MallsCategory]?
{
if let array = NSUserDefaults.standardUserDefaults().objectForKey(MallsCategory.CategoriesKey)
{
return NSKeyedUnarchiver.unarchiveObjectWithData(array as! NSData) as? [MallsCategory]
}
return nil
}
}
| mit | cc095a309677364bc41a997e8813a109 | 27.8125 | 102 | 0.609544 | 4.159398 | false | false | false | false |
pirsquareff/travis-ci-getting-started | MovingHelper/ModelControllers/SectionSplitter.swift | 22 | 1177 | //
// SectionSplitter.swift
// MovingHelper
//
// Created by Ellen Shapiro on 6/9/15.
// Copyright (c) 2015 Razeware. All rights reserved.
//
import Foundation
/*
Helper struct to split up the array of tasks into sections based on the due date of each task.
*/
struct SectionSplitter {
private static func tasksForDueDate(dueDate: TaskDueDate, allTasks: [Task]) -> [Task] {
var tasks = allTasks.filter {
task in
return task.dueDate == dueDate
}
tasks.sortInPlace({ $0.taskID > $1.taskID })
return tasks
}
static func sectionsFromTasks(allTasks: [Task]) -> [[Task]] {
let oneMonthBefore = tasksForDueDate(.OneMonthBefore, allTasks: allTasks)
let oneWeekBefore = tasksForDueDate(.OneWeekBefore, allTasks: allTasks)
let oneDayBefore = tasksForDueDate(.OneDayBefore, allTasks: allTasks)
let oneDayAfter = tasksForDueDate(.OneDayAfter, allTasks: allTasks)
let oneWeekAfter = tasksForDueDate(.OneWeekAfter, allTasks: allTasks)
let oneMonthAfter = tasksForDueDate(.OneMonthAfter, allTasks: allTasks)
return [oneMonthBefore, oneWeekBefore, oneDayBefore, oneDayAfter, oneWeekAfter, oneMonthAfter]
}
} | mit | 687f7349586b403520b303e8adde2caf | 31.722222 | 98 | 0.719626 | 3.833876 | false | false | false | false |
brentsimmons/Evergreen | Account/Sources/Account/FeedProvider/Twitter/TwitterMention.swift | 1 | 652 | //
// TwitterMention.swift
// Account
//
// Created by Maurice Parker on 4/18/20.
// Copyright © 2020 Ranchero Software, LLC. All rights reserved.
//
import Foundation
struct TwitterMention: Codable, TwitterEntity {
let name: String?
let indices: [Int]?
let screenName: String?
let idStr: String?
enum CodingKeys: String, CodingKey {
case name = "url"
case indices = "indices"
case screenName = "screen_name"
case idStr = "idStr"
}
func renderAsHTML() -> String {
var html = String()
if let screenName = screenName {
html += "<a href=\"https://twitter.com/\(screenName)\">@\(screenName)</a>"
}
return html
}
}
| mit | 58c3c5f6aeec2ef7b7ffba6797735171 | 18.727273 | 77 | 0.660522 | 3.271357 | false | false | false | false |
dbruzzone/wishing-tree | iOS/Control/Control/BluetoothManager.swift | 1 | 4480 | //
// BluetoothManager.swift
// Control
//
// Created by Davide Bruzzone on 12/4/15.
// Copyright © 2015 Bitwise Samurai. All rights reserved.
//
import Foundation
import CoreBluetooth
// TODO
// The protocol that informs delegates when BluetoothManager-related events occur
protocol BluetoothManagerDelegate {
func hardwareReady()
func peripheralDiscovered()
}
// The protocol that informs delegates when peripheral-related events occur
protocol PeripheralDelegate {
func peripheralSelected(peripheral: CBPeripheral)
}
// The protocol that informs serviceDelegate when peripheral service-related events occur
protocol PeripheralServiceDelegate {
func servicesDiscovered(services: [CBService])
}
// The protocol that informs characteristicDelegate when service characteristic-related events occur
protocol ServiceCharacteristicDelegate {
func characteristicsDiscovered(characteristics: [CBCharacteristic])
}
class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
// The class' singleton instance
static let sharedInstance = BluetoothManager()
// TODO
var peripheralDelegate: BluetoothManagerDelegate?
var serviceDelegate: PeripheralServiceDelegate?
var characteristicDelegate: ServiceCharacteristicDelegate?
var centralManager: CBCentralManager?
var discoveredPeripherals: [CBPeripheral] = []
// The flag that indicates whether the central manager has been initialized - This only
// happens once when the BluetoothManager singleton is instantiated - and the Bluetooth
// hardware is ready
var hardwareReady: Bool = false
var scanning: Bool = false
override init () {
super.init()
}
func start() {
centralManager = CBCentralManager.init(delegate: self, queue: nil, options: nil)
}
func scan() {
centralManager!.scanForPeripheralsWithServices(nil, options: nil)
scanning = true
}
func stopScanning() {
centralManager!.stopScan()
scanning = false
}
func connectToPeripheral(peripheral: CBPeripheral) {
centralManager!.connectPeripheral(peripheral, options: nil)
}
func discoverCharacteristics(peripheral: CBPeripheral, service: CBService) {
peripheral.discoverCharacteristics(nil, forService: service)
}
// MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(central: CBCentralManager) {
switch (central.state) {
case CBCentralManagerState.PoweredOff:
print("The Bluetooth hardware is powered off")
case CBCentralManagerState.PoweredOn:
print("The Bluetooth hardware is ready")
hardwareReady = true
peripheralDelegate!.hardwareReady()
case CBCentralManagerState.Resetting:
print("The Bluetooth hardware is resetting")
case CBCentralManagerState.Unauthorized:
print("The Bluetooth hardware's state is unauthorized")
case CBCentralManagerState.Unknown:
print("The Bluetooth hardware's state is unknown")
case CBCentralManagerState.Unsupported:
print("The device doesn't have Bluetooth hardware")
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
if !(discoveredPeripherals.contains(peripheral)) {
discoveredPeripherals.append(peripheral)
print("Peripheral: \(peripheral)")
peripheralDelegate!.peripheralDiscovered()
}
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil)
}
// MARK: - CBPeripheralDelegate
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
for service: CBService in peripheral.services! {
print("Service: \(service)")
}
serviceDelegate!.servicesDiscovered(peripheral.services!)
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
for characteristic: CBCharacteristic in service.characteristics! {
print("Characteristic: \(characteristic)")
}
characteristicDelegate!.characteristicsDiscovered(service.characteristics!)
}
}
| gpl-3.0 | 367d55837b762fc431494f076b979058 | 30.992857 | 157 | 0.711766 | 5.734955 | false | false | false | false |
mssun/passforios | passKit/Extensions/Array+Slices.swift | 2 | 814 | //
// Array+Slices.swift
// passKit
//
// Created by Danny Moesch on 28.02.20.
// Copyright © 2020 Bob Sun. All rights reserved.
//
extension Array {
func slices(count: UInt) -> [ArraySlice<Element>] {
guard count != 0 else {
return []
}
let sizeEach = Int(self.count / Int(count))
var currentIndex = startIndex
var slices = [ArraySlice<Element>]()
for _ in 0 ..< count {
let toIndex = index(currentIndex, offsetBy: sizeEach, limitedBy: endIndex) ?? endIndex
slices.append(self[currentIndex ..< toIndex])
currentIndex = toIndex
}
if currentIndex != endIndex {
slices[slices.endIndex - 1].append(contentsOf: self[currentIndex ..< endIndex])
}
return slices
}
}
| mit | a58ab166638e79ccd49adcb1396c558d | 29.111111 | 98 | 0.575646 | 4.370968 | false | false | false | false |
skylib/SnapPageableArray | Example/ViewController.swift | 1 | 4292 | import UIKit
import SnapPageableArray
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView?
static let kPageSize: UInt = 40
var array = PageableArray<LocalData>(capacity: 960, pageSize: ViewController.kPageSize)
var genDataQueue: DispatchQueue = DispatchQueue(label: "genDataQueue", attributes: DispatchQueue.Attributes.concurrent)
override func viewDidLoad() {
super.viewDidLoad()
array.delegate = self
delay(3.0) {
self.reloadRandomRange()
}
delay(5.0) {
self.topUp()
}
}
func topUp() {
genDataQueue.async {
var data = [LocalData]()
for _ in 0..<ViewController.kPageSize {
data.append(self.genDataElement())
}
DispatchQueue.main.async {
let _ = self.array.topUpWithElements(data)
self.collectionView?.reloadData()
self.delay(5.0) {
self.topUp()
}
}
}
}
func reloadRandomRange() {
var start: UInt = UInt(Double(array.count) * drand48())
if start > array.count - ViewController.kPageSize {
start = array.count - ViewController.kPageSize
}
let end = start + ViewController.kPageSize
let range: CountableRange<UInt> = start..<end
loadContentForRange(range, pageSize: ViewController.kPageSize)
collectionView?.reloadData()
delay(3.0) {
self.reloadRandomRange()
}
}
func delay(_ secs: Double, f: @escaping () -> ()) {
let delayTime = DispatchTime.now() + Double(Int64(secs * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
f()
}
}
func genDataElement() -> LocalData {
var rnd: UInt64 = 0
arc4random_buf(&rnd, MemoryLayout.size(ofValue: rnd))
let color = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: CGFloat(drand48()))
return LocalData(id: rnd, color: color)
}
}
extension ViewController: PageableArrayDelegate {
func loadContentForRange(_ range: CountableRange<UInt>, pageSize: UInt) {
genDataQueue.async {
var data = [LocalData]()
for _ in 0..<pageSize {
data.append(self.genDataElement())
}
let pageNumber = range.lowerBound / pageSize
let page = Pageable(page: pageNumber, pageSize: pageSize)
DispatchQueue.main.async {
self.array.updatePage(page, withElements: data)
}
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Int(array.count)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath) as! Cell
let data = array[UInt((indexPath as NSIndexPath).item)]
cell.backgroundColor = data?.color ?? UIColor.clear
cell.setText(data?.cacheId ?? "N/A")
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let fullWidth = self.view.bounds.size.width
let width: CGFloat
if fullWidth >= 1024 {
width = (fullWidth - 45) / 8.0
} else if fullWidth >= 768 {
width = (fullWidth - 35) / 6.0
} else if fullWidth >= 414 {
width = (fullWidth - 20) / 3.0
} else {
width = (fullWidth - 15) / 2.0
}
return CGSize(width: floor(width), height: floor(width))
}
}
| bsd-3-clause | 6d9cc6dcf18973969bbb693a3e48a388 | 30.101449 | 160 | 0.58644 | 4.91638 | false | false | false | false |
aryshin2016/swfWeibo | WeiBoSwift/WeiBoSwift/Classes/SwiftClass/Weibo/MenuTableController.swift | 1 | 3121 | //
// MenuTableController.swift
// WeiBoSwift
//
// Created by itogame on 2017/8/23.
// Copyright © 2017年 itogame. All rights reserved.
//
import UIKit
class MenuTableController: 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 didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 9dd5257fd59d2eb5ba48d43a529ae0ee | 31.821053 | 136 | 0.669981 | 5.275804 | false | false | false | false |
darren90/Gankoo_Swift | Gankoo/Gankoo/Lib/Vendor/DatePicker/DateCollectionViewCell.swift | 2 | 2591 | //
// DateCollectionViewCell.swift
// DateTimePicker
//
// Created by Huong Do on 9/26/16.
// Copyright © 2016 ichigo. All rights reserved.
//
import UIKit
class DateCollectionViewCell: UICollectionViewCell {
var dayLabel: UILabel! // rgb(128,138,147)
var numberLabel: UILabel!
var darkColor = UIColor(red: 0, green: 22.0/255.0, blue: 39.0/255.0, alpha: 1)
var highlightColor = UIColor(red: 0/255.0, green: 199.0/255.0, blue: 194.0/255.0, alpha: 1)
override init(frame: CGRect) {
dayLabel = UILabel(frame: CGRect(x: 5, y: 15, width: frame.width - 10, height: 20))
dayLabel.font = UIFont.systemFont(ofSize: 10)
dayLabel.textAlignment = .center
numberLabel = UILabel(frame: CGRect(x: 5, y: 30, width: frame.width - 10, height: 40))
numberLabel.font = UIFont.systemFont(ofSize: 25)
numberLabel.textAlignment = .center
super.init(frame: frame)
contentView.addSubview(dayLabel)
contentView.addSubview(numberLabel)
contentView.backgroundColor = .white
contentView.layer.cornerRadius = 3
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isSelected: Bool {
didSet {
dayLabel.textColor = isSelected == true ? .white : darkColor.withAlphaComponent(0.5)
numberLabel.textColor = isSelected == true ? .white : darkColor
contentView.backgroundColor = isSelected == true ? highlightColor : .white
contentView.layer.borderWidth = isSelected == true ? 0 : 1
}
}
func populateItem(date: Date, highlightColor: UIColor, darkColor: UIColor) {
self.highlightColor = highlightColor
self.darkColor = darkColor
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
dayLabel.text = dateFormatter.string(from: date).uppercased()
dayLabel.textColor = isSelected == true ? .white : darkColor.withAlphaComponent(0.5)
let numberFormatter = DateFormatter()
numberFormatter.dateFormat = "d"
numberLabel.text = numberFormatter.string(from: date)
numberLabel.textColor = isSelected == true ? .white : darkColor
contentView.layer.borderColor = darkColor.withAlphaComponent(0.2).cgColor
contentView.backgroundColor = isSelected == true ? highlightColor : .white
}
}
| apache-2.0 | a574ef087a188e93bb3b38c91c8267ca | 37.088235 | 96 | 0.644402 | 4.567901 | false | false | false | false |
gigascorp/fiscal-cidadao | ios/FiscalCidadao/Denuncia.swift | 1 | 1261 | /*
Copyright (c) 2009-2014, Apple Inc. All rights reserved.
Copyright (C) 2016 Andrea Mendonça, Emílio Weba, Guilherme Ribeiro, Márcio Oliveira, Thiago Nunes, Wallas Henrique
This file is part of Fiscal Cidadão.
Fiscal Cidadão 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.
Fiscal Cidadão 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 Fiscal Cidadão. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
class Denuncia: NSObject
{
var id = 0
var photos = [String]()
var convenioId : Int
let userId : String?
var comments : String
var denunciaDate : String?
var status : String?
var convenio : Convenio?
init(convenioId : Int)
{
userId = Perfil.getUserIdByDevice()
self.convenioId = convenioId;
comments = ""
}
}
| gpl-3.0 | 12435ff14f6ec0896eb48f640bd29018 | 29.585366 | 116 | 0.710526 | 3.823171 | false | false | false | false |
matouka-suzuki/objc.io-swift-snippets | Permutations.playground/section-1.swift | 1 | 1003 | // Playground - noun: a place where people can play
// Permutations
// http://www.objc.io/snippets/10.html
/* Decompose Snippet
http://www.objc.io/snippets/1.html
*/
extension Array {
var decompose : (head: T, tail: [T])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
/* Flattening and mapping arrays
http://www.objc.io/snippets/4.html
*/
infix operator >>= {}
func >>=<A, B>(xs: [A], f: A -> [B]) -> [B] {
return xs.map(f).reduce([], combine: +)
}
// MARK: -
func between<T>(x: T, ys: [T]) -> [[T]]{
if let (head, tail) = ys.decompose {
return [[x] + ys] + between(x, tail).map { [head] + $0 }
} else {
return [[x]]
}
}
let array = between(0, [1, 2, 3])
func permutations<T>(xs: [T]) -> [[T]] {
if let (head, tail) = xs.decompose {
return permutations(tail) >>= { permTail in
between(head, permTail)
}
} else {
return [[]]
}
}
let permtationList = permutations([1,2,3]) | mit | e104a0c00b342a842b932f49695948cb | 20.361702 | 68 | 0.534397 | 2.967456 | false | false | false | false |
byss/KBAPISupport | KBAPISupport.playground/Sources/ResponseView.swift | 1 | 1057 | import AppKit
import Cocoa
public final class ResponseView: NSView {
public enum State {
case ready;
case loading;
case success;
case failure;
fileprivate var imageName: NSImage.Name {
switch (self) {
case .ready:
return NSImage.statusNoneName;
case .loading:
return NSImage.statusPartiallyAvailableName;
case .success:
return NSImage.statusAvailableName;
case .failure:
return NSImage.statusUnavailableName;
}
}
}
public var state: State {
didSet {
self.resultImage.image = NSImage (named: state.imageName);
}
}
private unowned let resultImage: NSImageView;
public override init (frame: NSRect) {
self.state = .ready;
let resultImage = NSImageView (frame: NSRect (origin: .zero, size: frame.size));
resultImage.autoresizingMask = [.width, .height];
resultImage.image = NSImage (named: self.state.imageName);
self.resultImage = resultImage;
super.init (frame: frame);
self.addSubview (resultImage);
}
public required init (coder aDecoder: NSCoder) {
fatalError ();
}
}
| mit | 382dc4df731f9b8d50a9d944e3930769 | 22.488889 | 82 | 0.707663 | 3.558923 | false | false | false | false |
MichaelSelsky/TheBeatingAtTheGates | Carthage/Checkouts/VirtualGameController/Samples/SceneKitDemo/SceneKitDemo/GameViewController.swift | 1 | 2754 | //
// GameViewController.swift
// SceneKitDemo
//
// Created by Rob Reuss on 12/8/15.
// Copyright (c) 2015 Rob Reuss. All rights reserved.
//
import QuartzCore
import SceneKit
import GameController
import VirtualGameController
#if os(iOS) || os(tvOS)
import UIKit
#endif
var ship: SCNNode!
var lightNode: SCNNode!
var cameraNode: SCNNode!
var sharedCode: SharedCode!
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
VgcManager.startAs(.Central, appIdentifier: "vgc", customElements: CustomElements(), customMappings: CustomMappings(), includesPeerToPeer: true)
// create a new scene
let scene = SCNScene(named: "art.scnassets/ship.scn")!
// create and add a camera to the scene
cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
// create and add a light to the scene
lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
lightNode.eulerAngles = SCNVector3Make(0.0, 3.1415/2.0, 0.0);
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
#if os(OSX)
ambientLightNode.light!.color = NSColor.darkGrayColor()
#endif
#if os(iOS) || os(tvOS)
ambientLightNode.light!.color = UIColor.darkGrayColor()
#endif
scene.rootNode.addChildNode(ambientLightNode)
// retrieve the ship node
ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
#if os(OSX)
scnView.backgroundColor = NSColor.blackColor()
#endif
#if os(iOS) || os(tvOS)
scnView.backgroundColor = UIColor.blackColor()
#endif
sharedCode = SharedCode()
sharedCode.setup(ship, lightNode: lightNode, cameraNode: cameraNode)
//scnView.delegate = sharedCode
}
}
| mit | 8a464a21fe28bae04e44a531c8c562b2 | 29.94382 | 152 | 0.621278 | 4.78125 | false | false | false | false |
lennet/proNotes | app/proNotes/Components/CircleView.swift | 1 | 1088 | //
// CircleView.swift
// proNotes
//
// Created by Leo Thomas on 24/12/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
@IBDesignable
class CircleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clear
}
override func prepareForInterfaceBuilder() {
backgroundColor = UIColor.clear
}
@IBInspectable
var radius: CGFloat = 10 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable
var strokeColor: UIColor = UIColor.black {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let circleRect = CGRect(center: bounds.getCenter(), size: CGSize(width: radius * 2, height: radius * 2))
strokeColor.setStroke()
context?.strokeEllipse(in: circleRect)
}
}
| mit | f10a805306b14b4c4157513e918801be | 19.12963 | 112 | 0.607176 | 4.685345 | false | false | false | false |
BareFeetWare/BFWDrawView | BFWDrawView/Modules/Draw/Model/Dictionary+Words.swift | 1 | 920 | //
// Dictionary+Words.swift
//
// Created by Tom Brodhurst-Hill on 9/05/2015.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
extension Dictionary where Key == String {
func object(forLongestPrefixKeyMatchingWordsIn wordsString: String) -> Value? {
guard let prefix = wordsString.longestWordsMatch(inPrefixes: Array(keys))
else { return nil }
return self[prefix]
}
func object(forWordsKey wordsKey: String) -> Value? {
let object: Value?
if let exactMatchObject = self[wordsKey] {
object = exactMatchObject
} else {
let searchKey = wordsKey.lowercasedWords
if let key = Array(keys).first(where: { searchKey == $0.lowercasedWords } ) {
object = self[key]
} else {
object = nil
}
}
return object
}
}
| mit | 4db14d475d3ee1517051a17658234ae0 | 28.677419 | 89 | 0.582609 | 4.319249 | false | false | false | false |
OpenStreetMap-Monitoring/OsMoiOs | iOsmo/TcpClient.swift | 2 | 10748 | //
// TcpClient.swift
// iOsmo
//
// Created by Olga Grineva on 25/03/15.
// Copyright (c) 2014 Olga Grineva, (c) 2016 Alexey Sirotkin. All rights reserved.
//
import Foundation
open class TcpClient : NSObject, StreamDelegate {
fileprivate var sendQueue = DispatchQueue(label: "com.iOsmo.SendQueue")
fileprivate let log = LogQueue.sharedLogQueue
private var inputStream: InputStream?
private var outputStream: OutputStream?
private var _messagesQueue:Array<String> = [String]()
open var callbackOnParse: ((String) -> Void)?
open var callbackOnError: ((Bool) -> Void)?
open var callbackOnSendStart: (() -> Void)?
open var callbackOnReceiveEnd: (() -> Void)?
open var callbackOnSendEnd: ((String) -> Void)?
open var callbackOnConnect: (() -> Void)?
open var callbackOnCloseConnection: (() -> Void)?
var isOpen = false
var authenticating = false;
deinit{
if let inputStr = self.inputStream{
inputStr.close()
inputStr.remove(from: RunLoop.main, forMode: RunLoop.Mode.default)
}
if let outputStr = self.outputStream{
outputStr.close()
outputStr.remove(from: RunLoop.main, forMode: RunLoop.Mode.default)
}
}
open func createConnection(_ token: Token){
if (token.port>0) {
if ( inputStream != nil || outputStream != nil ) {
self.closeConnection()
}
Stream.getStreamsToHost(withName: token.address, port: token.port, inputStream: &inputStream, outputStream: &outputStream)
if inputStream != nil && outputStream != nil {
isOpen = false
inputStream!.delegate = self
outputStream!.delegate = self
inputStream!.schedule(in: RunLoop.main, forMode: RunLoop.Mode.default)
outputStream!.schedule(in: RunLoop.main, forMode: RunLoop.Mode.default)
inputStream!.setProperty(StreamSocketSecurityLevel.tlSv1.rawValue, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outputStream!.setProperty(StreamSocketSecurityLevel.tlSv1.rawValue, forKey: Stream.PropertyKey.socketSecurityLevelKey)
inputStream!.open()
outputStream!.open()
} else {
log.enqueue("createConnection ERROR: nil stream")
}
}
}
final func openCompleted(stream: Stream){
log.enqueue("\(stream == self.inputStream ? "input" : "output") stream openCompleted")
if(inputStream?.streamStatus == .open && outputStream?.streamStatus == .open){
if isOpen == false {
isOpen = true
if (callbackOnConnect != nil) {
DispatchQueue.main.async {
self.callbackOnConnect!()
}
}
}
}
}
open func closeConnection() {
log.enqueue("closing input and output streams")
if (inputStream != nil) {
inputStream?.delegate = nil
inputStream?.close()
inputStream?.remove(from: RunLoop.main, forMode: RunLoop.Mode.default)
inputStream = nil
}
if (outputStream != nil) {
outputStream?.delegate = nil
outputStream?.close()
outputStream?.remove(from: RunLoop.main, forMode: RunLoop.Mode.default)
outputStream = nil
}
if (isOpen) {
isOpen = false
if (self.callbackOnCloseConnection != nil) {
DispatchQueue.main.async {
self.callbackOnCloseConnection!()
}
}
}
}
final func writeToStream(){
if (self.outputStream != nil && (isOpen == true || _messagesQueue.count % 10 == 0)) { //Пишем только в открытое соединение
if _messagesQueue.count > 0 /*&& self.outputStream!.hasSpaceAvailable */ {
var req: String = ""
sendQueue.sync {
req = self._messagesQueue.removeLast()
}
self.log.enqueue("c: \(req)")
let message = "\(req)\n"
if let outputStream = self.outputStream, let data = message.data(using: String.Encoding.utf8) {
if (self.callbackOnSendStart != nil) {
self.callbackOnSendStart!()
}
let wb = outputStream.write((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), maxLength: data.count)
if (wb == -1 ) {
sendQueue.async {
self._messagesQueue.append(message)
}
self.log.enqueue("error: write to output stream")
if self.callbackOnError != nil {
self.callbackOnError!(true)
}
return
}
if (self.callbackOnSendEnd != nil) {
self.callbackOnSendEnd!(req)
}
} else {
self.log.enqueue("error: send request")
if self.callbackOnError != nil {
self.callbackOnError!(true)
}
}
}
}
}
final func send(message:String){
let command = message.components(separatedBy: "|").first!
//Отправляем список координат ?
if command == Tags.buffer.rawValue {
var idx = 0;
sendQueue.sync {
//Удаляем из очереди сообщений все ранее неотправленные координаты, т.к. они должны содержаться в текущем запросе
for msg in _messagesQueue {
let cmd = msg.components(separatedBy: "|").first!
if cmd == Tags.buffer.rawValue || cmd == Tags.coordinate.rawValue {
_messagesQueue.remove(at: idx);
break;
} else {
idx = idx + 1
}
}
}
}
sendQueue.sync {
var should_add = true
if command == AnswTags.auth.rawValue {
if (self.authenticating) {
should_add = false
} else {
self.authenticating = true
}
} else {
self.authenticating = false
}
if should_add {
_messagesQueue.append(message)
}
}
writeToStream()
}
private var message = "";
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch (eventCode) {
case Stream.Event():
print ("None")
case Stream.Event.endEncountered:
log.enqueue("\(aStream == self.inputStream ? "input" : "output") stream endEcountered")
self.closeConnection()
if callbackOnError != nil {
let reconnect = aStream == self.inputStream ? false : true
callbackOnError!(reconnect)
}
return
case Stream.Event.openCompleted:
openCompleted(stream: aStream)
case Stream.Event.errorOccurred:
log.enqueue("\(aStream == self.inputStream ? "input" : "output") stream errorOccurred, connection is out")
//Были открыты оба потока ?
if (self.isOpen) {
//Ошибка возникла в потоке записи - тогда делаем попытку восстановить соединение
let reconnect = aStream == self.outputStream ? false : true
self.closeConnection()
if callbackOnError != nil {
callbackOnError!(reconnect)
}
}
case Stream.Event.hasSpaceAvailable:
writeToStream()
break
case Stream.Event.hasBytesAvailable:
let bufferSize = 1024
var buffer = [UInt8](repeating: 0, count: bufferSize)
var len: Int = 0
if let iStream = inputStream {
if (callbackOnSendStart != nil) {
callbackOnSendStart!()
}
while(iStream.hasBytesAvailable) {
len = iStream.read(&buffer, maxLength: bufferSize)
if len > 0 {
if let output = NSString(bytes: &buffer, length: len, encoding: String.Encoding.utf8.rawValue) {
message = "\(message)\(output)"
}
}
}
if (callbackOnReceiveEnd != nil) {
callbackOnReceiveEnd!()
}
} else {
log.enqueue("Stream is empty")
return
}
if !message.isEmpty {
//Копим сообщение, пока не получим от сервера \n
let responceSplit = message.components(separatedBy: "\n")
//print(message)
var count = 0
for res in responceSplit {
if !res.isEmpty{
let subst = message[message.index(message.endIndex, offsetBy: -1)..<message.endIndex]
if responceSplit.count < 2 && subst != "\n"{
return
} else {
log.enqueue("s: \(res)")
if let call = self.callbackOnParse {
call(res)
}
}
let resAdvance = res + "\n"
message = (responceSplit.count != count && message.endIndex >= resAdvance.endIndex) ? String(message[ resAdvance.endIndex..<message.endIndex]) : res
count += 1
}
}
}
default:
log.enqueue("Some unhandled event \(eventCode) was occured in stream")
}
}
}
| gpl-3.0 | 5a71501616edb21690ae0c6320a24293 | 37.233577 | 173 | 0.488545 | 5.245869 | false | false | false | false |
BrandonMA/SwifterUI | Improved SwifterUI.playground/Contents.swift | 1 | 28141 | import UIKit
import PlaygroundSupport
// MARK: - Layout
public typealias Constraint = NSLayoutConstraint
public typealias Constraints = [Constraint]
public struct SFDimension {
public var type: SFDimensionType
public var value: CGFloat
public static var zero: SFDimension = SFDimension(value: 0)
public enum SFDimensionType {
case point
case fraction
}
public init(type: SFDimensionType = .point, value: CGFloat) {
self.type = type
self.value = value
}
}
public enum ConstraintType: String {
case width
case height
case centerX
case centerY
case top
case right
case bottom
case left
}
public enum ConstraintAxis {
case horizontal
case vertical
}
public enum ConstraintEdge {
case top
case right
case bottom
case left
case centerX
case centerY
}
public enum ConstraintRelation {
case equal
case greater
case less
}
public extension Constraint {
@discardableResult
public final func set(identifier: String) -> Self {
self.identifier = identifier
return self
}
@discardableResult
public final func set(active: Bool) -> Self {
self.isActive = active
return self
}
}
public extension Array where Element: Constraint {
public func activate() { Constraint.activate(self) }
public func deactivate() { Constraint.deactivate(self) }
public func forEachConstraint(where view: UIView, completion: @escaping (Constraint) -> Void) {
forEach { (constraint) in
if let firstItem = constraint.firstItem as? UIView, firstItem == view {
completion(constraint)
}
}
}
}
extension NSLayoutDimension {
func constraint(to anchor: NSLayoutDimension, dimension: SFDimension, relation: ConstraintRelation = .equal, margin: CGFloat = 0.0, priority: UILayoutPriority = .required) -> Constraint {
let newConstraint: Constraint
switch dimension.type {
case .fraction:
switch relation {
case .equal: newConstraint = constraint(equalTo: anchor, multiplier: dimension.value, constant: margin)
case .greater: newConstraint = constraint(greaterThanOrEqualTo: anchor, multiplier: dimension.value, constant: margin)
case .less: newConstraint = constraint(lessThanOrEqualTo: anchor, multiplier: dimension.value, constant: margin)
}
case .point:
switch relation {
case .equal: newConstraint = constraint(equalToConstant: dimension.value)
case .greater: newConstraint = constraint(greaterThanOrEqualToConstant: dimension.value)
case .less: newConstraint = constraint(lessThanOrEqualToConstant: dimension.value)
}
}
newConstraint.priority = priority
return newConstraint
}
}
public enum SFError: String, Error {
case LayoutParent = "No parent found"
}
public protocol SFLayoutView {
func prepareSubviews()
func setConstraints()
func add(subView: UIView)
func getAnchorView(_ view: UIView?) -> UIView?
func getAllConstraints() -> Constraints
func removeAllConstraints()
func getConstraint(type constraintType: ConstraintType) -> Constraint?
func removeConstraint(type constraintType: ConstraintType)
func set(height: SFDimension?, relatedTo view: UIView?, relation: ConstraintRelation, margin: CGFloat, priority: UILayoutPriority) -> Constraint
func set(width: SFDimension?, relatedTo view: UIView?, relation: ConstraintRelation, margin: CGFloat, priority: UILayoutPriority) -> Constraint
func clipCenterX(to edge: ConstraintEdge, of view: UIView?, margin: CGFloat, relation: ConstraintRelation, priority: UILayoutPriority, useSafeArea: Bool) -> Constraint
}
extension SFLayoutView where Self: UIView {
public func add(subView: UIView) {
subView.translatesAutoresizingMaskIntoConstraints = false
addSubview(subView)
}
public func getAnchorView(_ view: UIView?) -> UIView? {
if let view = view {
return view
} else if let superview = superview {
return superview
} else {
return nil
}
}
public func getAllConstraints() -> Constraints {
var constraints: Constraints = []
self.constraints.forEachConstraint(where: self) { (constraint) in
constraints.append(constraint)
}
superview?.constraints.forEachConstraint(where: self, completion: { (constraint) in
constraints.append(constraint)
})
return constraints
}
public func removeAllConstraints() {
guard let superview = superview else { return }
let constraints = getAllConstraints()
constraints.forEach { [unowned self] (constraint) in
self.removeConstraint(constraint)
superview.removeConstraint(constraint)
}
}
public func getConstraint(type constraintType: ConstraintType) -> Constraint? {
var finalConstraint: Constraint?
func check(constraint: Constraint) {
if constraint.identifier == constraintType.rawValue {
finalConstraint = constraint
return
}
}
constraints.forEachConstraint(where: self) { check(constraint: $0) }
if finalConstraint == nil {
superview?.constraints.forEachConstraint(where: self, completion: { check(constraint: $0) })
}
return finalConstraint
}
public func removeConstraint(type constraintType: ConstraintType) {
guard let oldConstraint = getConstraint(type: constraintType) else { return }
self.removeConstraint(oldConstraint)
self.superview?.removeConstraint(oldConstraint)
}
public func set(height: SFDimension? = nil, relatedTo view: UIView? = nil, relation: ConstraintRelation = .equal, margin: CGFloat = 0.0, priority: UILayoutPriority = .required) -> Constraint {
guard let anchorView = getAnchorView(view) else { fatalError() }
let heightConstraint: Constraint
if let height = height {
heightConstraint = heightAnchor.constraint(to: anchorView.heightAnchor, dimension: height, relation: relation, margin: margin)
} else {
heightConstraint = heightAnchor.constraint(equalTo: anchorView.heightAnchor, multiplier: 1)
}
heightConstraint.set(active: true).set(identifier: ConstraintType.height.rawValue)
heightConstraint.priority = priority
return heightConstraint
}
public func set(width: SFDimension? = nil, relatedTo view: UIView? = nil, relation: ConstraintRelation = .equal, margin: CGFloat = 0.0, priority: UILayoutPriority = .required) -> Constraint {
guard let anchorView = getAnchorView(view) else { fatalError() }
let widthConstraint: Constraint
if let width = width {
widthConstraint = widthAnchor.constraint(to: anchorView.widthAnchor, dimension: width, relation: relation, margin: margin)
} else {
widthConstraint = widthAnchor.constraint(equalTo: anchorView.widthAnchor, multiplier: 1)
}
widthConstraint.set(active: true).set(identifier: ConstraintType.width.rawValue)
widthConstraint.priority = priority
return widthConstraint
}
private func clipEdge<Anchor>(childAnchor: NSLayoutAnchor<Anchor>,
parentAnchor: NSLayoutAnchor<Anchor>,
margin: CGFloat,
priority: UILayoutPriority,
relation: ConstraintRelation = .equal) -> Constraint {
let constraint: NSLayoutConstraint
switch relation {
case .equal:
constraint = childAnchor.constraint(equalTo: parentAnchor, constant: margin)
case .greater:
constraint = childAnchor.constraint(greaterThanOrEqualTo: parentAnchor, constant: margin)
case .less:
constraint = childAnchor.constraint(lessThanOrEqualTo: parentAnchor, constant: margin)
}
constraint.priority = priority
return constraint
}
private func clipYAxisAnchor(childAnchor: NSLayoutYAxisAnchor,
to edge: ConstraintEdge,
of view: UIView?,
margin: CGFloat,
relation: ConstraintRelation,
priority: UILayoutPriority,
useSafeArea: Bool) -> Constraint {
guard let anchorView = getAnchorView(view) else { fatalError() }
switch edge {
case .top:
return clipEdge(childAnchor: childAnchor,
parentAnchor: useSafeArea == true ? anchorView.safeAreaLayoutGuide.topAnchor : anchorView.topAnchor,
margin: margin,
priority: priority,
relation: relation)
case .bottom:
return clipEdge(childAnchor: childAnchor,
parentAnchor: useSafeArea == true ? anchorView.safeAreaLayoutGuide.bottomAnchor : anchorView.bottomAnchor,
margin: margin,
priority: priority,
relation: relation)
case .centerY:
return clipEdge(childAnchor: childAnchor,
parentAnchor: useSafeArea == true ? anchorView.safeAreaLayoutGuide.centerYAnchor : anchorView.centerYAnchor,
margin: margin,
priority: priority,
relation: relation)
default: fatalError()
}
}
private func clipXAxisAnchor(childAnchor: NSLayoutXAxisAnchor,
to edge: ConstraintEdge,
of view: UIView?,
margin: CGFloat,
relation: ConstraintRelation,
priority: UILayoutPriority,
useSafeArea: Bool) -> Constraint {
guard let anchorView = getAnchorView(view) else { fatalError() }
switch edge {
case .right:
return clipEdge(childAnchor: childAnchor,
parentAnchor: useSafeArea == true ? anchorView.safeAreaLayoutGuide.rightAnchor : anchorView.rightAnchor,
margin: margin,
priority: priority,
relation: relation)
case .left:
return clipEdge(childAnchor: childAnchor,
parentAnchor: useSafeArea == true ? anchorView.safeAreaLayoutGuide.leftAnchor : anchorView.leftAnchor,
margin: margin,
priority: priority,
relation: relation)
case .centerX:
return clipEdge(childAnchor: childAnchor,
parentAnchor: useSafeArea == true ? anchorView.safeAreaLayoutGuide.centerXAnchor : anchorView.centerXAnchor,
margin: margin,
priority: priority,
relation: relation)
default: fatalError()
}
}
public func clipCenterX(to edge: ConstraintEdge,
of view: UIView? = nil,
margin: CGFloat = 0,
relation: ConstraintRelation = .equal,
priority: UILayoutPriority = .required,
useSafeArea: Bool = true) -> Constraint {
return clipXAxisAnchor(childAnchor: centerXAnchor,
to: edge, of: view,
margin: margin,
relation: relation,
priority: priority,
useSafeArea: useSafeArea)
.set(identifier: ConstraintType.centerX.rawValue)
.set(active: true)
}
public func clipCenterY(to edge: ConstraintEdge,
of view: UIView? = nil,
margin: CGFloat = 0,
relation: ConstraintRelation = .equal,
priority: UILayoutPriority = .required,
useSafeArea: Bool = true) -> Constraint {
return clipYAxisAnchor(childAnchor: centerYAnchor,
to: edge, of: view,
margin: margin,
relation: relation,
priority: priority,
useSafeArea: useSafeArea)
.set(identifier: ConstraintType.centerY.rawValue)
.set(active: true)
}
public func clipTop(to edge: ConstraintEdge,
of view: UIView? = nil,
margin: CGFloat = 0,
relation: ConstraintRelation = .equal,
priority: UILayoutPriority = .required,
useSafeArea: Bool = true) -> Constraint {
return clipYAxisAnchor(childAnchor: topAnchor,
to: edge, of: view,
margin: margin,
relation: relation,
priority: priority,
useSafeArea: useSafeArea)
.set(identifier: ConstraintType.top.rawValue)
.set(active: true)
}
public func clipRight(to edge: ConstraintEdge,
of view: UIView? = nil,
margin: CGFloat = 0,
relation: ConstraintRelation = .equal,
priority: UILayoutPriority = .required,
useSafeArea: Bool = true) -> Constraint {
let margin = margin * -1
return clipXAxisAnchor(childAnchor: rightAnchor,
to: edge, of: view,
margin: margin,
relation: relation,
priority: priority,
useSafeArea: useSafeArea)
.set(identifier: ConstraintType.right.rawValue)
.set(active: true)
}
public func clipBottom(to edge: ConstraintEdge,
of view: UIView? = nil,
margin: CGFloat = 0,
relation: ConstraintRelation = .equal,
priority: UILayoutPriority = .required,
useSafeArea: Bool = true) -> Constraint {
let margin = margin * -1
return clipYAxisAnchor(childAnchor: bottomAnchor,
to: edge, of: view,
margin: margin,
relation: relation,
priority: priority,
useSafeArea: useSafeArea)
.set(identifier: ConstraintType.bottom.rawValue)
.set(active: true)
}
public func clipLeft(to edge: ConstraintEdge,
of view: UIView? = nil,
margin: CGFloat = 0,
relation: ConstraintRelation = .equal,
priority: UILayoutPriority = .required,
useSafeArea: Bool = true) -> Constraint {
return clipXAxisAnchor(childAnchor: leftAnchor,
to: edge, of: view,
margin: margin,
relation: relation,
priority: priority,
useSafeArea: useSafeArea)
.set(identifier: ConstraintType.left.rawValue)
.set(active: true)
}
public func center(in view: UIView? = nil,
margin: CGPoint = .zero,
priority: UILayoutPriority = .required) -> [Constraint] {
guard let anchorView = getAnchorView(view) else { fatalError() }
var constraints: [Constraint] = []
constraints.append(clipCenterX(to: .centerX,
of: anchorView,
margin: margin.x,
relation: .equal,
priority: priority,
useSafeArea: false))
constraints.append(clipCenterY(to: .centerY,
of: anchorView,
margin: margin.y,
relation: .equal,
priority: priority,
useSafeArea: false))
return constraints
}
public func clipSides(to view: UIView? = nil,
exclude: [ConstraintEdge] = [],
margin: UIEdgeInsets = .zero,
relation: ConstraintRelation = .equal,
priority: UILayoutPriority = .required,
useSafeArea: Bool = true) -> [Constraint] {
var constraints: [Constraint] = []
if exclude.contains(.top) == false {
constraints.append(clipTop(to: .top,
of: view,
margin: margin.top,
relation: relation,
priority: priority,
useSafeArea: useSafeArea))
}
if exclude.contains(.right) == false {
constraints.append(clipRight(to: .right,
of: view,
margin: margin.right,
relation: relation,
priority: priority,
useSafeArea: useSafeArea))
}
if exclude.contains(.bottom) == false {
constraints.append(clipBottom(to: .bottom,
of: view,
margin: margin.bottom,
relation: relation,
priority: priority,
useSafeArea: useSafeArea))
}
if exclude.contains(.left) == false {
constraints.append(clipLeft(to: .left,
of: view,
margin: margin.left,
relation: relation,
priority: priority,
useSafeArea: useSafeArea))
}
return constraints
}
}
// MARK: - Colors
public struct SFColorManager {
private(set) var currentColorScheme: SFColorScheme
private(set) var colorSchemes: Array<SFColorScheme> = []
private(set) var viewControllers: Array<SFViewController> = []
public var animationDuration: TimeInterval = 1.0
public init(colorScheme: SFColorScheme) {
currentColorScheme = colorScheme
register(colorScheme: colorScheme)
}
public init(colorSchemes: Array<SFColorScheme>, selectedIndex: Int = 0) {
currentColorScheme = colorSchemes[selectedIndex]
self.colorSchemes = colorSchemes
selectColorScheme(with: selectedIndex)
}
public mutating func register(colorScheme: SFColorScheme) {
colorSchemes.append(colorScheme)
}
public mutating func selectColorScheme(with identifier: String) {
colorSchemes.forEach { (colorScheme) in
if colorScheme.identifier == identifier {
currentColorScheme = colorScheme
updateColors()
}
}
}
public mutating func selectColorScheme(with index: Int = 0) {
currentColorScheme = colorSchemes[index]
updateColors()
}
public mutating func register(viewController: SFViewController) {
viewControllers.append(viewController)
viewController.updateViewColors(with: currentColorScheme)
}
public mutating func deregister(viewController: SFViewController) {
viewControllers.removeAll(where: { $0 === viewController })
}
public func updateColors() {
let animator = UIViewPropertyAnimator(duration: animationDuration, curve: .easeInOut) {
self.viewControllers.forEach { (viewController) in
viewController.updateViewColors(with: self.currentColorScheme)
}
}
animator.startAnimation()
}
}
public struct SFColorScheme {
public var identifier: String
public var backgroundColor: UIColor
public var textColor: UIColor
public var contrastBackgroundColor: UIColor
public var placeholderColor: UIColor
public var interactiveColor: UIColor
public var blurEffectStyle: UIBlurEffect.Style
public var scrollIndicatorStyle: UIScrollView.IndicatorStyle
public var activityIndicatorStyle: UIActivityIndicatorView.Style
public var separatorColor: UIColor
public var barStyle: UIBarStyle
public var statusBarStyle: UIStatusBarStyle
public var keyboardStyle: UIKeyboardAppearance
}
public protocol SFColorView {
func updateColors(with colorScheme: SFColorScheme)
func updateSubviewsColors(with colorScheme: SFColorScheme)
}
public protocol SFColorController {
var sfview: SFView! { get }
func updateViewColors(with colorScheme: SFColorScheme)
}
extension UIViewController: SFColorController {
public var sfview: SFView! { return view as? SFView }
public func updateViewColors(with colorScheme: SFColorScheme) {
sfview.updateColors(with: colorScheme)
}
}
// MARK: - Main
open class SFView: UIView, SFLayoutView, SFColorView {
open var identifier = "SFView"
public override init(frame: CGRect = .zero) {
super.init(frame: frame)
prepareSubviews()
setConstraints()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func prepareSubviews() {
}
open func setConstraints() {
}
public func updateColors(with colorScheme: SFColorScheme) {
backgroundColor = colorScheme.backgroundColor
tintColor = colorScheme.interactiveColor
updateSubviewsColors(with: colorScheme)
}
public func updateSubviewsColors(with colorScheme: SFColorScheme) {
subviews.forEach {
if let view = $0 as? SFColorView {
view.updateColors(with: colorScheme)
}
}
}
}
open class SFViewController: UIViewController {
// MARK: - Instance Properties
var statusBarIsHidden: Bool = false {
didSet {
self.setNeedsStatusBarAppearanceUpdate()
}
}
override open var prefersStatusBarHidden: Bool { return self.statusBarIsHidden }
var statusBarStyle: UIStatusBarStyle = .default {
didSet {
self.setNeedsStatusBarAppearanceUpdate()
}
}
override open var preferredStatusBarStyle: UIStatusBarStyle { return self.statusBarStyle }
var autorotate = true
override open var shouldAutorotate: Bool {
return self.autorotate
}
// MARK: - Initializers
public init() {
super.init(nibName: nil, bundle: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Instance Methods
open override func loadView() {
self.view = SFView()
}
open override func viewWillAppear(_ animated: Bool) {
if let navigationController = self.navigationController {
prepare(navigationController: navigationController)
}
if let tabBarController = self.tabBarController {
prepare(tabBarController: tabBarController)
}
}
open func prepare(navigationController: UINavigationController) {}
open func prepare(tabBarController: UITabBarController) {}
}
let colorSchemeOne = SFColorScheme(identifier: "White", backgroundColor: .white, textColor: .black, contrastBackgroundColor: .lightGray, placeholderColor: .lightText, interactiveColor: .blue, blurEffectStyle: .dark, scrollIndicatorStyle: .black, activityIndicatorStyle: .gray, separatorColor: .gray, barStyle: .default, statusBarStyle: .default, keyboardStyle: .light)
let colorSchemeTwo = SFColorScheme(identifier: "Black", backgroundColor: .black, textColor: .white, contrastBackgroundColor: .lightGray, placeholderColor: .lightText, interactiveColor: .orange, blurEffectStyle: .dark, scrollIndicatorStyle: .black, activityIndicatorStyle: .gray, separatorColor: .gray, barStyle: .default, statusBarStyle: .default, keyboardStyle: .light)
let colorSchemeThree = SFColorScheme(identifier: "Red", backgroundColor: .red, textColor: .white, contrastBackgroundColor: .lightGray, placeholderColor: .lightText, interactiveColor: .yellow, blurEffectStyle: .dark, scrollIndicatorStyle: .black, activityIndicatorStyle: .gray, separatorColor: .gray, barStyle: .default, statusBarStyle: .default, keyboardStyle: .light)
var colorManager = SFColorManager(colorSchemes: [colorSchemeOne, colorSchemeTwo, colorSchemeThree])
class View: SFView {
lazy var subview: SFView = {
let view = SFView()
return view
}()
override func prepareSubviews() {
add(subView: subview)
}
override func setConstraints() {
subview.set(width: SFDimension(type: .point, value: 50), priority: UILayoutPriority.init(rawValue: 800))
subview.set(height: SFDimension(type: .point, value: 50), priority: UILayoutPriority.init(rawValue: 800))
subview.center()
}
override func updateColors(with colorScheme: SFColorScheme) {
backgroundColor = colorScheme.interactiveColor
updateSubviewsColors(with: colorScheme)
}
}
class ViewController: SFViewController {
lazy var newView = View()
override func viewDidLoad() {
sfview.add(subView: newView)
newView.clipSides()
}
}
let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView
colorManager.register(viewController: viewController)
var constraint = viewController.newView.subview.set(width: SFDimension(type: .point, value: 100), priority: UILayoutPriority.init(rawValue: 1000))
constraint.isActive = false
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
colorManager.selectColorScheme(with: 1)
constraint.isActive = true
UIView.animate(withDuration: 0.3, animations: {
viewController.sfview.layoutIfNeeded()
})
}
DispatchQueue.main.asyncAfter(deadline: .now() + 8) {
colorManager.selectColorScheme(with: 2)
constraint.isActive = false
UIView.animate(withDuration: 0.3, animations: {
viewController.sfview.layoutIfNeeded()
})
}
| mit | b99140fe4aa3f785a0d2740f67fb1579 | 36.571429 | 370 | 0.572332 | 5.804662 | false | false | false | false |
qmathe/Confetti | Geometry/Geometry.swift | 1 | 4998 | //
// Confetti
//
// Created by Quentin Mathé on 02/06/2016.
// Copyright © 2016 Quentin Mathé. All rights reserved.
//
import Foundation
import Tapestry
public protocol Geometry {
/// The coordinate space transformation to obtain position,
/// orientation/rotation, and scale of an object from its parent coordinate
/// space.
///
/// This is used to convert geometrical values from the parent coordinate
/// space to the object coordinate space. For converting geometry values
/// in the reverse direction, the invert matrix can be used.
var transform: Matrix4 { get set }
/// The center (x, y, z) of the object expressed in the parent coordinate
/// space.
///
/// The position is derived from transform.
var position: Position { get set }
/// The top-left origin (x, y) of the object in the parent coordinate space,
/// but constrained to a Z plane passing through the center of the object
/// and tracking the rotation of the object.
///
/// This is usually useless when working with 3D objects which aren't planes.
///
/// The origin is derived from position and size.
var origin: Point { get set }
/// The coordinate space transformation to obtain the anchor point used to
/// manipulate the object and apply geometry changes.
var pivot: Matrix4 { get set }
/// The anchor point used to manipulate the object and apply geometry changes.
///
/// Can be used to position the pivot.
///
/// The anchor point is derived from position and pivot.
var anchor: Position { get set }
/// The dimensions (x, y, z) of the object expressed in the world coordinate
/// space.
///
/// The size is derived from the mesh.
var size: Size { get set }
/// The dimensions (x, y) of the object in the parent coordinate space,
/// but constrained to a Z plane passing through the center of the object
/// and tracking the rotation of the object.
///
/// This is usually useless when working with 3D objects which aren't planes.
///
/// The extent is derived from origin and size.
var extent: Extent { get set }
var frame: Rect { get }
/// The orientation of the object according to its width and height,
/// without considering its rotation and parent coordinate space.
///
/// This is usually useless when working with 3D objects which aren't planes.
///
/// Changing the orientation, swaps the width and height values.
var orientation: Orientation { get set }
var mesh: Mesh { get set }
}
public extension Geometry {
public var position: Position {
get { return Position(x: transform.m14, y: transform.m24, z: transform.m34) }
set { transform.m14 = newValue.x; transform.m24 = newValue.y }
}
public var size: Size {
get { return mesh.size }
set { mesh.size = newValue }
}
// TODO: Implement converting between world and parent coordinate spaces as
// documented in Geometry.extent.
public var extent: Extent {
get { return Extent(width: mesh.size.x, height: mesh.size.y) }
set { size = Size(x: newValue.width, y: newValue.height, z: size.z) }
}
public var frame: Rect {
get { return Rect(origin: origin, extent: extent) }
}
public var anchor: Position {
get { return position }
set { position = newValue }
}
var orientation: Orientation {
get {
if size.x == size.y {
return .none
}
else if size.x > size.y {
return .horizontal
}
else if size.x < size.y {
return .vertical
}
else {
fatalError("Unexpected size comparison")
}
}
set {
if orientation == newValue {
return
}
size = Size(x: size.y, y: size.x, z: size.z)
}
}
// MARK: - Converting Between Coordinate Spaces
/// Returns a rect expressed in the parent coordinate space equivalent to _rect_ parameter
/// expressed in the receiver coordinate space.
public func convertToParent(_ rect: Rect) -> Rect {
var rectInParent = rect
rectInParent.origin.x = rect.origin.x + origin.x
rectInParent.origin.y = rect.origin.y + origin.y
return rectInParent
}
/// Returns a rect expressed in the receiver coordinate space equivalent to _rect_ parameter
/// expressed in the parent coordinate space.
public func convertFromParent(_ rect: Rect) -> Rect {
var rectInReceiver = rect
rectInReceiver.origin.x = rect.origin.x - origin.x
rectInReceiver.origin.y = rect.origin.y - origin.y
return rectInReceiver
}
/// Returns a point expressed in the parent coordinate space equivalent to _point_ parameter
/// expressed in the receiver coordinate space.
public func convertToPoint(_ point: Point) -> Point {
return convertToParent(Rect(origin: point, extent: .zero)).origin
}
/// Returns a point expressed in the receiver coordinate space equivalent to _point_ parameter
/// expressed in the parent coordinate space.
public func convertFromParent(_ point: Point) -> Point {
return convertFromParent(Rect(origin: point, extent: .zero)).origin
}
}
| mit | 51c2a263dcb02477a04aa8bba903fd54 | 33.448276 | 98 | 0.685085 | 3.854167 | false | false | false | false |
RDCEP/ggcmi | bin/agg.isi1/agg.long.isi1.swift | 1 | 868 | type file;
app (file o) agglongisi1 (string model, string gcm, string crop, string co2, string rcp, string var) {
agglongisi1 model gcm crop co2 rcp var stdout = @o;
}
string models[] = strsplit(arg("models"), ",");
string gcms[] = strsplit(arg("gcms"), ",");
string crops[] = strsplit(arg("crops"), ",");
string co2s[] = strsplit(arg("co2s"), ",");
string rcps[] = strsplit(arg("rcps"), ",");
string vars[] = strsplit(arg("vars"), ",");
foreach m in models {
foreach g in gcms {
foreach c in crops {
foreach co in co2s {
foreach r in rcps {
foreach v in vars {
file logfile <single_file_mapper; file = strcat("logs/", m, ".", g, ".", c, ".", co, ".", r, ".", v, ".txt")>;
logfile = agglongisi1(m, g, c, co, r, v);
}
}
}
}
}
}
| agpl-3.0 | 2299774bce66de450e1958e495268dc7 | 31.148148 | 128 | 0.510369 | 3.263158 | false | false | false | false |
Fenrikur/ef-app_ios | EurofurenceTests/Presenter Tests/Announcement Detail/Test Doubles/StubAnnouncementDetailInteractor.swift | 1 | 689 | @testable import Eurofurence
import EurofurenceModel
import EurofurenceModelTestDoubles
import Foundation
struct StubAnnouncementDetailInteractor: AnnouncementDetailInteractor {
let viewModel: AnnouncementViewModel
private var identifier: AnnouncementIdentifier
init(viewModel: AnnouncementViewModel = .random, for identifier: AnnouncementIdentifier = .random) {
self.viewModel = viewModel
self.identifier = identifier
}
func makeViewModel(for announcement: AnnouncementIdentifier, completionHandler: @escaping (AnnouncementViewModel) -> Void) {
guard identifier == announcement else { return }
completionHandler(viewModel)
}
}
| mit | 71d638679a4f30a098688eaec6928323 | 31.809524 | 128 | 0.770682 | 6.097345 | false | true | false | false |
hfutrell/BezierKit | BezierKit/Library/Path.swift | 1 | 16881 | //
// BezierPath.swift
// BezierKit
//
// Created by Holmes Futrell on 7/31/18.
// Copyright © 2018 Holmes Futrell. All rights reserved.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
private extension Array {
/// if an array has unused capacity returns a new array where `self.count == self.capacity`
/// can save memory when an array is immutable after adding some initial items
var copyByTrimmingReservedCapacity: Self {
guard self.capacity > self.count else { return self }
return withUnsafeBufferPointer { Self($0) }
}
}
@objc(BezierKitPathFillRule) public enum PathFillRule: NSInteger {
case winding = 0, evenOdd
}
internal func windingCountImpliesContainment(_ count: Int, using rule: PathFillRule) -> Bool {
switch rule {
case .winding:
return count != 0
case .evenOdd:
return count % 2 != 0
}
}
open class Path: NSObject {
/// lock to make external accessing of lazy vars threadsafe
private let lock = UnfairLock()
private class PathApplierFunctionContext {
var currentPoint: CGPoint?
var componentStartPoint: CGPoint?
var currentComponentPoints: [CGPoint] = []
var currentComponentOrders: [Int] = []
var components: [PathComponent] = []
func completeComponentIfNeededAndClearPointsAndOrders() {
if currentComponentPoints.isEmpty == false {
if currentComponentOrders.isEmpty == true {
currentComponentOrders.append(0)
}
components.append(PathComponent(points: currentComponentPoints.copyByTrimmingReservedCapacity,
orders: currentComponentOrders.copyByTrimmingReservedCapacity))
}
currentComponentPoints = []
currentComponentOrders = []
}
func appendCurrentPointIfEmpty() {
if currentComponentPoints.isEmpty {
currentComponentPoints = [self.currentPoint!]
}
}
}
#if canImport(CoreGraphics)
public var cgPath: CGPath {
return self.lock.sync { self._cgPath }
}
private lazy var _cgPath: CGPath = {
let mutablePath = CGMutablePath()
self.components.forEach {
$0.appendPath(to: mutablePath)
}
return mutablePath.copy()!
}()
#endif
public var isEmpty: Bool {
return self.components.isEmpty // components are not allowed to be empty
}
public var boundingBox: BoundingBox {
return self.lock.sync { self._boundingBox }
}
/// the smallest bounding box completely enclosing the points of the path, includings its control points.
public var boundingBoxOfPath: BoundingBox {
return self.lock.sync { self._boundingBoxOfPath }
}
private lazy var _boundingBox: BoundingBox = {
return self.components.reduce(BoundingBox.empty) {
BoundingBox(first: $0, second: $1.boundingBox)
}
}()
private lazy var _boundingBoxOfPath: BoundingBox = {
return self.components.reduce(BoundingBox.empty) {
BoundingBox(first: $0, second: $1.boundingBoxOfPath)
}
}()
private var _hash: Int?
public let components: [PathComponent]
public func selfIntersects(accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> Bool {
return !self.selfIntersections(accuracy: accuracy).isEmpty
}
public func selfIntersections(accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> [PathIntersection] {
var intersections: [PathIntersection] = []
for i in 0..<self.components.count {
for j in i..<self.components.count {
let componentIntersectionToPathIntersection = {(componentIntersection: PathComponentIntersection) -> PathIntersection in
PathIntersection(componentIntersection: componentIntersection, componentIndex1: i, componentIndex2: j)
}
if i == j {
intersections += self.components[i].selfIntersections(accuracy: accuracy).map(componentIntersectionToPathIntersection)
} else {
intersections += self.components[i].intersections(with: self.components[j], accuracy: accuracy).map(componentIntersectionToPathIntersection)
}
}
}
return intersections
}
public func intersects(_ other: Path, accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> Bool {
return !self.intersections(with: other, accuracy: accuracy).isEmpty
}
public func intersections(with other: Path, accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> [PathIntersection] {
guard self.boundingBox.overlaps(other.boundingBox) else {
return []
}
var intersections: [PathIntersection] = []
for i in 0..<self.components.count {
for j in 0..<other.components.count {
let componentIntersectionToPathIntersection = {(componentIntersection: PathComponentIntersection) -> PathIntersection in
PathIntersection(componentIntersection: componentIntersection, componentIndex1: i, componentIndex2: j)
}
let s1 = self.components[i]
let s2 = other.components[j]
let componentIntersections: [PathComponentIntersection] = s1.intersections(with: s2, accuracy: accuracy)
intersections += componentIntersections.map(componentIntersectionToPathIntersection)
}
}
return intersections
}
#if os(WASI) || os(Linux)
public convenience override init() {
self.init(components: [])
}
#else
@objc public convenience override init() {
self.init(components: [])
}
#endif
required public init(components: [PathComponent]) {
self.components = components
}
#if canImport(CoreGraphics)
convenience public init(cgPath: CGPath) {
let context = PathApplierFunctionContext()
func applierFunction(_ ctx: UnsafeMutableRawPointer?, _ element: UnsafePointer<CGPathElement>) {
guard let context = ctx?.assumingMemoryBound(to: PathApplierFunctionContext.self).pointee else {
fatalError("unexpected applierFunction context")
}
let points: UnsafeMutablePointer<CGPoint> = element.pointee.points
switch element.pointee.type {
case .moveToPoint:
context.completeComponentIfNeededAndClearPointsAndOrders()
context.componentStartPoint = points[0]
context.currentComponentOrders = []
context.currentComponentPoints = [points[0]]
context.currentPoint = points[0]
case .addLineToPoint:
context.appendCurrentPointIfEmpty()
context.currentComponentOrders.append(1)
context.currentComponentPoints.append(points[0])
context.currentPoint = points[0]
case .addQuadCurveToPoint:
context.appendCurrentPointIfEmpty()
context.currentComponentOrders.append(2)
context.currentComponentPoints.append(points[0])
context.currentComponentPoints.append(points[1])
context.currentPoint = points[1]
case .addCurveToPoint:
context.appendCurrentPointIfEmpty()
context.currentComponentOrders.append(3)
context.currentComponentPoints.append(points[0])
context.currentComponentPoints.append(points[1])
context.currentComponentPoints.append(points[2])
context.currentPoint = points[2]
case .closeSubpath:
if context.currentPoint != context.componentStartPoint {
context.currentComponentOrders.append(1)
context.currentComponentPoints.append(context.componentStartPoint!)
}
context.completeComponentIfNeededAndClearPointsAndOrders()
context.currentPoint = context.componentStartPoint!
@unknown default:
fatalError("unexpected unknown path element type \(element.pointee.type)")
}
}
withUnsafePointer(to: context) {
let rawPointer = UnsafeMutableRawPointer(mutating: $0)
cgPath.apply(info: rawPointer, function: applierFunction)
}
context.completeComponentIfNeededAndClearPointsAndOrders()
self.init(components: context.components)
}
public func apply(info: UnsafeMutableRawPointer?, function: CGPathApplierFunction) {
self.components.forEach {
$0.apply(info: info, function: function)
}
}
#endif
convenience public init(curve: BezierCurve) {
self.init(components: [PathComponent(curve: curve)])
}
convenience internal init(rect: CGRect) {
let points = [rect.origin,
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y),
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height),
CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height),
rect.origin]
let component = PathComponent(points: points, orders: [Int](repeating: 1, count: 4))
self.init(components: [component])
}
// MARK: - NSCoding
// (cannot be put in extension because init?(coder:) is a designated initializer)
public static var supportsSecureCoding: Bool {
return true
}
#if !os(WASI)
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.data)
}
required public convenience init?(coder aDecoder: NSCoder) {
guard let data = aDecoder.decodeData() else { return nil }
self.init(data: data)
}
#endif
// MARK: -
override open func isEqual(_ object: Any?) -> Bool {
// override is needed because NSObject implementation of isEqual(_:) uses pointer equality
guard let otherPath = object as? Path else {
return false
}
return self.components == otherPath.components
}
private func assertValidComponent(_ location: IndexedPathLocation) {
assert(location.componentIndex >= 0 && location.componentIndex < self.components.count)
}
public func point(at location: IndexedPathLocation) -> CGPoint {
self.assertValidComponent(location)
return self.components[location.componentIndex].point(at: location.locationInComponent)
}
public func derivative(at location: IndexedPathLocation) -> CGPoint {
self.assertValidComponent(location)
return self.components[location.componentIndex].derivative(at: location.locationInComponent)
}
public func normal(at location: IndexedPathLocation) -> CGPoint {
self.assertValidComponent(location)
return self.components[location.componentIndex].normal(at: location.locationInComponent)
}
internal func windingCount(_ point: CGPoint, ignoring: PathComponent? = nil) -> Int {
let windingCount = self.components.reduce(0) {
if $1 !== ignoring {
return $0 + $1.windingCount(at: point)
} else {
return $0
}
}
return windingCount
}
public func contains(_ point: CGPoint, using rule: PathFillRule = .winding) -> Bool {
let count = self.windingCount(point)
return windingCountImpliesContainment(count, using: rule)
}
public func contains(_ other: Path, using rule: PathFillRule = .winding, accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> Bool {
// first, check that each component of `other` starts inside self
for component in other.components {
let p = component.startingPoint
guard self.contains(p, using: rule) else {
return false
}
}
// next, for each intersection (if there are any) check that we stay inside the path
// TODO: use enumeration over intersections so we don't have to necessarily have to find each one
// TODO: make this work with winding fill rule and intersections that don't cross (suggestion, use AugmentedGraph)
return !self.intersects(other, accuracy: accuracy)
}
public func offset(distance d: CGFloat) -> Path {
return Path(components: self.components.compactMap {
$0.offset(distance: d)
})
}
public func disjointComponents() -> [Path] {
let rule: PathFillRule = .evenOdd
var outerComponents: [PathComponent: [PathComponent]] = [:]
var innerComponents: [PathComponent] = []
// determine which components are outer and which are inner
for component in self.components {
let windingCount = self.windingCount(component.startingPoint, ignoring: component)
if windingCountImpliesContainment(windingCount, using: rule) {
innerComponents.append(component)
} else {
outerComponents[component] = [component]
}
}
// file the inner components into their "owning" outer components
for component in innerComponents {
var owner: PathComponent?
for outer in outerComponents.keys {
if let owner = owner {
guard outer.boundingBox.intersection(owner.boundingBox) == outer.boundingBox else { continue }
}
if outer.contains(component.startingPoint, using: rule) {
owner = outer
}
}
if let owner = owner {
outerComponents[owner]?.append(component)
}
}
return outerComponents.values.map { Path(components: $0) }
}
public override var hash: Int {
// override is needed because NSObject hashing is independent of Swift's Hashable
return lock.sync {
if let _hash = _hash { return _hash }
var hasher = Hasher()
for component in components {
hasher.combine(component)
}
let h = hasher.finalize()
_hash = h
return h
}
}
}
#if !os(WASI)
extension Path: NSSecureCoding {}
#endif
extension Path: Transformable {
public func copy(using t: CGAffineTransform) -> Self {
return type(of: self).init(components: self.components.map { $0.copy(using: t)})
}
}
extension Path: Reversible {
public func reversed() -> Self {
return type(of: self).init(components: self.components.map { $0.reversed() })
}
}
public struct IndexedPathLocation: Equatable, Comparable {
public let componentIndex: Int
public let elementIndex: Int
public let t: CGFloat
public init(componentIndex: Int, elementIndex: Int, t: CGFloat) {
self.componentIndex = componentIndex
self.elementIndex = elementIndex
self.t = t
}
public init(componentIndex: Int, locationInComponent: IndexedPathComponentLocation) {
self.init(componentIndex: componentIndex, elementIndex: locationInComponent.elementIndex, t: locationInComponent.t)
}
public static func < (lhs: IndexedPathLocation, rhs: IndexedPathLocation) -> Bool {
if lhs.componentIndex < rhs.componentIndex {
return true
} else if lhs.componentIndex > rhs.componentIndex {
return false
}
if lhs.elementIndex < rhs.elementIndex {
return true
} else if lhs.elementIndex > rhs.elementIndex {
return false
}
return lhs.t < rhs.t
}
public var locationInComponent: IndexedPathComponentLocation {
return IndexedPathComponentLocation(elementIndex: self.elementIndex, t: self.t)
}
}
public struct PathIntersection: Equatable {
public let indexedPathLocation1, indexedPathLocation2: IndexedPathLocation
internal init(indexedPathLocation1: IndexedPathLocation, indexedPathLocation2: IndexedPathLocation) {
self.indexedPathLocation1 = indexedPathLocation1
self.indexedPathLocation2 = indexedPathLocation2
}
fileprivate init(componentIntersection: PathComponentIntersection, componentIndex1: Int, componentIndex2: Int) {
self.indexedPathLocation1 = IndexedPathLocation(componentIndex: componentIndex1, locationInComponent: componentIntersection.indexedComponentLocation1)
self.indexedPathLocation2 = IndexedPathLocation(componentIndex: componentIndex2, locationInComponent: componentIntersection.indexedComponentLocation2)
}
}
| mit | f1f13ae8d0d7f5bc2f1d75408087320b | 38.624413 | 160 | 0.640699 | 4.957416 | false | false | false | false |
navrit/dosenet-apps | iOS/DoseNet/Pods/JLToast/JLToast/JLToastView.swift | 4 | 8130 | /*
* JLToastView.swift
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2013-2015 Su Yeol Jeon
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*
*/
import UIKit
public let JLToastViewBackgroundColorAttributeName = "JLToastViewBackgroundColorAttributeName"
public let JLToastViewCornerRadiusAttributeName = "JLToastViewCornerRadiusAttributeName"
public let JLToastViewTextInsetsAttributeName = "JLToastViewTextInsetsAttributeName"
public let JLToastViewTextColorAttributeName = "JLToastViewTextColorAttributeName"
public let JLToastViewFontAttributeName = "JLToastViewFontAttributeName"
public let JLToastViewPortraitOffsetYAttributeName = "JLToastViewPortraitOffsetYAttributeName"
public let JLToastViewLandscapeOffsetYAttributeName = "JLToastViewLandscapeOffsetYAttributeName"
@objc public class JLToastView: UIView {
public var backgroundView: UIView!
public var textLabel: UILabel!
public var textInsets: UIEdgeInsets!
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let userInterfaceIdiom = UIDevice.currentDevice().userInterfaceIdiom
self.userInteractionEnabled = false
self.backgroundView = UIView()
self.backgroundView.frame = self.bounds
self.backgroundView.backgroundColor = self.dynamicType.defaultValueForAttributeName(
JLToastViewBackgroundColorAttributeName,
forUserInterfaceIdiom: userInterfaceIdiom
) as? UIColor
self.backgroundView.layer.cornerRadius = self.dynamicType.defaultValueForAttributeName(
JLToastViewCornerRadiusAttributeName,
forUserInterfaceIdiom: userInterfaceIdiom
) as! CGFloat
self.backgroundView.clipsToBounds = true
self.addSubview(self.backgroundView)
self.textLabel = UILabel()
self.textLabel.frame = self.bounds
self.textLabel.textColor = self.dynamicType.defaultValueForAttributeName(
JLToastViewTextColorAttributeName,
forUserInterfaceIdiom: userInterfaceIdiom
) as? UIColor
self.textLabel.backgroundColor = UIColor.clearColor()
self.textLabel.font = self.dynamicType.defaultValueForAttributeName(
JLToastViewFontAttributeName,
forUserInterfaceIdiom: userInterfaceIdiom
) as! UIFont
self.textLabel.numberOfLines = 0
self.textLabel.textAlignment = .Center;
self.addSubview(self.textLabel)
self.textInsets = (self.dynamicType.defaultValueForAttributeName(
JLToastViewTextInsetsAttributeName,
forUserInterfaceIdiom: userInterfaceIdiom
) as! NSValue).UIEdgeInsetsValue()
}
required convenience public init?(coder aDecoder: NSCoder) {
self.init()
}
func updateView() {
let deviceWidth = CGRectGetWidth(UIScreen.mainScreen().bounds)
let constraintSize = CGSize(width: deviceWidth * (280.0 / 320.0), height: CGFloat.max)
let textLabelSize = self.textLabel.sizeThatFits(constraintSize)
self.textLabel.frame = CGRect(
x: self.textInsets.left,
y: self.textInsets.top,
width: textLabelSize.width,
height: textLabelSize.height
)
self.backgroundView.frame = CGRect(
x: 0,
y: 0,
width: self.textLabel.frame.size.width + self.textInsets.left + self.textInsets.right,
height: self.textLabel.frame.size.height + self.textInsets.top + self.textInsets.bottom
)
var x: CGFloat
var y: CGFloat
var width:CGFloat
var height:CGFloat
let screenSize = UIScreen.mainScreen().bounds.size
let backgroundViewSize = self.backgroundView.frame.size
let orientation = UIApplication.sharedApplication().statusBarOrientation
let systemVersion = (UIDevice.currentDevice().systemVersion as NSString).floatValue
let userInterfaceIdiom = UIDevice.currentDevice().userInterfaceIdiom
let portraitOffsetY = self.dynamicType.defaultValueForAttributeName(
JLToastViewPortraitOffsetYAttributeName,
forUserInterfaceIdiom: userInterfaceIdiom
) as! CGFloat
let landscapeOffsetY = self.dynamicType.defaultValueForAttributeName(
JLToastViewLandscapeOffsetYAttributeName,
forUserInterfaceIdiom: userInterfaceIdiom
) as! CGFloat
if UIInterfaceOrientationIsLandscape(orientation) && systemVersion < 8.0 {
width = screenSize.height
height = screenSize.width
y = landscapeOffsetY
} else {
width = screenSize.width
height = screenSize.height
if UIInterfaceOrientationIsLandscape(orientation) {
y = landscapeOffsetY
} else {
y = portraitOffsetY
}
}
x = (width - backgroundViewSize.width) * 0.5
y = height - (backgroundViewSize.height + y)
self.frame = CGRect(x: x, y: y, width: backgroundViewSize.width, height: backgroundViewSize.height);
}
override public func hitTest(point: CGPoint, withEvent event: UIEvent!) -> UIView? {
if self.superview != nil {
let pointInWindow = self.convertPoint(point, toView: self.superview)
let contains = CGRectContainsPoint(self.frame, pointInWindow)
if contains && self.userInteractionEnabled {
return self
}
}
return nil
}
}
public extension JLToastView {
private struct Singleton {
static var defaultValues: [String: [UIUserInterfaceIdiom: AnyObject]] = [
// backgroundView.color
JLToastViewBackgroundColorAttributeName: [
.Unspecified: UIColor(white: 0, alpha: 0.7)
],
// backgroundView.layer.cornerRadius
JLToastViewCornerRadiusAttributeName: [
.Unspecified: 5
],
JLToastViewTextInsetsAttributeName: [
.Unspecified: NSValue(UIEdgeInsets: UIEdgeInsets(top: 6, left: 10, bottom: 6, right: 10))
],
// textLabel.textColor
JLToastViewTextColorAttributeName: [
.Unspecified: UIColor.whiteColor()
],
// textLabel.font
JLToastViewFontAttributeName: [
.Unspecified: UIFont.systemFontOfSize(12),
.Phone: UIFont.systemFontOfSize(12),
.Pad: UIFont.systemFontOfSize(16),
],
JLToastViewPortraitOffsetYAttributeName: [
.Unspecified: 30,
.Phone: 30,
.Pad: 60,
],
JLToastViewLandscapeOffsetYAttributeName: [
.Unspecified: 20,
.Phone: 20,
.Pad: 40,
],
]
}
class func defaultValueForAttributeName(attributeName: String,
forUserInterfaceIdiom userInterfaceIdiom: UIUserInterfaceIdiom)
-> AnyObject {
let valueForAttributeName = Singleton.defaultValues[attributeName]!
if let value: AnyObject = valueForAttributeName[userInterfaceIdiom] {
return value
}
return valueForAttributeName[.Unspecified]!
}
class func setDefaultValue(value: AnyObject,
forAttributeName attributeName: String,
userInterfaceIdiom: UIUserInterfaceIdiom) {
var values = Singleton.defaultValues[attributeName]!
values[userInterfaceIdiom] = value
Singleton.defaultValues[attributeName] = values
}
}
| mit | cb44b0cb0dae251def985c871a058307 | 37.714286 | 108 | 0.646617 | 5.638003 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios | Carthage/Checkouts/rides-ios-sdk/source/UberRides/Model/Product.swift | 1 | 8067 | //
// Product.swift
// UberRides
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// MARK: Products
/**
* Internal object that contains a list of Uber products.
*/
struct UberProducts: Codable {
var list: [Product]?
enum CodingKeys: String, CodingKey {
case list = "products"
}
}
// MARK: Product
/**
* Contains information for a single Uber product.
*/
@objc(UBSDKProduct) public class Product: NSObject, Codable {
/// Unique identifier representing a specific product for a given latitude & longitude.
@objc public private(set) var productID: String
/// Display name of product. Ex: "UberBLACK".
@objc public private(set) var name: String
/// Description of product. Ex: "The original Uber".
@objc public private(set) var productDescription: String
/// Capacity of product. Ex: 4, for a product that fits 4.
@objc public private(set) var capacity: Int
/// Image URL representing the product.
@objc public private(set) var imageURL: URL
/// The basic price details. See `PriceDetails` for structure.
@objc public private(set) var priceDetails: PriceDetails?
/// Allows users to get upfront fares, instead of time + distance.
@objc public private(set) var upfrontFareEnabled: Bool
/// Specifies whether this product allows cash payments
@objc public private(set) var cashEnabled: Bool
/// Specifies whether this product allows for the pickup and drop off of other riders during the trip
@objc public private(set) var isShared: Bool
/// The product group that this product belongs to
@objc public private(set) var productGroup: ProductGroup
enum CodingKeys: String, CodingKey {
case productID = "product_id"
case name = "display_name"
case productDescription = "description"
case capacity = "capacity"
case imageURL = "image"
case priceDetails = "price_details"
case upfrontFareEnabled = "upfront_fare_enabled"
case cashEnabled = "cash_enabled"
case isShared = "shared"
case productGroup = "product_group"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
productID = try container.decode(String.self, forKey: .productID)
name = try container.decode(String.self, forKey: .name)
productDescription = try container.decode(String.self, forKey: .productDescription)
capacity = try container.decode(Int.self, forKey: .capacity)
imageURL = try container.decode(URL.self, forKey: .imageURL)
priceDetails = try container.decodeIfPresent(PriceDetails.self, forKey: .priceDetails)
upfrontFareEnabled = try container.decode(Bool.self, forKey: .upfrontFareEnabled)
cashEnabled = try container.decode(Bool.self, forKey: .cashEnabled)
isShared = try container.decode(Bool.self, forKey: .isShared)
productGroup = try container.decode(ProductGroup.self, forKey: .productGroup)
}
}
// MARK: PriceDetails
/**
* Contains basic price details for an Uber product.
*/
@objc(UBSDKPriceDetails) public class PriceDetails: NSObject, Codable {
/// Unit of distance used to calculate fare (mile or km).
@objc public private(set) var distanceUnit: String
/// ISO 4217 currency code.
@objc public private(set) var currencyCode: String
/// The charge per minute (if applicable).
@objc public private(set) var costPerMinute: Double
/// The charge per distance unit (if applicable).
@objc public private(set) var costPerDistance: Double
/// The base price.
@objc public private(set) var baseFee: Double
/// The minimum price of a trip.
@objc public private(set) var minimumFee: Double
/// The fee if a rider cancels the trip after a grace period.
@objc public private(set) var cancellationFee: Double
/// Array containing additional fees added to the price. See `ServiceFee`.
@objc public private(set) var serviceFees: [ServiceFee]
enum CodingKeys: String, CodingKey {
case distanceUnit = "distance_unit"
case currencyCode = "currency_code"
case costPerMinute = "cost_per_minute"
case costPerDistance = "cost_per_distance"
case baseFee = "base"
case minimumFee = "minimum"
case cancellationFee = "cancellation_fee"
case serviceFees = "service_fees"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
distanceUnit = try container.decode(String.self, forKey: .distanceUnit)
currencyCode = try container.decode(String.self, forKey: .currencyCode)
costPerMinute = try container.decode(Double.self, forKey: .costPerMinute)
costPerDistance = try container.decode(Double.self, forKey: .costPerDistance)
baseFee = try container.decode(Double.self, forKey: .baseFee)
minimumFee = try container.decode(Double.self, forKey: .minimumFee)
cancellationFee = try container.decode(Double.self, forKey: .cancellationFee)
serviceFees = try container.decode([ServiceFee].self, forKey: .serviceFees)
}
}
// MARK: ServiceFee
/**
* Contains information for additional fees that can be added to the price of an Uber product.
*/
@objc(UBSDKServiceFee) public class ServiceFee: NSObject, Codable {
/// The name of the service fee.
@objc public private(set) var name: String
/// The amount of the service fee.
@objc public private(set) var fee: Double
enum CodingKeys: String, CodingKey {
case name = "name"
case fee = "fee"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
fee = try container.decode(Double.self, forKey: .fee)
}
}
/// Uber Product Category
@objc(UBSDKProductGroup) public enum ProductGroup: Int, Codable {
/// Shared rides products (eg, UberPOOL)
case rideshare
/// UberX
case uberX
/// UberXL
case uberXL
/// UberBLACK
case uberBlack
/// UberSUV
case suv
/// 3rd party taxis
case taxi
/// Unknown product group
case unknown
public init(from decoder: Decoder) throws {
let string = try decoder.singleValueContainer().decode(String.self).lowercased()
switch string {
case "rideshare":
self = .rideshare
case "uberx":
self = .uberX
case "uberxl":
self = .uberXL
case "uberblack":
self = .uberBlack
case "suv":
self = .suv
case "taxi":
self = .taxi
default:
self = .unknown
}
}
}
| mit | 60060b8a7345c75f2e9f3e2e8cf2997b | 36 | 105 | 0.673196 | 4.329576 | false | false | false | false |
BrisyIOS/zhangxuWeiBo | zhangxuWeiBo/zhangxuWeiBo/SwiftHeader.swift | 1 | 1680 | //
// SwiftHeader.swift
// zhangxuWeiBo
//
// Created by zhangxu on 16/6/11.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
// 屏幕宽度
let kScreenWidth = UIScreen.mainScreen().bounds.width;
// 屏幕高度
let kScreenHeight = UIScreen.mainScreen().bounds.height;
// 是否为iOS8版本
let IOS8 = Double(UIDevice.currentDevice().systemVersion) >= 8.0;
// document路径
let kDocumentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0];
// APPkey可以信息
let ZXAppKey = "594327966";
let ZXAppSecret = "e7536dd658b432a88080fd2a91f59082";
let ZXRedirectURL = "http://www.baidu.com";
let kCellMargin = CGFloat(8);
let kCellPadding = CGFloat(10);
let kPhotoW = CGFloat(70);
let kPhotoMargin = CGFloat(10);
let kPhotoH = CGFloat(70);
let kRepostedContentLabelFont = UIFont.systemFontOfSize(13);
let kEmotionMaxRows = 3;
let kEmotionMaxCols = 7;
let ZXEmotionDidSelectedNotification = "ZXEmotionDidSelectedNotification";
let ZXSelectedEmotion = "ZXSelectedEmotion";
let ZXEmotionDidDeletedNotification = "ZXEmotionDidDeletedNotification";
// 新特性图片个数
let ZXNewfeatureImageCount = 4;
// 是否为4英寸
let INCH_4 = Bool(kScreenHeight == 568.0);
// 根据rgb设置颜色
func RGB(r : CGFloat , g : CGFloat , b : CGFloat) -> UIColor {
let color = UIColor.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0);
return color;
}
// 返回最大列数
func photosMaxCols(photosCount : NSInteger?) -> NSInteger? {
if photosCount == 4 {
return 2;
} else {
return 3;
}
}
| apache-2.0 | dcf5b2b8644e9b6bb51772588ab91465 | 22.057971 | 145 | 0.712131 | 3.512141 | false | false | false | false |
eoger/firefox-ios | Client/Frontend/Browser/ContextMenuHelper.swift | 2 | 4001 | /* 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 WebKit
protocol ContextMenuHelperDelegate: AnyObject {
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer)
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer)
}
class ContextMenuHelper: NSObject {
struct Elements {
let link: URL?
let image: URL?
}
fileprivate weak var tab: Tab?
weak var delegate: ContextMenuHelperDelegate?
fileprivate var nativeHighlightLongPressRecognizer: UILongPressGestureRecognizer?
fileprivate var elements: Elements?
required init(tab: Tab) {
super.init()
self.tab = tab
nativeHighlightLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_highlightLongPressRecognized:") as? UILongPressGestureRecognizer
if let nativeLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_longPressRecognized:") as? UILongPressGestureRecognizer {
nativeLongPressRecognizer.removeTarget(nil, action: nil)
nativeLongPressRecognizer.addTarget(self, action: #selector(longPressGestureDetected))
}
}
func gestureRecognizerWithDescriptionFragment(_ descriptionFragment: String) -> UIGestureRecognizer? {
return tab?.webView?.scrollView.subviews.compactMap({ $0.gestureRecognizers }).joined().first(where: { $0.description.contains(descriptionFragment) })
}
@objc func longPressGestureDetected(_ sender: UIGestureRecognizer) {
if sender.state == .cancelled {
delegate?.contextMenuHelper(self, didCancelGestureRecognizer: sender)
return
}
guard sender.state == .began else {
return
}
// To prevent the tapped link from proceeding with navigation, "cancel" the native WKWebView
// `_highlightLongPressRecognizer`. This preserves the original behavior as seen here:
// https://github.com/WebKit/webkit/blob/d591647baf54b4b300ca5501c21a68455429e182/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm#L1600-L1614
if let nativeHighlightLongPressRecognizer = self.nativeHighlightLongPressRecognizer,
nativeHighlightLongPressRecognizer.isEnabled {
nativeHighlightLongPressRecognizer.isEnabled = false
nativeHighlightLongPressRecognizer.isEnabled = true
}
if let elements = self.elements {
delegate?.contextMenuHelper(self, didLongPressElements: elements, gestureRecognizer: sender)
self.elements = nil
}
}
}
extension ContextMenuHelper: TabContentScript {
class func name() -> String {
return "ContextMenuHelper"
}
func scriptMessageHandlerName() -> String? {
return "contextMenuMessageHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let data = message.body as? [String: AnyObject] else {
return
}
var linkURL: URL?
if let urlString = data["link"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
linkURL = URL(string: escapedURLString)
}
var imageURL: URL?
if let urlString = data["image"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
imageURL = URL(string: escapedURLString)
}
if linkURL != nil || imageURL != nil {
elements = Elements(link: linkURL, image: imageURL)
} else {
elements = nil
}
}
}
| mpl-2.0 | 4f6dd3bcaaa41aad8106a4f15c5d3ed2 | 38.613861 | 165 | 0.699575 | 5.480822 | false | false | false | false |
txlong/iOS | swift/100Day/Calculator/Calculator/UITextFieldX.swift | 1 | 1539 | //
// UITextFieldX.swift
// Calculator
//
// Created by iAnonymous on 16/8/27.
// Copyright © 2016年 iAnonymous. All rights reserved.
//
import UIKit
class UITextFieldX: UITextField {
override func drawRect(rect: CGRect) {
super.drawRect(rect)
// 键盘完成按钮
let toolBar = UIToolbar(frame: CGRectMake(0, 0, screenSize().width, 30))
toolBar.barStyle = UIBarStyle.Default
let btnFished = UIButton(frame: CGRectMake(0, 0, 50, 25))
btnFished.setTitleColor(RGB(4, g: 170, b: 174), forState: UIControlState.Normal)
btnFished.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
btnFished.setTitle("完成", forState: UIControlState.Normal)
btnFished.addTarget(self, action: #selector(UITextFieldX.finishTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
let item2 = UIBarButtonItem(customView: btnFished)
let space = UIView(frame: CGRectMake(0, 0, screenSize().width - btnFished.frame.width - 30, 25))
let item = UIBarButtonItem(customView: space)
toolBar.setItems([item,item2], animated: true)
self.inputAccessoryView = toolBar
}
func finishTapped(sender:UIButton){
self.resignFirstResponder()
}
}
func screenSize() -> CGSize{
return UIScreen.mainScreen().bounds.size
}
func RGB (r:CGFloat, g:CGFloat, b:CGFloat) -> UIColor {
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
} | gpl-2.0 | 96992d910a6f2f7b0cf778ce281a8e9c | 32.065217 | 132 | 0.658553 | 4.042553 | false | false | false | false |
informmegp2/inform-me | InformME/Content.swift | 1 | 26374 | //
// File.swift
// InformME
//
// Created by Amal Ibrahim on 2/4/16.
// Copyright © 2016 King Saud University. All rights reserved.
//
import Foundation
import UIKit
class Content {
var Title: String = ""
var Abstract: String = ""
var Images: [UIImage] = []
var Video: String = ""
var Pdf : String = ""
var likes: Like = Like()
var dislikes:Dislike = Dislike()
var comments: [Comment] = []
var shares: Int = 0
var label: String = ""
var contentId: Int?
var like: Int = 0
var dislike: Int = 0
var save:Bool = false;
var del:Bool = false
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "ContentImage.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func createContent(title: String,abstract: String ,video: String,Pdf: String,BLabel: String,EID:Int,image: [UIImage], completionHandler: (flag:Bool) -> ()) {
let l = BLabel
let SC = 0
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/AddContent.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
let postString = "Title="+title+"&Abstract="+abstract+"&ShareCounter=\(SC)&Label=\(l)&EventID=\(EID)&PDF=\(Pdf)&Video=\(video)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
print("response = \(response)")
}
task.resume()
addImage(title,abstract: abstract,BLabel: BLabel,EID: EID,image: image){
(flag:Bool) in
//we should perform all segues in the main thread
dispatch_async(dispatch_get_main_queue()) {
completionHandler(flag: flag)
}
}
}
func addImage(title: String,abstract: String ,BLabel: String,EID:Int,image: [UIImage] ,completionHandler: (flag:Bool) -> ()) {
let myGroup = dispatch_group_create()
let l = BLabel
let SC = 0
for i in 0 ..< image.count {
dispatch_group_enter(myGroup)
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/AddImage.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
let param : [String: String] = [
"Title" : title,
"Abstract" :abstract,
"EventID" :String(EID),
"ShareCounter" :String(SC),
"Label" : l,
"ImageNum" : String(i)
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image[i], -1)
if imageData==nil{
print("it is nil")}
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
dispatch_group_leave(myGroup)
}
task.resume()
}
if (image.count == 0){
completionHandler(flag: true)}
dispatch_group_notify(myGroup, dispatch_get_main_queue(), {
print("Finished all requests.")
completionHandler(flag: true)
})
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
func updateContent(title: String,abstract: String ,video: String,Pdf: String ,bLabel: String,image: [UIImage], TempV: String , TempP: String ,EID:Int, cID:Int ,completionHandler: (flag:Bool) -> ()) {
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/EditContent.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST"
let postString = "Title=\(title)&Abstract=\(abstract)&PDF=\(Pdf)&Video=\(video)&CID=\(cID)&pPDF=\(TempP)&pVideo=\(TempV)&label=\(bLabel)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
}
task.resume()
updateImage(title,abstract: abstract,BLabel: bLabel,EID: EID,image: image ){
(flag:Bool) in
//we should perform all segues in the main thread
dispatch_async(dispatch_get_main_queue()) {
completionHandler(flag: flag)
}
}
}
func updateImage(title: String,abstract: String ,BLabel: String,EID:Int,image: [UIImage],completionHandler: (flag:Bool) -> ()) {
let l = BLabel
let MYURL1 = NSURL(string:"http://bemyeyes.co/API/content/deleteImage.php")
let request1 = NSMutableURLRequest(URL:MYURL1!)
request1.HTTPMethod = "POST";
let postString1 = "Title=\(title)&Abstract=\(abstract)&EventID=\(EID)&Label=\(l)"
request1.HTTPBody = postString1.dataUsingEncoding(NSUTF8StringEncoding);
let task1 = NSURLSession.sharedSession().dataTaskWithRequest(request1) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
}
task1.resume()
for i in 0 ..< image.count {
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/updateImage.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
let param : [String: String] = [
"Title" : title,
"Abstract" :abstract,
"EventID" :String(EID),
"Label" : l,
"ImageNum" : String(i)
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image[i], -1)
if imageData==nil{
print("it is nil")}
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
}
task.resume()
}
completionHandler(flag: true)
}
func DeleteContent(id: Int ){
del = true
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/DeleteContent.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
let postString = "cid=\(id)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
//completionHandler(flag: f)
}
task.resume()
del = true
}
func requestcontentlist(ID: Int,completionHandler: (contentInfo:[Content]) -> ()){
var contentInfo: [Content] = []
let Eid=ID
print("\(Eid)")
let request = NSMutableURLRequest(URL: NSURL(string: "http://bemyeyes.co/API/content/SelectContent.php")!)
request.HTTPMethod = "POST"
let postString = "eid=\(Eid)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
for x in 0 ..< jsonResult.count {
let item = jsonResult[x] as AnyObject
let c : Content = Content()
c.contentId = Int(item["ContentID"] as! String)!
c.Title = item["Title"] as! String
c.Abstract = item["Abstract"] as! String
if item["Label"] is NSNull {
c.label = "No Label"
}
else{
c.label = item["Label"] as! String}
if item["PDFFiles"] is NSNull {
c.Pdf = "No PDF"
}
else{
c.Pdf = item["PDFFiles"] as! String
}
if item["Videos"] is NSNull {
c.Video = "No Video"
}
else{
c.Video = item["Videos"] as! String
}
if item["ShareCounter"] is NSNull || item["ShareCounter"] == nil {
c.shares = 0
}
else{
c.shares = Int(item["ShareCounter"] as! String)!
}
var comments: [Comment] = []
let itemC = item["Comments"] as! NSArray
for i in 0 ..< itemC.count {
let comment: Comment = Comment()
comment.comment = itemC[i]["CommentText"] as! String
comment.user.username = itemC[i]["UserName"] as! String
comments.append(comment)
}
c.comments = comments;
var images: [UIImage] = []
let itemI = item["Images"] as! NSArray
for i in 0 ..< itemI.count {
let url:NSURL = NSURL(string : itemI[i] as! String)!
let data = NSData(contentsOfURL: url)
let image=UIImage(data: data!)
images.append(image!)
}
c.Images = images;
if item["Like"] is NSNull || item["Like"] == nil {
c.like = 0
}
else{
let lk = item["Like"] as! String
c.like = Int(lk)!}
if item["dislike"] is NSNull || item["dislike"] == nil {
c.dislike = 0
}
else {
let dislk = item["dislike"] as! String
c.dislike = Int(dislk)!}
contentInfo.append(c)
print("DONE")
}
completionHandler(contentInfo: contentInfo)
} catch {
print("JSON serialization failed")
}
}
}
task.resume()
}
func shareContent(cid: Int, completionHandler: (done:Bool) -> ()) {
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/shareContent.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
//Change UserID"
let postString = "cid=\(cid)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
completionHandler(done: true)
}
task.resume()
}
func saveContent(uid: Int , cid: Int) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://bemyeyes.co/API/content/SaveContent.php")!)
request.HTTPMethod = "POST";
let postString = "uid=\(uid)&cid=\(cid)";
print("\(postString)")
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
}
task.resume()
}
func unsaveContent(uid: Int , cid: Int) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://bemyeyes.co/API/content/UnsaveContent.php")!)
request.HTTPMethod = "POST";
let postString = "uid=\(uid)&cid=\(cid)";
print("\(postString)")
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
}
task.resume()
}
func deleteComment(cid : Int, uid : Int,completionHandler: (done:Bool) -> ()) {
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/deletecomment.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
//Change UserID"
let postString = "cid=\(cid)&uid=\(uid)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
else { // You can print out response object
print("response = \(response)")
for i in 0 ..< self.comments.count
{
if (self.comments[i].user.userID == uid){
self.comments.removeAtIndex(i)
}//end if
}//end for
}// end else
completionHandler(done: true)
}
task.resume()
}
func updateEvaluation (cid: Int, uid:Int, likeNo:Int, dislikeNo:Int, completionHandler: (done:Bool) -> ()) {
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/updateEvaluation.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
//Change UserID"
let postString = "cid=\(cid)&uid=\(uid)&like=\(likeNo)&dislike=\(dislikeNo)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
completionHandler(done: true)
}
task.resume()
}
func disLikeContent(cid: Int, uid: Int, completionHandler: (done:Bool) -> ()) {
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/evaluate.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
//Change UserID"
let dislike = 1
let like = 0
let postString = "cid=\(cid)&uid=\(uid)&like=\(like)&dislike=\(dislike)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
completionHandler(done: true)
}
task.resume()
}
func likeContent(cid: Int, uid: Int, completionHandler: (done:Bool) -> ()){
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/evaluate.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
//Change UserID"
let dislike = 0
let like = 1
let postString = "cid=\(cid)&uid=\(uid)&like=\(like)&dislike=\(dislike)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
completionHandler(done: true)
}
task.resume()
}
//MARK --Found No Need for the commented methods
//func requestToAddComment() {}
//func requestToDeleteComment() {}
func saveComment(comment: Comment, completionHandler: (done:Bool) -> ()) {
let com = comment.comment
let user = comment.user.userID
let cid = comment.contentID
let MYURL = NSURL(string:"http://bemyeyes.co/API/content/addcomment.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
//Change UserID"
let postString = "cid=\(cid)&uid=\(user)&comment=\(com)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
completionHandler(done: true)
}
task.resume()
}
//MARK: --- THIS METHOD WAS MOVED FROM EVENTS CLASS ---
func ViewContent(ContentID: Int, UserID:Int, completionHandler: (content:Content) -> ()){
let request = NSMutableURLRequest(URL: NSURL(string: "http://bemyeyes.co/API/content/contentdetails.php")!)
request.HTTPMethod = "POST"
let postString = "cid=\(ContentID)&uid=\(UserID)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
print("\(response)")
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
for x in 0 ..< jsonResult.count {
let item = jsonResult[x] as AnyObject
let c : Content = Content()
c.contentId = Int(item["ContentID"] as! String)!
c.Title = item["Title"] as! String
c.Abstract = item["Abstract"] as! String
if item["PDFFiles"] is NSNull {
c.Pdf = "No PDF"
}
else{
c.Pdf = item["PDFFiles"] as! String
}
if item["Videos"] is NSNull {
c.Video = "No Video"
}
else{
c.Video = item["Videos"] as! String
}
c.shares = Int(item["ShareCounter"] as! String)!
c.label = item["Label"] as! String
var comments: [Comment] = []
let itemC = item["Comments"] as! NSArray
for i in 0 ..< itemC.count {
let comment: Comment = Comment()
comment.comment = itemC[i]["CommentText"] as! String
comment.user.username = itemC[i]["UserName"] as! String
comment.user.userID = Int(itemC[i]["UserID"] as! String)!
comments.append(comment)
}
c.comments = comments;
var images: [UIImage] = []
let itemI = item["Images"] as! NSArray
for i in 0 ..< itemI.count {
let url:NSURL = NSURL(string : itemI[i] as! String)!
let data = NSData(contentsOfURL: url)
let image=UIImage(data: data!)
images.append(image!)
}
c.Images = images;
if item["Like"] is NSNull {
c.like = 0
}
else{
let lk = item["Like"] as! String
c.like = Int(lk)!}
if item["dislike"] is NSNull {
c.dislike = 0
}
else {
let dislk = item["dislike"] as! String
c.dislike = Int(dislk)!}
completionHandler(content: c)
print("DONE")
}
} catch {
print("JSON serialization failed")
}
}
}
task.resume()
}
init ()
{ Title = ""
Abstract = ""
Images = [UIImage] ()
Video = ""
//Pdf: NSData = NSData() //this will be changed depending on our chosen type.
Pdf = ""
likes = Like()
dislikes = Dislike()
comments = [Comment]()
shares = 0
label = ""
contentId = 0}
init(json: [String: AnyObject])
{
contentId = Int(json["ContentID"] as! String)!
Title = json["Title"] as! String
if let NotSaved = (json["NotSaved"] as? String)
{if (!(NotSaved.isEmpty) && NotSaved == "0")
{self.save = true}}
}
}
| mit | 75d7ce7f9767528e3bee9f491bba98fa | 34.735772 | 203 | 0.464907 | 5.340826 | false | false | false | false |
dzt/MobilePassport | ios/ios/LoginViewController.swift | 1 | 4958 | //
// LoginViewController.swift
// ios
//
// Created by Ivan Chau on 1/19/16.
// Copyright © 2016 Ivan Chau & Peter Soboyejo. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var username : UITextField!
@IBOutlet weak var password : UITextField!
@IBOutlet weak var login : UIButton!
@IBOutlet weak var register : UIButton!
@IBOutlet weak var logo : UIImageView!
let socket = SocketIOClient(socketURL: NSURL(string:"localhost:3000")!)
var loggedIn = false;
let keychain = Keychain()
var userData = NSDictionary()
@IBAction func login(sender:UIButton){
if (self.username.text == "" || self.password.text == ""){
let alertView = UIAlertController(title: "UWOTM8", message: "Fam, what you tryna pull?", preferredStyle: .Alert)
let OK = UIAlertAction(title: "Is it 2 l8 2 say sorry", style: .Default, handler: nil)
alertView.addAction(OK)
self.presentViewController(alertView, animated: true, completion: nil);
return;
}
username.resignFirstResponder()
password.resignFirstResponder()
self.loginRequestWithParams(self.username.text!, passwordString: self.password.text!)
}
override func viewDidLoad() {
super.viewDidLoad()
self.socket.connect()
self.addSocketHandlers()
self.loggedIn = false;
logo.layer.masksToBounds = false
logo.layer.cornerRadius = logo.frame.height/2
logo.clipsToBounds = true
//comment below to force login
if(self.keychain.getPasscode("MPPassword")! != "" && self.keychain.getPasscode("MPUsername")! != ""){
self.loginRequestWithParams(self.keychain.getPasscode("MPUsername") as! String, passwordString: self.keychain.getPasscode("MPPassword") as! String)
}
// Do any additional setup after loading the view.
}
func addSocketHandlers(){
// Our socket handlers go here
socket.on("connect") {data, ack in
print("socket connected")
}
}
func loginRequestWithParams(usernameString : String, passwordString : String){
let headers = [
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded"
]
let usernameStr = "username=" + usernameString
let passwordStr = "&password=" + passwordString
let postData = NSMutableData(data: usernameStr.dataUsingEncoding(NSUTF8StringEncoding)!)
postData.appendData(passwordStr.dataUsingEncoding(NSUTF8StringEncoding)!)
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:3000/login")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
print(httpResponse)
if (httpResponse?.statusCode == 200){
dispatch_async(dispatch_get_main_queue(), {
//segue to main view.
if(self.keychain.getPasscode("MPPassword") == "" || self.keychain.getPasscode("MPUsername") == ""){
self.keychain.setPasscode("MPPassword", passcode: passwordString)
self.keychain.setPasscode("MPUsername", passcode: usernameString)
}
if (self.loggedIn == false){
self.performSegueWithIdentifier("LoginSegue", sender: self)
// use anyObj here
self.loggedIn = true;
}else{
}
})
}else{
print("error")
}
// use anyObj here
print("json error: \(error)")
}
})
dataTask.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
| mit | 51c158ca3b61018a67920e14bd531720 | 38.656 | 159 | 0.583216 | 5.206933 | false | false | false | false |
google/JacquardSDKiOS | JacquardSDK/Classes/Internal/FirmwareUpdate/CRC16.swift | 1 | 1057 | // Copyright 2021 Google LLC
//
// 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
/// This is a swift version of CRC-16-CCITT (polynomial 0x1021) with 0xFFFF initial value.
class CRC16 {
static func compute(in data: Data, seed: UInt16 = 0xFFFF) -> UInt16 {
let bytes = [UInt8](data)
var crc = seed
for byte in bytes {
crc = UInt16(crc >> 8 | crc << 8)
crc ^= UInt16(byte)
crc ^= UInt16(UInt8(crc & 0xFF) >> 4)
crc ^= (crc << 8) << 4
crc ^= ((crc & 0xFF) << 4) << 1
}
return crc
}
}
| apache-2.0 | 92f0d489dbe2a2e8aed1b9d45fcb8685 | 33.096774 | 90 | 0.666036 | 3.670139 | false | false | false | false |
vishalvshekkar/bingoNumberDraw | Bingo Draw/Bingo Draw/ViewController.swift | 1 | 3117 | //
// ViewController.swift
// Bingo Draw
//
// Created by Vishal V Shekkar on 06/11/15.
// Copyright © 2015 Vishal V Shekkar. All rights reserved.
//
import UIKit
var drawnNumbers : [Int] = []
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var drawnNumbersCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
drawnNumbersCollectionView.delegate = self
drawnNumbersCollectionView.dataSource = self
self.navigationItem.title = "Bingo"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func resetAction(sender: AnyObject) {
let alert = UIAlertController(title: "Reset", message: "Are you sure you want to reset generated numbers?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "Reset", style: UIAlertActionStyle.Destructive, handler: { [weak self] (action) -> Void in
drawnNumbers = []
self?.drawnNumbersCollectionView.reloadData()
}))
self.presentViewController(alert, animated: true, completion: nil)
}
@IBAction func drawAction(sender: AnyObject) {
if let randomNumberGenerated = getRandomNumber() {
drawnNumbers.append(randomNumberGenerated)
drawnNumbersCollectionView.reloadData()
}
else {
let alert = UIAlertController(title: "Finished", message: "You generated all possible numbers.\nReset to start over.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return drawnNumbers.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let drawnCell = drawnNumbersCollectionView.dequeueReusableCellWithReuseIdentifier("drawnNumbers", forIndexPath: indexPath) as! DrawnNumbersCell
drawnCell.drawnNumberLabel.text = "\(drawnNumbers[indexPath.item])"
return drawnCell
}
func getRandomNumber() -> Int? {
var randomNumber = randomInt(minimumInt, max: maximumInt)
if drawnNumbers.count <= maximumInt - minimumInt {
while drawnNumbers.contains(randomNumber) {
randomNumber = randomInt(minimumInt, max: maximumInt)
}
return randomNumber
}
else {
return nil
}
}
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
}
| mit | ba7aa181c18935ebcee2fd88a659de0b | 37.95 | 176 | 0.681001 | 5.15894 | false | false | false | false |
PseudoSudoLP/Bane | Carthage/Checkouts/PromiseKit/Categories/Foundation/NSObject+Promise.swift | 1 | 1756 | import Foundation
import PromiseKit
/**
To import the `NSObject` category:
use_frameworks!
pod "PromiseKit/Foundation"
Or `NSObject` is one of the categories imported by the umbrella pod:
use_frameworks!
pod "PromiseKit"
And then in your sources:
import PromiseKit
*/
extension NSObject {
public func observe<T>(keyPath: String) -> Promise<T> {
let (promise, fulfill, reject) = Promise<T>.defer()
KVOProxy(observee: self, keyPath: keyPath) { obj in
if let obj = obj as? T {
fulfill(obj)
} else {
let info = [NSLocalizedDescriptionKey: "The observed property was not of the requested type."]
reject(NSError(domain: PMKErrorDomain, code: PMKInvalidUsageError, userInfo: info))
}
}
return promise
}
}
private class KVOProxy: NSObject {
var retainCycle: KVOProxy?
let fulfill: (AnyObject?) -> Void
init(observee: NSObject, keyPath: String, resolve: (AnyObject?) -> Void) {
fulfill = resolve
super.init()
retainCycle = self
observee.addObserver(self, forKeyPath: keyPath, options: NSKeyValueObservingOptions.New, context: pointer)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == pointer {
fulfill(change[NSKeyValueChangeNewKey])
object.removeObserver(self, forKeyPath: keyPath)
retainCycle = nil
}
}
private lazy var pointer: UnsafeMutablePointer<KVOProxy> = {
return UnsafeMutablePointer<KVOProxy>(Unmanaged<KVOProxy>.passUnretained(self).toOpaque())
}()
}
| mit | d204b482a93ee8f2e7bc9f748771a5a8 | 30.357143 | 156 | 0.647494 | 4.784741 | false | false | false | false |
TouchInstinct/LeadKit | TIEcommerce/Sources/Filters/FiltersViews/RangeFilters/Models/Appearance/DefaultIntervalInputAppearance.swift | 1 | 2171 | //
// Copyright (c) 2022 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public struct DefaultIntervalInputAppearance {
public var textFieldsHeight: CGFloat
public var textFieldsWidth: CGFloat
public var textFieldLabelsSpacing: CGFloat
public var textFieldContentInsets: UIEdgeInsets
public var textFieldsBorderColor: UIColor
public var textFieldsBorderWidth: CGFloat
public init(textFieldsHeight: CGFloat = 32,
textFieldsWidth: CGFloat = 100,
textFieldLabelsSpacing: CGFloat = 4,
textFieldContentInsets: UIEdgeInsets = .init(top: 4, left: 8, bottom: 4, right: 8),
textFieldsBorderColor: UIColor = .black,
textFieldsBorderWidth: CGFloat = 1) {
self.textFieldsHeight = textFieldsHeight
self.textFieldsWidth = textFieldsWidth
self.textFieldLabelsSpacing = textFieldLabelsSpacing
self.textFieldContentInsets = textFieldContentInsets
self.textFieldsBorderColor = textFieldsBorderColor
self.textFieldsBorderWidth = textFieldsBorderWidth
}
}
| apache-2.0 | 1001fed92c23814ea8fa8ac1bb00cb68 | 44.229167 | 99 | 0.734224 | 4.967963 | false | false | false | false |
Marguerite-iOS/Marguerite | Marguerite/AboutTableViewController.swift | 1 | 5472 | //
// AboutTableViewController.swift
// A UITableViewController for displaying information about the app.
//
// Created by Kevin Conley on 3/11/15.
// Copyright (c) 2015 Kevin Conley. All rights reserved.
//
import UIKit
import SafariServices
class AboutTableViewController: UITableViewController, SFSafariViewControllerDelegate {
private var seperatorColor: UIColor!
private var tableViewBackgroundColor: UIColor!
// MARK: - Strings
private let headers: [String?] = [NSLocalizedString("Credits Header", comment: ""), NSLocalizedString("Contact Marguerite Header", comment: ""), NSLocalizedString("Open-source Header", comment: ""), NSLocalizedString("Other Apps Header", comment: ""), nil]
private let creditsStrings: [String] = [NSLocalizedString("Updated Version Title", comment: ""), NSLocalizedString("Original App Title", comment: ""), NSLocalizedString("Branding Title", comment: ""), NSLocalizedString("Misc. Images Title", comment: "")]
private let contactStrings: [String] = [NSLocalizedString("Main Office Title", comment: ""), NSLocalizedString("Website Title", comment: "")]
// MARK: - Links
private let officePhoneNumber = "650-724-9339"
private let websiteURL = "http://transportation.stanford.edu/marguerite"
private let gitHubURL = "http://atfinkeproductions.com/Marguerite"
// MARK: - View Transitions
override func viewDidLoad() {
tableViewBackgroundColor = tableView.backgroundColor
seperatorColor = tableView.separatorColor
updateTheme()
}
// MARK: - Night Mode
/**
Updates the UI colors
*/
func updateTheme() {
if ShuttleSystem.sharedInstance.nightModeEnabled {
tableView.backgroundColor = UIColor.darkModeTableViewColor()
tableView.separatorColor = UIColor.darkModeSeperatorColor()
} else {
tableView.backgroundColor = tableViewBackgroundColor
tableView.separatorColor = seperatorColor
}
}
// MARK: - Actions
@IBAction private func done(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
switch indexPath.section {
case 0:
cell.textLabel?.text = creditsStrings[indexPath.row]
case 1:
cell.textLabel?.text = contactStrings[indexPath.row]
case 2:
cell.textLabel?.text = NSLocalizedString("GitHub Title", comment: "")
case 3:
cell.textLabel?.text = "Stanford Laundry Rooms"
default:
break
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section {
case 1:
switch indexPath.row {
case 0:
callPhoneNumber(officePhoneNumber)
case 1:
openSafariController(websiteURL)
default:
break
}
case 2:
openSafariController(gitHubURL)
case 3:
openSafariController("http://atfinkeproductions.com/Laundry")
default:
break
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 2 {
return NSLocalizedString("Open-source Footer", comment: "")
}
return nil
}
// MARK: - URL Convenience Methods
private func callPhoneNumber(telephoneNumberString: String) {
if let url = NSURL(string: "tel://\(telephoneNumberString)") {
UIApplication.sharedApplication().openURL(url)
}
}
private func openSafariController(urlString: String) {
if let url = NSURL(string: urlString) {
if #available(iOS 9.0, *) {
UIApplication.sharedApplication().statusBarStyle = .Default
UIBarButtonItem.appearance().tintColor = UIColor.cardinalColor()
let controller = SFSafariViewController(URL: url)
controller.modalPresentationStyle = .FormSheet
controller.delegate = self
presentViewController(controller, animated: true, completion: nil)
} else {
UIApplication.sharedApplication().openURL(url)
}
}
}
@available(iOS 9.0, *)
func safariViewControllerDidFinish(controller: SFSafariViewController) {
UIApplication.sharedApplication().statusBarStyle = .LightContent
UIBarButtonItem.appearance().tintColor = UIColor.whiteColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIBarButtonItem.appearance().tintColor = UIColor.whiteColor()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIApplication.sharedApplication().statusBarStyle = .LightContent
}
}
| mit | 66b27c8c1bca0a98532808e0d89aff5f | 35.972973 | 260 | 0.64364 | 5.521695 | false | false | false | false |
lexchou/swallow | swallow/tests/semantics/TestOptional_OptionalChaining_Method.swift | 2 | 1127 | class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if buildingName != nil {
return buildingName
} else if buildingNumber != nil {
return buildingNumber
} else {
return nil
}
}
}
class Room
{
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
println("The number of rooms is \(numberOfRooms)")
}
var address: Address?
}
class Person {
var residence: Residence?
}
let john = Person()
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
john.residence?.address = someAddress
if john.residence?.printNumberOfRooms() != nil {
println("It was possible to print the number of rooms.")
} else {
println("It was not possible to print the number of rooms.")
} | bsd-3-clause | 7227bb7773c3d07987a230c1e4290f8f | 20.283019 | 64 | 0.590949 | 4.437008 | false | false | false | false |
guidomb/Portal | PortalExampleUITests/ViewDrivers/ModalScreenDriver.swift | 1 | 2006 | //
// ModalScreenDriver.swift
// PortalExampleUITests
//
// Created by Guido Marucci Blas on 6/11/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import XCTest
final class ModalScreenDriver {
static func isVisible(app: XCUIApplication) -> Bool {
return app.navigationBars["Modal"].exists
}
private let app: XCUIApplication
init(app: XCUIApplication) {
self.app = app
}
var isVisible: Bool {
return ModalScreenDriver.isVisible(app: app)
}
var counterLabelText: String {
let predicate = NSPredicate(format: "label BEGINSWITH 'Counter'")
return app.staticTexts.matching(predicate).firstMatch.label
}
var currentCounterValue: UInt {
return matchGroups(in: counterLabelText, with: "Counter ([0-9]+)")
.first
.flatMap { UInt($0) } ?? 0
}
func closeModal() {
app.buttons["Close"].tap()
}
func incrementCounter() {
app.buttons["Increment!"].tap()
}
func waitForCounterToFinishUpdating(timeout: TimeInterval = 10, file: StaticString = #file, line: UInt = #line) {
let counterFinishedUpdating = app.staticTexts["Counter 5"].waitForExistence(timeout: timeout)
XCTAssertTrue(counterFinishedUpdating, "Counter did not finish updating", file: file, line: line)
}
}
private func matchGroups(in string: String, with regexpString: String) -> [String] {
let stringRange = NSMakeRange(0, string.count)
guard let regexp = try? NSRegularExpression(pattern: regexpString, options: []),
let result = regexp.firstMatch(in: string, options: [], range: stringRange) else { return [] }
var extractedMatches: [String] = []
for index in (1..<result.numberOfRanges) {
if let range = Range(result.range(at: index), in: string) {
extractedMatches.append(String(string[range]))
}
}
return extractedMatches
}
| mit | 68caed749aa0b53bd69bae1e7c793f80 | 28.925373 | 117 | 0.634913 | 4.39693 | false | false | false | false |
xivol/MCS-V3-Mobile | examples/uiKit/UIKitCatalog.playground/Pages/UIStackView.xcplaygroundpage/Contents.swift | 1 | 1098 | //: # UIStackView
//:The UIStackView class provides a streamlined interface for laying out a collection of views in either a column or a row.
//:
//: [UIStackView API Reference](https://developer.apple.com/reference/uikit/uistackview)
import UIKit
import PlaygroundSupport
let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 250, height: 250))
for i in 1...5 {
let column = UIStackView(frame: CGRect(x: 0, y: 0, width: 50, height: 250))
for j in 1...3 {
let subview = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
subview.backgroundColor = UIColor(displayP3Red: 0.2 * CGFloat(i), green: 0.2 * CGFloat(j), blue: 0.2 * CGFloat(i + j), alpha: 1)
column.addArrangedSubview(subview)
}
column.distribution = .fillEqually
column.axis = .vertical
column.spacing = 1
stackView.addArrangedSubview(column)
}
stackView.distribution = .fillProportionally
stackView.axis = .horizontal
stackView.spacing = 1
PlaygroundPage.current.liveView = stackView
//: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
| mit | fe147b89811333ad3cdbb1d4633aa7d6 | 38.214286 | 136 | 0.696721 | 3.74744 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/Model/Store/Base/MStore.swift | 1 | 3413 | import Foundation
import StoreKit
class MStore
{
typealias PurchaseId = String
private(set) var mapItems:[PurchaseId:MStoreItem]
private(set) var references:[PurchaseId]
var error:String?
private let priceFormatter:NumberFormatter
init()
{
priceFormatter = NumberFormatter()
priceFormatter.numberStyle = NumberFormatter.Style.currencyISOCode
mapItems = [:]
references = []
addPurchase(item:MStoreItemPlus())
references.sort
{ (purchaseA:PurchaseId, purchaseB:PurchaseId) -> Bool in
let comparison:ComparisonResult = purchaseA.compare(purchaseB)
switch comparison
{
case ComparisonResult.orderedAscending,
ComparisonResult.orderedSame:
return true
case ComparisonResult.orderedDescending:
return false
}
}
}
//MARK: private
private func addPurchase(item:MStoreItem)
{
let purchaseId:PurchaseId = item.purchaseId
mapItems[purchaseId] = item
references.append(purchaseId)
}
//MARK: public
func loadSkProduct(skProduct:SKProduct)
{
let productId:String = skProduct.productIdentifier
guard
let mappedItem:MStoreItem = mapItems[productId]
else
{
return
}
mappedItem.skProduct = skProduct
priceFormatter.locale = skProduct.priceLocale
let priceNumber:NSDecimalNumber = skProduct.price
guard
let priceString:String = priceFormatter.string(from:priceNumber)
else
{
return
}
mappedItem.foundPurchase(price:priceString)
}
func updateTransactions(transactions:[SKPaymentTransaction])
{
for skPaymentTransaction:SKPaymentTransaction in transactions
{
let productId:String = skPaymentTransaction.payment.productIdentifier
guard
let mappedItem:MStoreItem = mapItems[productId]
else
{
continue
}
switch skPaymentTransaction.transactionState
{
case SKPaymentTransactionState.deferred:
mappedItem.statusDeferred()
break
case SKPaymentTransactionState.failed:
mappedItem.statusNew()
SKPaymentQueue.default().finishTransaction(skPaymentTransaction)
break
case SKPaymentTransactionState.purchased,
SKPaymentTransactionState.restored:
mappedItem.statusPurchased(callAction:true)
SKPaymentQueue.default().finishTransaction(skPaymentTransaction)
break
case SKPaymentTransactionState.purchasing:
mappedItem.statusPurchasing()
break
}
}
}
}
| mit | 9d26e48cd155cade5ef70b7d972b6043 | 25.457364 | 81 | 0.520363 | 6.771825 | false | false | false | false |
mparrish91/gifRecipes | application/ImgurLinkContainer.swift | 2 | 2786 | //
// ImgurLinkContainer.swift
// reddift
//
// Created by sonson on 2016/10/06.
// Copyright © 2016年 sonson. All rights reserved.
//
import reddift
import Foundation
class ImgurLinkContainer: MediaLinkContainer {
/// Shared session configuration
var sessionConfiguration: URLSessionConfiguration {
get {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 30
return configuration
}
}
override init(link: Link, width: CGFloat, fontSize: CGFloat = 18, thumbnails: [Thumbnail]) {
super.init(link: link, width: width, fontSize: fontSize, thumbnails: [])
self.thumbnails = thumbnails
let font = UIFont(name: UIFont.systemFont(ofSize: fontSize).fontName, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
attributedTitle = NSAttributedString(string: link.title).reconstruct(with: font, color: UIColor.black, linkColor: UIColor.blue)
titleSize = ThumbnailLinkCell.estimateTitleSize(attributedString: attributedTitle, withBountWidth: width, margin: .zero)
pageLoaded = false
}
override func prefetch(at: IndexPath) {
if pageLoaded { return }
guard let url = URL(string: link.url) else { return }
let https_url = url.httpsSchemaURL
var request = URLRequest(url: https_url)
request.addValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56", forHTTPHeaderField: "User-Agent")
let session: URLSession = URLSession(configuration: sessionConfiguration)
let task = session.dataTask(with: request, completionHandler: { (data, _, error) -> Void in
self.pageLoaded = true
if let error = error {
NotificationCenter.default.post(name: LinkContainerDidLoadImageName, object: nil, userInfo: ["error": error as NSError])
}
if let data = data, let decoded = String(data: data, encoding: .utf8) {
if !decoded.is404OfImgurcom {
self.thumbnails = decoded.extractImgurImageURL(parentID: self.link.id)
DispatchQueue.main.async(execute: { () -> Void in
NotificationCenter.default.post(name: LinkContainerDidLoadImageName, object: nil, userInfo: [MediaLinkContainerPrefetchAtIndexPathKey: at, MediaLinkContainerPrefetchContentKey: self])
})
}
} else {
NotificationCenter.default.post(name: LinkContainerDidLoadImageName, object: nil, userInfo: ["error": "can not decode html"])
}
})
task.resume()
}
}
| mit | 1b388694afd76d8607b3217d9b5f1541 | 46.982759 | 207 | 0.65433 | 4.757265 | false | true | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Settings/Auxiliary/Snippet.swift | 1 | 1140 | //
// Snippet.swift
//
//
// Created by Vladislav Fitc on 11.03.2020.
//
import Foundation
public struct Snippet: Codable, URLEncodable, Equatable {
/**
Attribute to snippet.
- Use "*" to snippet all attributes.
*/
public let attribute: Attribute
/**
Optional word count.
- Engine default: 10
*/
public var count: Int?
public init(attribute: Attribute, count: Int? = nil) {
self.attribute = attribute
self.count = count
}
}
extension Snippet: Builder {}
extension Snippet: RawRepresentable {
public var rawValue: String {
guard let countSuffix = count.flatMap({ ":\($0)" }) else {
return attribute.rawValue
}
return attribute.rawValue + countSuffix
}
public init(rawValue: String) {
let components = rawValue.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: true)
if let count = components.last.flatMap({ Int(String($0)) }), components.count == 2 {
self.attribute = Attribute(rawValue: String(components[0]))
self.count = count
} else {
self.attribute = Attribute(rawValue: rawValue)
self.count = nil
}
}
}
| mit | e1a3b3aa7b9a33473f86db913fb5fb07 | 20.509434 | 98 | 0.650877 | 4.05694 | false | false | false | false |
Rahulclaritaz/rahul | ixprez/ixprez/UIImageViewExtension.swift | 1 | 1907 | //
// ImageExtension.swift
// ixprez
//
// Created by Quad on 5/9/17.
// Copyright © 2017 Claritaz Techlabs. All rights reserved.
//
import Foundation
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView{
func getImageFromUrl(_ urlString : String)
{
self.image = nil
let catchImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage
if catchImage != nil
{
self.image = catchImage
}
else
{
let session = URLSession.shared
let url = URL(string:urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
let taskData = session.dataTask(with:url as URL, completionHandler: {(data,response,error) -> Void in
if (data != nil)
{
// Cache to image so it doesn't need to be reloaded every time the user scrolls and table cells are re-used.
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!)
{
imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
self.image = UIImage(data: data!)
}
}
}
})
taskData.resume()
}
}
}
| mit | e39b67a2d505c027f382937dc50cab51 | 21.690476 | 128 | 0.403463 | 6.734982 | false | false | false | false |
emaloney/CleanroomText | Sources/UIFontSizingExtension.swift | 1 | 6656 | //
// UIFontSizingExtension.swift
// Cleanroom Project
//
// Created by Evan Maloney on 7/29/15.
// Copyright © 2015 Gilt Groupe. All rights reserved.
//
#if !os(macOS)
import Foundation
import UIKit
/**
A `UIFont` extension that adds string sizing capabilities.
*/
extension UIFont
{
//==========================================================================
// MARK: Measuring text
//--------------------------------------------------------------------------
/**
Calculates the size of the bounding rectangle required to draw a given
text string in the font represented by the receiver.
- parameter string: The text string to measure.
- parameter maxWidth: The maximum width allowed for the text. If `string`
would not fit within `maxWidth` on a single line, it will be wrapped
according to the behavior of the specified line break mode.
- parameter maxHeight: The maximum height allowed for the text.
- parameter lineBreakMode: The line break mode to use for measuring.
- parameter allowFractionalSize: If `true`, the returned size may contain
fractional (non-integer sub-pixel) values. If `false`, the width and
height components rounded up to the nearest integer (whole-pixel) value.
- returns: The size required to draw the text string, constrained to the
given `maxWidth` and `maxHeight`.
*/
public func size(of string: String,
maxWidth: CGFloat = .greatestFiniteMagnitude,
maxHeight: CGFloat = .greatestFiniteMagnitude,
lineBreakMode: NSLineBreakMode = .byWordWrapping,
fractional allowFractionalSize: Bool = false)
-> CGSize
{
return size(of: string,
maxSize: CGSize(width: maxWidth, height: maxHeight),
lineBreakMode: lineBreakMode,
fractional: allowFractionalSize)
}
/**
Calculates the size of the bounding rectangle required to draw a given
text string in the font represented by the receiver.
- parameter string: The text string to measure.
- parameter maxSize: The maximum size allowed for the text. If `string`
would not fit within `maxSize.width` on a single line, it will be wrapped
according to the behavior of the specified line break mode.
- parameter lineBreakMode: The line break mode to use for measuring.
- parameter allowFractionalSize: If `true`, the returned size may contain
fractional (non-integer, sub-pixel) values. If `false`, the width and
height components rounded up to the nearest integer (whole-pixel) value.
- returns: The size required to draw the text string, constrained to the
given `maxSize`.
*/
public func size(of string: String,
maxSize: CGSize,
lineBreakMode: NSLineBreakMode = .byWordWrapping,
fractional allowFractionalSize: Bool = false)
-> CGSize
{
let style = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
style.lineBreakMode = .byWordWrapping
return size(of: string,
maxSize: maxSize,
paragraphStyle: style,
fractional: allowFractionalSize)
}
//==========================================================================
// MARK: Measuring text with a specific paragraph style
//--------------------------------------------------------------------------
/**
Calculates the size of the bounding rectangle required to draw a given text
string in the font represented by the receiver.
- parameter string: The text string to measure.
- parameter maxWidth: The maximum width allowed for the text. If `string`
would not fit within `maxWidth` on a single line, it will be wrapped
according to the specified paragraph style.
- parameter maxHeight: The maximum height allowed for the text.
- parameter paragraphStyle: The paragraph style for the text.
- parameter allowFractionalSize: If `true`, the returned size may contain
fractional (sub-pixel) values. If `false`, the width and height components
rounded up to the nearest integer (whole-pixel) value.
- returns: The size required to draw the text string, constrained to the
given `maxWidth` and `maxHeight`.
*/
public func size(of string: String,
maxWidth: CGFloat = .greatestFiniteMagnitude,
maxHeight: CGFloat = .greatestFiniteMagnitude,
paragraphStyle: NSParagraphStyle,
fractional allowFractionalSize: Bool = false)
-> CGSize
{
return size(of: string,
maxSize: CGSize(width: maxWidth, height: maxHeight),
paragraphStyle: paragraphStyle,
fractional: allowFractionalSize)
}
/**
Calculates the size of the bounding rectangle required to draw a given text
string in the font represented by the receiver.
- parameter string: The text string to measure.
- parameter maxSize: The maximum size allowed for the text. If `string`
would not fit within `maxSize.width` on a single line, it will be wrapped
according to the specified paragraph style.
- parameter paragraphStyle: The paragraph style for the text.
- parameter allowFractionalSize: If `true`, the returned size may contain
fractional (sub-pixel) values. If `false`, the width and height components
rounded up to the nearest integer (whole-pixel) value.
- returns: The size required to draw the text string, constrained to the
given `maxSize`.
*/
public func size(of string: String,
maxSize: CGSize,
paragraphStyle: NSParagraphStyle,
fractional allowFractionalSize: Bool = false)
-> CGSize
{
let rect = string.boundingRect(with: maxSize,
options: [.usesFontLeading,
.usesLineFragmentOrigin,
.truncatesLastVisibleLine],
attributes: [.font: self, .paragraphStyle: paragraphStyle],
context: nil)
let size: CGSize
if allowFractionalSize {
size = rect.size
} else {
size = CGSize(width: ceil(rect.width), height: ceil(rect.height))
}
return size
}
}
#endif
| mit | 56fcaa9258102c6dc04f2faa189b57b1 | 37.918129 | 98 | 0.602404 | 5.51367 | false | false | false | false |
vadymmarkov/PitchAssistant | Source/Estimation/Strategies/HPSEstimator.swift | 3 | 1142 | final class HPSEstimator: LocationEstimator {
private let harmonics = 5
private let minIndex = 20
func estimateLocation(buffer: Buffer) throws -> Int {
var spectrum = buffer.elements
let maxIndex = spectrum.count - 1
var maxHIndex = spectrum.count / harmonics
if maxIndex < maxHIndex {
maxHIndex = maxIndex
}
var location = minIndex
for j in minIndex...maxHIndex {
for i in 1...harmonics {
spectrum[j] *= spectrum[j * i]
}
if spectrum[j] > spectrum[location] {
location = j
}
}
var max2 = minIndex
var maxsearch = location * 3 / 4
if location > (minIndex + 1) {
if maxsearch <= (minIndex + 1) {
maxsearch = location
}
// swiftlint:disable for_where
for i in (minIndex + 1)..<maxsearch {
if spectrum[i] > spectrum[max2] {
max2 = i
}
}
if abs(max2 * 2 - location) < 4 {
if spectrum[max2] / spectrum[location] > 0.2 {
location = max2
}
}
}
return sanitize(location: location, reserveLocation: maxIndex, elements: spectrum)
}
}
| mit | 7026e360c4f29acd4bb6ad76e8a03f6e | 21.84 | 86 | 0.57268 | 3.924399 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Hearthstone/Secrets/OpponentSecrets.swift | 1 | 7732 | //
// OpponentSecrets.swift
// HSTracker
//
// Created by Benjamin Michotte on 9/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
import AppKit
class OpponentSecrets {
private(set) lazy var secrets = [SecretHelper]()
var proposedAttackerEntityId: Int = 0
var proposedDefenderEntityId: Int = 0
private(set) var game: Game
init(game: Game) {
self.game = game
}
var displayedClasses: [CardClass] {
return secrets.map({ $0.heroClass }).sorted {
$0.rawValue < $1.rawValue
}
}
func getIndexOffset(heroClass: CardClass, gameFormat: Format) -> Int {
switch heroClass {
case .hunter:
return 0
case .mage:
if displayedClasses.contains(.hunter) {
return SecretHelper.getMaxSecretCount(heroClass: .hunter, game: game)
}
return 0
case .paladin:
if displayedClasses.contains(.hunter) && displayedClasses.contains(.mage) {
return SecretHelper.getMaxSecretCount(heroClass: .hunter, game: game)
+ SecretHelper.getMaxSecretCount(heroClass: .mage, game: game)
}
if displayedClasses.contains(.hunter) {
return SecretHelper.getMaxSecretCount(heroClass: .hunter, game: game)
}
if displayedClasses.contains(.mage) {
return SecretHelper.getMaxSecretCount(heroClass: .mage, game: game)
}
return 0
default: break
}
return 0
}
func getHeroClass(cardId: String) -> CardClass? {
if let card = Cards.by(cardId: cardId) {
return card.playerClass
}
return nil
}
func trigger(cardId: String) {
if secrets.any({ $0.tryGetSecret(cardId: cardId) }) {
setZero(cardId: cardId)
} else {
setMax(cardId)
}
}
func newSecretPlayed(heroClass: CardClass, id: Int, turn: Int, knownCardId: String? = nil) {
let helper = SecretHelper(game: game, heroClass: heroClass, id: id, turnPlayed: turn)
if let knownCardId = knownCardId {
SecretHelper.getSecretIds(heroClass: heroClass, game: game).forEach({
helper.trySetSecret(cardId: $0, active: $0 == knownCardId)
})
}
secrets.append(helper)
Log.info?.message("Added secret with id: \(id)")
}
func secretRemoved(id: Int, cardId: String) {
if let index = secrets.index(where: { $0.id == id }) {
if index == -1 {
Log.warning?.message("Secret with id=\(id), cardId=\(cardId)"
+ " not found when trying to remove it.")
return
}
let attacker = game.entities[proposedAttackerEntityId]
let defender = game.entities[proposedDefenderEntityId]
// see http://hearthstone.gamepedia.com/Advanced_rulebook#Combat
// for fast vs. slow secrets
// a few fast secrets can modify combat
// freezing trap and vaporize remove the attacking minion
// misdirection, noble sacrifice change the target
// if multiple secrets are in play and a fast secret triggers,
// we need to eliminate older secrets which would have
// been triggered by the attempted combat
if CardIds.Secrets.FastCombat.contains(cardId) && attacker != nil && defender != nil {
zeroFromAttack(attacker: game.entities[proposedAttackerEntityId]!,
defender: game.entities[proposedDefenderEntityId]!,
fastOnly: true,
_stopIndex: index)
}
secrets.remove(secrets[index])
Log.info?.message("Removed secret with id:\(id)")
}
}
func zeroFromAttack(attacker: Entity, defender: Entity,
fastOnly: Bool = false, _stopIndex: Int = -1) {
var stopIndex = _stopIndex
if _stopIndex == -1 {
stopIndex = secrets.count
}
if game.opponentMinionCount < 7 {
setZeroOlder(cardId: CardIds.Secrets.Paladin.NobleSacrifice, stopIndex: stopIndex)
}
if defender.isHero {
if !fastOnly {
if game.opponentMinionCount < 7 {
setZeroOlder(cardId: CardIds.Secrets.Hunter.BearTrap, stopIndex: stopIndex)
}
setZeroOlder(cardId: CardIds.Secrets.Mage.IceBarrier, stopIndex: stopIndex)
}
setZeroOlder(cardId: CardIds.Secrets.Hunter.ExplosiveTrap, stopIndex: stopIndex)
if game.isMinionInPlay {
setZeroOlder(cardId: CardIds.Secrets.Hunter.Misdirection, stopIndex: stopIndex)
}
if attacker.isMinion {
setZeroOlder(cardId: CardIds.Secrets.Mage.Vaporize, stopIndex: stopIndex)
setZeroOlder(cardId: CardIds.Secrets.Hunter.FreezingTrap, stopIndex: stopIndex)
}
} else {
if !fastOnly && game.opponentMinionCount < 7 {
setZeroOlder(cardId: CardIds.Secrets.Hunter.SnakeTrap, stopIndex: stopIndex)
}
if attacker.isMinion {
setZeroOlder(cardId: CardIds.Secrets.Hunter.FreezingTrap, stopIndex: stopIndex)
}
}
}
func clearSecrets() {
secrets.removeAll()
Log.info?.message("Cleared secrets")
}
func setMax(_ cardId: String) {
if cardId.isBlank {
return
}
secrets.forEach {
$0.trySetSecret(cardId: cardId, active: true)
}
}
func setZero(cardId: String) {
if cardId.isBlank {
return
}
setZeroOlder(cardId: cardId, stopIndex: secrets.count)
}
func setZeroOlder(cardId: String, stopIndex: Int) {
if cardId.isBlank {
return
}
for index in 0 ..< stopIndex {
secrets[index].trySetSecret(cardId: cardId, active: false)
}
if stopIndex > 0 {
Log.info?.message("Set secret to zero: \(String(describing: Cards.by(cardId: cardId)))")
}
}
func getSecrets(gameFormat: Format) -> [Secret] {
let returnThis = displayedClasses.expand({
SecretHelper.getSecretIds(heroClass: $0, game: game).map {
Secret(cardId: $0, count: 0)
}
})
for secret in secrets {
for (cardId, possible) in secret.possibleSecrets where possible {
returnThis.firstWhere({ $0.cardId == cardId })?.count += 1
}
}
return returnThis
}
func allSecrets(gameFormat: Format) -> [Card] {
var cards: [Card] = []
getSecrets(gameFormat: gameFormat).forEach({ (secret) in
if let card = Cards.by(cardId: secret.cardId), secret.count > 0 {
card.count = secret.count
cards.append(card)
}
})
return cards
}
func getDefaultSecrets(heroClass: CardClass, gameFormat: Format) -> [Secret] {
return SecretHelper.getSecretIds(heroClass: heroClass, game: game).map {
Secret(cardId: $0, count: 1)
}
}
}
extension OpponentSecrets: CustomStringConvertible {
var description: String {
return "[OpponentSecret: "
+ "secrets=\(secrets)"
+ ", proposedAttackerEntityId=\(proposedAttackerEntityId)"
+ ", proposedDefenderEntityId=\(proposedDefenderEntityId)]"
}
}
| mit | 7594e049d94b2d705e777a4826ae05d4 | 32.613043 | 100 | 0.570172 | 4.599048 | false | false | false | false |
TangentMicroServices/HoursService.iOSClient | HoursService.iOSClient/HoursService.iOSClientTests/HoursService_iOSClientTests.swift | 1 | 2921 | //
// HoursService_iOSClientTests.swift
// HoursService.iOSClientTests
//
// Created by Ian Roberts on 2/10/15.
// Copyright (c) 2015 Ian Roberts. All rights reserved.
//
import UIKit
import XCTest
import HoursService_iOSClient
class HoursService_iOSClientTests: XCTestCase {
var token: String = ""
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
func testAddEntry(){
var data = [
"user": 1,
"project_id": 1,
"project_task_id": 1,
"status": "Open",
"day": "2015-02-19",
"start_time": "14:13:09",
"end_time": "14:13:09",
"comments": "Test post",
"hours": "4.00",
"overtime": false,
"tags": ""
]
}
func testAuthUserSuccess(){
var serviceApi = ServiceApi()
var username: String = "admin"
var password: String = "a"
serviceApi.authenticateUser(username, password: password, callback: { (success:String?, error:String?) -> () in
XCTAssertNil(error, "Auth user error should return nil")
XCTAssertNotNil(success, "A token should be returned")
self.token = success!
})
}
func testAuthUserFail(){
var serviceApi = ServiceApi()
var username: String = "fail"
var password: String = "fail"
serviceApi.authenticateUser(username, password: password, callback: { (success:String?, error:String?) -> () in
XCTAssertNil(success, "Auth user should return nil")
XCTAssertNotNil(error, "A token should be returned")
})
}
func testGetEntriesSuccess(){
/*var serviceApi = ServiceApi()
serviceApi.getEntries(token, callback: { (success:NSArray?, error:String?) -> () in
XCTAssertNil(error, "Get entry error should return nil")
XCTAssertNotNil(success, "An array of data should be returned")
XCTAssertGreaterThan(success!.count, 70, "More then 0 entries were returned")
XCTAssertNotNil(success?[0]["comments"], "Comments exist")
})
*/
}
}
| mit | 0ea744532521eb8fa2e0d4831f26faeb | 28.505051 | 119 | 0.552893 | 4.696141 | false | true | false | false |
mpsnp/ReSwift | ReSwiftTests/StandardActionTests.swift | 3 | 5787 | //
// StandardActionTests.swift
// ReSwift
//
// Created by Benjamin Encz on 12/29/15.
// Copyright © 2015 Benjamin Encz. All rights reserved.
//
import XCTest
import ReSwift
class StandardActionInitTests: XCTestCase {
/**
it can be initialized with just a type
*/
func testInitWithType() {
let action = StandardAction(type: "Test")
XCTAssertEqual(action.type, "Test")
}
/**
it can be initialized with a type and a payload
*/
func testInitWithTypeAndPayload() {
let action = StandardAction(type:"Test", payload: ["testKey": 5 as AnyObject])
let payload = action.payload!["testKey"]! as! Int
XCTAssertEqual(payload, 5)
XCTAssertEqual(action.type, "Test")
}
}
class StandardActionInitSerializationTests: XCTestCase {
/**
it can initialize action with a dictionary
*/
func testCanInitWithDictionary() {
let actionDictionary: [String: AnyObject] = [
"type": "TestType" as AnyObject,
"payload": "ReSwift_Null" as AnyObject,
"isTypedAction": true as AnyObject
]
let action = StandardAction(dictionary: actionDictionary)
XCTAssertEqual(action?.type, "TestType")
XCTAssertNil(action?.payload)
XCTAssertEqual(action?.isTypedAction, true)
}
/**
it can convert an action to a dictionary
*/
func testConvertActionToDict() {
let action = StandardAction(type:"Test", payload: ["testKey": 5 as AnyObject],
isTypedAction: true)
let dictionary = action.dictionaryRepresentation
let type = dictionary["type"] as! String
let payload = dictionary["payload"] as! [String: AnyObject]
let isTypedAction = dictionary["isTypedAction"] as! Bool
XCTAssertEqual(type, "Test")
XCTAssertEqual(payload["testKey"] as? Int, 5)
XCTAssertEqual(isTypedAction, true)
}
/**
it can serialize / deserialize actions with payload and without custom type
*/
func testWithPayloadWithoutCustomType() {
let action = StandardAction(type:"Test", payload: ["testKey": 5 as AnyObject])
let dictionary = action.dictionaryRepresentation
let deserializedAction = StandardAction(dictionary: dictionary)
let payload = deserializedAction?.payload?["testKey"] as? Int
XCTAssertEqual(payload, 5)
XCTAssertEqual(deserializedAction?.type, "Test")
}
/**
it can serialize / deserialize actions with payload and with custom type
*/
func testWithPayloadAndCustomType() {
let action = StandardAction(type:"Test", payload: ["testKey": 5 as AnyObject],
isTypedAction: true)
let dictionary = action.dictionaryRepresentation
let deserializedAction = StandardAction(dictionary: dictionary)
let payload = deserializedAction?.payload?["testKey"] as? Int
XCTAssertEqual(payload, 5)
XCTAssertEqual(deserializedAction?.type, "Test")
XCTAssertEqual(deserializedAction?.isTypedAction, true)
}
/**
it can serialize / deserialize actions without payload and without custom type
*/
func testWithoutPayloadOrCustomType() {
let action = StandardAction(type:"Test", payload: nil)
let dictionary = action.dictionaryRepresentation
let deserializedAction = StandardAction(dictionary: dictionary)
XCTAssertNil(deserializedAction?.payload)
XCTAssertEqual(deserializedAction?.type, "Test")
}
/**
it can serialize / deserialize actions without payload and with custom type
*/
func testWithoutPayloadWithCustomType() {
let action = StandardAction(type:"Test", payload: nil,
isTypedAction: true)
let dictionary = action.dictionaryRepresentation
let deserializedAction = StandardAction(dictionary: dictionary)
XCTAssertNil(deserializedAction?.payload)
XCTAssertEqual(deserializedAction?.type, "Test")
XCTAssertEqual(deserializedAction?.isTypedAction, true)
}
/**
it initializer returns nil when invalid dictionary is passed in
*/
func testReturnsNilWhenInvalid() {
let deserializedAction = StandardAction(dictionary: [:])
XCTAssertNil(deserializedAction)
}
}
class StandardActionConvertibleInit: XCTestCase {
/**
it initializer returns nil when invalid dictionary is passed in
*/
func testInitWithStandardAction() {
let standardAction = StandardAction(type: "Test", payload: ["value": 10 as AnyObject])
let action = SetValueAction(standardAction)
XCTAssertEqual(action.value, 10)
}
func testInitWithStringStandardAction() {
let standardAction = StandardAction(type: "Test", payload: ["value": "10" as AnyObject])
let action = SetValueStringAction(standardAction)
XCTAssertEqual(action.value, "10")
}
}
class StandardActionConvertibleTests: XCTestCase {
/**
it can be converted to a standard action
*/
func testConvertToStandardAction() {
let action = SetValueAction(5)
let standardAction = action.toStandardAction()
XCTAssertEqual(standardAction.type, "SetValueAction")
XCTAssertEqual(standardAction.isTypedAction, true)
XCTAssertEqual(standardAction.payload?["value"] as? Int, 5)
}
func testConvertToStringStandardAction() {
let action = SetValueStringAction("5")
let standardAction = action.toStandardAction()
XCTAssertEqual(standardAction.type, "SetValueStringAction")
XCTAssertEqual(standardAction.isTypedAction, true)
XCTAssertEqual(standardAction.payload?["value"] as? String, "5")
}
}
| mit | 883bba00821c9ca8cd4c5e80325082ad | 29.613757 | 96 | 0.668337 | 5.044464 | false | true | false | false |
danielalves/megaman-ios | Megaman/Vector3D.swift | 1 | 4149 | //
// Vector3D.swift
// Megaman
//
// Created by Daniel L. Alves on 4/6/14.
// Copyright (c) 2014 Daniel L. Alves. All rights reserved.
//
import UIKit
struct Vector3D : CustomStringConvertible, Equatable
{
var x : CGFloat = 0.0
var y : CGFloat = 0.0
var z : CGFloat = 0.0
var module : CGFloat
{
return CGFloat(sqrtf( CFloat(x*x + y*y + z*z) ))
}
init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat)
{
self.x = x
self.y = y
self.z = z
}
init(point: CGPoint)
{
x = point.x
y = point.y
z = 0.0
}
init(cgVector: CGVector)
{
x = cgVector.dx
y = cgVector.dy
z = 0.0
}
init(other: Vector3D)
{
x = other.x
y = other.y
z = other.z
}
func dot(other: Vector3D) -> CGFloat
{
return x * other.x + y * other.y + z * other.z
}
func cross(other: Vector3D) -> Vector3D
{
return Vector3D( y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x )
}
func angleBetween(other: Vector3D) -> CGFloat
{
return CGFloat(radiansToDegrees( CFloat(acosf(CFloat( normalized().dot( other.normalized()))))))
}
mutating func normalize() -> Vector3D
{
let m = module
if fdif( CFloat(m), f2: CFloat(0.0))
{
x /= m
y /= m
z /= m
}
return self
}
func normalized() -> Vector3D
{
var clone = self
return clone.normalize()
}
func toCGPoint() -> CGPoint
{
return CGPoint( x: x, y: y )
}
func toCGVector() -> CGVector
{
return CGVector( dx: x, dy: y )
}
subscript(index: Int) -> CGFloat
{
get
{
assert( index >= 0 && index < 3, "index must be positive and less than 3" )
switch index
{
case 0:
return x
case 1:
return y
case 2:
return z
// Will never run: assert is protecting us
default:
return CGFloat.NaN;
}
}
set(newValue)
{
assert( index >= 0 && index < 3, "index must be positive and less than 3" )
switch index
{
case 0:
x = newValue
case 1:
y = newValue
case 2:
z = newValue
// Will never run: assert is protecting us
default:
return;
}
}
}
var description: String
{
return "x: \(x), y: \(y), z: \(z)"
}
}
func + (left: Vector3D, right: Vector3D) -> Vector3D
{
return Vector3D( left.x + right.x, left.y + right.y, left.z + right.z )
}
func - (left: Vector3D, right: Vector3D) -> Vector3D
{
return Vector3D( left.x - right.x, left.y - right.y, left.z - right.z )
}
prefix func - (vector: Vector3D) -> Vector3D
{
return Vector3D( -vector.x, -vector.y, -vector.z )
}
func += (inout left: Vector3D, right: Vector3D)
{
left = left + right
}
func -= (inout left: Vector3D, right: Vector3D)
{
left = left - right
}
prefix func ++ (inout vector: Vector3D) -> Vector3D
{
vector += Vector3D(1.0, 1.0, 1.0)
return vector
}
func == (left: Vector3D, right: Vector3D) -> Bool
{
return ( left.x == right.x ) && ( left.y == right.y ) && ( left.z == right.z )
}
func * (left: Vector3D, right: CGFloat) -> Vector3D
{
return Vector3D( left.x * right, left.y * right, left.z * right )
}
func * (left: CGFloat, right: Vector3D) -> Vector3D
{
return right * left
}
func * (left: Vector3D, right: Vector3D) -> CGFloat
{
return left.dot( right )
}
infix operator ** {}
func ** (left: Vector3D, right: Vector3D) -> Vector3D
{
return left.cross( right )
}
| mit | 831bfa50ab654c43cd68e1622f9e328d | 15.081395 | 104 | 0.469511 | 3.558319 | false | false | false | false |
jpchmura/JPCDataSourceController | JPCDataSourceControllerExamples/JPCDataSourceControllerExamplesTests/DataSourceControllerTests.swift | 1 | 56421 | //
// DataSourceControllerTests.swift
// JPCDataSourceControllerExamples
//
// Created by Jon Chmura on 4/3/15.
// Copyright (c) 2015 Jon Chmura. All rights reserved.
//
import UIKit
import XCTest
import JPCDataSourceControllerExamples
import Quick
import Nimble
class DataSourceControllerSpec : QuickSpec {
// MARK: - Shared Mocks
class FetchRequestMock: FetchRequest {
var executeCalled = 0
var executeCallbacks: [(result: LoadModelContentResult) -> Void] = []
var cancelCalled = 0
var result: LoadModelContentResult?
func execute(completion: (result: LoadModelContentResult) -> Void) {
executeCallbacks.append(completion)
executeCalled++
}
func cancel() {
cancelCalled++
}
func finishWithResult(result: LoadModelContentResult) {
self.result = result
if let handler = self.executeCallbacks.first {
handler(result: result)
}
}
}
class ModelMock: Model {
var prepareContentCalled = 0
var prepareContentResult: LoadModelContentResult? = LoadModelContentResult.Success(resultCount: 1)
func prepareContent() -> LoadModelContentResult {
prepareContentCalled++
return prepareContentResult!
}
subscript(outerIndexPath: NSIndexPath) -> Model? {
get {
return nil
}
}
func numberOfSections() -> Int {
return 0
}
func numberOfItems(inSection section: Int) -> Int {
return 0
}
func item(forIndexPath indexPath: NSIndexPath) -> AnyObject? {
return nil
}
func headerItem(forSection section: Int) -> AnyObject? {
return nil
}
func footerItem(forSection section: Int) -> AnyObject? {
return nil
}
func supplementaryViewItem(forIndexPath indexPath: NSIndexPath, ofKind kind: String) -> AnyObject? {
return nil
}
}
override func spec() {
// MARK: -
// MARK: - Data Source Controller Spec
// MARK: -
describe("Data Source Controller State") { () -> Void in
var dataSourceController: DataSourceController!
var tableView: UITableView!
beforeEach({ () -> () in
tableView = UITableView()
dataSourceController = DataSourceController(profile: DataSourceController.Profile.TableView(tableView))
})
// MARK: - Activity State Machine
describe("Activity State Machine") { () -> Void in
class OperationStateTestsMock: DataSourceController {
var contentStateMock = DataSourceController.ContentState.Init
var operationStateTransitions: [DataSourceController.OperationState] = []
override var contentState: DataSourceController.ContentState {
get {
return contentStateMock
}
set {
contentStateMock = newValue
}
}
var lastFetchSuccessMock: Bool = false
override var lastFetchWasSuccessful: Bool {
get {
return lastFetchSuccessMock
}
}
private override func transition(toOperationState state: DataSourceController.OperationState) -> Bool {
self.operationStateTransitions.append(state)
return super.transition(toOperationState: state)
}
}
class AnimatorMock: DataSourceReloadData {
var willUpdateCalls: [Model] = []
var performColCalls: [Model] = []
var performTableCalls: [Model] = []
private override func willUpdate(modelBeforeUpdate model: Model) {
self.willUpdateCalls.append(model)
}
private override func performUpdates(modelAfterUpdate model: Model, onCollectionView collectionView: UICollectionView) {
self.performColCalls.append(model)
}
private override func performUpdates(modelAfterUpdate model: Model, onTableView tableView: UITableView) {
self.performTableCalls.append(model)
}
}
var dataSourceControllerMock: OperationStateTestsMock {
get {
return dataSourceController as! OperationStateTestsMock
}
}
var animatorMock: AnimatorMock!
beforeEach() { () -> () in
dataSourceController = OperationStateTestsMock(profile: DataSourceController.Profile.TableView(tableView))
animatorMock = AnimatorMock()
dataSourceController.animator = animatorMock
}
it ("Should be Idle On init") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
// MARK: Transitions
describe("Allowed Transitions") { () -> Void in
class TransitionTestsMock: DataSourceController {
var mockOperationState: OperationState = DataSourceController.OperationState.Idle
override var operationState: OperationState {
get {
return mockOperationState
}
}
}
var transitionMock: TransitionTestsMock!
beforeEach() { () -> () in
transitionMock = TransitionTestsMock(profile: DataSourceController.Profile.TableView(UITableView()))
}
context("Idle") { () -> Void in
beforeEach() { () -> () in
transitionMock.mockOperationState = .Idle
}
it ("Cant transition to Idle") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Idle)) == false
}
it ("Can transition to Fetch") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Fetch)) == true
}
it ("Can transition to Prepare") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Prepare)) == true
}
it ("Can transition to Reload") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Reload)) == true
}
}
context("Fetch") { () -> Void in
beforeEach() { () -> () in
transitionMock.mockOperationState = .Fetch
}
it ("Can transition to Idle") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Idle)) == true
}
it ("Cant transition to Fetch") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Fetch)) == false
}
it ("Can transition to Prepare") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Prepare)) == true
}
it ("Cant transition to Reload") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Reload)) == false
}
}
context("Prepare") { () -> Void in
beforeEach() { () -> () in
transitionMock.mockOperationState = .Prepare
}
it ("Can transition to Idle") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Idle)) == true
}
it ("Cant transition to Fetch") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Fetch)) == false
}
it ("Cant transition to Prepare") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Prepare)) == false
}
it ("Can transition to Reload") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Reload)) == true
}
}
context("Reload") { () -> Void in
beforeEach() { () -> () in
transitionMock.mockOperationState = .Reload
}
it ("Can transition to Idle") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Idle)) == true
}
it ("Cant transition to Fetch") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Fetch)) == false
}
it ("Cant transition to Prepare") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Prepare)) == false
}
it ("Cant transition to Reload") { () -> Void in
expect(transitionMock.canTransition(toOperationState: .Reload)) == false
}
}
}
// MARK: Idle
describe("Idle") { () -> Void in
context("viewWillAppear") { () -> Void in
beforeEach() { () -> () in
dataSourceController.shouldFetchContentOnAppear = .Never
dataSourceController.shouldPrepareContentOnAppear = .Never
}
context("Content State is Init") { () -> Void in
beforeEach() { () -> () in
dataSourceControllerMock.contentStateMock = .Init
dataSourceController.viewWillAppear()
}
it("Should transition to Fetch") { () -> () in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Fetch))
}
}
context("Content State is Error") { () -> Void in
beforeEach() { () -> () in
dataSourceControllerMock.contentStateMock = .Error
dataSourceController.viewWillAppear()
}
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
context("shouldFetchOnAppear is OnError") { () -> Void in
beforeEach() { () -> () in
dataSourceController.shouldFetchContentOnAppear = .OnError
dataSourceController.viewWillAppear()
}
it("Should transition to Fetch") { () -> () in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Fetch))
}
}
context("shouldPrepareContentOnAppear is OnError") { () -> Void in
beforeEach() { () -> () in
dataSourceController.shouldPrepareContentOnAppear = .OnError
dataSourceController.viewWillAppear()
}
it("Should transition to Prepare") { () -> () in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Prepare))
}
}
}
context("Content state is Complete") { () -> Void in
beforeEach() { () -> () in
dataSourceControllerMock.contentStateMock = .Complete
dataSourceController.viewWillAppear()
}
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
context("shouldFetchOnAppear is Always") { () -> Void in
beforeEach() { () -> () in
dataSourceController.shouldFetchContentOnAppear = .Always
dataSourceController.viewWillAppear()
}
it("Should transition to Fetch") { () -> () in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Fetch))
}
}
context("shouldPrepareContentOnAppear is Always") { () -> Void in
beforeEach() { () -> () in
dataSourceController.shouldPrepareContentOnAppear = .Always
dataSourceController.viewWillAppear()
}
it("Should transition to Prepare") { () -> () in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Prepare))
}
}
}
}
context("viewWillDisappear") { () -> Void in
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
}
context("Fetch called") { () -> Void in
beforeEach() { () -> () in
dataSourceController.fetchContent()
}
it ("Should transition to Fetch") { () -> Void in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Fetch))
}
}
context("Prepare called") { () -> Void in
beforeEach() { () -> () in
dataSourceController.prepareContent()
}
it ("Should transition to Prepare") { () -> Void in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Prepare))
}
}
context("Cancel called") { () -> Void in
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
}
} // END Describe Idle
// MARK: Fetch
describe("Fetch") { () -> Void in
var fetchRequests: [FetchRequestMock]!
beforeEach() { () -> () in
let fetch1 = FetchRequestMock()
let fetch2 = FetchRequestMock()
dataSourceController.fetchRequests = [fetch1, fetch2]
fetchRequests = [fetch1, fetch2]
dataSourceController.transition(toOperationState: .Fetch)
}
it ("Cant transition to Prepare before fetch finishes") { () -> Void in
expect(dataSourceController.canTransition(toOperationState: .Prepare)).to(beFalse())
}
it ("Should execute all FetchRequests") { () -> Void in
expect(fetchRequests[0].executeCalled).to(equal(1))
expect(fetchRequests[1].executeCalled).to(equal(1))
}
context("No Fetches") { () -> Void in
beforeEach() { () -> () in
dataSourceController.transition(toOperationState: .Idle)
dataSourceController.fetchRequests.removeAll(keepCapacity: false)
dataSourceController.transition(toOperationState: .Fetch)
}
it ("Should continue to Prepare") { () -> Void in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Prepare))
}
}
context("onComplete") { () -> Void in
let completeBlock = { () -> () in
// Call callbacks on fetch request to trigger completion
let result = LoadModelContentResult.Success(resultCount: 1)
for aFetch in fetchRequests {
aFetch.finishWithResult(result)
}
}
context("Success!") { () -> Void in
beforeEach() { () -> () in
dataSourceControllerMock.lastFetchSuccessMock = true
completeBlock()
}
it ("Should update lastFetchDate") { () -> Void in
expect(dataSourceController.lastFetchDate?.timeIntervalSinceNow).to(beCloseTo(0, within: 100))
}
it ("Should transition to Prepare") { () -> Void in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Prepare))
}
}
context("Failure") { () -> Void in
beforeEach() { () -> () in
dataSourceControllerMock.lastFetchSuccessMock = false
completeBlock()
}
it ("Should update lastFetchDate") { () -> Void in
expect(dataSourceController.lastFetchDate?.timeIntervalSinceNow).to(beCloseTo(0, within: 100))
}
it ("Should transition to Idle") { () -> Void in
expect(dataSourceControllerMock.operationStateTransitions).toNot(contain(DataSourceController.OperationState.Prepare))
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
}
}
context("viewWillAppear") { () -> Void in
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Fetch))
}
}
context("viewWillDisappear") { () -> Void in
context("shouldCancelFetchOnDisappear is set") { () -> Void in
beforeEach() { () -> () in
dataSourceController.shouldCancelFetchOnDisappear = true
dataSourceController.viewWillDisappear()
}
it ("Should cancel Fetch") { () -> Void in
expect(fetchRequests[0].cancelCalled).to(equal(1))
expect(fetchRequests[1].cancelCalled).to(equal(1))
}
it ("Should transition to Idle") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
}
context("shouldCancelFetchOnDisappear is not set") { () -> Void in
beforeEach() { () -> () in
dataSourceController.shouldCancelFetchOnDisappear = false
dataSourceController.viewWillDisappear()
}
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Fetch))
}
}
}
context("Fetch called") { () -> Void in
beforeEach() { () -> () in
dataSourceController.fetchContent()
}
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Fetch))
}
}
context("Prepare called") { () -> Void in
beforeEach() { () -> () in
dataSourceController.prepareContent()
}
it ("Should do nothing") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Fetch))
}
}
context("Cancel called") { () -> Void in
beforeEach() { () -> () in
dataSourceController.cancelOperations()
}
it ("Should cancel Fetch") { () -> Void in
expect(fetchRequests[0].cancelCalled).to(equal(1))
expect(fetchRequests[1].cancelCalled).to(equal(1))
}
it ("Should transition to Idle") { () -> Void in
expect(dataSourceController.operationState).to(equal(DataSourceController.OperationState.Idle))
}
}
} // END Describe Fetch
// MARK: Prepare
describe("Prepare") { () -> Void in
var models: [ModelMock]!
let setup = { (success: Bool) -> () in
let model1 = ModelMock()
let model2 = ModelMock()
let composite = BasicCompositeModel(models: [model1, model2])
model1.prepareContentResult = success ? LoadModelContentResult.Success(resultCount: 1) : LoadModelContentResult.Failure()
dataSourceController.model = composite
models = [model1, model2]
dataSourceController.transition(toOperationState: .Prepare)
}
context("Success") { () -> Void in
beforeEach() { () -> () in
setup(true)
}
it ("Should call prepare on Models") { () -> Void in
expect(models[0].prepareContentCalled).to(equal(1))
expect(models[1].prepareContentCalled).to(equal(1))
}
it ("Should call willUpdate on Animator") { () -> Void in
expect(animatorMock.willUpdateCalls.count) == 1
}
it ("Should transition to Reload") { () -> Void in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Reload))
}
}
context("Failure") { () -> Void in
beforeEach() { () -> () in
setup(false)
}
it ("Should call prepare on Models") { () -> Void in
expect(models[0].prepareContentCalled).to(equal(1))
expect(models[1].prepareContentCalled).to(equal(1))
}
it ("Should transition to Reload") { () -> Void in
expect(dataSourceControllerMock.operationStateTransitions).to(contain(DataSourceController.OperationState.Reload))
}
}
} // END Describe Prepare
// MARK: Reload
describe("Reload") { () -> Void in
var model: ModelMock!
beforeEach() { () -> () in
model = ModelMock()
}
context("Collection View") { () -> Void in
beforeEach() { () -> () in
dataSourceController = DataSourceController(profile: DataSourceController.Profile.CollectionView(UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())))
dataSourceController.animator = animatorMock
dataSourceController.model = model
dataSourceController.transition(toOperationState: .Reload)
}
it ("Should call performUpdates") { () -> Void in
expect(animatorMock.performColCalls.count) == 1
}
}
context("Table View") { () -> Void in
beforeEach() { () -> () in
dataSourceController = DataSourceController(profile: DataSourceController.Profile.TableView(UITableView()))
dataSourceController.animator = animatorMock
dataSourceController.model = model
dataSourceController.transition(toOperationState: .Reload)
}
it ("Should call performUpdates") { () -> Void in
expect(animatorMock.performTableCalls.count) == 1
}
}
}
} // END Describe Activity State Machine
// MARK: - Content State Machine
describe("Content State Machine") { () -> Void in
class DelegateMock: DataSourceControllerDelegate {
var shouldErrorFetches: Bool? = nil
var shouldErrorPrepare: Bool? = nil
private func dataSourceController(controller: DataSourceController, cellFactoryForModel model: Model, atIndexPath indexPath: NSIndexPath) -> CellFactory? {
return nil
}
private func dataSourceController(controller: DataSourceController, embeddedCollectionViewForModel model: Model, atIndexPath: NSIndexPath) -> UICollectionView? {
return nil
}
private func dataSourceController(controller: DataSourceController, shouldErrorForFetches fetchRequests: [FetchRequest]) -> Bool? {
return shouldErrorFetches
}
private func dataSourceController(controller: DataSourceController, shouldErrorForModel model: Model) -> Bool? {
return shouldErrorPrepare
}
private func dataSourceController(controller: DataSourceController, didTransitionToOperationState toState: DataSourceController.OperationState, fromState: DataSourceController.OperationState) {
}
private func dataSourceController(controller: DataSourceController, didTransitionToContentState toState: DataSourceController.ContentState, fromState: DataSourceController.ContentState) {
}
}
var delegate: DelegateMock!
beforeEach() { () -> () in
delegate = DelegateMock()
dataSourceController.delegate = delegate
}
context("Activity state Fetch -> Prepare") { () -> Void in
var fetchRequests: [FetchRequestMock]!
beforeEach() { () -> () in
let fetch1 = FetchRequestMock()
let fetch2 = FetchRequestMock()
dataSourceController.fetchRequests = [fetch1, fetch2]
fetchRequests = [fetch1, fetch2]
dataSourceController.transition(toOperationState: .Fetch)
}
context("All fetches successful") { () -> Void in
beforeEach() { () -> () in
let result = LoadModelContentResult.Success(resultCount: 1)
for aFetch in fetchRequests {
aFetch.finishWithResult(result)
}
}
it ("Should transition to Complete") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Complete))
}
}
context("Some fetches errored") { () -> Void in
let failFetchesBlock = { (response: Bool?) -> () in
delegate.shouldErrorFetches = response
let result = LoadModelContentResult.Failure()
for aFetch in fetchRequests {
aFetch.finishWithResult(result)
}
}
context("Delegate doesnt respond") { () -> Void in
beforeEach() { () -> () in
failFetchesBlock(nil)
}
it ("Should transition to Error") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Error))
}
}
context("Delegate responds true") { () -> Void in
beforeEach() { () -> () in
failFetchesBlock(true)
}
it ("Should transition to Error") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Error))
}
}
context("Delegate responds false") { () -> Void in
beforeEach() { () -> () in
failFetchesBlock(false)
}
it ("Should transition to Complete") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Complete))
}
}
}
}
context("Activity state Prepare -> Reload") { () -> Void in
var models: [ModelMock]!
beforeEach() { () -> () in
let model1 = ModelMock()
let model2 = ModelMock()
let composite = BasicCompositeModel(models: [model1, model2])
dataSourceController.model = composite
models = [model1, model2]
}
context("All Prepares successful") { () -> Void in
beforeEach() { () -> () in
for aModel in models {
aModel.prepareContentResult = LoadModelContentResult.Success(resultCount: 1)
}
dataSourceController.transition(toOperationState: .Prepare)
}
it ("Should transition to Complete") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Complete))
}
}
let failModelsBlock = { (response: Bool?) -> () in
for aModel in models {
aModel.prepareContentResult = LoadModelContentResult.Failure()
}
delegate.shouldErrorPrepare = response
dataSourceController.transition(toOperationState: .Prepare)
}
context("Some prepares errored") { () -> Void in
context("Delegate doesnt respond") { () -> Void in
beforeEach() { () -> () in
failModelsBlock(nil)
}
it ("Should transition to Error") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Error))
}
}
context("Delegate responds true") { () -> Void in
beforeEach() { () -> () in
failModelsBlock(true)
}
it ("Should transition to Error") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Error))
}
}
context("Delegate responds false") { () -> Void in
beforeEach() { () -> () in
failModelsBlock(false)
}
it ("Should transition to Complete") { () -> Void in
expect(dataSourceController.contentState).to(equal(DataSourceController.ContentState.Complete))
}
}
}
}
} // END Describe Content State Machine
describe("Background view") { () -> Void in
class BackgroundViewTestsMock: DataSourceController {
var mockOperationState: OperationState = DataSourceController.OperationState.Idle
var mockContentState: ContentState = DataSourceController.ContentState.Init
override var operationState: OperationState {
get {
return mockOperationState
}
}
override var contentState: ContentState {
get {
return mockContentState
}
}
}
var mockController: BackgroundViewTestsMock! {
get {
return dataSourceController as! BackgroundViewTestsMock
}
}
var backgroundView: BackgroundView? {
get {
return dataSourceController.backgroundView
}
}
beforeEach() { () -> () in
dataSourceController = BackgroundViewTestsMock(profile: DataSourceController.Profile.TableView(UITableView()))
backgroundView?.pullToRefreshView = PullToRefreshView()
backgroundView?.loadingView = LoadingView()
backgroundView?.errorView = UIView()
backgroundView?.pagingView = PagingView()
}
it ("Should initialize Background view") { () -> Void in
expect(backgroundView).toNot(beNil())
}
context("Init - Idle") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Idle
mockController.mockContentState = .Init
mockController.refreshBackgroundView()
}
it ("Should show none") { () -> Void in
expect(backgroundView?.visibleViews).to(beEmpty())
}
}
context("Init - Fetch") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Fetch
mockController.mockContentState = .Init
mockController.refreshBackgroundView()
}
it ("Should not show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should show Loading") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.Loading))
}
it ("Should not show Error") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Error))
}
it ("Should not show Paging") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Paging))
}
it ("Should animate loading") { () -> Void in
expect(backgroundView?.loadingView?.loadingActive) == true
}
}
context("Init - Prepare") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Prepare
mockController.mockContentState = .Init
mockController.refreshBackgroundView()
}
it ("Should not show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should show Loading") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.Loading))
}
it ("Should not show Error") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Error))
}
it ("Should not show Paging") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Paging))
}
it ("Should animate loading") { () -> Void in
expect(backgroundView?.loadingView?.loadingActive) == true
}
}
context("Complete - Idle") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Idle
mockController.mockContentState = .Complete
mockController.refreshBackgroundView()
}
it ("Should show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should not show Loading") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Loading))
}
it ("Should not show Error") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Error))
}
it ("Should show Paging") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.Paging))
}
}
context("Complete - Fetch, Prepare") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Fetch
mockController.mockContentState = .Complete
mockController.refreshBackgroundView()
}
it ("Should show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should not show Loading") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Loading))
}
it ("Should not show Error") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Error))
}
it ("Should not show Paging") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Paging))
}
it ("Should animate Refresh") { () -> Void in
expect(backgroundView?.pullToRefreshView?.loadingActive) == true
}
}
context("Complete - Prepare") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Prepare
mockController.mockContentState = .Complete
mockController.refreshBackgroundView()
}
it ("Should show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should not show Loading") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Loading))
}
it ("Should not show Error") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Error))
}
it ("Should not show Paging") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Paging))
}
it ("Should animate Refresh") { () -> Void in
expect(backgroundView?.pullToRefreshView?.loadingActive) == true
}
}
context("Error - Idle") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Idle
mockController.mockContentState = .Error
mockController.refreshBackgroundView()
}
it ("Should not show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should not show Loading") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Loading))
}
it ("Should show Error") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.Error))
}
it ("Should not show Paging") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Paging))
}
}
context("Error - Fetch, Prepare") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Fetch
mockController.mockContentState = .Error
mockController.refreshBackgroundView()
}
it ("Should not show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should show Loading") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.Loading))
}
it ("Should not show Error") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Error))
}
it ("Should not show Paging") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Paging))
}
it ("Should animate loading") { () -> Void in
expect(backgroundView?.loadingView?.loadingActive) == true
}
}
context("Error - Prepare") { () -> Void in
beforeEach() { () -> () in
mockController.mockOperationState = .Prepare
mockController.mockContentState = .Error
mockController.refreshBackgroundView()
}
it ("Should not show Refresh") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.PullToRefresh))
}
it ("Should show Loading") { () -> Void in
expect(backgroundView?.visibleViews).to(contain(BackgroundView.Views.Loading))
}
it ("Should not show Error") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Error))
}
it ("Should not show Paging") { () -> Void in
expect(backgroundView?.visibleViews).toNot(contain(BackgroundView.Views.Paging))
}
it ("Should animate loading") { () -> Void in
expect(backgroundView?.loadingView?.loadingActive) == true
}
}
}
} // END Describe DataSource Controller
} // END Spec
}
| mit | 85e679ee5fa174d3af1b5919d6aa1efa | 45.133279 | 214 | 0.395314 | 7.771488 | false | false | false | false |
LoginRadius/ios-sdk | Example/SwiftDemo/SwiftDemo/DetailViewControllerUISetup.swift | 1 | 13526 | //
// DetailViewControllerUISetup.swift
// SwiftDemo
//
// Created by LoginRadius Development Team on 2017-05-19.
// Copyright © 2017 LoginRadius Inc. All rights reserved.
//
import Foundation
import Eureka
import SwiftyJSON
extension DetailViewController
{
func smallUserProfileUISetup()
{
var userEmail="";
if ((userProfile["Email"].array)) != nil && (userProfile["Email"].array)?.isEmpty == false{
userEmail = (((userProfile["Email"].array)?[0]["Value"] )?.string)!
}
var userCountry:String? = nil
if let addrArr = userProfile["Country"].dictionary,
let countryStr = addrArr["Name"]?.string
{
userCountry = countryStr
}
let gender = userProfile["Gender"].string ?? "?"
let profileCondition = Condition.function(["User Profile"], { form in
return !((form.rowBy(tag: "User Profile") as? SwitchRow)?.value ?? false)
})
form +++ Section("User Profile API Demo")
<<< SwitchRow("User Profile")
{
$0.title = $0.tag
$0.value = true
}
<<< NameRow("FirstName")
{
$0.title = "First Name"
$0.hidden = profileCondition
$0.value = userProfile[$0.tag!].stringValue
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< NameRow("LastName")
{
$0.title = "Last Name"
$0.hidden = profileCondition
$0.value = userProfile[$0.tag!].stringValue
$0.add(rule: RuleRequired())
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< EmailRow("Email")
{
$0.title = $0.tag
$0.hidden = profileCondition
$0.value = userEmail ?? nil
$0.disabled = Condition(booleanLiteral: true)
}
<<< SegmentedRow<String>("Gender"){
$0.title = $0.tag
$0.hidden = profileCondition
$0.options = ["M","F","?"]
$0.add(rule: RuleRequired())
$0.value = gender
}
<<< PushRow<String>("Country") {
$0.title = $0.tag
$0.hidden = profileCondition
$0.options = countries
$0.value = userCountry
$0.selectorTitle = "Country"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< TextRow("IsSecurePassword"){
$0.title = $0.tag
$0.hidden = profileCondition
$0.value = (userProfile[$0.tag!].boolValue ? "true" : "false")
$0.disabled = Condition(booleanLiteral: true)
}
<<< ButtonRow("Update Profile")
{
$0.title = $0.tag
$0.hidden = profileCondition
}.onCellSelection{ cell, row in
self.validateUserProfileInput()
}
+++ Section("up<->vfp")
{
$0.header = nil
$0.hidden = profileCondition
}
<<< ButtonRow("View Full Profile")
{
$0.title = $0.tag
$0.hidden = profileCondition
}.onCellSelection{ cell, row in
self.showFullProfileController()
}
}
func accessTokenUISetup()
{
let accessCondition = Condition.function(["Access Token"], { form in
return !((form.rowBy(tag: "Access Token") as? SwitchRow)?.value ?? false)
})
form +++ Section("Access Token API Demo")
<<< SwitchRow("Access Token")
{
$0.title = $0.tag
$0.value = false
}
<<< AccountRow("Access Token Text")
{
$0.title = "Access Token"
$0.disabled = Condition(booleanLiteral: true)
$0.hidden = accessCondition
$0.value = self.accessToken
}
<<< ButtonRow("Validate Access Token")
{
$0.title = "Validate"
$0.hidden = accessCondition
}.onCellSelection{ cell, row in
self.validateAccessToken()
}
<<< ButtonRow("Invalidate Access Token")
{
$0.title = "Invalidate"
$0.hidden = accessCondition
}.onCellSelection{ cell, row in
self.invalidateAccessToken()
}
}
func customObjectUISetup()
{
let objectCondition = Condition.function(["Custom Object"], { form in
return !((form.rowBy(tag: "Custom Object") as? SwitchRow)?.value ?? false)
})
let objectCreateCondition = Condition.function(["Custom Object", "Create Custom Obj"], { form in
let cusObj = (form.rowBy(tag: "Custom Object") as? SwitchRow)?.value ?? false
let cusObjCr = (form.rowBy(tag: "Create Custom Obj") as? SwitchRow)?.value ?? false
return !(cusObj && cusObjCr)
})
let objectGetCondition = Condition.function(["Custom Object","Get Custom Obj"], { form in
let cusObj = (form.rowBy(tag: "Custom Object") as? SwitchRow)?.value ?? false
let cusObjGetUID = (form.rowBy(tag: "Get Custom Obj") as? SwitchRow)?.value ?? false
return !(cusObj && cusObjGetUID)
})
let objectGetWithRecordIdCondition = Condition.function(["Custom Object","Get Custom Obj with RecordId"], { form in
let cusObj = (form.rowBy(tag: "Custom Object") as? SwitchRow)?.value ?? false
let cusObjGetR = (form.rowBy(tag: "Get Custom Obj with RecordId") as? SwitchRow)?.value ?? false
return !(cusObj && cusObjGetR)
})
let objectPutCondition = Condition.function(["Custom Object","Put Custom Obj"], { form in
let cusObj = (form.rowBy(tag: "Custom Object") as? SwitchRow)?.value ?? false
let cusObjPut = (form.rowBy(tag: "Put Custom Obj") as? SwitchRow)?.value ?? false
return !(cusObj && cusObjPut)
})
let objectDelCondition = Condition.function(["Custom Object","Delete Custom Obj"], { form in
let cusObj = (form.rowBy(tag: "Custom Object") as? SwitchRow)?.value ?? false
let cusObjDel = (form.rowBy(tag: "Delete Custom Obj") as? SwitchRow)?.value ?? false
return !(cusObj && cusObjDel)
})
form +++ Section("Custom Object API Demo")
<<< SwitchRow("Custom Object")
{
$0.title = $0.tag
$0.value = false
}
<<< SwitchRow("Create Custom Obj")
{
$0.title = $0.tag
$0.hidden = objectCondition
}
<<< AccountRow("CrCO Object Name")
{
$0.title = "Object Name"
$0.hidden = objectCreateCondition
$0.placeholder = "See LR dashboard for obj name"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< LabelRow("CrCO DataLabel")
{
$0.title = "Payload Data"
$0.hidden = objectCreateCondition
}
<<< AccountRow("CrCO Data")
{
$0.title = "Data"
$0.placeholder = "{\"customdata1\": \"my customdata1\"}"
$0.hidden = objectCreateCondition
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< ButtonRow("CrCO Send")
{
$0.title = "Create Custom Object"
$0.hidden = objectCreateCondition
}.onCellSelection{cell, row in
self.createCustomObject()
}
<<< SwitchRow("Get Custom Obj")
{
$0.title = $0.tag
$0.hidden = objectCondition
}
<<< AccountRow("GetCO Object Name")
{
$0.title = "Object Name"
$0.hidden = objectGetCondition
$0.placeholder = "See LR dashboard for obj name"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< ButtonRow("GetCO Send")
{
$0.title = "Get Custom Object"
$0.hidden = objectGetCondition
}.onCellSelection{cell, row in
self.getCustomObject()
}
<<< SwitchRow("Get Custom Obj with RecordId")
{
$0.title = $0.tag
$0.hidden = objectCondition
}
<<< AccountRow("GetCO RecordId with RecordId")
{
$0.title = "Record Id"
$0.hidden = objectGetWithRecordIdCondition
$0.placeholder = "Record Id"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< AccountRow("GetCO Object Name with RecordId")
{
$0.title = "Object Name"
$0.hidden = objectGetWithRecordIdCondition
$0.placeholder = "See LR dashboard for obj name"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< ButtonRow("GetCO Send with RecordId")
{
$0.title = "Get Custom Object with RecordId"
$0.hidden = objectGetWithRecordIdCondition
}.onCellSelection{cell, row in
self.getCustomObjectWithRecordId()
}
<<< SwitchRow("Put Custom Obj")
{
$0.title = $0.tag
$0.hidden = objectCondition
}.onCellSelection{cell, row in
self.getCustomObjectWithRecordId()
}
<<< AccountRow("PutCO RecordId")
{
$0.title = "Record Id"
$0.hidden = objectPutCondition
$0.placeholder = "Record Id"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< AccountRow("PutCO Object Name")
{
$0.title = "Object Name"
$0.hidden = objectPutCondition
$0.placeholder = "See LR dashboard for obj name"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< LabelRow("PutCO DataLabel")
{
$0.title = "Payload Data"
$0.hidden = objectPutCondition
}
<<< AccountRow("PutCO Data")
{
$0.title = "Data"
$0.placeholder = "{\"customdata1\": \"my customdata1\"}"
$0.hidden = objectPutCondition
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< ButtonRow("PutCO Send")
{
$0.title = "Put Custom Object"
$0.hidden = objectPutCondition
}.onCellSelection{cell, row in
self.putCustomObject()
}
<<< SwitchRow("Delete Custom Obj")
{
$0.title = $0.tag
$0.hidden = objectCondition
}
<<< AccountRow("DelCO RecordId")
{
$0.title = "Record Id"
$0.hidden = objectDelCondition
$0.placeholder = "Record Id"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< AccountRow("DelCO Object Name")
{
$0.title = "Object Name"
$0.hidden = objectDelCondition
$0.placeholder = "See LR dashboard for obj name"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnDemand
}.onRowValidationChanged { cell, row in
self.toggleRedBorderShowErrorMessage(cell: cell, row: row)
}
<<< ButtonRow("DelCO Send")
{
$0.title = "Delete Custom Object"
$0.hidden = objectDelCondition
}.onCellSelection{cell, row in
self.delCustomObject()
}
}
}
| mit | 39287ce9d9ea75c22f237dcd420b545c | 34.970745 | 123 | 0.52902 | 4.561551 | false | false | false | false |
AlexeyDemedetskiy/BillScaner | BillScaner/sources/QRScanerViewController.swift | 1 | 2257 | //
// QRScaner.swift
// BillScaner
//
// Created by Alexey Demedetskii on 5/26/17.
// Copyright © 2017 Alexey Demedeckiy. All rights reserved.
//
import UIKit
import AVFoundation
class QRScanerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
struct ViewModel {
var processPayload: (Data) -> Void
}
var viewModel = ViewModel { _ in }
let captureSession = AVCaptureSession()
override func viewDidLoad() {
let input: AVCaptureInput = try! AVCaptureDeviceInput(
device: AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
)
captureSession.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
guard let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else {
fatalError("Cannot instantiate preview layer")
}
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer)
}
override func viewWillAppear(_ animated: Bool) {
captureSession.startRunning()
}
/// We need to stop it before animation will start.
override func viewWillDisappear(_ animated: Bool) {
captureSession.stopRunning()
}
func captureOutput(_ captureOutput: AVCaptureOutput!,
didOutputMetadataObjects metadataObjects: [Any]!,
from connection: AVCaptureConnection!)
{
guard let metadataObjects = metadataObjects as? [AVMetadataMachineReadableCodeObject]
else { return }
guard let qrCode = metadataObjects.first(where: { $0.type == AVMetadataObjectTypeQRCode })
else { return }
guard let data = qrCode.stringValue.data(using: .utf8) else { return }
DispatchQueue.main.async { self.viewModel.processPayload(data) }
}
}
| mit | 2aed9f2ac5f83bb4c2d785521708b1ed | 33.181818 | 98 | 0.667996 | 5.952507 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/ViewRelated/Aztec/Extensions/ImageAttachment+WordPress.swift | 1 | 2214 | import Foundation
import Aztec
/// ImageAttachment extension to support extra attributes needed by the WordPress app.
///
extension ImageAttachment {
var width: Int? {
get {
guard let stringInt = extraAttributes["width"] else {
return nil
}
return Int(stringInt)
}
set {
if let nonNilValue = newValue {
extraAttributes["width"] = "\(nonNilValue)"
} else {
extraAttributes.removeValue(forKey: "width")
}
}
}
var height: Int? {
get {
guard let stringInt = extraAttributes["height"] else {
return nil
}
return Int(stringInt)
}
set {
if let nonNilValue = newValue {
extraAttributes["height"] = "\(nonNilValue)"
} else {
extraAttributes.removeValue(forKey: "height")
}
}
}
var imageID: Int? {
get {
guard let classAttribute = extraAttributes["class"] else {
return nil
}
let attributes = classAttribute.components(separatedBy: " ")
guard let imageIDAttribute = attributes.filter({ (value) -> Bool in
value.hasPrefix("wp-image-")
}).first else {
return nil
}
let imageIDString = imageIDAttribute.removingPrefix("wp-image-")
return Int(imageIDString)
}
set {
var attributes = [String]()
if let classAttribute = extraAttributes["class"] {
attributes = classAttribute.components(separatedBy: " ")
}
attributes = attributes.filter({ (value) -> Bool in
!value.hasPrefix("wp-image-")
})
if let nonNilValue = newValue {
attributes.append("wp-image-\(nonNilValue)")
}
if extraAttributes.isEmpty {
extraAttributes.removeValue(forKey: "class")
} else {
extraAttributes["class"] = attributes.joined(separator: " ")
}
}
}
}
| gpl-2.0 | 90039a77171e9b38bea2ecf6763871b2 | 29.75 | 86 | 0.498645 | 5.296651 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.