repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
anatoliyv/navigato
|
Navigato/Classes/SourceApps/NavigatoSourceApp.swift
|
1
|
3146
|
//
// NavigatoSourceApp.swift
// Navigato
//
// Created by Anatoliy Voropay on 10/26/17.
//
import Foundation
import CoreLocation
/// Protocol to describe Source App behaviour for Navigato
public protocol NavigatoSourceAppProtocol {
/// Source app name
var name: String { get }
/// Return `true` if source app is available
var isAvailable: Bool { get }
/// Open source app with address String
func open(withAddress address: String)
/// Open source app with `CLLocation`
func open(withLocation location: CLLocation)
/// Open source app with search query
func open(withQuery query: String)
// MARK: Low-level interface
/// Return path for request
func path(forRequest request: Navigato.RequestType) -> String
/// Open source app with specific `Navigato.RequestType`
func open(withRequest request: Navigato.RequestType, value: Any)
}
/// Base class for all Source App subclasses
public class NavigatoSourceApp: NavigatoSourceAppProtocol {
public var name: String {
assertionFailure("Implementation required")
return ""
}
public func path(forRequest request: Navigato.RequestType) -> String {
assertionFailure("Implementation required")
return ""
}
/// Return `true` if source app is available
public var isAvailable: Bool {
let path = self.path(forRequest: .address)
guard let url = URL(string: path) else { return false }
return UIApplication.shared.canOpenURL(url)
}
/// Open source app with address String
public func open(withAddress address: String) {
open(withRequest: .search, value: address as Any)
}
/// Open source app with `CLLocation`
public func open(withLocation location: CLLocation) {
open(withRequest: .location, value: location as Any)
}
/// Open source app with search query
public func open(withQuery query: String) {
open(withRequest: .search, value: query as Any)
}
public func open(withRequest request: Navigato.RequestType, value: Any) {
let path = self.path(forRequest: request)
var destinationURL: URL?
switch request {
case .address, .search:
guard let string = (value as? String)?.addingPercentEncoding(withAllowedCharacters: queryCharacterSet) else { return }
destinationURL = URL(string: path + string)
case .location:
guard let location = value as? CLLocation else { return }
let string = [location.coordinate.latitude, location.coordinate.longitude].map({ String($0) }).joined(separator: ",")
destinationURL = URL(string: path + string)
}
guard let url = destinationURL else { return }
guard UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.openURL(url)
}
private var queryCharacterSet: CharacterSet {
let characterSet = NSMutableCharacterSet()
characterSet.formUnion(with: CharacterSet.urlQueryAllowed)
characterSet.removeCharacters(in: "&")
return characterSet as CharacterSet
}
}
|
mit
|
7f9eb2c5ac2c77c0d6fd9f2e0b833e65
| 30.777778 | 130 | 0.671011 | 4.688525 | false | false | false | false |
eridbardhaj/Weather
|
Weather/Classes/Models/Forecast.swift
|
1
|
832
|
//
// Forecast.swift
// Weather
//
// Created by Erid Bardhaj on 4/29/15.
// Copyright (c) 2015 STRV. All rights reserved.
//
import UIKit
import ObjectMapper
class Forecast: Mappable
{
var m_temperature: Double = 0.0
var m_day: Double = 0.0
var m_weatherType: Int = 0
var m_weatherDescription: String = ""
required init?(_ map: Map)
{
mapping(map)
}
//MARK: - Mappable
func mapping(map: Map)
{
let list = map["list"]
var m_weatherArr1: NSArray = NSArray()
m_weatherArr1 <- list["weather"]
m_weatherType = m_weatherArr1[0].objectForKey("id") as! Int
m_weatherDescription = m_weatherArr1[0].objectForKey("main") as! String
m_temperature <- list["temp.day"]
m_day <- list["dt"]
}
}
|
mit
|
2b00d6915a6adbda4d77143f884cdc35
| 20.921053 | 79 | 0.56851 | 3.555556 | false | false | false | false |
seanwoodward/IBAnimatable
|
IBAnimatable/AnimatableStackView.swift
|
1
|
3793
|
//
// Created by Jake Lin on 12/11/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
// FIXME: almost same as `AnimatableView`, Need to refactor to encasuplate.
@available(iOS 9, *)
@IBDesignable public class AnimatableStackView: UIStackView, CornerDesignable, FillDesignable, BorderDesignable, RotationDesignable, ShadowDesignable, TintDesignable, GradientDesignable, MaskDesignable, Animatable {
// MARK: - CornerDesignable
@IBInspectable public var cornerRadius: CGFloat = CGFloat.NaN {
didSet {
configCornerRadius()
}
}
// MARK: - FillDesignable
@IBInspectable public var fillColor: UIColor? {
didSet {
configFillColor()
}
}
@IBInspectable public var predefinedColor: String? {
didSet {
configFillColor()
}
}
@IBInspectable public var opacity: CGFloat = CGFloat.NaN {
didSet {
configOpacity()
}
}
// MARK: - BorderDesignable
@IBInspectable public var borderColor: UIColor? {
didSet {
configBorder()
}
}
@IBInspectable public var borderWidth: CGFloat = CGFloat.NaN {
didSet {
configBorder()
}
}
@IBInspectable public var borderSide: String? {
didSet {
configBorder()
}
}
// MARK: - RotationDesignable
@IBInspectable public var rotate: CGFloat = CGFloat.NaN {
didSet {
configRotate()
}
}
// MARK: - ShadowDesignable
@IBInspectable public var shadowColor: UIColor? {
didSet {
configShadowColor()
}
}
@IBInspectable public var shadowRadius: CGFloat = CGFloat.NaN {
didSet {
configShadowRadius()
}
}
@IBInspectable public var shadowOpacity: CGFloat = CGFloat.NaN {
didSet {
configShadowOpacity()
}
}
@IBInspectable public var shadowOffset: CGPoint = CGPoint(x: CGFloat.NaN, y: CGFloat.NaN) {
didSet {
configShadowOffset()
}
}
// MARK: - TintDesignable
@IBInspectable public var tintOpacity: CGFloat = CGFloat.NaN
@IBInspectable public var shadeOpacity: CGFloat = CGFloat.NaN
@IBInspectable public var toneColor: UIColor?
@IBInspectable public var toneOpacity: CGFloat = CGFloat.NaN
// MARK: - GradientDesignable
@IBInspectable public var startColor: UIColor?
@IBInspectable public var endColor: UIColor?
@IBInspectable public var predefinedGradient: String?
@IBInspectable public var startPoint: String?
// MARK: - MaskDesignable
@IBInspectable public var maskType: String? {
didSet {
configMask()
configBorder()
}
}
// MARK: - Animatable
@IBInspectable public var animationType: String?
@IBInspectable public var autoRun: Bool = true
@IBInspectable public var duration: Double = Double.NaN
@IBInspectable public var delay: Double = Double.NaN
@IBInspectable public var damping: CGFloat = CGFloat.NaN
@IBInspectable public var velocity: CGFloat = CGFloat.NaN
@IBInspectable public var force: CGFloat = CGFloat.NaN
@IBInspectable public var repeatCount: Float = Float.NaN
@IBInspectable public var x: CGFloat = CGFloat.NaN
@IBInspectable public var y: CGFloat = CGFloat.NaN
// MARK: - Lifecycle
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configInspectableProperties()
}
public override func awakeFromNib() {
super.awakeFromNib()
configInspectableProperties()
}
public override func layoutSubviews() {
super.layoutSubviews()
configAfterLayoutSubviews()
autoRunAnimation()
}
// MARK: - Private
private func configInspectableProperties() {
configAnimatableProperties()
configTintedColor()
}
private func configAfterLayoutSubviews() {
configMask()
configBorder()
configGradient()
}
}
|
mit
|
2a7335714fab894100564b935d9e6522
| 24.449664 | 215 | 0.688819 | 4.855314 | false | true | false | false |
wikimedia/wikipedia-ios
|
WMF Framework/Remote Notifications/Model/PushNotificationsCache.swift
|
1
|
701
|
import Foundation
/// Shared cache object used by the Notifications Service Extension for persisted values set in the main app, and vice versa.
public struct PushNotificationsCache: Codable {
public var settings: PushNotificationsSettings
public var notifications: Set<RemoteNotificationsAPIController.NotificationsResult.Notification>
public var currentUnreadCount: Int = 0
public init(settings: PushNotificationsSettings, notifications: Set<RemoteNotificationsAPIController.NotificationsResult.Notification>, currentUnreadCount: Int = 0) {
self.settings = settings
self.notifications = notifications
self.currentUnreadCount = currentUnreadCount
}
}
|
mit
|
8b43f4d74539441f6dbbd37fcf3ef896
| 49.071429 | 170 | 0.787447 | 5.841667 | false | false | false | false |
oneCup/MyWeiBo
|
MyWeiBoo/MyWeiBoo/Class/Module/Home/YFWebController.swift
|
1
|
1060
|
//
// YFWebController.swift
// MyWeiBoo
//
// Created by 李永方 on 15/10/25.
// Copyright © 2015年 李永方. All rights reserved.
//
import UIKit
import SVProgressHUD
class YFWebController: UIViewController,UIWebViewDelegate {
/// 要加载的url
var url: NSURL?
override func loadView() {
super.loadView()
view = webView
webView.delegate = self
webView.frame = UIScreen.mainScreen().bounds
webView.backgroundColor = UIColor.redColor()
}
override func viewDidLoad() {
super.viewDidLoad()
title = "网页"
//加载URL
if url != nil {
webView.loadRequest(NSURLRequest(URL: url!))
}
}
// MARK: 代理方法
func webViewDidStartLoad(webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(webView: UIWebView) {
SVProgressHUD.dismiss()
}
// MARK:懒加载
private lazy var webView = UIWebView()
}
|
mit
|
d79bbcf6d0abcc6c46d61ab2fb6377e5
| 17.454545 | 59 | 0.566502 | 4.677419 | false | false | false | false |
roshkadev/Form
|
Form/Classes/DatePicker/DatePicker.swift
|
1
|
7942
|
//
// DatePicker.swift
// Pods
//
// Created by Paul Von Schrottky on 4/30/17.
//
//
import UIKit
/// A `DatePickerEvent` associated with a `DatePicker`.
public enum DatePickerEvent {
case shouldFocus // Return `false` to disable `DatePicker` focus. Not applicable to embedded pickers.
case focus // The `DatePicker` gained focus. Not applicable to embedded pickers.
case onChange // The value of the `DatePicker` has changed (comes to rest).
case shouldBlur // Return `false` to disable `DatePicker` blur. Not applicable to embedded pickers.
case blur // The `DatePicker` lost focus. Not applicable to embedded pickers.
case submit // The containing `Form` received a `FormEvent.submit` event.
}
public enum DatePickerRestriction {
case none
case weekday
case weekend
}
/// A `DatePickerReaction` is the response of a `DatePicker` to a `DatePickerReaction`.
public enum DatePickerReaction {
case none
case lastSelection
case previous
case next
case shake
case alert(String)
case popup(String)
case submit(PickerRestriction)
}
public enum DatePickerPresentationStyle {
case keyboard
case embedded
case dialog
}
public typealias DatePickerValidation = (event: DatePickerEvent, restriction: DatePickerRestriction, reaction: DatePickerReaction)
public typealias DatePickerValidationResult = (isValid: Bool, reaction: DatePickerReaction)
final public class DatePicker: NSObject {
// #MARK - Field
public var form: Form!
public var row: Row!
public var view: FieldView
public var contentView: UIView
public var stackView: UIStackView
public var title: String?
public var label: FieldLabel?
public var key: String?
/// The constraint used to show and hide the field.
/// The underlying text field of this `DatePicker`. nil when embedded is true.
var textField: UITextField?
/// The underlying picker view of this `DatePicker`.
var datePickerInputView: DatePickerInputView
/// The underlying picker view of this `DatePicker`.
var datePicker: UIDatePicker {
return datePickerInputView.datePicker
}
/// This field's padding.
public var padding = Space.default
///
var style: DatePickerPresentationStyle = .embedded
/// Storage for this date picker's validations.
public var validations = [DatePickerValidation]()
/// `DatePickerEvent` handlers.
public var handlers = [(event: DatePickerEvent, handler: ((DatePicker) -> Void))]()
fileprivate var lastDate: Date?
public var formBindings = [(event: FormEvent, field: Field, handler: ((Field) -> Void))]()
@discardableResult
override public init() {
view = FieldView()
stackView = UIStackView()
label = FieldLabel()
datePickerInputView = UINib(nibName: "DatePickerInputView", bundle: Bundle(for: type(of: self))).instantiate(withOwner: nil, options: nil)[0] as! DatePickerInputView
datePickerInputView.datePicker.datePickerMode = UIDatePickerMode.dateAndTime
contentView = datePickerInputView
super.init()
datePickerInputView.buttonCallback = { self.form.didTapNextFrom(field: self) }
datePicker.addTarget(self, action: #selector(valueChanged), for: .valueChanged)
view.translatesAutoresizingMaskIntoConstraints = false
switch style {
case .keyboard:
let textField = UITextField()
textField.borderStyle = .roundedRect
textField.inputView = datePickerInputView
textField.form_fill(parentView: view, withPadding: padding)
datePickerInputView.backgroundColor = .lightGray
self.textField = textField
case .embedded:
datePickerInputView.form_fill(parentView: view, withPadding: padding)
case .dialog:
break
}
}
public var value: Any? {
switch style {
case .keyboard:
if let text = textField?.text?.trimmingCharacters(in: .whitespacesAndNewlines), text.isEmpty == false {
return text
}
return nil
case .embedded:
if let text = textField?.text?.trimmingCharacters(in: .whitespacesAndNewlines), text.isEmpty == false {
return text
}
return nil
default:
return nil
}
}
@discardableResult
public func bind(_ binding:@escaping ((Date?) -> Void)) -> Self {
handlers.append((.onChange, {
binding($0.datePicker.date)
}))
return self
}
@discardableResult
public func key(_ key: String?) -> Self {
self.key = key
return self
}
func valueChanged(sender: UIDatePicker) {
let isValid = validateForEvent(event: DatePickerEvent.onChange)
if isValid {
lastDate = sender.date
handlers.filter { $0.event == .onChange }.forEach { $0 }
}
}
}
extension DatePicker: Field {
public func style(_ style: ((DatePicker) -> Void)) -> Self {
style(self)
return self
}
public var canBecomeFirstResponder: Bool {
return style == .keyboard
}
public func becomeFirstResponder() {
if style == .keyboard { textField?.becomeFirstResponder() }
}
public func didChangeContentSizeCategory() {
textField?.font = UIFont.preferredFont(forTextStyle: .body)
}
}
/// Public interface for validating an instance of `DatePicker`.
extension DatePicker {
public func validateForEvent(event: DatePickerEvent) -> Bool {
// Apply any event handlers.
handlers.filter { $0.event == event }.forEach { $0.handler(self) }
let selectedDate = datePickerInputView.datePicker.date
let isDateInWeekend = Calendar.current.isDateInWeekend(selectedDate)
let failingValidation: DatePickerValidationResult? = validations.filter {
$0.event == event // Only get events of the specified type.
}.map {
switch $0 {
case (_, .weekday, let reaction):
return (isDateInWeekend, reaction)
case (_, .weekend, let reaction):
return (!isDateInWeekend, reaction)
default:
return (true, .none)
}
}.filter { $0.isValid == false }.first
if let failingValidation = failingValidation {
switch failingValidation.reaction {
case .shake:
view.shake()
case .alert(let message):
print(message)
default:
break
}
if let lastDate = lastDate {
datePicker.setDate(lastDate, animated: true)
}
return false
}
return true
}
public func bind(_ event: DatePickerEvent, _ restriction: DatePickerRestriction, _ reaction: DatePickerReaction) -> Self {
validations.append(DatePickerValidation(event, restriction, reaction))
return self
}
public func validateForEvent(event: PickerEvent) -> Bool {
return true
}
}
/// Public interface for configuring an instance of `DatePicker`.
extension DatePicker {
public func placeholder(_ placeholder: String?) -> Self {
textField?.placeholder = placeholder
return self
}
public func earliest(date: Date) -> Self {
datePicker.minimumDate = date
return self
}
public func latest(date: Date) -> Self {
datePicker.maximumDate = date
return self
}
}
|
mit
|
c758e28eda4507b29607ec16c466b69f
| 28.969811 | 173 | 0.61244 | 5.204456 | false | false | false | false |
ios-plugin/uexChart
|
EUExChart/EUExChart/PieChart.swift
|
1
|
4866
|
//
// PieChart.swift
// EUExChart
//
// Created by CeriNo on 2016/10/27.
// Copyright © 2016年 AppCan. All rights reserved.
//
import Foundation
import AppCanKit
import AppCanKitSwift
import Charts
class PieChart{
struct Entity: JSArgumentConvertible{
var title: String!
var color: UIColor!
var value: Double!
static func jsa_fromJSArgument(_ argument: JSArgument) -> Entity? {
var entity = Entity()
guard
entity.color <~ argument["color"],
entity.title <~ argument["title"],
entity.value <~ argument["value"]
else{
return nil
}
return entity
}
}
let view = PieChartView()
var showPercent = false
var eventHandler: ChartEvent.Handler?
var id: String!
var isScrollWithWeb = false
var duration: TimeInterval!
var formatData: FormatData!
required init?(jsConfig: JSArgument){
guard self.initialize(jsConfig: jsConfig) else{
return nil
}
view.delegate = self
var holeColor = UIColor.clear
holeColor <~ jsConfig["centerColor"]
view.holeColor = holeColor
view.rotationAngle = 0
view.rotationEnabled = true
view.highlightPerTapEnabled = true
showPercent <~ jsConfig["showPercent"]
view.usePercentValuesEnabled = showPercent
configureFrame(jsConfig: jsConfig)
configureLegend(jsConfig: jsConfig)
configureDescription(jsConfig: jsConfig)
configureBackgroundColor(jsConfig: jsConfig)
configureHole(jsConfig: jsConfig)
configureCenterString(jsConfig: jsConfig)
configureChartData(jsConfig: jsConfig)
}
}
extension PieChart: Chart{
var chartView: ChartViewBase{
get{
return view
}
}
}
extension PieChart{
func configureHole(jsConfig: JSArgument){
view.drawHoleEnabled = ~jsConfig["showCenter"] ?? true
view.holeColor <~ jsConfig["centerColor"]
let centerRadius: CGFloat = ~jsConfig["centerRadius"] ?? 40
let centerTransRadius: CGFloat = ~jsConfig["centerTransRadius"] ?? 42
view.holeRadiusPercent = centerRadius / 100
view.transparentCircleRadiusPercent = centerTransRadius / 100
}
func configureCenterString(jsConfig: JSArgument){
let centerTitle = ~jsConfig["centerTitle"] ?? ""
let centerSummary = ~jsConfig["centerSummary"] ?? ""
let str = NSMutableAttributedString(string: "\(centerTitle)\n\(centerSummary)")
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
str.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, str.length))
let range = NSMakeRange(0, centerTitle.characters.count)
str.addAttribute(NSFontAttributeName, value: formatData.descFont, range: range)
str.addAttribute(NSForegroundColorAttributeName, value: formatData.descTextColor, range: range)
view.centerAttributedText = str
view.drawCenterTextEnabled <~ jsConfig["showTitle"]
}
func configureChartData(jsConfig: JSArgument){
guard let entities: [Entity] = ~jsConfig["data"] ,entities.count > 0 else{
return
}
var dataArray = [PieChartDataEntry]()
var colorArray = [UIColor]()
for entity in entities{
dataArray.append(PieChartDataEntry(value: entity.value, label: entity.title))
colorArray.append(entity.color)
}
let dataSet = PieChartDataSet(values: dataArray, label: "")
dataSet.colors = colorArray
dataSet.sliceSpace = 3.0
dataSet.selectionShift = 6
dataSet.valueTextColor = formatData.valueTextColor
dataSet.valueFont = formatData.valueFont
dataSet.drawValuesEnabled = formatData.showValue
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumIntegerDigits = 10
formatter.maximumFractionDigits = 2
if showPercent{
formatter.percentSymbol = "%"
formatter.multiplier = 1.0
}else if formatData.showUnit{
formatter.percentSymbol = formatData.unit
}else{
formatter.percentSymbol = ""
}
dataSet.valueFormatter = DefaultValueFormatter(formatter: formatter)
let chartData = PieChartData(dataSet: dataSet)
view.data = chartData
}
}
extension PieChart: ChartViewDelegate{
func chartValueSelected(_ chartView: Charts.ChartViewBase, entry: Charts.ChartDataEntry, highlight: Charts.Highlight){
self.eventHandler?(ChartEvent.selected(entry: entry, highlight: highlight))
}
}
|
lgpl-3.0
|
2d5e1c1f7c4533b46cc736f9587e87c7
| 31.205298 | 122 | 0.642813 | 4.957187 | false | true | false | false |
jakerockland/Swisp
|
Sources/SwispFramework/Environment/Operators.swift
|
1
|
8913
|
//
// Operators.swift
// SwispFramework
//
// MIT License
//
// Copyright (c) 2018 Jake Rockland (http://jakerockland.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import Foundation
/**
Provides the following basic operators as static functions:
- `+`
- `-`
- `*`
- `/`
- `>`
- `<`
- `>=`
- `<=`
- `=`
*/
internal struct Operators {
/**
Static function for `+` operator
*/
static func add(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
let double = Double(lhs) + Double(rhs)
if double < Double(Int.max) && double > Double(-Int.max){
return Int(double)
} else {
return double
}
case let (lhs as Double, rhs as Double):
return lhs + rhs
case let (lhs as Int, rhs as Double):
return Double(lhs) + rhs
case let (lhs as Double, rhs as Int):
return lhs + Double(rhs)
case let (lhs as String, rhs as String):
return lhs + rhs
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `-` operator
*/
static func subtract(_ args: [Any]) throws -> Any? {
if args.count == 1 {
switch (args[safe: 0]) {
case let (val as Int):
return -val
case let (val as Double):
return -val
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
} else if args.count == 2 {
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
let double = Double(lhs) - Double(rhs)
if double < Double(Int.max) && double > Double(-Int.max){
return Int(double)
} else {
return double
}
case let (lhs as Double, rhs as Double):
return lhs - rhs
case let (lhs as Int, rhs as Double):
return Double(lhs) - rhs
case let (lhs as Double, rhs as Int):
return lhs - Double(rhs)
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
} else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `*` operator
*/
static func multiply(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
let double = Double(lhs) * Double(rhs)
if double < Double(Int.max) && double > Double(-Int.max){
return Int(double)
} else {
return double
}
case let (lhs as Double, rhs as Double):
return lhs * rhs
case let (lhs as Int, rhs as Double):
return Double(lhs) * rhs
case let (lhs as Double, rhs as Int):
return lhs * Double(rhs)
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `/` operator
*/
static func divide(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
return lhs / rhs
case let (lhs as Double, rhs as Double):
return lhs / rhs
case let (lhs as Int, rhs as Double):
return Double(lhs) / rhs
case let (lhs as Double, rhs as Int):
return lhs / Double(rhs)
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `%` operator
*/
static func mod(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
return lhs % rhs
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `>` operator
*/
static func greaterThan(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
return lhs > rhs
case let (lhs as Double, rhs as Double):
return lhs > rhs
case let (lhs as String, rhs as String):
return lhs > rhs
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `<` operator
*/
static func lessThan(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
return lhs < rhs
case let (lhs as Double, rhs as Double):
return lhs < rhs
case let (lhs as String, rhs as String):
return lhs < rhs
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `>=` operator
*/
static func greaterThanEqual(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
return lhs >= rhs
case let (lhs as Double, rhs as Double):
return lhs >= rhs
case let (lhs as String, rhs as String):
return lhs >= rhs
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `<=` operator
*/
static func lessThanEqual(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
return lhs <= rhs
case let (lhs as Double, rhs as Double):
return lhs <= rhs
case let (lhs as String, rhs as String):
return lhs <= rhs
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
/**
Static function for `=` operator
*/
static func equal(_ args: [Any]) throws -> Any? {
guard args.count == 2 else {
throw SwispError.SyntaxError(message: "invalid procedure input")
}
switch (args[safe: 0], args[safe: 1]) {
case let (lhs as Int, rhs as Int):
return lhs == rhs
case let (lhs as Double, rhs as Double):
return lhs == rhs
case let (lhs as String, rhs as String):
return lhs == rhs
default:
throw SwispError.SyntaxError(message: "invalid procedure input")
}
}
}
|
mit
|
1f1489b9b8a85431e2f434e8c147b897
| 33.019084 | 93 | 0.547403 | 4.50379 | false | false | false | false |
1457792186/JWSwift
|
SwiftLearn/SwiftDemo/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel.swift
|
1
|
16860
|
//
// LTMorphingLabel.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2017 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files
// (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
import QuartzCore
private func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
enum LTMorphingPhases: Int {
case start, appear, disappear, draw, progress, skipFrames
}
typealias LTMorphingStartClosure =
() -> Void
typealias LTMorphingEffectClosure =
(Character, _ index: Int, _ progress: Float) -> LTCharacterLimbo
typealias LTMorphingDrawingClosure =
(LTCharacterLimbo) -> Bool
typealias LTMorphingManipulateProgressClosure =
(_ index: Int, _ progress: Float, _ isNewChar: Bool) -> Float
typealias LTMorphingSkipFramesClosure =
() -> Int
@objc public protocol LTMorphingLabelDelegate {
@objc optional func morphingDidStart(_ label: LTMorphingLabel)
@objc optional func morphingDidComplete(_ label: LTMorphingLabel)
@objc optional func morphingOnProgress(_ label: LTMorphingLabel, progress: Float)
}
// MARK: - LTMorphingLabel
@IBDesignable open class LTMorphingLabel: UILabel {
@IBInspectable open var morphingProgress: Float = 0.0
@IBInspectable open var morphingDuration: Float = 0.6
@IBInspectable open var morphingCharacterDelay: Float = 0.026
@IBInspectable open var morphingEnabled: Bool = true
@IBOutlet open weak var delegate: LTMorphingLabelDelegate?
open var morphingEffect: LTMorphingEffect = .scale
var startClosures = [String: LTMorphingStartClosure]()
var effectClosures = [String: LTMorphingEffectClosure]()
var drawingClosures = [String: LTMorphingDrawingClosure]()
var progressClosures = [String: LTMorphingManipulateProgressClosure]()
var skipFramesClosures = [String: LTMorphingSkipFramesClosure]()
var diffResults: LTStringDiffResult?
var previousText = ""
var currentFrame = 0
var totalFrames = 0
var totalDelayFrames = 0
var totalWidth: Float = 0.0
var previousRects = [CGRect]()
var newRects = [CGRect]()
var charHeight: CGFloat = 0.0
var skipFramesCount: Int = 0
#if TARGET_INTERFACE_BUILDER
let presentingInIB = true
#else
let presentingInIB = false
#endif
override open var font: UIFont! {
get {
return super.font ?? UIFont.systemFont(ofSize: 15)
}
set {
super.font = newValue
setNeedsLayout()
}
}
override open var text: String! {
get {
return super.text ?? ""
}
set {
guard text != newValue else { return }
previousText = text ?? ""
diffResults = previousText.diffWith(newValue)
super.text = newValue ?? ""
morphingProgress = 0.0
currentFrame = 0
totalFrames = 0
setNeedsLayout()
if !morphingEnabled {
return
}
if presentingInIB {
morphingDuration = 0.01
morphingProgress = 0.5
} else if previousText != text {
displayLink.isPaused = false
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.start)"
if let closure = startClosures[closureKey] {
return closure()
}
delegate?.morphingDidStart?(self)
}
}
}
open override func setNeedsLayout() {
super.setNeedsLayout()
previousRects = rectsOfEachCharacter(previousText, withFont: font)
newRects = rectsOfEachCharacter(text ?? "", withFont: font)
}
override open var bounds: CGRect {
get {
return super.bounds
}
set {
super.bounds = newValue
setNeedsLayout()
}
}
override open var frame: CGRect {
get {
return super.frame
}
set {
super.frame = newValue
setNeedsLayout()
}
}
fileprivate lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(
target: self,
selector: #selector(LTMorphingLabel.displayFrameTick)
)
displayLink.add(to: .current, forMode: .commonModes)
return displayLink
}()
deinit {
displayLink.remove(from: .current, forMode: .commonModes)
displayLink.invalidate()
}
lazy var emitterView: LTEmitterView = {
let emitterView = LTEmitterView(frame: self.bounds)
self.addSubview(emitterView)
return emitterView
}()
}
// MARK: - Animation extension
extension LTMorphingLabel {
@objc func displayFrameTick() {
if displayLink.duration > 0.0 && totalFrames == 0 {
var frameRate = Float(0)
if #available(iOS 10.0, tvOS 10.0, *) {
var frameInterval = 1
if displayLink.preferredFramesPerSecond == 60 {
frameInterval = 1
} else if displayLink.preferredFramesPerSecond == 30 {
frameInterval = 2
} else {
frameInterval = 1
}
frameRate = Float(displayLink.duration) / Float(frameInterval)
} else {
frameRate = Float(displayLink.duration) / Float(displayLink.frameInterval)
}
totalFrames = Int(ceil(morphingDuration / frameRate))
let totalDelay = Float((text!).characters.count) * morphingCharacterDelay
totalDelayFrames = Int(ceil(totalDelay / frameRate))
}
currentFrame += 1
if previousText != text && currentFrame < totalFrames + totalDelayFrames + 5 {
morphingProgress += 1.0 / Float(totalFrames)
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.skipFrames)"
if let closure = skipFramesClosures[closureKey] {
skipFramesCount += 1
if skipFramesCount > closure() {
skipFramesCount = 0
setNeedsDisplay()
}
} else {
setNeedsDisplay()
}
if let onProgress = delegate?.morphingOnProgress {
onProgress(self, morphingProgress)
}
} else {
displayLink.isPaused = true
delegate?.morphingDidComplete?(self)
}
}
// Could be enhanced by kerning text:
// http://stackoverflow.com/questions/21443625/core-text-calculate-letter-frame-in-ios
func rectsOfEachCharacter(_ textToDraw: String, withFont font: UIFont) -> [CGRect] {
var charRects = [CGRect]()
var leftOffset: CGFloat = 0.0
charHeight = "Leg".size(withAttributes: [.font: font]).height
let topOffset = (bounds.size.height - charHeight) / 2.0
for char in textToDraw.characters {
let charSize = String(char).size(withAttributes: [.font: font])
charRects.append(
CGRect(
origin: CGPoint(
x: leftOffset,
y: topOffset
),
size: charSize
)
)
leftOffset += charSize.width
}
totalWidth = Float(leftOffset)
var stringLeftOffSet: CGFloat = 0.0
switch textAlignment {
case .center:
stringLeftOffSet = CGFloat((Float(bounds.size.width) - totalWidth) / 2.0)
case .right:
stringLeftOffSet = CGFloat(Float(bounds.size.width) - totalWidth)
default:
()
}
var offsetedCharRects = [CGRect]()
for r in charRects {
offsetedCharRects.append(r.offsetBy(dx: stringLeftOffSet, dy: 0.0))
}
return offsetedCharRects
}
func limboOfOriginalCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
var currentRect = previousRects[index]
let oriX = Float(currentRect.origin.x)
var newX = Float(currentRect.origin.x)
let diffResult = diffResults!.0[index]
var currentFontSize: CGFloat = font.pointSize
var currentAlpha: CGFloat = 1.0
switch diffResult {
// Move the character that exists in the new text to current position
case .same:
newX = Float(newRects[index].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .move(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .moveAndAdd(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
default:
// Otherwise, remove it
// Override morphing effect with closure in extenstions
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.disappear)"
] {
return closure(char, index, progress)
} else {
// And scale it by default
let fontEase = CGFloat(
LTEasing.easeOutQuint(
progress, 0, Float(font.pointSize)
)
)
// For emojis
currentFontSize = max(0.0001, font.pointSize - fontEase)
currentAlpha = CGFloat(1.0 - progress)
currentRect = previousRects[index].offsetBy(
dx: 0,
dy: CGFloat(font.pointSize - currentFontSize)
)
}
}
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: currentFontSize,
drawingProgress: 0.0
)
}
func limboOfNewCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
let currentRect = newRects[index]
var currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0, Float(font.pointSize))
)
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.appear)"
] {
return closure(char, index, progress)
} else {
currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0.0, Float(font.pointSize))
)
// For emojis
currentFontSize = max(0.0001, currentFontSize)
let yOffset = CGFloat(font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: currentRect.offsetBy(dx: 0, dy: yOffset),
alpha: CGFloat(morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
}
func limboOfCharacters() -> [LTCharacterLimbo] {
var limbo = [LTCharacterLimbo]()
// Iterate original characters
for (i, character) in previousText.characters.enumerated() {
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, false)
} else {
progress = min(1.0, max(0.0, morphingProgress + morphingCharacterDelay * Float(i)))
}
let limboOfCharacter = limboOfOriginalCharacter(character, index: i, progress: progress)
limbo.append(limboOfCharacter)
}
// Add new characters
for (i, character) in (text!).characters.enumerated() {
if i >= diffResults?.0.count {
break
}
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, true)
} else {
progress = min(1.0, max(0.0, morphingProgress - morphingCharacterDelay * Float(i)))
}
// Don't draw character that already exists
if diffResults?.skipDrawingResults[i] == true {
continue
}
if let diffResult = diffResults?.0[i] {
switch diffResult {
case .moveAndAdd, .replace, .add, .delete:
let limboOfCharacter = limboOfNewCharacter(
character,
index: i,
progress: progress
)
limbo.append(limboOfCharacter)
default:
()
}
}
}
return limbo
}
}
// MARK: - Drawing extension
extension LTMorphingLabel {
override open func didMoveToSuperview() {
if let s = text {
text = s
}
// Load all morphing effects
for effectName: String in LTMorphingEffect.allValues {
let effectFunc = Selector("\(effectName)Load")
if responds(to: effectFunc) {
perform(effectFunc)
}
}
}
override open func drawText(in rect: CGRect) {
if !morphingEnabled || limboOfCharacters().count == 0 {
super.drawText(in: rect)
return
}
for charLimbo in limboOfCharacters() {
let charRect = charLimbo.rect
let willAvoidDefaultDrawing: Bool = {
if let closure = drawingClosures[
"\(morphingEffect.description)\(LTMorphingPhases.draw)"
] {
return closure($0)
}
return false
}(charLimbo)
if !willAvoidDefaultDrawing {
var attrs: [NSAttributedStringKey: Any] = [
.foregroundColor: textColor.withAlphaComponent(charLimbo.alpha)
]
if let font = UIFont(name: font.fontName, size: charLimbo.size) {
attrs[.font] = font
}
let s = String(charLimbo.char)
s.draw(in: charRect, withAttributes: attrs)
}
}
}
}
|
apache-2.0
|
e466fba1d6a6d7bdbfeabad9e7a1755c
| 32.238659 | 100 | 0.539461 | 5.185231 | false | false | false | false |
fgulan/letter-ml
|
project/LetterML/Frameworks/framework/Source/iOS/PictureInput.swift
|
7
|
8261
|
import OpenGLES
import UIKit
public class PictureInput: ImageSource {
public let targets = TargetContainer()
var imageFramebuffer:Framebuffer!
var hasProcessedImage:Bool = false
public init(image:CGImage, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) {
// TODO: Dispatch this whole thing asynchronously to move image loading off main thread
let widthOfImage = GLint(image.width)
let heightOfImage = GLint(image.height)
// If passed an empty image reference, CGContextDrawImage will fail in future versions of the SDK.
guard((widthOfImage > 0) && (heightOfImage > 0)) else { fatalError("Tried to pass in a zero-sized image") }
var widthToUseForTexture = widthOfImage
var heightToUseForTexture = heightOfImage
var shouldRedrawUsingCoreGraphics = false
// For now, deal with images larger than the maximum texture size by resizing to be within that limit
let scaledImageSizeToFitOnGPU = GLSize(sharedImageProcessingContext.sizeThatFitsWithinATextureForSize(Size(width:Float(widthOfImage), height:Float(heightOfImage))))
if ((scaledImageSizeToFitOnGPU.width != widthOfImage) && (scaledImageSizeToFitOnGPU.height != heightOfImage)) {
widthToUseForTexture = scaledImageSizeToFitOnGPU.width
heightToUseForTexture = scaledImageSizeToFitOnGPU.height
shouldRedrawUsingCoreGraphics = true
}
if (smoothlyScaleOutput) {
// In order to use mipmaps, you need to provide power-of-two textures, so convert to the next largest power of two and stretch to fill
let powerClosestToWidth = ceil(log2(Float(widthToUseForTexture)))
let powerClosestToHeight = ceil(log2(Float(heightToUseForTexture)))
widthToUseForTexture = GLint(round(pow(2.0, powerClosestToWidth)))
heightToUseForTexture = GLint(round(pow(2.0, powerClosestToHeight)))
shouldRedrawUsingCoreGraphics = true
}
var imageData:UnsafeMutablePointer<GLubyte>!
var dataFromImageDataProvider:CFData!
var format = GL_BGRA
if (!shouldRedrawUsingCoreGraphics) {
/* Check that the memory layout is compatible with GL, as we cannot use glPixelStore to
* tell GL about the memory layout with GLES.
*/
if ((image.bytesPerRow != image.width * 4) || (image.bitsPerPixel != 32) || (image.bitsPerComponent != 8))
{
shouldRedrawUsingCoreGraphics = true
} else {
/* Check that the bitmap pixel format is compatible with GL */
let bitmapInfo = image.bitmapInfo
if (bitmapInfo.contains(.floatComponents)) {
/* We don't support float components for use directly in GL */
shouldRedrawUsingCoreGraphics = true
} else {
let alphaInfo = CGImageAlphaInfo(rawValue:bitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue)
if (bitmapInfo.contains(.byteOrder32Little)) {
/* Little endian, for alpha-first we can use this bitmap directly in GL */
if ((alphaInfo != CGImageAlphaInfo.premultipliedFirst) && (alphaInfo != CGImageAlphaInfo.first) && (alphaInfo != CGImageAlphaInfo.noneSkipFirst)) {
shouldRedrawUsingCoreGraphics = true
}
} else if ((bitmapInfo.contains(CGBitmapInfo())) || (bitmapInfo.contains(.byteOrder32Big))) {
/* Big endian, for alpha-last we can use this bitmap directly in GL */
if ((alphaInfo != CGImageAlphaInfo.premultipliedLast) && (alphaInfo != CGImageAlphaInfo.last) && (alphaInfo != CGImageAlphaInfo.noneSkipLast)) {
shouldRedrawUsingCoreGraphics = true
} else {
/* Can access directly using GL_RGBA pixel format */
format = GL_RGBA
}
}
}
}
}
// CFAbsoluteTime elapsedTime, startTime = CFAbsoluteTimeGetCurrent();
if (shouldRedrawUsingCoreGraphics) {
// For resized or incompatible image: redraw
imageData = UnsafeMutablePointer<GLubyte>.allocate(capacity:Int(widthToUseForTexture * heightToUseForTexture) * 4)
let genericRGBColorspace = CGColorSpaceCreateDeviceRGB()
let imageContext = CGContext(data: imageData, width: Int(widthToUseForTexture), height: Int(heightToUseForTexture), bitsPerComponent: 8, bytesPerRow: Int(widthToUseForTexture) * 4, space: genericRGBColorspace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
// CGContextSetBlendMode(imageContext, kCGBlendModeCopy); // From Technical Q&A QA1708: http://developer.apple.com/library/ios/#qa/qa1708/_index.html
imageContext?.draw(image, in:CGRect(x:0.0, y:0.0, width:CGFloat(widthToUseForTexture), height:CGFloat(heightToUseForTexture)))
} else {
// Access the raw image bytes directly
dataFromImageDataProvider = image.dataProvider?.data
imageData = UnsafeMutablePointer<GLubyte>(mutating:CFDataGetBytePtr(dataFromImageDataProvider))
}
sharedImageProcessingContext.runOperationSynchronously{
do {
// TODO: Alter orientation based on metadata from photo
self.imageFramebuffer = try Framebuffer(context:sharedImageProcessingContext, orientation:orientation, size:GLSize(width:widthToUseForTexture, height:heightToUseForTexture), textureOnly:true)
} catch {
fatalError("ERROR: Unable to initialize framebuffer of size (\(widthToUseForTexture), \(heightToUseForTexture)) with error: \(error)")
}
glBindTexture(GLenum(GL_TEXTURE_2D), self.imageFramebuffer.texture)
if (smoothlyScaleOutput) {
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR_MIPMAP_LINEAR)
}
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, widthToUseForTexture, heightToUseForTexture, 0, GLenum(format), GLenum(GL_UNSIGNED_BYTE), imageData)
if (smoothlyScaleOutput) {
glGenerateMipmap(GLenum(GL_TEXTURE_2D))
}
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
}
if (shouldRedrawUsingCoreGraphics) {
imageData.deallocate(capacity:Int(widthToUseForTexture * heightToUseForTexture) * 4)
}
}
public convenience init(image:UIImage, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) {
self.init(image:image.cgImage!, smoothlyScaleOutput:smoothlyScaleOutput, orientation:orientation)
}
public convenience init(imageName:String, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) {
guard let image = UIImage(named:imageName) else { fatalError("No such image named: \(imageName) in your application bundle") }
self.init(image:image.cgImage!, smoothlyScaleOutput:smoothlyScaleOutput, orientation:orientation)
}
public func processImage(synchronously:Bool = false) {
if synchronously {
sharedImageProcessingContext.runOperationSynchronously{
self.updateTargetsWithFramebuffer(self.imageFramebuffer)
self.hasProcessedImage = true
}
} else {
sharedImageProcessingContext.runOperationAsynchronously{
self.updateTargetsWithFramebuffer(self.imageFramebuffer)
self.hasProcessedImage = true
}
}
}
public func transmitPreviousImage(to target:ImageConsumer, atIndex:UInt) {
if hasProcessedImage {
imageFramebuffer.lock()
target.newFramebufferAvailable(imageFramebuffer, fromSourceIndex:atIndex)
}
}
}
|
mit
|
0ebc2ba0305f21101e3d774a5998b133
| 54.817568 | 322 | 0.645079 | 5.208701 | false | false | false | false |
panjinqiang11/Swift-WeiBo
|
WeiBo/WeiBo/Class/Model/PJStatus.swift
|
1
|
1885
|
//
// PJStatus.swift
// WeiBo
//
// Created by 潘金强 on 16/7/12.
// Copyright © 2016年 潘金强. All rights reserved.
//
import UIKit
//微博模型
class PJStatus: NSObject {
//创建时间
var created_at: String?
//微博id
var id: Int64 = 0
//微博信息内容
var text: String?
//微博来源
var source: String?
var user: PJUser?
// 转发数
var reposts_count: Int = 0
// 评论数
var comments_count: Int = 0
// 表态数(赞)
var attitudes_count: Int = 0
// 转发微博
var retweeted_status: PJStatus?
//配图信息
var pic_urls: [PJStatusPicInfo]?
init(dic:[String: AnyObject]){
super.init()
setValuesForKeysWithDictionary(dic)
}
//防止崩溃
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
// MARK: - 修改字典转模型
override func setValue(value: AnyObject?, forKey key: String) {
if key == "user" {
//如果key值为user 单独字典转模型
user = PJUser(dic: value as! [String :AnyObject])
}else if key == "retweeted_status"{
retweeted_status = PJStatus(dic: value as! [String :AnyObject])
}else if key == "pic_urls" {
guard let dicArr = value as? [[String:AnyObject]] else {
return
}
var temperArr = [PJStatusPicInfo]()
for dic in dicArr {
let picInfo = PJStatusPicInfo(dic: dic)
temperArr.append(picInfo)
}
pic_urls = temperArr
}else {
super.setValue(value, forKey: key)
}
}
}
|
mit
|
fa81a0e1faa627c261c72a5f409c51a6
| 22.026316 | 76 | 0.484 | 4.107981 | false | false | false | false |
steelwheels/Coconut
|
CoconutData/Source/Value/CNStorageRecord.swift
|
1
|
3868
|
/**
* @file CNStorageRecord.swift
* @brief Define CNRecord class
* @par Copyright
* Copyright (C) 2021-2022 Steel Wheels Project
*/
import Foundation
public class CNStorageRecord: CNRecord
{
public static let RecordIdItem = "recordId"
static let ClassName = "record"
private enum SourceData {
case table(CNStorageTable, Int) // (Source table, index)
case cache(Dictionary<String, CNValue>) // (property-name, property-value)
}
private var mTypes: Dictionary<String, CNValueType>
private var mSource: SourceData
public var index: Int? { get {
switch mSource {
case .table(_, let idx): return idx
case .cache(_): return nil
}
}}
public init(table tbl: CNStorageTable, index idx: Int){
mSource = .table(tbl, idx)
mTypes = CNStorageRecord.defaultTypes(fields: tbl.defaultFields)
}
public init(defaultFields fields: Dictionary<String, CNValue>){
mSource = .cache(fields)
mTypes = CNStorageRecord.defaultTypes(fields: fields)
}
private static func defaultTypes(fields flds: Dictionary<String, CNValue>) -> Dictionary<String, CNValueType> {
var result: Dictionary<String, CNValueType> = [:]
for fname in flds.keys {
if let val = flds[fname] {
result[fname] = val.valueType
}
}
return result
}
public var fieldCount: Int { get {
switch mSource {
case .table(let tbl, _):
return tbl.defaultFields.count
case .cache(let dict):
return dict.count
}
}}
public var fieldNames: Array<String> { get {
switch mSource {
case .table(let tbl, _):
return Array(tbl.defaultFields.keys)
case .cache(let dict):
return Array(dict.keys)
}
}}
public var fieldTypes: Dictionary<String, CNValueType> { get {
return mTypes
}}
public func value(ofField name: String) -> CNValue? {
switch mSource {
case .table(let tbl, let idx):
if let val = tbl.getRecordValue(index: idx, field: name) {
return val
} else {
return tbl.defaultFields[name]
}
case .cache(let dict):
return dict[name]
}
}
public func setValue(value val: CNValue, forField name: String) -> Bool {
switch mSource {
case .table(let tbl, let idx):
if let curval = tbl.getRecordValue(index: idx, field: name) {
if CNIsSameValue(nativeValue0: curval, nativeValue1: val) {
return true // already set
}
let cval = CNCastValue(from: val, to: curval.valueType)
return tbl.setRecordValue(cval, index: idx, field: name)
} else {
return tbl.setRecordValue(val, index: idx, field: name)
}
case .cache(let dict):
var newdict = dict
let newval: CNValue
if let curval = newdict[name] {
newval = CNCastValue(from: val, to: curval.valueType)
} else {
newval = val
}
newdict[name] = newval
mSource = .cache(newdict)
return true
}
}
public func cachedValues() -> Dictionary<String, CNValue>? {
switch mSource {
case .table(_, _):
return nil
case .cache(let dict):
return dict
}
}
public func toDictionary() -> Dictionary<String, CNValue> {
var result: Dictionary<String, CNValue> = [:]
for field in self.fieldNames.sorted() {
if let val = value(ofField: field) {
result[field] = val
}
}
CNValue.setClassName(toValue: &result, className: CNStorageRecord.ClassName)
return result
}
public static func fromDictionary(value val: Dictionary<String, CNValue>) -> CNRecord? {
if CNValue.hasClassName(inValue: val, className: CNStorageRecord.ClassName) {
var dupval = val ; CNValue.removeClassName(fromValue: &dupval)
let newrec = CNStorageRecord(defaultFields: dupval)
return newrec
} else {
return nil
}
}
public func compare(forField name: String, with rec: CNRecord) -> ComparisonResult {
let s0 = self.value(ofField: name) ?? CNValue.null
let s1 = rec.value(ofField: name) ?? CNValue.null
return CNCompareValue(nativeValue0: s0, nativeValue1: s1)
}
}
|
lgpl-2.1
|
20e72a5fe0e275aeb80df9ace91a70c7
| 24.786667 | 112 | 0.68304 | 3.134522 | false | false | false | false |
dilizarov/realm-cocoa
|
RealmSwift-swift1.2/Object.swift
|
13
|
10235
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
In Realm you define your model classes by subclassing `Object` and adding properties to be persisted.
You then instantiate and use your custom subclasses instead of using the Object class directly.
```swift
class Dog: Object {
dynamic var name: String = ""
dynamic var adopted: Bool = false
let siblings = List<Dog>
}
```
### Supported property types
- `String`
- `Int`
- `Float`
- `Double`
- `Bool`
- `NSDate`
- `NSData`
- `Object` subclasses for to-one relationships
- `List<T: Object>` for to-many relationships
### Querying
You can gets `Results` of an Object subclass via tha `objects(_:)` free function or
the `objects(_:)` instance method on `Realm`.
### Relationships
See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
*/
public class Object: RLMObjectBase, Equatable, Printable {
// MARK: Initializers
/**
Initialize a standalone (unpersisted) Object.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
:see: Realm().add(_:)
*/
public required override init() {
super.init()
}
/**
Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
:param: value The value used to populate the object. This can be any key/value coding compliant
object, or a JSON object such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
*/
public init(value: AnyObject) {
self.dynamicType.sharedSchema() // ensure this class' objectSchema is loaded in the partialSharedSchema
super.init(value: value, schema: RLMSchema.partialSharedSchema())
}
// MARK: Properties
/// The `Realm` this object belongs to, or `nil` if the object
/// does not belong to a realm (the object is standalone).
public var realm: Realm? {
if let rlmReam = RLMObjectBaseRealm(self) {
return Realm(rlmReam)
}
return nil
}
/// The `ObjectSchema` which lists the persisted properties for this object.
public var objectSchema: ObjectSchema {
return ObjectSchema(RLMObjectBaseObjectSchema(self))
}
/// Indicates if an object can no longer be accessed.
public override var invalidated: Bool { return super.invalidated }
/// Returns a human-readable description of this object.
public override var description: String { return super.description }
#if os(OSX)
/// Helper to return the class name for an Object subclass.
public final override var className: String { return "" }
#else
/// Helper to return the class name for an Object subclass.
public final var className: String { return "" }
#endif
// MARK: Object Customization
/**
Override to designate a property as the primary key for an `Object` subclass. Only properties of
type String and Int can be designated as the primary key. Primary key
properties enforce uniqueness for each value whenever the property is set which incurs some overhead.
Indexes are created automatically for primary key properties.
:returns: Name of the property designated as the primary key, or `nil` if the model has no primary key.
*/
public class func primaryKey() -> String? { return nil }
/**
Override to return an array of property names to ignore. These properties will not be persisted
and are treated as transient.
:returns: `Array` of property names to ignore.
*/
public class func ignoredProperties() -> [String] { return [] }
/**
Return an array of property names for properties which should be indexed. Only supported
for string and int properties.
:returns: `Array` of property names to index.
*/
public class func indexedProperties() -> [String] { return [] }
// MARK: Inverse Relationships
/**
Get an `Array` of objects of type `className` which have this object as the given property value. This can
be used to get the inverse relationship value for `Object` and `List` properties.
:param: className The type of object on which the relationship to query is defined.
:param: property The name of the property which defines the relationship.
:returns: An `Array` of objects of type `className` which have this object as their value for the `propertyName` property.
*/
public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] {
return RLMObjectBaseLinkingObjectsOfClass(self, T.className(), propertyName) as! [T]
}
// MARK: Key-Value Coding & Subscripting
/// Returns or sets the value of the property with the given name.
public subscript(key: String) -> AnyObject? {
get {
if realm == nil {
return self.valueForKey(key)
}
let property = RLMValidatedGetProperty(self, key)
if property.type == .Array {
return self.listForProperty(property)
}
return RLMDynamicGet(self, property)
}
set(value) {
if realm == nil {
self.setValue(value, forKey: key)
}
else {
RLMDynamicValidatedSet(self, key, value)
}
}
}
// MARK: Private functions
// FIXME: None of these functions should be exposed in the public interface.
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(value: AnyObject, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
// Helper for getting the list object for a property
internal func listForProperty(prop: RLMProperty) -> RLMListBase {
return object_getIvar(self, prop.swiftListIvar) as! RLMListBase
}
}
// MARK: Equatable
/// Returns whether both objects are equal.
/// Objects are considered equal when they are both from the same Realm
/// and point to the same underlying object in the database.
public func == <T: Object>(lhs: T, rhs: T) -> Bool {
return RLMObjectBaseAreEqual(lhs, rhs)
}
/// Object interface which allows untyped getters and setters for Objects.
/// :nodoc:
public final class DynamicObject: Object {
private var listProperties = [String: List<DynamicObject>]()
// Override to create List<DynamicObject> on access
internal override func listForProperty(prop: RLMProperty) -> RLMListBase {
if let list = listProperties[prop.name] {
return list
}
let list = List<DynamicObject>()
listProperties[prop.name] = list
return list
}
/// :nodoc:
public override func valueForUndefinedKey(key: String) -> AnyObject? {
return self[key]
}
/// :nodoc:
public override func setValue(value: AnyObject?, forUndefinedKey key: String) {
self[key] = value
}
/// :nodoc:
public override class func shouldIncludeInDefaultSchema() -> Bool {
return false
}
}
/// :nodoc:
/// Internal class. Do not use directly.
public class ObjectUtil: NSObject {
@objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.ignoredProperties() as NSArray?
}
return nil
}
@objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.indexedProperties() as NSArray?
}
return nil
}
// Get the names of all properties in the object which are of type List<>
@objc private class func getGenericListPropertyNames(obj: AnyObject) -> NSArray {
let reflection = reflect(obj)
var properties = [String]()
// Skip the first property (super):
// super is an implicit property on Swift objects
for i in 1..<reflection.count {
let mirror = reflection[i].1
if mirror.valueType is RLMListBase.Type {
properties.append(reflection[i].0)
}
}
return properties
}
@objc private class func initializeListProperty(object: RLMObjectBase, property: RLMProperty, array: RLMArray) {
(object as! Object).listForProperty(property)._rlmArray = array
}
@objc private class func getOptionalPropertyNames(object: AnyObject) -> NSArray {
let reflection = reflect(object)
var properties = [String]()
// Skip the first property (super):
// super is an implicit property on Swift objects
for i in 1..<reflection.count {
let mirror = reflection[i].1
if mirror.disposition == .Optional {
properties.append(reflection[i].0)
}
}
return properties
}
@objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? {
return nil
}
}
|
apache-2.0
|
58c88ad83c71212d5f9fa09e1ebf61ee
| 32.557377 | 126 | 0.647289 | 4.714417 | false | false | false | false |
rgkobashi/PhotoSearcher
|
PhotoViewer/PhotoViewModel.swift
|
1
|
2085
|
//
// PhotoViewModel.swift
// PhotoViewer
//
// Created by Rogelio Martinez Kobashi on 3/1/17.
// Copyright © 2017 Rogelio Martinez Kobashi. All rights reserved.
//
import Foundation
import UIKit
class PhotoViewModel
{
private var photo: Photo
var text: String {
return photo.text
}
private var originalImg: UIImage?
var originalImage: UIImage? {
return originalImg
}
private var thumbnailImg: UIImage?
var thumbnailImage: UIImage? {
return thumbnailImg
}
var likesCount: Int? {
if let instagramPhoto = photo as? InstagramPhoto
{
return instagramPhoto.likesCount
}
else
{
return nil
}
}
var date: Int? {
if let instagramPhoto = photo as? InstagramPhoto
{
return instagramPhoto.date
}
else
{
return nil
}
}
var commentsCount: Int? {
if let instagramPhoto = photo as? InstagramPhoto
{
return instagramPhoto.commentsCount
}
else
{
return nil
}
}
init (photo: Photo)
{
self.photo = photo
}
func downloadOriginalImage(_ suceedHandler: @escaping VoidCompletionHandler, failedHandler: @escaping ErrorCompletionHandler)
{
Utilities.downloadImageFrom(self.photo.originalUrl, suceedHandler: { [weak self] (result) in
self?.originalImg = result as? UIImage
suceedHandler()
}, failedHandler: { (error) in
failedHandler(error)
})
}
func downloadThumbnailImage(_ suceedHandler: @escaping VoidCompletionHandler, failedHandler: @escaping ErrorCompletionHandler)
{
Utilities.downloadImageFrom(self.photo.thumbnailUrl, suceedHandler: { [weak self] (result) in
self?.thumbnailImg = result as? UIImage
suceedHandler()
}, failedHandler: { (error) in
failedHandler(error)
})
}
}
|
mit
|
9da8527ee3be358b1f53851211c6b987
| 22.954023 | 130 | 0.578695 | 4.880562 | false | false | false | false |
zisko/swift
|
test/SILOptimizer/pgo_si_inlinelarge.swift
|
1
|
3128
|
// RUN: rm -rf %t && mkdir %t
// RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_si_inlinelarge -o %t/main
// RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main
// RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_si_inlinelarge -o - | %FileCheck %s --check-prefix=SIL
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_si_inlinelarge -o - | %FileCheck %s --check-prefix=SIL-OPT
// REQUIRES: profile_runtime
// REQUIRES: OS=macosx
public func bar(_ x: Int64) -> Int64 {
if (x == 0) {
return 42
}
if (x == 1) {
return 6
}
if (x == 2) {
return 9
}
if (x == 3) {
return 93
}
if (x == 4) {
return 94
}
if (x == 5) {
return 95
}
if (x == 6) {
return 96
}
if (x == 7) {
return 97
}
if (x == 8) {
return 98
}
if (x == 9) {
return 99
}
if (x == 10) {
return 910
}
if (x == 11) {
return 911
}
if (x == 11) {
return 911
}
if (x == 11) {
return 911
}
if (x == 12) {
return 912
}
if (x == 13) {
return 913
}
if (x == 14) {
return 914
}
if (x == 15) {
return 916
}
if (x == 17) {
return 917
}
if (x == 18) {
return 918
}
if (x == 19) {
return 919
}
if (x % 2 == 0) {
return 4242
}
var ret : Int64 = 0
for currNum in stride(from: 5, to: x, by: 5) {
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
}
return ret
}
// SIL-LABEL: sil @$S18pgo_si_inlinelarge3fooyys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
// SIL-OPT-LABEL: sil @$S18pgo_si_inlinelarge3fooyys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
public func foo(_ x: Int64) {
// SIL: switch_enum {{.*}} : $Optional<Int64>, case #Optional.some!enumelt.1: {{.*}} !case_count(100), case #Optional.none!enumelt: {{.*}} !case_count(1)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(50)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(1)
// SIL-OPT: integer_literal $Builtin.Int64, 93
// SIL-OPT: integer_literal $Builtin.Int64, 42
// SIL-OPT: function_ref @$S18pgo_si_inlinelarge3barys5Int64VADF : $@convention(thin) (Int64) -> Int64
var sum : Int64 = 0
for index in 1...x {
if (index % 2 == 0) {
sum += bar(index)
}
if (index == 50) {
sum += bar(index)
}
sum += 1
}
print(sum)
}
// SIL-LABEL: } // end sil function '$S18pgo_si_inlinelarge3fooyys5Int64VF'
// SIL-OPT-LABEL: } // end sil function '$S18pgo_si_inlinelarge3fooyys5Int64VF'
foo(100)
|
apache-2.0
|
c69ecb19d2070392618f2b0ec53e241e
| 23.061538 | 172 | 0.564258 | 2.810422 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/FeedBack/Controller/ReasonForMetailEmptyViewController.swift
|
1
|
3973
|
//
// ReasonForMetailEmptyViewController.swift
// OMS-WH
//
// Created by xuech on 2017/11/24.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class ReasonForMetailEmptyViewController: UITableViewController {
private var dataSource = [[String:AnyObject]]()
private var code : String = ""
var callBackSelectedReason : ((_ reason:String,_ reasonRemark:String)->())?
let resonView = OfflineReasonView.loadFromNib()
override func viewDidLoad() {
super.viewDidLoad()
title = "原因"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.done, target: self, action: #selector(doneAction))
navigationItem.rightBarButtonItem?.isEnabled = false
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.tableFooterView = resonView
loadData()
}
@objc private func doneAction(){
let reasonMark = resonView.reasonView.text ?? ""
if let callBack = callBackSelectedReason,code != "" {
callBack(code,reasonMark)
self.navigationController?.popViewController(animated: true)
}
}
private func loadData(){
XCHRefershUI.show()
moyaNetWork.request(.dictoryList(paramters: ["dictTypeCode": "OPFDME"])) { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(withStatus: data["msg"] as? String ?? "")
return
}
if let resultValue = data["info"] as? [[String : AnyObject]]{
self.dataSource = resultValue
self.tableView.reloadData()
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if let text = dataSource[indexPath.row]["dictValueName"] as? String{
cell.textLabel?.text = text
}
cell.textLabel?.textAlignment = NSTextAlignment.left
cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
cell.textLabel?.textColor = kAppearanceColor
return cell
}
fileprivate var selectedReasonArray : [String] = []
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
navigationItem.rightBarButtonItem?.isEnabled = true
let cell = tableView.cellForRow(at: indexPath)
var arry = tableView.visibleCells
for i in 0 ..< arry.count {
let cells: UITableViewCell = arry[i]
cells.accessoryType = .none
}
cell?.accessoryType = .checkmark
code = dataSource[indexPath.row]["dictValueCode"] as? String ?? ""
let selectedName = dataSource[indexPath.row]["dictValueName"] as? String ?? ""
if !self.selectedReasonArray.contains(selectedName) {
self.selectedReasonArray.append(selectedName)
resonView.reasonView.text = self.selectedReasonArray.joined(separator: ",")
}
}
}
|
mit
|
941ca067277db242ecb74ff6496be4d2
| 36.980769 | 151 | 0.603797 | 5.217966 | false | false | false | false |
Daemon-Devarshi/MedicationSchedulerSwift3.0
|
Medication/ViewControllers/AddNewForms/AddNewMedicationViewController.swift
|
1
|
10171
|
//
// AddNewMedicationViewController.swift
// Medication
//
// Created by Devarshi Kulshreshtha on 8/20/16.
// Copyright © 2016 Devarshi. All rights reserved.
//
import UIKit
import CoreData
import EventKit
class AddNewMedicationViewController: FormBaseViewController {
//MARK: Constants declarations
static let pushSegueIdentifier = "PushAddNewMedicationViewController"
//MARK: Var declarations
// Pickers
fileprivate var timePicker: UIDatePicker!
fileprivate var unitPicker: UIPickerView!
fileprivate var priorityPicker: UIPickerView!
// Values displayed in pickers
fileprivate var pirorityModes: [PriorityMode] = [.high, .medium, .low]
fileprivate var units: [Units] = [.pills, .ml]
fileprivate var eventStore: EKEventStore?
fileprivate var selectedMedicine: Medicine?
fileprivate var selectedPriority: PriorityMode?
fileprivate var selectedUnit: Units?
fileprivate var scheduleTime: Date?
var patient: Patient! {
didSet {
managedObjectContext = patient.managedObjectContext
}
}
//MARK: Outlets declarations
@IBOutlet weak var medicineField: UITextField!
@IBOutlet weak var scheduleMedicationField: UITextField!
@IBOutlet weak var dosageField: UITextField!
@IBOutlet weak var selectUnitField: UITextField!
@IBOutlet weak var selectPriorityField: UITextField!
//MARK: Overriden methods
override func viewDidLoad() {
super.viewDidLoad()
configureDatePicker()
configurePickerViews()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let segueIdentifier = segue.identifier {
if segueIdentifier == MedicinesTableViewController.pushSegueIdentifier {
// passing managedObjectContext to PatientsTableViewController
let medicinesTableViewController = segue.destination as! MedicinesTableViewController
medicinesTableViewController.managedObjectContext = managedObjectContext
medicinesTableViewController.medicineSelectionHandler = { [weak self](selectedMedicine) in
// weak used to break retain cycle
guard let _self = self else {
return
}
_self.medicineField.text = selectedMedicine.name
_self.selectedMedicine = selectedMedicine
}
}
}
}
}
//MARK:- Implementing UIPickerViewDataSource, UIPickerViewDelegate protocols
extension AddNewMedicationViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == unitPicker {
return units.count
}
else if pickerView == priorityPicker{
return pirorityModes.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var title: String?
if pickerView == unitPicker {
title = units[row].description
}
else if pickerView == priorityPicker{
title = pirorityModes[row].description
}
return title
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == unitPicker {
let value = units[row]
selectedUnit = value
selectUnitField.text = value.description
}
else if pickerView == priorityPicker {
let value = pirorityModes[row]
selectedPriority = value
selectPriorityField.text = value.description
}
}
}
//MARK:- Utility methods
extension AddNewMedicationViewController {
// Scheduling reminders
fileprivate func scheduleReminder() {
if let eventStore = eventStore {
let reminder = EKReminder(eventStore: eventStore)
let notes = "\(selectedMedicine!.name!) \(dosageField.text!) \(selectedUnit!.description)"
reminder.title = "Provide \(notes) to \(patient.fullName!)"
reminder.notes = notes
reminder.calendar = eventStore.defaultCalendarForNewReminders()
let alarm = EKAlarm(absoluteDate: scheduleTime!)
reminder.addAlarm(alarm)
reminder.priority = selectedPriority!.rawValue
let recurrenceRule = EKRecurrenceRule(recurrenceWith: .daily, interval: 1, end: nil)
reminder.recurrenceRules = [recurrenceRule]
// setting dueDateComponents for recurring events
let gregorian = NSCalendar(identifier:NSCalendar.Identifier.gregorian)
let dailyComponents = gregorian?.components([.year, .month, .day, .hour, .minute, .second, .timeZone], from: scheduleTime!)
reminder.dueDateComponents = dailyComponents
do {
try eventStore.save(reminder, commit: true)
displaySingleButtonActionAlert(withTitle: "Success!", message: "Medication successfully scheduled.") {[weak self] in
// weak used to break retain cycle
guard let _self = self else {
return
}
_ = _self.navigationController?.popViewController(animated: true)
}
} catch {
let error = error as NSError
print("\(error), \(error.userInfo)")
displaySingleButtonActionAlert(withTitle: "Error!", message: error.localizedDescription)
}
}
}
// Configuring date picker
fileprivate func configureDatePicker() {
timePicker = UIDatePicker(frame: CGRect.zero)
timePicker.datePickerMode = .time
timePicker.backgroundColor = UIColor.white
timePicker.addTarget(self, action: #selector(AddNewMedicationViewController.medicationScheduleChanged), for: .valueChanged)
scheduleMedicationField.inputView = timePicker
}
// Configuring all picker views
fileprivate func configurePickerViews() {
// configuring unitPicker
unitPicker = UIPickerView()
unitPicker.delegate = self
unitPicker.dataSource = self
selectUnitField.inputView = unitPicker
// configuring priorityPicker
priorityPicker = UIPickerView()
priorityPicker.delegate = self
priorityPicker.dataSource = self
selectPriorityField.inputView = priorityPicker
}
}
//MARK:- User actions and text field delegate
extension AddNewMedicationViewController {
override func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// to disable text editing on fields which have input view associated with them
if textField == scheduleMedicationField || textField == selectPriorityField || textField == selectUnitField {
return false
}
return true
}
func medicationScheduleChanged(_ sender:UIDatePicker) {
scheduleTime = sender.date.fullMinuteTime()
scheduleMedicationField.text = scheduleTime!.displayTime()
}
@IBAction func scheduleMedication(_ sender: AnyObject) {
// validations
guard let dosage = dosageField.text else {
displaySingleButtonActionAlert(withTitle: "Error!", message: "Please enter all details.")
return
}
guard let selectedMedicine = selectedMedicine, let selectedPriority = selectedPriority, let selectedUnit = selectedUnit, let scheduleTime = scheduleTime else {
displaySingleButtonActionAlert(withTitle: "Error!", message: "Please enter all details.")
return
}
// Create medication and assign values to its attributes
let medication = Medication.createMedication(withPatient: patient, inManagedObjectContext: managedObjectContext)
medication.dosage = NSNumber(value: Int32(dosage)!)
medication.unit = NSNumber(value: Int32(selectedUnit.rawValue))
medication.priority = NSNumber(value: Int32(selectedPriority.rawValue))
medication.scheduleTime = scheduleTime as NSDate
medication.medicine = selectedMedicine
medication.patient = patient
// saving in local db + creating reminder
do {
try managedObjectContext.save()
// scheduling the reminder
if eventStore == nil {
eventStore = EKEventStore()
eventStore!.requestAccess(
to: .reminder, completion: {[weak self](granted, error) in
guard let _self = self else {
return
}
// Background to main thread
DispatchQueue.main.async(execute: {
if !granted {
print("Access to store not granted")
print(error!.localizedDescription)
_self.displaySingleButtonActionAlert(withTitle: "Permission Declined!", message: "Reminder could not be scheduled.")
} else {
print("Access granted")
_self.scheduleReminder()
}
})
})
}
else {
scheduleReminder()
}
} catch {
let error = error as NSError
print("\(error), \(error.userInfo)")
displaySingleButtonActionAlert(withTitle: "Error!", message: error.localizedDescription)
}
}
}
|
mit
|
d062dbe116fc92478cbe7852fba1e93f
| 38.115385 | 168 | 0.612291 | 5.749011 | false | false | false | false |
Dsringari/scan4pase
|
Project/scan4pase/CartProductDetailVC.swift
|
1
|
5728
|
//
// CartProductDetailVC.swift
// scan4pase
//
// Created by Dhruv Sringari on 7/5/16.
// Copyright © 2016 Dhruv Sringari. All rights reserved.
//
import UIKit
import MagicalRecord
class CartProductDetailVC: UIViewController, UITextFieldDelegate {
@IBOutlet var name: UILabel!
@IBOutlet var quantity: UITextField!
@IBOutlet var taxable: UISegmentedControl!
@IBOutlet var addtoCartButton: UIButton!
var product: Product!
fileprivate var cartProduct: CartProduct!
var edit = false
var saved = false
enum ValidationError: Error {
case quantityZero
case quantityInvalid
case quantityNone
}
lazy var formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumIntegerDigits = 1
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 0
return formatter
}()
let moc = NSManagedObjectContext.mr_default()
override func viewDidLoad() {
super.viewDidLoad()
quantity.delegate = self
if let cartProduct = CartProduct.mr_findFirst(byAttribute: "product", withValue: product, in: moc) {
self.cartProduct = cartProduct
} else {
cartProduct = CartProduct.mr_createEntity(in: moc)
cartProduct.product = product
}
hideKeyboardWhenTappedAround()
// Do any additional setup after loading the view.
name.text = product.name
if let quantity = cartProduct.quantity {
self.quantity.text = quantity.stringValue
if self.quantity.text == "0" {
self.quantity.text = "1"
}
}
if let taxable = cartProduct.taxable {
self.taxable.selectedSegmentIndex = taxable.boolValue ? 0 : 1
}
if edit {
addtoCartButton.setTitle("Save", for: UIControlState())
}
title = product.sku
let keyboardDoneButtonView = UIToolbar()
keyboardDoneButtonView.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissKeyboard))
let flexibleWidth = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
keyboardDoneButtonView.items = [flexibleWidth, doneButton]
quantity.inputAccessoryView = keyboardDoneButtonView
}
@IBAction func addToCart(_ sender: AnyObject) {
do {
try validateEntries()
} catch ValidationError.quantityZero {
let alert = UIAlertController(title: "Error!", message: "The quantity can not be less than or equal to zero.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
} catch ValidationError.quantityNone {
let alert = UIAlertController(title: "Error!", message: "The product must have a quantity.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
} catch ValidationError.quantityInvalid {
let alert = UIAlertController(title: "Error!", message: "The quantity is invalid.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
} catch {
let alert = UIAlertController(title: "Wow!", message: "You broke me beyond error recognition.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
}
cartProduct.quantity = NSDecimalNumber(decimal: formatter.number(from: quantity.text!)!.decimalValue)
cartProduct.taxable = NSNumber(value: (taxable.selectedSegmentIndex == 0) as Bool)
moc.mr_saveToPersistentStoreAndWait()
saved = true
_ = navigationController?.popToRootViewController(animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingFromParentViewController && !saved && !edit {
cartProduct.mr_deleteEntity()
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func validateEntries() throws {
if (quantity.text == "") {
throw ValidationError.quantityNone
} else if let num = formatter.number(from: quantity.text!) {
if num.doubleValue <= 0 {
throw ValidationError.quantityZero
}
} else {
throw ValidationError.quantityInvalid
}
}
@IBAction func increase(_ sender: AnyObject) {
if var num = Int(quantity.text!) {
num += 1
quantity.text = String(num)
}
}
@IBAction func decrease(_ sender: AnyObject) {
if var num = Int(quantity.text!), num - 1 > 0 {
num -= 1
quantity.text = String(num)
}
}
@IBAction func cancel(_ sender: AnyObject) {
_ = self.navigationController?.popToRootViewController(animated: true)
}
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.
}
*/
}
|
apache-2.0
|
8e4a336a2a1c2653d19a8abe890bcbfd
| 31.174157 | 137 | 0.666841 | 4.574281 | false | false | false | false |
rexmas/Crust
|
Crust/Mapper/MappingProtocols.swift
|
1
|
10061
|
import Foundation
import JSONValueRX
public enum CollectionInsertionMethod<Element> {
case append
case replace(delete: ((_ orphansToDelete: AnyCollection<Element>) -> AnyCollection<Element>)?)
}
public typealias CollectionUpdatePolicy<Element> =
(insert: CollectionInsertionMethod<Element>, unique: Bool, nullable: Bool)
public indirect enum Binding<K: MappingKey, M: Mapping> {
case mapping(K, M)
case collectionMapping(K, M, CollectionUpdatePolicy<M.MappedObject>)
public var keyPath: String {
switch self {
case .mapping(let key, _):
return key.keyPath
case .collectionMapping(let key, _, _):
return key.keyPath
}
}
public var key: K {
switch self {
case .mapping(let key, _):
return key
case .collectionMapping(let key, _, _):
return key
}
}
public var mapping: M {
switch self {
case .mapping(_, let mapping):
return mapping
case .collectionMapping(_, let mapping, _):
return mapping
}
}
public var collectionUpdatePolicy: CollectionUpdatePolicy<M.MappedObject> {
switch self {
case .mapping(_, _):
return (.replace(delete: nil), true, true)
case .collectionMapping(_, _, let method):
return method
}
}
internal func nestedBinding(`for` nestedKeys: M.MappingKeyType)
-> Binding<M.MappingKeyType, M> {
switch self {
case .mapping(_, let mapping):
return .mapping(nestedKeys, mapping)
case .collectionMapping(_, let mapping, let method):
return .collectionMapping(nestedKeys, mapping, method)
}
}
}
public protocol Mapping {
/// The class, struct, enum type we are mapping to.
associatedtype MappedObject
/// The DB adapter type.
associatedtype AdapterKind: PersistanceAdapter
associatedtype MappingKeyType: MappingKey
var adapter: AdapterKind { get }
typealias PrimaryKeyTransform = (JSONValue, MappingPayload<AnyMappingKey>?) throws -> CVarArg?
/// Describes a primary key on the `MappedObject`.
/// - property: Primary key property name on `MappedObject`.
/// - keyPath: The key path into the JSON blob to retrieve the primary key's value.
/// A `nil` value returns the whole JSON blob for this object.
/// - transform: Transform executed on the retrieved primary key's value before usage. The
/// JSON returned from `keyPath` is passed into this transform. The full parent payload is additionally
/// handed in for arbitrary usage, such as mapping from a uuid in the parent object.
/// A `nil` `transform` or `nil` returned value means the JSON value is not tranformed before
/// being used. Can `throw` an error which stops mapping and returns the error to the caller.
typealias PrimaryKeyDescriptor = (property: String, keyPath: String?, transform: PrimaryKeyTransform?)
/// The primaryKeys on `MappedObject`. Primary keys are mapped separately from what is mapped in
/// `mapping(toMap:payload:)` and are never remapped to objects fetched from the database.
var primaryKeys: [PrimaryKeyDescriptor]? { get }
/// Override to perform mappings to properties.
func mapping(toMap: inout MappedObject, payload: MappingPayload<MappingKeyType>) throws
}
public enum DefaultDatabaseTag: String {
case realm = "Realm"
case coreData = "CoreData"
case none = "None"
}
/// A PersistanceAdapter to use to write and read objects from a persistance layer.
public protocol PersistanceAdapter {
/// The type of object being mapped to. If Realm then RLMObject or Object. If Core Data then NSManagedObject.
associatedtype BaseType
/// The type of returned results after a fetch.
associatedtype ResultsType: Collection
/// Informs the caller if the PersistanceAdapter is currently within a transaction. The type which inherits PersistanceAdapter
/// will generally set this value to `true` explicitly or implicitly in the call to `mappingWillBegin`
/// `false` in the call to `mappingDidEnd`.
///
/// The `Mapper` will check for this value before calling `mappingWillBegin`, and if `true` will _not_ call `mappingWillBegin`
/// and if `false` will call `mappingWillBegin`, even in nested object mappings.
var isInTransaction: Bool { get }
/// Used to designate the database type being written to by this adapter. This is checked before calls to `mappingWillBegin` and
/// `mappingDidEnd`. If the same `dataBaseTag` is used for a nested mapping as a parent mapping, then `mappingWillBegin` and
/// `mappingDidEnd` will not be called for the nested mapping. This prevents illegal recursive transactions from being started during mapping.
/// `DefaultDatabaseTag` provides some defaults to use for often use iOS databases, or none at all.
var dataBaseTag: String { get }
/// Called at the beginning of mapping a json blob. Good place to start a write transaction. Will only
/// be called once at the beginning of a tree of nested objects being mapped assuming `isInTransaction` is set to
/// `true` during that first call.
func mappingWillBegin() throws
/// Called at the end of mapping a json blob. Good place to close a write transaction. Will only
/// be called once at the end of a tree of nested objects being mapped.
func mappingDidEnd() throws
/// Called if mapping errored. Good place to cancel a write transaction. Mapping will no longer
/// continue after this is called.
func mappingErrored(_ error: Error)
/// Use this to globally transform the value of primary keys before they are mapped.
/// E.g. our JSON model uses Double for numbers. If the primary key is an Int you must
/// either transform the primary key in the mapping or you can dynamically check if the
/// property is an Int here and transform Double to properties of Int in all cases.
func sanitize(primaryKeyProperty property: String, forValue value: CVarArg, ofType baseType: BaseType.Type) -> CVarArg?
/// Fetch objects from local persistance.
///
/// - parameter baseType: The type of object being returned by the query
/// - parameter primaryKeyValues: An Array of of Dictionaries of primary keys to values to query. Each
/// Dictionary is a query for a single object with possible composite keys (multiple primary keys).
///
/// The query should have a form similar to "Dict0Key0 == Dict0Val0 AND Dict0Key1 == Dict0Val1 OR
/// Dict1Key0 == Dict1Val0 AND Dict1Key1 == Dict1Val1" etc. Where Dict0 is the first dictionary in the
/// array and contains all the primary key/value pairs to search for for a single object of type `type`.
/// - parameter isMapping: Indicates whether or not we're in the process of mapping an object. If `true` then
/// the `PersistanceAdapter` may need to avoid querying the store since the returned object's primary key may be written
/// to if available. If this is the case, the `PersistanceAdapter` may need to return any objects cached in memory during the current
/// mapping process, not query the persistance layer.
/// - returns: Results of the query.
func fetchObjects(baseType: BaseType.Type, primaryKeyValues: [[String : CVarArg]], isMapping: Bool) -> ResultsType?
/// Create a default object of type `BaseType`. This is called between `mappingWillBegin` and `mappingDidEnd` and
/// will be the object that Crust then maps to.
func createObject(baseType: BaseType.Type) throws -> BaseType
/// Delete an object.
func deleteObject(_ obj: BaseType) throws
/// Save a set of mapped objects. Called right before `mappingDidEnd`.
func save(objects: [ BaseType ]) throws
}
public protocol Transform: AnyMapping {
associatedtype MappingKeyType = RootKey
func fromJSON(_ json: JSONValue) throws -> MappedObject
func toJSON(_ obj: MappedObject) -> JSONValue
}
public extension Transform {
func mapping(toMap: inout MappedObject, payload: MappingPayload<RootKey>) {
switch payload.dir {
case .fromJSON:
do {
try toMap = self.fromJSON(payload.json)
}
catch let err {
payload.error = err
}
case .toJSON:
payload.json = self.toJSON(toMap)
}
}
}
extension Optional: AnyMappable where Wrapped: AnyMappable {
public init() {
self = .some(Wrapped())
}
}
struct OptionalAnyMapping<M: AnyMapping>: AnyMapping {
typealias MappedObject = Optional<M.MappedObject>
typealias MappingKeyType = M.MappingKeyType
let wrappedMapping: M
init(wrappedMapping: M) {
self.wrappedMapping = wrappedMapping
}
func mapping(toMap: inout Optional<M.MappedObject>, payload: MappingPayload<M.MappingKeyType>) throws {
guard toMap != nil else { return }
try self.wrappedMapping.mapping(toMap: &(toMap!), payload: payload)
}
}
public protocol StringRawValueTransform: Transform where MappedObject: RawRepresentable, MappedObject.RawValue == String { }
extension StringRawValueTransform {
public func fromJSON(_ json: JSONValue) throws -> MappedObject {
switch json {
case .string(let str):
guard let val = MappedObject(rawValue: str) else {
throw MappingError.stringRawValueTransformFailure(value: str, toType: MappedObject.self)
}
return val
default:
throw MappingError.stringRawValueTransformFailure(value: json.values(), toType: MappedObject.self)
}
}
public func toJSON(_ obj: MappedObject) -> JSONValue {
return .string(obj.rawValue)
}
}
|
mit
|
5e17e4a84753fdaf8b5e3191e30a4e85
| 42.554113 | 146 | 0.671404 | 4.779572 | false | false | false | false |
ptarjan/cordova-hot-code-push
|
src/ios/SocketIOClientSwift/SocketParser.swift
|
9
|
6315
|
//
// SocketParser.swift
// Socket.IO-Client-Swift
//
// 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
class SocketParser {
private static func isCorrectNamespace(nsp: String, _ socket: SocketIOClient) -> Bool {
return nsp == socket.nsp
}
private static func handleEvent(p: SocketPacket, socket: SocketIOClient) {
guard isCorrectNamespace(p.nsp, socket) else { return }
socket.handleEvent(p.event, data: p.args ?? [],
isInternalMessage: false, wantsAck: p.id)
}
private static func handleAck(p: SocketPacket, socket: SocketIOClient) {
guard isCorrectNamespace(p.nsp, socket) else { return }
socket.handleAck(p.id, data: p.data)
}
private static func handleBinary(p: SocketPacket, socket: SocketIOClient) {
guard isCorrectNamespace(p.nsp, socket) else { return }
socket.waitingData.append(p)
}
private static func handleConnect(p: SocketPacket, socket: SocketIOClient) {
if p.nsp == "/" && socket.nsp != "/" {
socket.joinNamespace()
} else if p.nsp != "/" && socket.nsp == "/" {
socket.didConnect()
} else {
socket.didConnect()
}
}
static func parseString(message: String) -> SocketPacket? {
var parser = SocketStringReader(message: message)
guard let type = SocketPacket.PacketType(str: parser.read(1))
else {return nil}
if !parser.hasNext {
return SocketPacket(type: type, nsp: "/")
}
var namespace: String?
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
if let holders = Int(parser.readUntilStringOccurence("-")) {
placeholders = holders
} else {
return nil
}
}
if parser.currentCharacter == "/" {
namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd()
}
if !parser.hasNext {
return SocketPacket(type: type, id: -1,
nsp: namespace ?? "/", placeholders: placeholders)
}
var idString = ""
while parser.hasNext {
if let int = Int(parser.read(1)) {
idString += String(int)
} else {
parser.advanceIndexBy(-2)
break
}
}
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
let data = parseData(noPlaceholders) as? [AnyObject] ?? [noPlaceholders]
return SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders)
}
// Parses data for events
static func parseData(data: String) -> AnyObject? {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
return try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers)
} catch {
Logger.error("Parsing JSON: %@", type: "SocketParser", args: data)
return nil
}
}
// Parses messages recieved
static func parseSocketMessage(message: String, socket: SocketIOClient) {
guard !message.isEmpty else { return }
Logger.log("Parsing %@", type: "SocketParser", args: message)
guard let pack = parseString(message) else {
Logger.error("Parsing message: %@", type: "SocketParser", args: message)
return
}
Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
switch pack.type {
case .Event:
handleEvent(pack, socket: socket)
case .Ack:
handleAck(pack, socket: socket)
case .BinaryEvent:
handleBinary(pack, socket: socket)
case .BinaryAck:
handleBinary(pack, socket: socket)
case .Connect:
handleConnect(pack, socket: socket)
case .Disconnect:
socket.didDisconnect("Got Disconnect")
case .Error:
socket.didError("Error: \(pack.data)")
}
}
static func parseBinaryData(data: NSData, socket: SocketIOClient) {
guard !socket.waitingData.isEmpty else {
Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
let shouldExecute = socket.waitingData[socket.waitingData.count - 1].addData(data)
guard shouldExecute else {
return
}
var packet = socket.waitingData.removeLast()
packet.fillInPlaceholders()
if packet.type != .BinaryAck {
socket.handleEvent(packet.event, data: packet.args ?? [],
isInternalMessage: false, wantsAck: packet.id)
} else {
socket.handleAck(packet.id, data: packet.args)
}
}
}
|
mit
|
9d434505bc13b941f60fe83a9b9d4b80
| 35.085714 | 98 | 0.58939 | 4.809596 | false | false | false | false |
maxadamski/swift-corelibs-foundation
|
Foundation/NSURLRequest.swift
|
2
|
16543
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/*!
@header NSURLRequest.h
This header file describes the constructs used to represent URL
load requests in a manner independent of protocol and URL scheme.
Immutable and mutable variants of this URL load request concept
are described, named NSURLRequest and NSMutableURLRequest,
respectively. A collection of constants is also declared to
exercise control over URL content caching policy.
<p>NSURLRequest and NSMutableURLRequest are designed to be
customized to support protocol-specific requests. Protocol
implementors who need to extend the capabilities of NSURLRequest
and NSMutableURLRequest are encouraged to provide categories on
these classes as appropriate to support protocol-specific data. To
store and retrieve data, category methods can use the
<tt>+propertyForKey:inRequest:</tt> and
<tt>+setProperty:forKey:inRequest:</tt> class methods on
NSURLProtocol. See the NSHTTPURLRequest on NSURLRequest and
NSMutableHTTPURLRequest on NSMutableURLRequest for examples of
such extensions.
<p>The main advantage of this design is that a client of the URL
loading library can implement request policies in a standard way
without type checking of requests or protocol checks on URLs. Any
protocol-specific details that have been set on a URL request will
be used if they apply to the particular URL being loaded, and will
be ignored if they do not apply.
*/
/*!
@enum NSURLRequestCachePolicy
@discussion The NSURLRequestCachePolicy enum defines constants that
can be used to specify the type of interactions that take place with
the caching system when the URL loading system processes a request.
Specifically, these constants cover interactions that have to do
with whether already-existing cache data is returned to satisfy a
URL load request.
@constant NSURLRequestUseProtocolCachePolicy Specifies that the
caching logic defined in the protocol implementation, if any, is
used for a particular URL load request. This is the default policy
for URL load requests.
@constant NSURLRequestReloadIgnoringLocalCacheData Specifies that the
data for the URL load should be loaded from the origin source. No
existing local cache data, regardless of its freshness or validity,
should be used to satisfy a URL load request.
@constant NSURLRequestReloadIgnoringLocalAndRemoteCacheData Specifies that
not only should the local cache data be ignored, but that proxies and
other intermediates should be instructed to disregard their caches
so far as the protocol allows. Unimplemented.
@constant NSURLRequestReloadIgnoringCacheData Older name for
NSURLRequestReloadIgnoringLocalCacheData.
@constant NSURLRequestReturnCacheDataElseLoad Specifies that the
existing cache data should be used to satisfy a URL load request,
regardless of its age or expiration date. However, if there is no
existing data in the cache corresponding to a URL load request,
the URL is loaded from the origin source.
@constant NSURLRequestReturnCacheDataDontLoad Specifies that the
existing cache data should be used to satisfy a URL load request,
regardless of its age or expiration date. However, if there is no
existing data in the cache corresponding to a URL load request, no
attempt is made to load the URL from the origin source, and the
load is considered to have failed. This constant specifies a
behavior that is similar to an "offline" mode.
@constant NSURLRequestReloadRevalidatingCacheData Specifies that
the existing cache data may be used provided the origin source
confirms its validity, otherwise the URL is loaded from the
origin source. Unimplemented.
*/
public enum NSURLRequestCachePolicy : UInt {
case UseProtocolCachePolicy
case ReloadIgnoringLocalCacheData
case ReloadIgnoringLocalAndRemoteCacheData // Unimplemented
public static var ReloadIgnoringCacheData: NSURLRequestCachePolicy { return .ReloadIgnoringLocalCacheData }
case ReturnCacheDataElseLoad
case ReturnCacheDataDontLoad
case ReloadRevalidatingCacheData // Unimplemented
}
/*!
@enum NSURLRequestNetworkServiceType
@discussion The NSURLRequestNetworkServiceType enum defines constants that
can be used to specify the service type to associate with this request. The
service type is used to provide the networking layers a hint of the purpose
of the request.
@constant NSURLNetworkServiceTypeDefault Is the default value for an NSURLRequest
when created. This value should be left unchanged for the vast majority of requests.
@constant NSURLNetworkServiceTypeVoIP Specifies that the request is for voice over IP
control traffic.
@constant NSURLNetworkServiceTypeVideo Specifies that the request is for video
traffic.
@constant NSURLNetworkServiceTypeBackground Specifies that the request is for background
traffic (such as a file download).
@constant NSURLNetworkServiceTypeVoice Specifies that the request is for voice data.
*/
public enum NSURLRequestNetworkServiceType : UInt {
case NetworkServiceTypeDefault // Standard internet traffic
case NetworkServiceTypeVoIP // Voice over IP control traffic
case NetworkServiceTypeVideo // Video traffic
case NetworkServiceTypeBackground // Background traffic
case NetworkServiceTypeVoice // Voice data
}
/*!
@class NSURLRequest
@abstract An NSURLRequest object represents a URL load request in a
manner independent of protocol and URL scheme.
@discussion NSURLRequest encapsulates two basic data elements about
a URL load request:
<ul>
<li>The URL to load.
<li>The policy to use when consulting the URL content cache made
available by the implementation.
</ul>
In addition, NSURLRequest is designed to be extended to support
protocol-specific data by adding categories to access a property
object provided in an interface targeted at protocol implementors.
<ul>
<li>Protocol implementors should direct their attention to the
NSURLRequestExtensibility category on NSURLRequest for more
information on how to provide extensions on NSURLRequest to
support protocol-specific request information.
<li>Clients of this API who wish to create NSURLRequest objects to
load URL content should consult the protocol-specific NSURLRequest
categories that are available. The NSHTTPURLRequest category on
NSURLRequest is an example.
</ul>
<p>
Objects of this class are used to create NSURLConnection instances,
which can are used to perform the load of a URL, or as input to the
NSURLConnection class method which performs synchronous loads.
*/
public class NSURLRequest : NSObject, NSSecureCoding, NSCopying, NSMutableCopying {
private var _URL : NSURL?
private var _mainDocumentURL: NSURL?
private var _httpHeaderFields: [String: String]?
public func copyWithZone(zone: NSZone) -> AnyObject {
NSUnimplemented()
}
public func mutableCopyWithZone(zone: NSZone) -> AnyObject {
NSUnimplemented()
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public func encodeWithCoder(aCoder: NSCoder) {
NSUnimplemented()
}
private override init() {}
/*!
@method requestWithURL:
@abstract Allocates and initializes an NSURLRequest with the given
URL.
@discussion Default values are used for cache policy
(NSURLRequestUseProtocolCachePolicy) and timeout interval (60
seconds).
@param URL The URL for the request.
@result A newly-created and autoreleased NSURLRequest instance.
*/
/*
@method supportsSecureCoding
@abstract Indicates that NSURLRequest implements the NSSecureCoding protocol.
@result A BOOL value set to YES.
*/
public static func supportsSecureCoding() -> Bool { return true }
/*!
@method requestWithURL:cachePolicy:timeoutInterval:
@abstract Allocates and initializes a NSURLRequest with the given
URL and cache policy.
@param URL The URL for the request.
@param cachePolicy The cache policy for the request.
@param timeoutInterval The timeout interval for the request. See the
commentary for the <tt>timeoutInterval</tt> for more information on
timeout intervals.
@result A newly-created and autoreleased NSURLRequest instance.
*/
/*!
@method initWithURL:
@abstract Initializes an NSURLRequest with the given URL.
@discussion Default values are used for cache policy
(NSURLRequestUseProtocolCachePolicy) and timeout interval (60
seconds).
@param URL The URL for the request.
@result An initialized NSURLRequest.
*/
public convenience init(URL: NSURL) {
self.init()
_URL = URL
}
/*!
@method URL
@abstract Returns the URL of the receiver.
@result The URL of the receiver.
*/
/*@NSCopying */public var URL: NSURL? { return _URL }
/*!
@method mainDocumentURL
@abstract The main document URL associated with this load.
@discussion This URL is used for the cookie "same domain as main
document" policy. There may also be other future uses.
See setMainDocumentURL:
@result The main document URL.
*/
/*@NSCopying*/ public var mainDocumentURL: NSURL? { return _mainDocumentURL }
/*!
@method HTTPMethod
@abstract Returns the HTTP request method of the receiver.
@result the HTTP request method of the receiver.
*/
public var HTTPMethod: String? { get { return "GET" } }
/*!
@method allHTTPHeaderFields
@abstract Returns a dictionary containing all the HTTP header fields
of the receiver.
@result a dictionary containing all the HTTP header fields of the
receiver.
*/
public var allHTTPHeaderFields: [String : String]? { return _httpHeaderFields }
/*!
@method valueForHTTPHeaderField:
@abstract Returns the value which corresponds to the given header
field. Note that, in keeping with the HTTP RFC, HTTP header field
names are case-insensitive.
@param field the header field name to use for the lookup
(case-insensitive).
@result the value associated with the given header field, or nil if
there is no value associated with the given header field.
*/
public func valueForHTTPHeaderField(field: String) -> String? { return _httpHeaderFields?[field.lowercaseString] }
}
/*!
@class NSMutableURLRequest
@abstract An NSMutableURLRequest object represents a mutable URL load
request in a manner independent of protocol and URL scheme.
@discussion This specialization of NSURLRequest is provided to aid
developers who may find it more convenient to mutate a single request
object for a series of URL loads instead of creating an immutable
NSURLRequest for each load. This programming model is supported by
the following contract stipulation between NSMutableURLRequest and
NSURLConnection: NSURLConnection makes a deep copy of each
NSMutableURLRequest object passed to one of its initializers.
<p>NSMutableURLRequest is designed to be extended to support
protocol-specific data by adding categories to access a property
object provided in an interface targeted at protocol implementors.
<ul>
<li>Protocol implementors should direct their attention to the
NSMutableURLRequestExtensibility category on
NSMutableURLRequest for more information on how to provide
extensions on NSMutableURLRequest to support protocol-specific
request information.
<li>Clients of this API who wish to create NSMutableURLRequest
objects to load URL content should consult the protocol-specific
NSMutableURLRequest categories that are available. The
NSMutableHTTPURLRequest category on NSMutableURLRequest is an
example.
</ul>
*/
public class NSMutableURLRequest : NSURLRequest {
private var _HTTPMethod: String? = "GET"
public required init?(coder aDecoder: NSCoder) {
super.init()
}
private override init() { super.init() }
/*!
@method URL
@abstract Sets the URL of the receiver.
@param URL The new URL for the receiver.
*/
/*@NSCopying */ public override var URL: NSURL? {
get {
return _URL
}
set(newURL) {
_URL = newURL
}
}
/*!
@method setMainDocumentURL:
@abstract Sets the main document URL
@param URL The main document URL.
@discussion The caller should pass the URL for an appropriate main
document, if known. For example, when loading a web page, the URL
of the main html document for the top-level frame should be
passed. This main document will be used to implement the cookie
"only from same domain as main document" policy, and possibly
other things in the future.
*/
/*@NSCopying*/ public override var mainDocumentURL: NSURL? {
get {
return _mainDocumentURL
} set(newMainDocumentURL) {
_mainDocumentURL = newMainDocumentURL
}
}
/*!
@method HTTPMethod
@abstract Sets the HTTP request method of the receiver.
@result the HTTP request method of the receiver.
*/
public override var HTTPMethod: String? {
get {
return _HTTPMethod
} set(newHTTPMethod) {
_HTTPMethod = newHTTPMethod
}
}
/*!
@method setValue:forHTTPHeaderField:
@abstract Sets the value of the given HTTP header field.
@discussion If a value was previously set for the given header
field, that value is replaced with the given value. Note that, in
keeping with the HTTP RFC, HTTP header field names are
case-insensitive.
@param value the header field value.
@param field the header field name (case-insensitive).
*/
public func setValue(value: String?, forHTTPHeaderField field: String) {
if _httpHeaderFields == nil {
_httpHeaderFields = [:]
}
if let existingHeader = _httpHeaderFields?.filter({ (existingField, _) -> Bool in
return existingField.lowercaseString == field.lowercaseString
}).first {
let (existingField, _) = existingHeader
_httpHeaderFields?.removeValueForKey(existingField)
}
_httpHeaderFields?[field] = value
}
/*!
@method addValue:forHTTPHeaderField:
@abstract Adds an HTTP header field in the current header
dictionary.
@discussion This method provides a way to add values to header
fields incrementally. If a value was previously set for the given
header field, the given value is appended to the previously-existing
value. The appropriate field delimiter, a comma in the case of HTTP,
is added by the implementation, and should not be added to the given
value by the caller. Note that, in keeping with the HTTP RFC, HTTP
header field names are case-insensitive.
@param value the header field value.
@param field the header field name (case-insensitive).
*/
public func addValue(value: String, forHTTPHeaderField field: String) {
if _httpHeaderFields == nil {
_httpHeaderFields = [:]
}
if let existingHeader = _httpHeaderFields?.filter({ (existingField, _) -> Bool in
return existingField.lowercaseString == field.lowercaseString
}).first {
let (existingField, existingValue) = existingHeader
_httpHeaderFields?[existingField] = "\(existingValue),\(value)"
} else {
_httpHeaderFields?[field] = value
}
}
}
|
apache-2.0
|
9f4f5c12789041fb8d1a5b919b9bc022
| 38.576555 | 118 | 0.708396 | 5.425713 | false | false | false | false |
pietrocaselani/Trakt-Swift
|
Trakt/Models/Base/BaseEpisode.swift
|
1
|
1668
|
import Foundation
public final class BaseEpisode: Codable, Hashable {
public let number: Int
public let collectedAt: Date?
public let plays: Int?
public let lastWatchedAt: Date?
public let completed: Bool?
private enum CodingKeys: String, CodingKey {
case number
case collectedAt = "collected_at"
case lastWatchedAt = "last_watched_at"
case plays
case completed
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.number = try container.decode(Int.self, forKey: .number)
self.plays = try container.decodeIfPresent(Int.self, forKey: .plays)
self.completed = try container.decodeIfPresent(Bool.self, forKey: .completed)
let collectedAt = try container.decodeIfPresent(String.self, forKey: .collectedAt)
self.collectedAt = TraktDateTransformer.dateTimeTransformer.transformFromJSON(collectedAt)
let lastWatchedAt = try container.decodeIfPresent(String.self, forKey: .lastWatchedAt)
self.lastWatchedAt = TraktDateTransformer.dateTimeTransformer.transformFromJSON(lastWatchedAt)
}
public var hashValue: Int {
var hash = number.hashValue
if let collectedAtHash = collectedAt?.hashValue {
hash = hash ^ collectedAtHash
}
if let playsHash = plays?.hashValue {
hash = hash ^ playsHash
}
if let lastWatchedAtHash = lastWatchedAt?.hashValue {
hash = hash ^ lastWatchedAtHash
}
if let completedHash = completed?.hashValue {
hash = hash ^ completedHash
}
return hash
}
public static func == (lhs: BaseEpisode, rhs: BaseEpisode) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
|
unlicense
|
3698c0743957b50ecb40238271ac1a82
| 28.263158 | 96 | 0.731415 | 4.028986 | false | false | false | false |
KevinShawn/HackingWithSwift
|
project34/Project34/Board.swift
|
24
|
3994
|
//
// Board.swift
// Project34
//
// Created by Hudzilla on 19/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import GameplayKit
import UIKit
enum ChipColor: Int {
case None = 0
case Red
case Black
}
class Board: NSObject, GKGameModel {
static var width = 7
static var height = 6
var slots = [ChipColor]()
var currentPlayer: Player
var players: [GKGameModelPlayer]? {
return Player.allPlayers
}
var activePlayer: GKGameModelPlayer? {
return currentPlayer
}
override init() {
currentPlayer = Player.allPlayers[0]
for _ in 0 ..< Board.width * Board.height {
slots.append(.None)
}
super.init()
}
func chipInColumn(column: Int, row: Int) -> ChipColor {
return slots[row + column * Board.height]
}
func setChip(chip: ChipColor, inColumn column: NSInteger, row: NSInteger) {
slots[row + column * Board.height] = chip;
}
func squaresMatchChip(chip: ChipColor, row: Int, col: Int, moveX: Int, moveY: Int) -> Bool {
// bail out early if we can't win from here
if row + (moveY * 3) < 0 { return false }
if row + (moveY * 3) >= Board.height { return false }
if col + (moveX * 3) < 0 { return false }
if col + (moveX * 3) >= Board.width { return false }
// still here? Check every square
if chipInColumn(col, row: row) != chip { return false }
if chipInColumn(col + moveX, row: row + moveY) != chip { return false }
if chipInColumn(col + (moveX * 2), row: row + (moveY * 2)) != chip { return false }
if chipInColumn(col + (moveX * 3), row: row + (moveY * 3)) != chip { return false }
return true
}
func nextEmptySlotInColumn(column: Int) -> Int? {
for var row = 0; row < Board.height; row++ {
if chipInColumn(column, row:row) == .None {
return row
}
}
return nil;
}
func canMoveInColumn(column: Int) -> Bool {
return nextEmptySlotInColumn(column) != nil
}
func addChip(chip: ChipColor, inColumn column: Int) {
if let row = nextEmptySlotInColumn(column) {
setChip(chip, inColumn:column, row:row)
}
}
func isFull() -> Bool {
for var column = 0; column < Board.width; column++ {
if canMoveInColumn(column) {
return false
}
}
return true;
}
func isWinForPlayer(player: GKGameModelPlayer) -> Bool {
let chip = (player as! Player).chip
for var row = 0; row < Board.height; row++ {
for var col = 0; col < Board.width; col++ {
if squaresMatchChip(chip, row: row, col: col, moveX: 1, moveY: 0) {
return true
} else if squaresMatchChip(chip, row: row, col: col, moveX: 0, moveY: 1) {
return true
} else if squaresMatchChip(chip, row: row, col: col, moveX: 1, moveY: 1) {
return true
} else if squaresMatchChip(chip, row: row, col: col, moveX: 1, moveY: -1) {
return true
}
}
}
return false
}
func copyWithZone(zone: NSZone) -> AnyObject {
let copy = Board()
copy.setGameModel(self)
return copy
}
func setGameModel(gameModel: GKGameModel) {
if let board = gameModel as? Board {
slots = board.slots
currentPlayer = board.currentPlayer
}
}
func gameModelUpdatesForPlayer(player: GKGameModelPlayer) -> [GKGameModelUpdate]? {
// 1
if let playerObject = player as? Player {
// 2
if isWinForPlayer(playerObject) || isWinForPlayer(playerObject.opponent) {
return nil
}
// 3
var moves = [Move]()
// 4
for var column = 0; column < Board.width; column++ {
if canMoveInColumn(column) {
// 5
moves.append(Move(column: column))
}
}
// 6
return moves;
}
return nil
}
func applyGameModelUpdate(gameModelUpdate: GKGameModelUpdate) {
if let move = gameModelUpdate as? Move {
addChip(currentPlayer.chip, inColumn: move.column)
currentPlayer = currentPlayer.opponent
}
}
func scoreForPlayer(player: GKGameModelPlayer) -> Int {
if let playerObject = player as? Player {
if isWinForPlayer(playerObject) {
return 1000
} else if isWinForPlayer(playerObject.opponent) {
return -1000
}
}
return 0
}
}
|
unlicense
|
0cb1ef71309a0c395dcc7df8d20e5322
| 21.948276 | 93 | 0.649887 | 3.119531 | false | false | false | false |
dreamsxin/swift
|
test/Interpreter/SDK/CGImportAsMember.swift
|
3
|
1586
|
// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: OS=macosx
import Foundation
import CoreGraphics
class Colors {
// TODO: when issue is fixed, migrate these to CGColor class properties
static var black = CGColor.constantColor(for: CGColor.black)!
static var white = CGColor.constantColor(for: CGColor.white)!
// FIXME: this triggers an assert in SILVerifier
static var clear = CGColor.constantColor(for: CGColor.clear)!
class func printColors() {
print("Colors") // CHECK: Colors
print(black) // CHECK: Generic Gray Profile
print(white) // CHECK: Generic Gray Profile
print(clear) // CHECK: Generic Gray Profile
}
}
// TODO: ColorSpaces with their empty-argument-label pattern, when issue is
// fixed.
class Events {
static var mouseDefault = CGEventMouseSubtype.defaultType
static var mouseTabletPoint = CGEventMouseSubtype.tabletPoint
static var tapDefault = CGEventTapOptions.defaultTap
static var tapListenOnly = CGEventTapOptions.listenOnly
static var privateID = CGEventSourceStateID.privateState
static var combinedSessionID = CGEventSourceStateID.combinedSessionState
class func printEvents() {
print("Events") // CHECK-LABEL: Events
print(mouseDefault.rawValue) // CHECK: 0
print(mouseTabletPoint.rawValue) // CHECK: 1
print(tapDefault.rawValue) // CHECK: 0
print(tapListenOnly.rawValue) // CHECK: 1
print(privateID.rawValue) // CHECK: -1
print(combinedSessionID.rawValue) // CHECK: 0
}
}
Colors.printColors()
Events.printEvents()
|
apache-2.0
|
de5c2ce0c3ce6109a59ab48c22c98b00
| 31.367347 | 76 | 0.733291 | 3.868293 | false | false | false | false |
klundberg/swift-corelibs-foundation
|
Foundation/NSDateFormatter.swift
|
1
|
20044
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public class DateFormatter : Formatter {
typealias CFType = CFDateFormatter
private var __cfObject: CFType?
private var _cfObject: CFType {
guard let obj = __cfObject else {
#if os(OSX) || os(iOS)
let dateStyle = CFDateFormatterStyle(rawValue: CFIndex(self.dateStyle.rawValue))!
let timeStyle = CFDateFormatterStyle(rawValue: CFIndex(self.timeStyle.rawValue))!
#else
let dateStyle = CFDateFormatterStyle(self.dateStyle.rawValue)
let timeStyle = CFDateFormatterStyle(self.timeStyle.rawValue)
#endif
let obj = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, dateStyle, timeStyle)!
_setFormatterAttributes(obj)
if let dateFormat = _dateFormat {
CFDateFormatterSetFormat(obj, dateFormat._cfObject)
}
__cfObject = obj
return obj
}
return obj
}
public override init() {
super.init()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
public var formattingContext: Context = .unknown // default is NSFormattingContextUnknown
public func objectValue(_ string: String, range rangep: UnsafeMutablePointer<NSRange>) throws -> AnyObject? { NSUnimplemented() }
public override func string(for obj: AnyObject) -> String? {
guard let date = obj as? Date else { return nil }
return string(from: date)
}
public func string(from date: Date) -> String {
return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, _cfObject, date._cfObject)._swiftObject
}
public func date(from string: String) -> Date? {
var range = CFRange(location: 0, length: string.length)
let date = withUnsafeMutablePointer(&range) { (rangep: UnsafeMutablePointer<CFRange>) -> Date? in
guard let res = CFDateFormatterCreateDateFromString(kCFAllocatorSystemDefault, _cfObject, string._cfObject, rangep) else {
return nil
}
return res._swiftObject
}
return date
}
public class func localizedString(from date: Date, dateStyle dstyle: Style, timeStyle tstyle: Style) -> String {
let df = DateFormatter()
df.dateStyle = dstyle
df.timeStyle = tstyle
return df.string(for: date._nsObject)!
}
public class func dateFormat(fromTemplate tmplate: String, options opts: Int, locale: Locale?) -> String? {
guard let res = CFDateFormatterCreateDateFormatFromTemplate(kCFAllocatorSystemDefault, tmplate._cfObject, CFOptionFlags(opts), locale?._cfObject) else {
return nil
}
return res._swiftObject
}
public func setLocalizedDateFormatFromTemplate(_ dateFormatTemplate: String) {
NSUnimplemented()
}
private func _reset() {
__cfObject = nil
}
internal func _setFormatterAttributes(_ formatter: CFDateFormatter) {
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterIsLenient, value: lenient._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterTimeZone, value: timeZone?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterCalendarName, value: _calendar?.calendarIdentifier._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterTwoDigitStartDate, value: _twoDigitStartDate?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterDefaultDate, value: defaultDate?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterCalendar, value: _calendar?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterEraSymbols, value: _eraSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterMonthSymbols, value: _monthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortMonthSymbols, value: _shortMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterWeekdaySymbols, value: _weekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortWeekdaySymbols, value: _shortWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterAMSymbol, value: _AMSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterPMSymbol, value: _PMSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterLongEraSymbols, value: _longEraSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortMonthSymbols, value: _veryShortMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterStandaloneMonthSymbols, value: _standaloneMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortStandaloneMonthSymbols, value: _shortStandaloneMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortStandaloneMonthSymbols, value: _veryShortStandaloneMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortWeekdaySymbols, value: _veryShortWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterStandaloneWeekdaySymbols, value: _standaloneWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortStandaloneWeekdaySymbols, value: _shortStandaloneWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortStandaloneWeekdaySymbols, value: _veryShortStandaloneWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterQuarterSymbols, value: _quarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortQuarterSymbols, value: _shortQuarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterStandaloneQuarterSymbols, value: _standaloneQuarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortStandaloneQuarterSymbols, value: _shortStandaloneQuarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterGregorianStartDate, value: _gregorianStartDate?._cfObject)
}
internal func _setFormatterAttribute(_ formatter: CFDateFormatter, attributeName: CFString, value: AnyObject?) {
if let value = value {
CFDateFormatterSetProperty(formatter, attributeName, value)
}
}
private var _dateFormat: String? { willSet { _reset() } }
public var dateFormat: String! {
get {
guard let format = _dateFormat else {
return __cfObject.map { CFDateFormatterGetFormat($0)._swiftObject } ?? ""
}
return format
}
set {
_dateFormat = newValue
}
}
public var dateStyle: Style = .noStyle { willSet { _dateFormat = nil; _reset() } }
public var timeStyle: Style = .noStyle { willSet { _dateFormat = nil; _reset() } }
/*@NSCopying*/ public var locale: Locale! = .currentLocale() { willSet { _reset() } }
public var generatesCalendarDates = false { willSet { _reset() } }
/*@NSCopying*/ public var timeZone: TimeZone! = .systemTimeZone() { willSet { _reset() } }
/*@NSCopying*/ internal var _calendar: Calendar! { willSet { _reset() } }
public var calendar: Calendar! {
get {
guard let calendar = _calendar else {
return CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterCalendar) as! Calendar
}
return calendar
}
set {
_calendar = newValue
}
}
public var lenient = false { willSet { _reset() } }
/*@NSCopying*/ internal var _twoDigitStartDate: Date? { willSet { _reset() } }
public var twoDigitStartDate: Date? {
get {
guard let startDate = _twoDigitStartDate else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterTwoDigitStartDate) as? NSDate)?._swiftObject
}
return startDate
}
set {
_twoDigitStartDate = newValue
}
}
/*@NSCopying*/ public var defaultDate: Date? { willSet { _reset() } }
internal var _eraSymbols: [String]! { willSet { _reset() } }
public var eraSymbols: [String]! {
get {
guard let symbols = _eraSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterEraSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_eraSymbols = newValue
}
}
internal var _monthSymbols: [String]! { willSet { _reset() } }
public var monthSymbols: [String]! {
get {
guard let symbols = _monthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterMonthSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_monthSymbols = newValue
}
}
internal var _shortMonthSymbols: [String]! { willSet { _reset() } }
public var shortMonthSymbols: [String]! {
get {
guard let symbols = _shortMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortMonthSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_shortMonthSymbols = newValue
}
}
internal var _weekdaySymbols: [String]! { willSet { _reset() } }
public var weekdaySymbols: [String]! {
get {
guard let symbols = _weekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterWeekdaySymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_weekdaySymbols = newValue
}
}
internal var _shortWeekdaySymbols: [String]! { willSet { _reset() } }
public var shortWeekdaySymbols: [String]! {
get {
guard let symbols = _shortWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortWeekdaySymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_shortWeekdaySymbols = newValue
}
}
internal var _AMSymbol: String! { willSet { _reset() } }
public var AMSymbol: String! {
get {
guard let symbol = _AMSymbol else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterAMSymbol) as! NSString)._swiftObject
}
return symbol
}
set {
_AMSymbol = newValue
}
}
internal var _PMSymbol: String! { willSet { _reset() } }
public var PMSymbol: String! {
get {
guard let symbol = _PMSymbol else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterPMSymbol) as! NSString)._swiftObject
}
return symbol
}
set {
_PMSymbol = newValue
}
}
internal var _longEraSymbols: [String]! { willSet { _reset() } }
public var longEraSymbols: [String]! {
get {
guard let symbols = _longEraSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterLongEraSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_longEraSymbols = newValue
}
}
internal var _veryShortMonthSymbols: [String]! { willSet { _reset() } }
public var veryShortMonthSymbols: [String]! {
get {
guard let symbols = _veryShortMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortMonthSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_veryShortMonthSymbols = newValue
}
}
internal var _standaloneMonthSymbols: [String]! { willSet { _reset() } }
public var standaloneMonthSymbols: [String]! {
get {
guard let symbols = _standaloneMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterStandaloneMonthSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_standaloneMonthSymbols = newValue
}
}
internal var _shortStandaloneMonthSymbols: [String]! { willSet { _reset() } }
public var shortStandaloneMonthSymbols: [String]! {
get {
guard let symbols = _shortStandaloneMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortStandaloneMonthSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_shortStandaloneMonthSymbols = newValue
}
}
internal var _veryShortStandaloneMonthSymbols: [String]! { willSet { _reset() } }
public var veryShortStandaloneMonthSymbols: [String]! {
get {
guard let symbols = _veryShortStandaloneMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortStandaloneMonthSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_veryShortStandaloneMonthSymbols = newValue
}
}
internal var _veryShortWeekdaySymbols: [String]! { willSet { _reset() } }
public var veryShortWeekdaySymbols: [String]! {
get {
guard let symbols = _veryShortWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortWeekdaySymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_veryShortWeekdaySymbols = newValue
}
}
internal var _standaloneWeekdaySymbols: [String]! { willSet { _reset() } }
public var standaloneWeekdaySymbols: [String]! {
get {
guard let symbols = _standaloneWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterStandaloneWeekdaySymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_standaloneWeekdaySymbols = newValue
}
}
internal var _shortStandaloneWeekdaySymbols: [String]! { willSet { _reset() } }
public var shortStandaloneWeekdaySymbols: [String]! {
get {
guard let symbols = _shortStandaloneWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortStandaloneWeekdaySymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_shortStandaloneWeekdaySymbols = newValue
}
}
internal var _veryShortStandaloneWeekdaySymbols: [String]! { willSet { _reset() } }
public var veryShortStandaloneWeekdaySymbols: [String]! {
get {
guard let symbols = _veryShortStandaloneWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortStandaloneWeekdaySymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_veryShortStandaloneWeekdaySymbols = newValue
}
}
internal var _quarterSymbols: [String]! { willSet { _reset() } }
public var quarterSymbols: [String]! {
get {
guard let symbols = _quarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterQuarterSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_quarterSymbols = newValue
}
}
internal var _shortQuarterSymbols: [String]! { willSet { _reset() } }
public var shortQuarterSymbols: [String]! {
get {
guard let symbols = _shortQuarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortQuarterSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_shortQuarterSymbols = newValue
}
}
internal var _standaloneQuarterSymbols: [String]! { willSet { _reset() } }
public var standaloneQuarterSymbols: [String]! {
get {
guard let symbols = _standaloneQuarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterStandaloneQuarterSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_standaloneQuarterSymbols = newValue
}
}
internal var _shortStandaloneQuarterSymbols: [String]! { willSet { _reset() } }
public var shortStandaloneQuarterSymbols: [String]! {
get {
guard let symbols = _shortStandaloneQuarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortStandaloneQuarterSymbols) as! NSArray
return cfSymbols.bridge().map { ($0 as! NSString).bridge() }
}
return symbols
}
set {
_shortStandaloneQuarterSymbols = newValue
}
}
internal var _gregorianStartDate: Date? { willSet { _reset() } }
public var gregorianStartDate: Date? {
get {
guard let startDate = _gregorianStartDate else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterGregorianStartDate) as? NSDate)?._swiftObject
}
return startDate
}
set {
_gregorianStartDate = newValue
}
}
public var doesRelativeDateFormatting = false { willSet { _reset() } }
}
extension DateFormatter {
public enum Style : UInt {
case noStyle
case shortStyle
case mediumStyle
case longStyle
case fullStyle
}
}
|
apache-2.0
|
6658bcb0e209d12d9afdac940a4ef1a7
| 40.585062 | 161 | 0.634255 | 5.581732 | false | false | false | false |
mypalal84/GoGoGithub
|
GoGoGithub/GoGoGithub/CustomTransition.swift
|
1
|
1074
|
//
// CustomTransition.swift
// GoGoGithub
//
// Created by A Cahn on 4/5/17.
// Copyright © 2017 A Cahn. All rights reserved.
//
import UIKit
class CustomTransition : NSObject, UIViewControllerAnimatedTransitioning {
var duration: TimeInterval
init(duration: TimeInterval = 0.4) {
self.duration = duration
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
transitionContext.containerView.addSubview(toViewController.view)
toViewController.view.alpha = 0.0
UIView.animate(withDuration: self.duration, animations: {
toViewController.view.alpha = 1.0
}) { (finished) in
transitionContext.completeTransition(true)
}
}
}
|
mit
|
61d511ed0855077a5ac3bd2843d30d1a
| 27.236842 | 109 | 0.656104 | 5.446701 | false | false | false | false |
sschiau/swift-package-manager
|
Sources/TestSupport/XCTAssertHelpers.swift
|
2
|
4879
|
/*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import POSIX
import Utility
#if os(macOS)
import class Foundation.Bundle
#endif
public func XCTAssertBuilds(
_ path: AbsolutePath,
configurations: Set<Configuration> = [.Debug, .Release],
file: StaticString = #file,
line: UInt = #line,
Xcc: [String] = [],
Xld: [String] = [],
Xswiftc: [String] = [],
env: [String: String]? = nil
) {
for conf in configurations {
do {
print(" Building \(conf)")
_ = try executeSwiftBuild(
path,
configuration: conf,
Xcc: Xcc,
Xld: Xld,
Xswiftc: Xswiftc,
env: env)
} catch {
XCTFail("""
`swift build -c \(conf)' failed:
\(error)
""", file: file, line: line)
}
}
}
public func XCTAssertSwiftTest(
_ path: AbsolutePath,
file: StaticString = #file,
line: UInt = #line,
env: [String: String]? = nil
) {
do {
_ = try SwiftPMProduct.SwiftTest.execute([], packagePath: path, env: env)
} catch {
XCTFail("""
`swift test' failed:
\(error)
""", file: file, line: line)
}
}
public func XCTAssertBuildFails(
_ path: AbsolutePath,
file: StaticString = #file,
line: UInt = #line,
Xcc: [String] = [],
Xld: [String] = [],
Xswiftc: [String] = [],
env: [String: String]? = nil
) {
do {
_ = try executeSwiftBuild(path, Xcc: Xcc, Xld: Xld, Xswiftc: Xswiftc)
XCTFail("`swift build' succeeded but should have failed", file: file, line: line)
} catch SwiftPMProductError.executionFailure(let error, _, _) {
switch error {
case ProcessResult.Error.nonZeroExit(let result) where result.exitStatus != .terminated(code: 0):
break
default:
XCTFail("`swift build' failed in an unexpected manner")
}
} catch {
XCTFail("`swift build' failed in an unexpected manner")
}
}
public func XCTAssertFileExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {
if !isFile(path) {
XCTFail("Expected file doesn't exist: \(path.asString)", file: file, line: line)
}
}
public func XCTAssertDirectoryExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {
if !isDirectory(path) {
XCTFail("Expected directory doesn't exist: \(path.asString)", file: file, line: line)
}
}
public func XCTAssertNoSuchPath(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {
if exists(path) {
XCTFail("path exists but should not: \(path.asString)", file: file, line: line)
}
}
public func XCTAssertThrows<T: Swift.Error>(
_ expectedError: T,
file: StaticString = #file,
line: UInt = #line,
_ body: () throws -> Void
) where T: Equatable {
do {
try body()
XCTFail("body completed successfully", file: file, line: line)
} catch let error as T {
XCTAssertEqual(error, expectedError, file: file, line: line)
} catch {
XCTFail("unexpected error thrown", file: file, line: line)
}
}
public func XCTAssertThrows<T: Swift.Error, Ignore>(
_ expression: @autoclosure () throws -> Ignore,
file: StaticString = #file,
line: UInt = #line,
_ errorHandler: (T) -> Bool
) {
do {
let result = try expression()
XCTFail("body completed successfully: \(result)", file: file, line: line)
} catch let error as T {
XCTAssertTrue(errorHandler(error), "Error handler returned false")
} catch {
XCTFail("unexpected error thrown", file: file, line: line)
}
}
public func XCTNonNil<T>(
_ optional: T?,
file: StaticString = #file,
line: UInt = #line,
_ body: (T) throws -> Void
) {
guard let optional = optional else {
return XCTFail("Unexpected nil value", file: file, line: line)
}
do {
try body(optional)
} catch {
XCTFail("Unexpected error \(error)", file: file, line: line)
}
}
public func XCTAssertNoDiagnostics(_ engine: DiagnosticsEngine, file: StaticString = #file, line: UInt = #line) {
let diagnostics = engine.diagnostics.filter({ $0.behavior != .note })
if diagnostics.isEmpty { return }
let diags = engine.diagnostics.map({ "- " + $0.localizedDescription }).joined(separator: "\n")
XCTFail("Found unexpected diagnostics: \n\(diags)", file: file, line: line)
}
|
apache-2.0
|
ecf4dea33bc1bb1edc9f682a2d6c22a7
| 28.215569 | 113 | 0.596434 | 4.055694 | false | false | false | false |
danielallsopp/Charts
|
Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift
|
15
|
5896
|
//
// BarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
public class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet
{
private func initialize()
{
self.highlightColor = NSUIColor.blackColor()
self.calcStackSize(yVals as! [BarChartDataEntry])
self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry])
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!)
{
_entryCountStacks = 0
for i in 0 ..< yVals.count
{
let vals = yVals[i].values
if (vals == nil)
{
_entryCountStacks += 1
}
else
{
_entryCountStacks += vals!.count
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(yVals: [BarChartDataEntry]!)
{
for i in 0 ..< yVals.count
{
if let vals = yVals[i].values
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
public override func calcMinMax(start start : Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for i in start.stride(through: endValue, by: 1)
{
if let e = _yVals[i] as? BarChartDataEntry
{
if !e.value.isNaN
{
if e.values == nil
{
if e.value < _yMin
{
_yMin = e.value
}
if e.value > _yMax
{
_yMax = e.value
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the maximum number of bars that can be stacked upon another in this DataSet.
public var stackSize: Int
{
return _stackSize
}
/// - returns: true if this DataSet is stacked (stacksize > 1) or not.
public var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// - returns: the overall entry count, including counting each stack-value individually
public var entryCountStacks: Int
{
return _entryCountStacks
}
/// array of labels used to describe the different values of the stacked bars
public var stackLabels: [String] = ["Stack"]
// MARK: - Styling functions and accessors
/// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
public var barSpace: CGFloat = 0.15
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
public var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn.
public var barBorderWidth : CGFloat = 0.0
/// the color drawing borders around the bars.
public var barBorderColor = NSUIColor.blackColor()
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
public var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BarChartDataSet
copy._stackSize = _stackSize
copy._entryCountStacks = _entryCountStacks
copy.stackLabels = stackLabels
copy.barSpace = barSpace
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
|
apache-2.0
|
8546de77d7a5d359cc85ecb7d3a0a162
| 28.049261 | 148 | 0.52137 | 5.26899 | false | false | false | false |
ioscreator/ioscreator
|
IOSVolumeViewTutorial/IOSVolumeViewTutorial/ViewController.swift
|
1
|
1393
|
//
// ViewController.swift
// IOSVolumeViewTutorial
//
// Created by Arthur Knopper on 03/04/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
let wrapperView = UIView(frame: CGRect(x: 30, y: 200, width: 300, height: 20))
@IBAction func playSound(_ sender: Any) {
// 1
audioPlayer.play()
// 2
view.backgroundColor = UIColor.clear
view.addSubview(wrapperView)
// 3
let volumeView = MPVolumeView(frame: wrapperView.bounds)
wrapperView.addSubview(volumeView)
}
@IBAction func stopSound(_ sender: Any) {
audioPlayer.stop()
wrapperView.removeFromSuperview()
}
override func viewDidLoad() {
super.viewDidLoad()
// 1
if let asset = NSDataAsset(name: "amorphis-my-enemy") {
// 2
do {
try AVAudioSession.sharedInstance().setCategory(.playback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(data:asset.data, fileTypeHint:"mp3")
audioPlayer.prepareToPlay()
} catch {
print("error")
}
}
}
}
|
mit
|
3b9c362897480eb982148f597daf6f21
| 24.309091 | 84 | 0.578305 | 4.971429 | false | false | false | false |
nifty-swift/Nifty
|
Sources/gt.swift
|
2
|
2683
|
/***************************************************************************************************
* gt.swift
*
* This file provides public functionality for greater-than comparison.
*
* Author: Philip Erickson
* Creation Date: 1 May 2016
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2016 Philip Erickson
**************************************************************************************************/
public func > <T>(left: Matrix<T>, right: Matrix<T>) -> Matrix<Double>
where T: Comparable { return gt(left, right) }
public func > <T>(left: Matrix<T>, right: T) -> Matrix<Double>
where T: Comparable { return gt(left, right) }
public func > <T>(left: T, right: Matrix<T>) -> Matrix<Double>
where T: Comparable { return gt(left, right) }
/// Determine greater than inequality.
///
/// - Paramters:
/// - A: Matrix to compare
/// - B: Matrix to compare against
/// - Returns: matrix with ones where comparison is true and zeros elsewhere
public func gt<T>(_ A: Matrix<T>, _ B: Matrix<T>) -> Matrix<Double>
where T: Comparable
{
precondition(A.size == B.size, "Matrices must be same size")
var m = [Double]()
for i in 0..<A.count
{
m.append(A[i] > B[i] ? 1 : 0)
}
return Matrix(A.size, m)
}
/// Determine greater than inequality.
///
/// - Paramters:
/// - A: Matrix to compare
/// - b: Value to compare against
/// - Returns: matrix with ones where comparison is true and zeros elsewhere
public func gt<T>(_ A: Matrix<T>, _ b: T) -> Matrix<Double>
where T: Comparable
{
var m = [Double]()
for i in 0..<A.count
{
m.append(A[i] > b ? 1 : 0)
}
return Matrix(A.size, m)
}
/// Determine greater than inequality.
///
/// - Paramters:
/// - a: Number to compare
/// - B: Value to compare against
/// - Returns: matrix with ones where comparison is true and zeros elsewhere
public func gt<T>(_ a: T, _ B: Matrix<T>) -> Matrix<Double>
where T: Comparable
{
var m = [Double]()
for i in 0..<B.count
{
m.append(a > B[i] ? 1 : 0)
}
return Matrix(B.size, m)
}
|
apache-2.0
|
da1bed30fe35009bb7ddf0f7e79c8cde
| 31.337349 | 101 | 0.576221 | 3.805674 | false | false | false | false |
natecook1000/swift
|
test/SILGen/foreign_errors.swift
|
2
|
19093
|
// RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name foreign_errors -parse-as-library %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import errors
// CHECK-LABEL: sil hidden @$S14foreign_errors5test0yyKF : $@convention(thin) () -> @error Error
func test0() throws {
// Create a strong temporary holding nil before we perform any further parts of function emission.
// CHECK: [[ERR_TEMP0:%.*]] = alloc_stack $Optional<NSError>
// CHECK: inject_enum_addr [[ERR_TEMP0]] : $*Optional<NSError>, #Optional.none!enumelt
// CHECK: [[SELF:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!1.foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// Create an unmanaged temporary, copy into it, and make a AutoreleasingUnsafeMutablePointer.
// CHECK: [[ERR_TEMP1:%.*]] = alloc_stack $@sil_unmanaged Optional<NSError>
// CHECK: [[T0:%.*]] = load_borrow [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = ref_to_unmanaged [[T0]]
// CHECK: store [[T1]] to [trivial] [[ERR_TEMP1]]
// CHECK: address_to_pointer [[ERR_TEMP1]]
// Call the method.
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{.*}}, [[SELF]])
// Writeback to the first temporary.
// CHECK: [[T0:%.*]] = load [trivial] [[ERR_TEMP1]]
// CHECK: [[T1:%.*]] = unmanaged_to_ref [[T0]]
// CHECK: [[T1_COPY:%.*]] = copy_value [[T1]]
// CHECK: assign [[T1_COPY]] to [[ERR_TEMP0]]
// Pull out the boolean value and compare it to zero.
// CHECK: [[BOOL_OR_INT:%.*]] = struct_extract [[RESULT]]
// CHECK: [[RAW_VALUE:%.*]] = struct_extract [[BOOL_OR_INT]]
// On some platforms RAW_VALUE will be compared against 0; on others it's
// already an i1 (bool) and those instructions will be skipped. Just do a
// looser check.
// CHECK: cond_br {{%.+}}, [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
try ErrorProne.fail()
// Normal path: fall out and return.
// CHECK: [[NORMAL_BB]]:
// CHECK: return
// Error path: fall out and rethrow.
// CHECK: [[ERROR_BB]]:
// CHECK: [[T0:%.*]] = load [take] [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = function_ref @$S10Foundation22_convertNSErrorToErrorys0E0_pSo0C0CSgF : $@convention(thin) (@guaranteed Optional<NSError>) -> @owned Error
// CHECK: [[T2:%.*]] = apply [[T1]]([[T0]])
// CHECK: throw [[T2]] : $Error
}
extension NSObject {
@objc func abort() throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] @$SSo8NSObjectC14foreign_errorsE5abortyyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: [[T0:%.*]] = function_ref @$SSo8NSObjectC14foreign_errorsE5abortyyKF : $@convention(method) (@guaranteed NSObject) -> @error Error
// CHECK: try_apply [[T0]](
// CHECK: bb1(
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, {{1|-1}}
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb2([[ERR:%.*]] : @owned $Error):
// CHECK: switch_enum %0 : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt.1: bb3, case #Optional.none!enumelt: bb4
// CHECK: bb3([[UNWRAPPED_OUT:%.+]] : @trivial $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$S10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt.1, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$SSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
// CHECK: bb4:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
// CHECK: bb5:
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, 0
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb6([[BOOL:%.*]] : @trivial $ObjCBool):
// CHECK: return [[BOOL]] : $ObjCBool
@objc func badDescription() throws -> String {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] @$SSo8NSObjectC14foreign_errorsE14badDescriptionSSyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[UNOWNED_ARG0:%.*]] : @trivial $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[UNOWNED_ARG1:%.*]] : @unowned $NSObject):
// CHECK: [[ARG1:%.*]] = copy_value [[UNOWNED_ARG1]]
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[T0:%.*]] = function_ref @$SSo8NSObjectC14foreign_errorsE14badDescriptionSSyKF : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error Error)
// CHECK: try_apply [[T0]]([[BORROWED_ARG1]]) : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error Error), normal [[NORMAL_BB:bb[0-9][0-9]*]], error [[ERROR_BB:bb[0-9][0-9]*]]
//
// CHECK: [[NORMAL_BB]]([[RESULT:%.*]] : @owned $String):
// CHECK: [[T0:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]]
// CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_RESULT]])
// CHECK: [[T2:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]] : $NSString
// CHECK: end_borrow [[BORROWED_RESULT]] from [[RESULT]]
// CHECK: destroy_value [[RESULT]]
// CHECK: br bb6([[T2]] : $Optional<NSString>)
//
// CHECK: [[ERROR_BB]]([[ERR:%.*]] : @owned $Error):
// CHECK: switch_enum [[UNOWNED_ARG0]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9][0-9]*]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9][0-9]*]]
//
// CHECK: [[SOME_BB]]([[UNWRAPPED_OUT:%.+]] : @trivial $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$S10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt.1, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$SSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
//
// CHECK: [[NONE_BB]]:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
//
// CHECK: bb5:
// CHECK: [[T0:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt
// CHECK: br bb6([[T0]] : $Optional<NSString>)
//
// CHECK: bb6([[T0:%.*]] : @owned $Optional<NSString>):
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[T0]] : $Optional<NSString>
// CHECK-LABEL: sil hidden [thunk] @$SSo8NSObjectC14foreign_errorsE7takeIntyySiKFTo : $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[ERROR:%[0-9]+]] : @trivial $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[SELF:%[0-9]+]] : @unowned $NSObject)
@objc func takeInt(_ i: Int) throws { }
// CHECK-LABEL: sil hidden [thunk] @$SSo8NSObjectC14foreign_errorsE10takeDouble_3int7closureySd_S3iXEtKFTo : $@convention(objc_method) (Double, Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @convention(block) @noescape (Int) -> Int, NSObject) -> ObjCBool
// CHECK: bb0([[D:%[0-9]+]] : @trivial $Double, [[INT:%[0-9]+]] : @trivial $Int, [[ERROR:%[0-9]+]] : @trivial $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[CLOSURE:%[0-9]+]] : @unowned $@convention(block) @noescape (Int) -> Int, [[SELF:%[0-9]+]] : @unowned $NSObject):
@objc func takeDouble(_ d: Double, int: Int, closure: (Int) -> Int) throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
}
let fn = ErrorProne.fail
// CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10ErrorProneC4failyyKFZTcTO : $@convention(thin) (@thick ErrorProne.Type) -> @owned @callee_guaranteed () -> @error Error
// CHECK: [[T0:%.*]] = function_ref @$SSo10ErrorProneC4failyyKFZTO : $@convention(method) (@thick ErrorProne.Type) -> @error Error
// CHECK-NEXT: [[T1:%.*]] = partial_apply [callee_guaranteed] [[T0]](%0)
// CHECK-NEXT: return [[T1]]
// CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10ErrorProneC4failyyKFZTO : $@convention(method) (@thick ErrorProne.Type) -> @error Error {
// CHECK: [[SELF:%.*]] = thick_to_objc_metatype %0 : $@thick ErrorProne.Type to $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!1.foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{%.*}}, [[SELF]])
// CHECK: cond_br
// CHECK: return
// CHECK: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK: [[T1:%.*]] = apply {{%.*}}([[T0]])
// CHECK: throw [[T1]]
func testArgs() throws {
try ErrorProne.consume(nil)
}
// CHECK-LABEL: sil hidden @$S14foreign_errors8testArgsyyKF : $@convention(thin) () -> @error Error
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.consume!1.foreign : (ErrorProne.Type) -> (Any?) throws -> (), $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
func testBridgedResult() throws {
let array = try ErrorProne.collection(withCount: 0)
}
// CHECK-LABEL: sil hidden @$S14foreign_errors17testBridgedResultyyKF : $@convention(thin) () -> @error Error {
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.collection!1.foreign : (ErrorProne.Type) -> (Int) throws -> [Any], $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> @autoreleased Optional<NSArray>
// rdar://20861374
// Clear out the self box before delegating.
class VeryErrorProne : ErrorProne {
init(withTwo two: AnyObject?) throws {
try super.init(one: two)
}
}
// SEMANTIC SIL TODO: _TFC14foreign_errors14VeryErrorPronec has a lot more going
// on than is being tested here, we should consider adding FileCheck tests for
// it.
// CHECK-LABEL: sil hidden @$S14foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc
// CHECK: bb0([[ARG1:%.*]] : @owned $Optional<AnyObject>, [[ARG2:%.*]] : @owned $VeryErrorProne):
// CHECK: [[BOX:%.*]] = alloc_box ${ var VeryErrorProne }
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]
// CHECK: [[PB:%.*]] = project_box [[MARKED_BOX]]
// CHECK: store [[ARG2]] to [init] [[PB]]
// CHECK: [[T0:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[T1:%.*]] = upcast [[T0]] : $VeryErrorProne to $ErrorProne
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK-NOT: [[BOX]]{{^[0-9]}}
// CHECK-NOT: [[PB]]{{^[0-9]}}
// CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]]
// CHECK-NEXT: [[DOWNCAST_BORROWED_T1:%.*]] = unchecked_ref_cast [[BORROWED_T1]] : $ErrorProne to $VeryErrorProne
// CHECK-NEXT: [[T2:%.*]] = objc_super_method [[DOWNCAST_BORROWED_T1]] : $VeryErrorProne, #ErrorProne.init!initializer.1.foreign : (ErrorProne.Type) -> (Any?) throws -> ErrorProne, $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @owned ErrorProne) -> @owned Optional<ErrorProne>
// CHECK: end_borrow [[BORROWED_T1]] from [[T1]]
// CHECK: apply [[T2]]([[ARG1_COPY]], {{%.*}}, [[T1]])
// rdar://21051021
// CHECK: sil hidden @$S14foreign_errors12testProtocolyySo010ErrorProneD0_pKF : $@convention(thin) (@guaranteed ErrorProneProtocol) -> @error Error
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $ErrorProneProtocol):
func testProtocol(_ p: ErrorProneProtocol) throws {
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.obliterate!1.foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, τ_0_0) -> ObjCBool
try p.obliterate()
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.invigorate!1.foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, {{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, Optional<@convention(block) () -> ()>, τ_0_0) -> ObjCBool
try p.invigorate(callback: {})
}
// rdar://21144509 - Ensure that overrides of replace-with-() imports are possible.
class ExtremelyErrorProne : ErrorProne {
override func conflict3(_ obj: Any, error: ()) throws {}
}
// CHECK-LABEL: sil hidden @$S14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKF
// CHECK-LABEL: sil hidden [thunk] @$S14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKFTo : $@convention(objc_method) (AnyObject, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, ExtremelyErrorProne) -> ObjCBool
// These conventions are usable because of swift_error. rdar://21715350
func testNonNilError() throws -> Float {
return try ErrorProne.bounce()
}
// CHECK-LABEL: sil hidden @$S14foreign_errors15testNonNilErrorSfyKF :
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.bounce!1.foreign : (ErrorProne.Type) -> () throws -> Float, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Float
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: assign {{%.*}} to [[OPTERR]]
// CHECK: [[T0:%.*]] = load [take] [[OPTERR]]
// CHECK: switch_enum [[T0]] : $Optional<NSError>, case #Optional.some!enumelt.1: [[ERROR_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResult() throws -> CInt {
return try ErrorProne.ounce()
}
// CHECK-LABEL: sil hidden @$S14foreign_errors19testPreservedResults5Int32VyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounce!1.foreign : (ErrorProne.Type) -> () throws -> Int32, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultBridged() throws -> Int {
return try ErrorProne.ounceWord()
}
// CHECK-LABEL: sil hidden @$S14foreign_errors26testPreservedResultBridgedSiyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounceWord!1.foreign : (ErrorProne.Type) -> () throws -> Int, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int{{.*}}"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultInverted() throws {
try ErrorProne.once()
}
// CHECK-LABEL: sil hidden @$S14foreign_errors27testPreservedResultInvertedyyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.once!1.foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[ERROR_BB:bb[0-9]+]], [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return {{%.+}} : $()
// CHECK: [[ERROR_BB]]
// Make sure that we do not crash when emitting the error value here.
//
// TODO: Add some additional filecheck tests.
extension NSURL {
func resourceValue<T>(forKey key: String) -> T? {
var prop: AnyObject? = nil
_ = try? self.getResourceValue(&prop, forKey: key)
return prop as? T
}
}
|
apache-2.0
|
96e0f17905d70b57f0e7f70547165a09
| 60.37299 | 342 | 0.641431 | 3.436622 | false | true | false | false |
dusanIntellex/backend-operation-layer
|
Example/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift
|
1
|
2240
|
//
// SchedulerServices+Emulation.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
enum SchedulePeriodicRecursiveCommand {
case tick
case dispatchStart
}
final class SchedulePeriodicRecursive<State> {
typealias RecursiveAction = (State) -> State
typealias RecursiveScheduler = AnyRecursiveScheduler<SchedulePeriodicRecursiveCommand>
private let _scheduler: SchedulerType
private let _startAfter: RxTimeInterval
private let _period: RxTimeInterval
private let _action: RecursiveAction
private var _state: State
private var _pendingTickCount = AtomicInt(0)
init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) {
_scheduler = scheduler
_startAfter = startAfter
_period = period
_action = action
_state = state
}
func start() -> Disposable {
return _scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: _startAfter, action: self.tick)
}
func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) -> Void {
// Tries to emulate periodic scheduling as best as possible.
// The problem that could arise is if handling periodic ticks take too long, or
// tick interval is short.
switch command {
case .tick:
scheduler.schedule(.tick, dueTime: _period)
// The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately.
// Else work will be scheduled after previous enqueued work completes.
if _pendingTickCount.increment() == 0 {
self.tick(.dispatchStart, scheduler: scheduler)
}
case .dispatchStart:
_state = _action(_state)
// Start work and schedule check is this last batch of work
if _pendingTickCount.decrement() > 1 {
// This gives priority to scheduler emulation, it's not perfect, but helps
scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart)
}
}
}
}
|
mit
|
c69c639efba6b4212b0e55cd8f29238c
| 35.704918 | 137 | 0.669495 | 4.95354 | false | false | false | false |
ViewModelKit/ViewModelKit
|
Source/Protocol.swift
|
1
|
5580
|
//
// Protocol.swift
// SimpleViewModel
//
// Created by Tongtong Xu on 16/3/3.
// Copyright © 2016年 Tongtong Xu. All rights reserved.
//
import Foundation
///------------------------------------------------------------------------------------------------
public typealias BaseAutoInitializeViewModelType = protocol<BaseViewModelType,BaseAutoInitialization>
///------------------------------------------------------------------------------------------------
public protocol BaseAutoInitialization {
init()
}
///------------------------------------------------------------------------------------------------
public protocol BaseModelType {
}
///------------------------------------------------------------------------------------------------
public protocol BaseViewModelType {
}
///------------------------------------------------------------------------------------------------
public protocol BaseListViewModelType: class, BaseViewModelType {
var objs: [BaseModelType] { get set }
func numberOfSections() -> Int
func numberOfItemsInSection(section: Int) -> Int
func itemAtIndexPath(indexPath: NSIndexPath) -> BaseModelType
func cellInfoAtIndexPath(indexPath: NSIndexPath) -> (cellType: BaseClassIdentifier.Type?, BaseCellModelType: BaseCellModelType.Type?)
}
///------------------------------------------------------------------------------------------------
public protocol BaseListViewModelTypeAddition: class {
typealias T: BaseModelType
}
public extension BaseListViewModelTypeAddition where Self: BaseListViewModelType {
var items: [T] {
get {
return safeObjs
}
set {
objs = newValue.map{ $0 }
}
}
private var safeObjs: [T] {
if let _objs = objs as? [T] {
return _objs
}
objs = []
return self.safeObjs
}
}
///------------------------------------------------------------------------------------------------
public protocol BaseCellModelType: class {
var obj: BaseModelType! { get set }
init(_ x: BaseModelType)
}
///------------------------------------------------------------------------------------------------
public protocol BaseCellModelTypeAddition {
typealias T: BaseModelType
}
public extension BaseCellModelTypeAddition where Self: BaseCellModelType{
var model: T {
return obj as! T
}
}
///------------------------------------------------------------------------------------------------
public protocol BaseControllerType: class {
var obj: BaseViewModelType! { get set }
}
///------------------------------------------------------------------------------------------------
public protocol BaseControllerTypeAddition: class {
typealias T: BaseAutoInitializeViewModelType
}
public extension BaseControllerTypeAddition where Self: BaseControllerType {
var viewModel: T {
get {
return safeObj
}
set {
obj = newValue
}
}
private var safeObj: T {
if let _obj = obj as? T {
return _obj
}
obj = T()
return self.safeObj
}
}
///------------------------------------------------------------------------------------------------
public protocol BaseListControllerType {
var _obj: BaseListViewModelType! { get set }
}
public extension BaseListControllerType where Self: BaseControllerType {
var _obj: BaseListViewModelType! {
get {
return _safeObj
}
set {
obj = newValue
}
}
private var _safeObj: BaseListViewModelType {
if let __obj = obj as? BaseListViewModelType {
return __obj
}
return ListViewModelPlaceholder()
}
}
///------------------------------------------------------------------------------------------------
public protocol BaseListViewCellType: class {
var obj: BaseCellModelType! { get set }
func bindingCellModel(cellModel: BaseCellModelType)
}
///------------------------------------------------------------------------------------------------
public protocol BaseListViewCellTypeAddition {
typealias T: BaseCellModelType
}
public extension BaseListViewCellTypeAddition where Self: BaseListViewCellType {
var cellModel: T {
return obj as! T
}
}
///------------------------------------------------------------------------------------------------
private class ListViewModelPlaceholder: BaseListViewModelType {
var objs: [BaseModelType] = []
required init() { }
func cellIdentifierAtIndexPath(indexPath: NSIndexPath) -> String {
return ""
}
func numberOfSections() -> Int {
return 0
}
func numberOfItemsInSection(section: Int) -> Int {
return objs.count
}
func itemAtIndexPath(indexPath: NSIndexPath) -> BaseModelType {
return objs[indexPath.row]
}
func cellInfoAtIndexPath(indexPath: NSIndexPath) -> (cellType: BaseClassIdentifier.Type?, BaseCellModelType: BaseCellModelType.Type?) {
return (nil, nil)
}
}
///------------------------------------------------------------------------------------------------
public protocol BaseClassIdentifier: class {
static var reuseIdentifier: String { get }
}
extension BaseClassIdentifier {
public static var reuseIdentifier: String {
return String(self)
}
}
|
mit
|
80e4c8fa7c985f71cb71fc69c477d456
| 24.008969 | 139 | 0.463332 | 6.075163 | false | false | false | false |
ryanchang/osfstore-ios
|
OSFStore/controller/ProductListViewController.swift
|
1
|
6674
|
//
// ProductListViewController.swift
// OSFStore
//
// Created by Ryan Chang on 14/11/23.
// Copyright (c) 2014年 CandZen Co., Ltd. All rights reserved.
//
import UIKit
class ProductListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var products: [Product] = []
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
println("viewDidLoad")
// Don't call this when using storyboard
// self.tableView.registerClass(ProductCell.self, forCellReuseIdentifier: "ProductCell")
}
override func viewWillAppear(animated: Bool) {
getProducts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showHUD() {
//SVProgressHUD.showSuccessWithStatus("It works!")
//SVProgressHUD.show()
getProducts()
getProduct(1)
}
func getProducts() -> [Product] {
var products: [Product] = []
let manager = AFHTTPRequestOperationManager()
SVProgressHUD.show()
manager.GET("http://addmenow.net:4000/api/products", parameters: nil, success: { (operation, responseObject: AnyObject!) -> Void in
var error: NSError?
if let json: NSArray = responseObject as? NSArray {
// Use _stdlib_getDemangledTypeName to inspect the data type
//println(_stdlib_getDemangledTypeName(json))
for product in json {
if let p = product as? NSDictionary {
if let id = p.valueForKey("id") as? Int {
println(id)
if let name = p.valueForKey("name") as? String {
println(name)
if let desc = p.valueForKey("desc") as? String {
println(desc)
if let price = p.valueForKey("price") as? Float {
println(price)
var product: Product = Product(id: id, name: name, desc: desc, price: price)
products.append(product)
}
}
}
}
}
//println(_stdlib_getemangledTypeName(product))
}
self.products = products
self.tableView.reloadData()
}
}) { (operation, error) -> Void in
println(error)
}
//SVProgressHUD.dismiss()
return products
}
func getProduct(productId: Int) -> Product? {
var error: NSError?
var product: Product?
let manager = AFHTTPRequestOperationManager()
manager.GET("http://addmenow.net:4000/api/products/\(productId)", parameters: nil, success: { (operation, responseObject) -> Void in
println(responseObject)
if let p: NSDictionary = responseObject as? NSDictionary {
if let id = p.valueForKey("id") as? Int {
if let name = p.valueForKey("name") as? String {
if let desc = p.valueForKey("desc") as? String {
if let price = p.valueForKey("price") as? Float {
product = Product(id: id, name: name, desc: desc, price: price)
}
}
}
}
}
}) { (operation, error) -> Void in
println(error)
}
return product
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.products.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let product = products[indexPath.row]
var cell: ProductCell? =
tableView.dequeueReusableCellWithIdentifier("ProductCell")
as? ProductCell
//
// if let optionalCell: ProductCell? = tableView.dequeueReusableCellWithIdentifier("ProductCell") as? ProductCell {
// cell = optionalCell!
// }
println("cell: \(cell)")
if cell == nil {
println("create new cell")
cell = ProductCell(style: UITableViewCellStyle.Default, reuseIdentifier: "ProductCell")
}
println("cell: \(cell), product: \(product), name: \(cell!.name.text)")
cell!.name.text = product.name
cell!.price.text = NSString(format: "%.2f", product.price)
// let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
// let manager = AFURLSessionManager(sessionConfiguration: configuration)
// let url = NSURL(string: "http://addmenow.net:4000/images/\(product.productId).jpg")
// let request = NSURLRequest(URL: url!)
// let downloadTask = manager.downloadTaskWithRequest(request, progress: nil, destination: { (targetPath, response) -> NSURL! in
// let documentDirectoryURL = NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DownloadsDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false, error: nil)
// return documentDirectoryURL?.URLByAppendingPathComponent(response.suggestedFilename!)
// }) { (response, filePath, error) -> Void in
// println("downloaded to: \(filePath)")
// let image = UIImage(data: NSData(contentsOfURL: filePath)!)
// cell!.pic.image = image
// }
//
// downloadTask.resume()
let url = NSURL(string: "http://addmenow.net:4000/images/\(product.productId).jpg")
let request = NSURLRequest(URL: url!)
let placeholderImage = UIImage(named: "placeholder")
cell?.pic.setImageWithURLRequest(request, placeholderImage: placeholderImage, success: { (request, response, image) -> Void in
cell!.pic.image = image
}, failure: { (request, response, error) -> Void in
println(error)
})
return cell!
}
}
|
mit
|
f098249683fd62054b7b16a921154f13
| 40.675 | 229 | 0.55189 | 5.279493 | false | false | false | false |
iOSWizards/AwesomeMedia
|
Example/Pods/AwesomeCore/AwesomeCore/Classes/NetworkServices/CategoryTrainingsNS.swift
|
1
|
2025
|
//
// CategoryTrainingsNS.swift
// AwesomeCore
//
// Created by Leonardo Vinicius Kaminski Ferreira on 06/09/17.
//
import Foundation
class CategoryTrainingsNS: BaseNS {
static var shared = CategoryTrainingsNS()
lazy var awesomeRequester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm)
var categoryTrainingsRequest: URLSessionDataTask?
override init() {}
func fetchCategoryTrainings(withCategory category: String, params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping (CategoryTrainings?, ErrorData?) -> Void) {
func processResponse(data: Data?, error: ErrorData? = nil, response: @escaping (CategoryTrainings?, ErrorData?) -> Void ) -> Bool {
if let jsonObject = AwesomeCoreParser.jsonObject(data) as? [String: AnyObject] {
self.categoryTrainingsRequest = nil
response(CategoryTrainingsMP.parseCategoryTrainingsFrom(jsonObject), nil)
return true
} else {
self.categoryTrainingsRequest = nil
if let error = error {
response(nil, error)
return false
}
response(nil, ErrorData(.unknown, "response Data could not be parsed"))
return false
}
}
let url = String(format: ACConstants.shared.categoryTrainingsURL, category)
let method: URLMethod = .GET
if params.contains(.shouldFetchFromCache) {
_ = processResponse(data: dataFromCache(url, method: method, params: params, bodyDict: nil), response: response)
}
categoryTrainingsRequest = awesomeRequester.performRequestAuthorized(url, forceUpdate: true) { (data, error, responseType) in
if processResponse(data: data, error: error, response: response) {
self.saveToCache(url, method: method, bodyDict: nil, data: data)
}
}
}
}
|
mit
|
197a11bc93b89c23e14a5a8d1ecfce57
| 37.207547 | 179 | 0.621728 | 4.903148 | false | false | false | false |
jeffreybergier/Hipstapaper
|
Hipstapaper/Packages/V3Interface/Sources/V3Interface/Main/MainWindow.swift
|
1
|
4055
|
//
// Created by Jeffrey Bergier on 2022/06/17.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// 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 SwiftUI
import Umbrella
import V3Store
import V3Style
import V3Localize
import V3Errors
import V3WebsiteEdit
public struct MainWindow: Scene {
@StateObject private var localizeBundle = LocalizeBundle()
@StateObject private var controller = Controller.newEnvironment()
@StateObject private var mainMenuState = BulkActions.newEnvironment()
public init() {}
public var body: some Scene {
WindowGroup {
switch self.controller.value {
case .success(let controller):
MainView()
.environmentObject(self.controller)
.environmentObject(self.localizeBundle)
.environmentObject(self.mainMenuState)
.environment(\.managedObjectContext, controller.context)
case .failure(let error):
Text(String(describing: error))
}
}
.commands {
MainMenu(state: self.mainMenuState,
controller: self.controller,
bundle: self.localizeBundle)
}
}
}
internal struct MainView: View {
@Navigation private var nav
@Selection private var selection
@Errors private var errorQueue
@Controller private var controller
@V3Style.MainMenu private var style
@HACK_EditMode private var isEditMode
internal var body: some View {
ErrorResponder(toPresent: self.$nav.isError,
storeErrors: self.nav.isPresenting,
inStorage: self.$errorQueue)
{
NavigationSplitView {
Sidebar()
} detail: {
Detail()
.animation(.default, value: self.isEditMode)
.editMode(force: self.isEditMode)
}
.modifier(BulkActionsHelper())
.modifier(WebsiteEditSheet(self.$nav.isWebsitesEdit, start: .website))
.modifier(self.style.syncIndicator(self.controller.syncProgress.progress))
.onReceive(self.controller.syncProgress.objectWillChange) { _ in
DispatchQueue.main.async {
let errors = self.controller.syncProgress.errors.map { $0.codableValue }
guard errors.isEmpty == false else { return }
self.controller.syncProgress.errors.removeAll()
self.errorQueue.append(contentsOf: errors)
}
}
} onConfirmation: {
switch $0 {
case .deleteWebsites(let deleted):
self.selection.websites.subtract(deleted)
case .deleteTags(let deleted):
guard deleted.contains(self.selection.tag ?? .default) else { return }
self.selection.tag = .default
}
}
}
}
|
mit
|
1386d0178584fb8b93f0690293a5e3db
| 37.254717 | 92 | 0.62836 | 4.867947 | false | false | false | false |
ishkawa/DIKit
|
Sources/DIGenKit/CodeGenerator.swift
|
1
|
4613
|
//
// CodeGenerator.swift
// dikitgenTests
//
// Created by Yosuke Ishikawa on 2017/09/16.
//
import Foundation
import SourceKittenFramework
public final class CodeGenerator {
let moduleNames: [String]
let resolvers: [Resolver]
public convenience init(path: String, excluding exclusions: [String] = []) throws {
try self.init(files: files(atPath: path, excluding: exclusions))
}
public init(files: [File]) throws {
let types = try Array(files
.map { file in
return try Structure(file: file)
.substructures
.compactMap { Type(structure: $0, file: file) }
}
.joined())
let imports = try Array(files
.map { file -> [Import] in
return try Import.imports(from: file)
}
.joined())
.reduce([] as [Import]) { imports, newImport in
return imports.contains(where: { $0.moduleName == newImport.moduleName })
? imports
: imports + [newImport]
}
let resolvers = try types
.compactMap { type -> Resolver? in
do {
return try Resolver(type: type, allTypes: types)
} catch let error as Resolver.Error where error.reason == .protocolConformanceNotFound {
return nil
} catch {
throw error
}
}
self.moduleNames = imports.map({ $0.moduleName }).sorted(by: <)
self.resolvers = resolvers.sorted { (lhs, rhs) in return lhs.name < rhs.name }
}
public func generate() throws -> String {
class Buffer {
var result = ""
var indentCount = 0
func append(_ string: String) {
for line in string.components(separatedBy: .newlines) {
guard !line.isEmpty else {
result += "\n"
continue
}
var indent = ""
if indentCount > 0 {
indent = Array(repeating: " ", count: indentCount).joined()
}
result += "\(indent)\(line)\n"
}
}
}
let buffer = Buffer()
buffer.append("""
//
// Resolver.swift
// Generated by dikitgen.
//
""")
buffer.append("")
if !moduleNames.isEmpty {
for moduleName in moduleNames {
buffer.append("import \(moduleName)")
}
buffer.append("")
}
for resolver in resolvers {
buffer.append("extension \(resolver.name) {")
buffer.indentCount += 1
for method in resolver.sortedGeneratedMethods {
buffer.append("")
buffer.append("func \(method.name)(\(method.parametersDeclaration)) -> \(method.returnTypeName) {")
buffer.indentCount += 1
for line in method.bodyLines {
buffer.append(line)
}
buffer.indentCount -= 1
buffer.append("}")
}
buffer.append("")
buffer.indentCount -= 1
buffer.append("}")
}
return buffer.result
}
}
private func files(atPath path: String, excluding exclusions: [String]) -> [File] {
let exclusions = exclusions.map { $0.last == "/" ? $0 : $0 + "/" }
let url = URL(fileURLWithPath: path)
let fileManager = FileManager.default
var files = [] as [File]
var isDirectory = false as ObjCBool
if fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory) {
if isDirectory.boolValue {
let enumerator = fileManager.enumerator(atPath: path)
while let subpath = enumerator?.nextObject() as? String {
if exclusions.contains(where: { subpath.hasPrefix($0) }) { continue }
let url = url.appendingPathComponent(subpath)
if url.pathExtension == "swift", let file = File(path: url.path), file.contents.contains("DIKit") {
files.append(file)
}
}
} else if let file = File(path: url.path) {
files.append(file)
}
}
return files
}
|
mit
|
a8590aa790560284b3bda24d48339386
| 30.59589 | 115 | 0.482766 | 5.114191 | false | false | false | false |
aestesis/Aether
|
Project/sources/Foundation/Float128.swift
|
1
|
11545
|
//
// Decimal.swift
// Alib
//
// Created by renan jegouzo on 17/09/2016.
// Copyright © 2016 aestesis. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Swift
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: not implemented, do it!
// example: http://stackoverflow.com/questions/18492674/16bit-float-multiplication-in-c
// doc: http://www.rfwireless-world.com/Tutorials/floating-point-tutorial.html
// https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BinMath/multFloat.html
// https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BinMath/addFloat.html
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Float128 {
// TODO: complete Float128 struct
static let bitM:UInt64 = 0x8000000000000000
var n:Bool // value = n(-) * 1.m * 2^e
var e:Int32
var m:UInt64
public init() {
n = false
e = 0
m = 0
}
public init(_ value:Double) {
Debug.assert(Double.radix==2)
if value != 0 {
self.n = (value.sign == .minus)
self.e = Int32(value.exponent) - 63
self.m = Float128.bitM + value.significandBitPattern << (UInt64(63-52))
self.normalize()
} else {
n = false
e = 0
m = 0
}
}
public init(_ value:Int) {
if value>=0 {
n = false
e = 0
m = UInt64(value)
} else {
n = true
e = 0
m = UInt64(-value)
}
self.normalize()
}
public init(mantissa:UInt64,exponent:Int32,negative:Bool) {
self.n = negative
self.e = exponent
self.m = mantissa
self.normalize()
}
public var abs : Float128 {
return Float128(mantissa:m,exponent:e,negative:false)
}
public var doubleValue : Double {
if n {
return -pow(2.0,Double(e)) * Double(m)
} else {
return pow(2.0,Double(e)) * Double(m)
}
}
mutating func normalize() {
if m != 0 {
while (m & Float128.bitM) == 0 {
m <<= 1
e -= 1
}
} else {
e = 0
n = false
}
}
}
public func ==(l:Float128,r:Float128) -> Bool {
return l.m == r.m && l.e == r.e && l.n == r.n
}
public func !=(l:Float128,r:Float128) -> Bool {
return (l.m != r.m) || (l.e != r.e) || (l.n != r.n)
}
public func *(l:Float128,r:Float128) -> Float128 { // TODO: multiplication based on UInt128
let m = mul128(l.m,r.m).h
let e = l.e + r.e + Int32(64)
let n = (l.n != r.n) // xor
return Float128(mantissa: m, exponent: e, negative: n)
}
func mul128(_ x:UInt64,_ y:UInt64) -> (h:UInt64,l:UInt64) { // from: http://www.edaboard.com/thread253439.html
let xl = x & UInt64(0xffffffff)
let xh = x >> UInt64(32)
let yl = y & UInt64(0xffffffff)
let yh = y >> UInt64(32)
let xlyl = xl*yl
let xhyl = xh*yl
let xlyh = xl*yh
let xhyh = xh*yh
var l = xlyl & 0xffffffff
var h = (xlyl>>32)+(xhyl & 0xffffffff)+(xlyh & 0xffffffff)
l += (h & 0xffffffff) << 32
h >>= 32
h += (xhyl>>32)+(xlyh>>32)+xhyh
return (h:h,l:l)
}
public func +(l:Float128,r:Float128) -> Float128 {
var a = l
var b = r
if a.m == 0 {
return b
}
if b.m == 0 {
return a
}
if a.e>b.e {
let d = a.e-b.e
if d>=64 {
return a
}
b.m = (b.m >> UInt64(d))
b.e = a.e
} else {
let d = b.e-a.e
if d>=64 {
return b
}
a.m = (a.m >> UInt64(d))
a.e = b.e
}
if a.n == b.n {
var e = a.e
let mr = UInt64.addWithOverflow(a.m,b.m)
var m = mr.0
if mr.overflow {
m = (Float128.bitM | (mr.0 >> 1))
e += 1
}
return Float128(mantissa:m,exponent:e,negative:a.n)
} else if b.n {
let mr = UInt64.subtractWithOverflow(a.m,b.m)
var m:UInt64 = 0
var n:Bool = false
if mr.overflow {
n = true
m = ~mr.0
} else {
m = mr.0 // TODO: check if need a ~
}
return Float128(mantissa:m,exponent:a.e,negative:n)
} else {
let mr = UInt64.subtractWithOverflow(b.m,a.m)
var m:UInt64 = 0
var n:Bool = false
if mr.overflow {
n = true
m = ~mr.0
} else {
m = mr.0 // TODO: check if need a ~
}
return Float128(mantissa:m,exponent:a.e,negative:n)
}
}
public func -(l:Float128,r:Float128) -> Float128 {
return l+Float128(mantissa:r.m,exponent:r.e,negative:!r.n)
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Float256 {
// TODO: complete Float256 struct
static let bitM:UInt64 = 0x8000000000000000
static let hp = pow(Double(2),Double(64))
var n:Bool // value = n(-) * 1.m * 2^e
var e:Int32
var m:UInt128
public init() {
n = false
e = 0
m = UInt128(0)
}
public init(_ value:Double) {
Debug.assert(Double.radix==2)
if value != 0 {
n = (value.sign == .minus)
e = Int32(value.exponent) - 127
m = UInt128(upperBits:Float256.bitM + value.significandBitPattern << (UInt64(63-52)),lowerBits:0)
self.normalize()
} else {
n = false
e = 0
m = UInt128(0)
}
}
public init(_ value:Int) {
if value>=0 {
n = false
e = -64
m = UInt128(upperBits:UInt64(value),lowerBits:0)
} else {
n = true
e = 0
m = UInt128(upperBits:UInt64(-value),lowerBits:0)
}
self.normalize()
}
public init(mh:UInt64,ml:UInt64,exponent:Int32,negative:Bool) {
self.n = negative
self.e = exponent
self.m = UInt128(upperBits:mh,lowerBits:ml)
self.normalize()
}
public init(m:UInt128,exponent:Int32,negative:Bool) {
self.n = negative
self.e = exponent
self.m = m
self.normalize()
}
public var abs : Float256 {
return Float256(m:m,exponent:e,negative:false)
}
public var doubleValue : Double {
if n {
return -pow(2.0,Double(e)) * (Double(m.value.upperBits) * Float256.hp + Double(m.value.lowerBits))
} else {
return pow(2.0,Double(e)) * (Double(m.value.upperBits) * Float256.hp + Double(m.value.lowerBits))
}
}
mutating func normalize() {
if m.value.upperBits == 0 && m.value.lowerBits == 0 {
e = 0
n = false
} else {
while (m.value.upperBits & Float256.bitM) == 0 {
m <<= 1
e -= 1
}
}
}
}
public func ==(l:Float256,r:Float256) -> Bool {
return l.m == r.m && l.e == r.e && l.n == r.n
}
public func !=(l:Float256,r:Float256) -> Bool {
return l.m != r.m || l.e != r.e || l.n != r.n
}
public func *(l:Float256,r:Float256) -> Float256 {
let m = mul256((h:l.m.value.upperBits,l:l.m.value.lowerBits),(h:r.m.value.upperBits,l:r.m.value.lowerBits))
let e = l.e + r.e + Int32(128)
let n = (l.n != r.n)
return Float256(mh:m.h,ml:m.l,exponent:e,negative: n)
}
func mul256(_ x:(h:UInt64,l:UInt64),_ y:(h:UInt64,l:UInt64)) -> (h:UInt64,l:UInt64,overflow:Bool) { // from: http://www.edaboard.com/thread253439.html
let xlyl = mul128(x.l,y.l)
let xhyl = mul128(x.h,y.l)
let xlyh = mul128(x.l,y.h)
let xhyh = mul128(x.h,y.h)
var sum:(h:UInt64,l:UInt64) = (h:0,l:0)
var o=UInt64.addWithOverflow(xlyl.h, xhyl.l)
if o.overflow {
sum.l += 1
}
o=UInt64.addWithOverflow(o.0, xlyh.l)
if o.overflow {
sum.l += 1
}
o=UInt64.addWithOverflow(sum.l, xlyl.h)
if o.overflow {
sum.h += 1
}
o=UInt64.addWithOverflow(o.0, xlyh.h)
if o.overflow {
sum.h += 1
}
o=UInt64.addWithOverflow(o.0, xhyh.l)
if o.overflow {
sum.h += 1
}
sum.l = o.0
o=UInt64.addWithOverflow(sum.h, xhyh.h)
sum.h = o.0
return (h:sum.h,l:sum.l,overflow:o.overflow)
}
public func +(l:Float256,r:Float256) -> Float256 {
var a = l
var b = r
if a.m == 0 {
return b
}
if b.m == 0 {
return a
}
if a.e>b.e {
let d = a.e-b.e
if d>=128 {
return a
}
b.m = b.m >> UInt128(Int(d))
b.e = a.e
} else {
let d = b.e-a.e
if d>=64 {
return b
}
a.m = a.m >> UInt128(Int(d))
a.e = b.e
}
if a.n == b.n {
var e = a.e
let mr = UInt128.addWithOverflow(a.m, b.m)
var m = mr.0
if mr.overflow {
m = (mr.0 >> 1)
m.value.upperBits |= Float256.bitM
e += 1
}
return Float256(m:m,exponent:e,negative:a.n)
} else if b.n {
let mr = UInt128.subtractWithOverflow(a.m,b.m)
var m = mr.0
var n = false
if mr.overflow {
n = true
m = ~mr.0
} else {
m = mr.0
}
return Float256(m:m,exponent:a.e,negative:n)
} else {
let mr = UInt128.subtractWithOverflow(b.m,a.m)
var m = mr.0
var n:Bool = false
if mr.overflow {
n = true
m = ~mr.0
}
return Float256(m:m,exponent:a.e,negative:n)
}
}
public func -(l:Float256,r:Float256) -> Float256 {
return l+Float256(m:r.m,exponent:r.e,negative:!r.n)
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
apache-2.0
|
d97cd036a3a1e25843e20d0e59cc58cc
| 29.949062 | 151 | 0.446292 | 3.456287 | false | false | false | false |
4faramita/TweeBox
|
TweeBox/TweetWithPicAndTextUsingButtonTableViewCell.swift
|
1
|
2582
|
//
// TweetWithPicAndTextUsingButtonTableViewCell.swift
// TweeBox
//
// Created by 4faramita on 2017/8/10.
// Copyright © 2017年 4faramita. All rights reserved.
//
import UIKit
import Kingfisher
import SKPhotoBrowser
class TweetWithPicAndTextUsingButtonTableViewCell: TweetTableViewCell {
@IBOutlet weak var tweetPicContent: UIImageView!
@IBOutlet weak var secondPic: UIImageView!
@IBOutlet weak var thirdPic: UIImageView!
@IBOutlet weak var fourthPic: UIImageView!
private func setPic(at position: Int, of total: Int) {
let media = tweet!.entities!.media!
let pics = [tweetPicContent, secondPic, thirdPic, fourthPic] // pointer or copy?
var aspect: CGFloat {
if (total == 2) || (total == 3 && position == 0) {
return Constants.thinAspect
} else {
return Constants.normalAspect
}
}
let pic = media[position]
let tweetPicURL = pic.mediaURL
let picWidth: CGFloat
let picHeight: CGFloat
let cutPoint = CGPoint(x: 0.5, y: 0.5)
// means cut from middle out
let actualHeight = CGFloat(pic.sizes.small.h)
let actualWidth = CGFloat(pic.sizes.small.w)
if actualHeight / actualWidth >= aspect {
// too long
picWidth = actualWidth
picHeight = picWidth * aspect
} else {
// too wide
picHeight = actualHeight
picWidth = picHeight / aspect
}
// Kingfisher
let placeholder = UIImage(named: "picPlaceholder")!.kf.image(withRoundRadius: Constants.picCornerRadius, fit: CGSize(width: picWidth, height: picHeight))
let processor = CroppingImageProcessor(size: CGSize(width: picWidth, height: picHeight), anchor: cutPoint) >> RoundCornerImageProcessor(cornerRadius: Constants.picCornerRadius)
if let picView = pics[position] {
// picView.kf.indicatorType = .activity
picView.kf.setImage(
with: tweetPicURL,
placeholder: placeholder,
options: [.transition(.fade(Constants.picFadeInDuration)), .processor(processor)]
)
}
}
override func updateUI() {
super.updateUI()
if let total = tweet?.entities?.media?.count {
for i in 0..<total {
setPic(at: i, of: total)
}
}
}
}
|
mit
|
d74e5bf135e26868b988b62421262538
| 30.072289 | 184 | 0.574254 | 4.784787 | false | false | false | false |
0x4a616e/ArtlessEdit
|
ArtlessEdit/EditorDefaultSettings.swift
|
1
|
6533
|
//
// UserDefaultsSettingsBridge.swift
// ArtlessEdit
//
// Created by Jan Gassen on 26/12/14.
// Copyright (c) 2014 Jan Gassen. All rights reserved.
//
import Foundation
class EditorDefaultSettings: EditorSettingsObservable, EditorSettings {
let THEME = "Theme"
let FONT_SIZE = "FontSize"
let DARK_MODE = "DarkMode"
let KEY_BINDINGS = "KeyBindings"
let CODE_FOLDING = "CodeFolding"
let SOFT_WRAP = "SoftWrap"
let SHOW_INVISIBLES = "ShowInvisibles"
let PRINT_MARGIN = "PrintMargin"
let ACTIVE_LINE = "ActiveLine"
let SOFT_TABS = "SoftTabs"
let INDENT_GUIDES = "IndentGuides"
let TAB_SIZE = "TabSize"
let SHOW_SIDEBAR = "ShowSidebar"
var mode: String?
lazy var userDefaults = NSUserDefaults.standardUserDefaults()
init(mode: String? = nil) {
super.init()
if (mode == nil) {
userDefaults.registerDefaults([
getKey(THEME): "clouds",
getKey(SHOW_SIDEBAR): true,
getKey(FONT_SIZE): 11
])
}
setMode(mode)
}
func setTheme(name: String) {
userDefaults.setObject(name, forKey: getKey(THEME))
}
func getTheme() -> String {
return userDefaults.objectForKey(getKey(THEME)) as? String ?? "clouds"
}
func setDarkMode(enabled: Bool) {
userDefaults.setBool(enabled, forKey: getKey(DARK_MODE))
}
func getDarkMode() -> Bool {
return userDefaults.boolForKey(getKey(DARK_MODE))
}
func setFontSize(size: Int) {
userDefaults.setInteger(size, forKey: getKey(FONT_SIZE))
}
func getFontSize() -> Int {
return userDefaults.integerForKey(getKey(FONT_SIZE))
}
func setKeyBindings(bindings: ACEKeyboardHandler) {
userDefaults.setInteger(Int(bindings.rawValue), forKey: getKey(KEY_BINDINGS))
}
func getKeyBindings() -> ACEKeyboardHandler {
if let keyBindings = ACEKeyboardHandler(rawValue: UInt(userDefaults.integerForKey(getKey(KEY_BINDINGS)))) {
return keyBindings
}
return ACEKeyboardHandler.Ace
}
func setCodeFolding(enabled: Bool){
userDefaults.setBool(enabled, forKey: getKey(CODE_FOLDING))
}
func getCodeFolding() -> Bool {
return userDefaults.boolForKey(getKey(CODE_FOLDING))
}
func setSoftWrap(enabled: Bool){
userDefaults.setBool(enabled, forKey: getKey(SOFT_WRAP))
}
func getSoftWrap() -> Bool {
return userDefaults.boolForKey(getKey(SOFT_WRAP))
}
func setShowInvisibles(enabled: Bool){
userDefaults.setBool(enabled, forKey: getKey(SHOW_INVISIBLES))
}
func getShowInvisibles() -> Bool {
return userDefaults.boolForKey(getKey(SHOW_INVISIBLES))
}
func setShowPrintMargin(enabled: Bool){
userDefaults.setBool(enabled, forKey: getKey(PRINT_MARGIN))
}
func getShowPrintMargin() -> Bool {
return userDefaults.boolForKey(getKey(PRINT_MARGIN))
}
func setHighlightActiveLine(enabled: Bool){
userDefaults.setBool(enabled, forKey: getKey(ACTIVE_LINE))
}
func getHighlightActiveLine() -> Bool {
return userDefaults.boolForKey(getKey(ACTIVE_LINE))
}
func setUseSoftTabs(enabled: Bool){
userDefaults.setBool(enabled, forKey: getKey(SOFT_TABS))
}
func getUseSoftTabs() -> Bool {
return userDefaults.boolForKey(getKey(SOFT_TABS))
}
func setTabSize(enabled: Int){
userDefaults.setInteger(enabled, forKey: getKey(TAB_SIZE))
}
func getTabSize() -> Int {
return userDefaults.integerForKey(getKey(TAB_SIZE))
}
func setDisplayIndentGuides(enabled: Bool){
userDefaults.setBool(enabled, forKey: getKey(INDENT_GUIDES))
}
func getDisplayIndentGuides() -> Bool {
return userDefaults.boolForKey(getKey(INDENT_GUIDES))
}
func getKey(key: String) -> String {
if (mode != nil) {
return mode! + "_" + key
}
return key
}
func getShowSidebar() -> Bool {
return userDefaults.boolForKey(getKey(SHOW_SIDEBAR))
}
func setShowSidebar(val: Bool) {
userDefaults.setBool(val, forKey: getKey(SHOW_SIDEBAR))
}
func setMode(mode: NSString?) {
self.mode = mode
if (mode != nil) {
loadDefaultSettings()
}
notifySubscribers(self)
}
func getMode() -> String? {
return mode
}
func loadDefaultSettings() {
if self.mode == nil {
return
}
let defaults = EditorDefaultSettings()
userDefaults.registerDefaults([
getKey(THEME) : defaults.getTheme(),
getKey(FONT_SIZE) : defaults.getFontSize(),
getKey(DARK_MODE) : defaults.getDarkMode(),
getKey(CODE_FOLDING): defaults.getCodeFolding(),
getKey(SOFT_WRAP): defaults.getSoftWrap(),
getKey(SHOW_INVISIBLES): defaults.getShowInvisibles(),
getKey(PRINT_MARGIN): defaults.getShowPrintMargin(),
getKey(ACTIVE_LINE): defaults.getHighlightActiveLine(),
getKey(SOFT_TABS): defaults.getUseSoftTabs(),
getKey(TAB_SIZE): defaults.getTabSize(),
getKey(INDENT_GUIDES): defaults.getDisplayIndentGuides(),
getKey(SHOW_SIDEBAR): defaults.getShowSidebar()
])
}
func resetToDefaults() {
if (self.mode == nil) {
return
}
userDefaults.removeObjectForKey(getKey(THEME))
userDefaults.removeObjectForKey(getKey(FONT_SIZE))
userDefaults.removeObjectForKey(getKey(DARK_MODE))
userDefaults.removeObjectForKey(getKey(CODE_FOLDING))
userDefaults.removeObjectForKey(getKey(SOFT_WRAP))
userDefaults.removeObjectForKey(getKey(SHOW_INVISIBLES))
userDefaults.removeObjectForKey(getKey(PRINT_MARGIN))
userDefaults.removeObjectForKey(getKey(ACTIVE_LINE))
userDefaults.removeObjectForKey(getKey(SOFT_TABS))
userDefaults.removeObjectForKey(getKey(TAB_SIZE))
userDefaults.removeObjectForKey(getKey(INDENT_GUIDES))
userDefaults.removeObjectForKey(getKey(SHOW_SIDEBAR))
}
class func getEditorDefaultSettings(forMode: String?) -> EditorDefaultSettings {
return EditorDefaultSettings(mode: forMode)
}
}
|
bsd-3-clause
|
32b07e9d083acdac84f7e9221f4f914b
| 28.972477 | 115 | 0.623756 | 4.462432 | false | false | false | false |
syoung-smallwisdom/BrickBot
|
BrickBot/BrickBot/BallView.swift
|
1
|
1490
|
//
// BallView.swift
// BrickBot
//
// Created by Shannon Young on 9/15/15.
// Copyright © 2015 Smallwisdom. All rights reserved.
//
import UIKit
class BallView: UIView {
@IBOutlet weak var connectionIndicator: UIActivityIndicatorView!
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.bounds.size.height/2.0;
}
var position: CGPoint = CGPointZero {
didSet {
updateBackgroundColor()
}
}
var connected: Bool = false {
didSet {
if (connected) {
connectionIndicator.stopAnimating()
}
else {
connectionIndicator.startAnimating()
}
updateBackgroundColor()
}
}
func updateBackgroundColor() {
if (connected) {
// For debugging purposes it is useful to have a color change associated with
// which joystick position the robot control is in
let binPos = BBRobotPosition(ballPosition: position)
let r: CGFloat = (binPos.steer == .Left) ? 1.0 : 0.0
let g: CGFloat = (binPos.steer == .Right) ? 1.0 : 0.0
let b: CGFloat = (binPos.steer == .Center) ? 1.0 : 0.0
self.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
else {
// RGB = (0, 0, 0)
self.backgroundColor = UIColor.blackColor()
}
}
}
|
mit
|
6a1366b200f2d0d721666f0cf323e48b
| 26.574074 | 90 | 0.549362 | 4.366569 | false | false | false | false |
nate-parrott/Ratty
|
RattyApp/Ratty Menu/MenuLoader.swift
|
1
|
3759
|
//
// MenuLoader.swift
// RattyApp
//
// Created by Nate Parrott on 2/18/15.
// Copyright (c) 2015 Nate Parrott. All rights reserved.
//
import UIKit
import NotificationCenter
class MenuLoader: NSObject {
private(set) var loading: Bool = false
private(set) var erroredOnLastLoad: Bool = false
private(set) var meals: [DiningAPI.MealMenu]?
private(set) var mealsLoadedDate: NSDate?
var onStateUpdated: (() -> ())?
private func stateUpdated() {
if let cb = onStateUpdated {
cb()
}
}
var onReload: (() -> ())?
override init() {
super.init()
if let (meals, date) = getCachedMenu() {
self.meals = meals
self.mealsLoadedDate = date
}
reloadIfNeeded()
}
func isMenuStale() -> Bool {
return mealsLoadedDate == nil || NSDate().dateByRemovingTime().compare(mealsLoadedDate!.dateByRemovingTime()) != .OrderedSame
}
var completionHandler: (NCUpdateResult -> ())?
func reloadIfNeeded() {
if isMenuStale() && !loading {
loading = true
erroredOnLastLoad = false
self.stateUpdated()
DiningAPI().getJsonForMenu("eatery", date: NSDate(), callback: { (let responseOpt, let errorOpt) -> () in
self.erroredOnLastLoad = true
if let resp = responseOpt {
self.cacheMenu(resp)
if let menusJson = resp["menus"] as? [[String: AnyObject]] {
let menus = menusJson.map({ DiningAPI.MealMenu(json: $0) })
self.meals = menus
self.mealsLoadedDate = NSDate()
self.erroredOnLastLoad = false
}
}
self.loading = false
self.stateUpdated()
if let cb = self.completionHandler {
self.completionHandler = nil
cb(self.erroredOnLastLoad ? .NewData : .Failed)
}
if let cb = self.onReload {
cb()
}
})
} else {
if let cb = self.completionHandler {
self.completionHandler = nil
cb(.NoData)
}
}
}
private func getCachedMenu() -> (meals: [DiningAPI.MealMenu], date: NSDate)? {
if let data = NSData(contentsOfFile: cachePath) {
if let r: AnyObject = try? NSJSONSerialization.JSONObjectWithData(data, options: []) {
if let dict = r as? [String: AnyObject] {
if let menuJsons: AnyObject = dict["menus"] {
if let m = menuJsons as? [[String: AnyObject]] {
let meals = m.map({DiningAPI.MealMenu(json: $0)})
let time = NSUserDefaults.standardUserDefaults().doubleForKey("CachedMenuDate")
return (meals: meals, date: NSDate(timeIntervalSinceReferenceDate: time))
}
}
}
}
}
return nil
}
private func cacheMenu(jsonResponse: [String: AnyObject]) {
let data = try! NSJSONSerialization.dataWithJSONObject(jsonResponse, options: [])
data.writeToFile(cachePath, atomically: true)
NSUserDefaults.standardUserDefaults().setDouble(NSDate.timeIntervalSinceReferenceDate(), forKey: "CachedMenuDate")
}
private var cachePath: String {
get {
return (NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("MenuCache.json")
}
}
}
|
mit
|
1f97e4c895cfa3524cae818dcb6d9a1b
| 35.852941 | 165 | 0.536845 | 4.99867 | false | false | false | false |
pawrsccouk/Stereogram
|
Stereogram-iPad/NSURL+Extensions.swift
|
1
|
710
|
//
// NSURL+Extensions.swift
// Stereogram-iPad
//
// Created by Patrick Wallace on 25/05/2015.
// Copyright (c) 2015 Patrick Wallace. All rights reserved.
//
import Foundation
extension NSURL {
/// True if the URL already exists and points to a directory.
/// False if it doesn't exist or points to another object type.
var isDirectory: Bool {
var isDirectory = UnsafeMutablePointer<ObjCBool>.alloc(1)
isDirectory.initialize(ObjCBool(false))
let fileManager = NSFileManager.defaultManager()
if let path = path {
let fileExists = fileManager.fileExistsAtPath(path, isDirectory:isDirectory)
let isDir = isDirectory.memory.boolValue
return fileExists && isDir
}
return false
}
}
|
mit
|
8f74f950da9f3c1c8ded59b603dadbed
| 24.392857 | 79 | 0.733803 | 3.879781 | false | false | false | false |
gouyz/GYZBaking
|
baking/Classes/Tool/tool/GYZUpdateVersionTool.swift
|
1
|
1761
|
//
// GYZUpdateVersionTool.swift
// LazyHuiSellers
//
// Created by gouyz on 2017/3/16.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
/// 更新类型
///
/// - noUpdate:
/// - update//需要更新,但不强制:
/// - updateNeed//强制更新:
enum UpdateVersionType: Int {
case noUpdate = 0 //不需要更新
case update //需要更新,但不强制
case updateNeed //强制更新
}
class GYZUpdateVersionTool: NSObject {
/// 获取当前版本号
///
/// - Returns:
class func getCurrVersion()->String{
return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
}
/// 判断是否需要更新
///
/// - Parameter newVersion: 新版本号
/// - Returns: 更新类型
class func compareVersion(newVersion: String)->UpdateVersionType{
if newVersion.isEmpty {
return .noUpdate
}
let currVersion = getCurrVersion()
if newVersion != currVersion {
let currArr = currVersion.components(separatedBy: ".")
let currVersionFirst = currArr[0]
let newArr = newVersion.components(separatedBy: ".")
let newVersionFirst = newArr[0]
if currVersionFirst != newVersionFirst {
return .updateNeed
}
if currArr[1] < newArr[1] {//新版本大于当前版本,提示更新
return .update
}
}
return .noUpdate
}
/// 去App Store下载APP
class func goAppStore(){
let url: URL = URL.init(string: "https://itunes.apple.com/us/app/id\(APPID)?ls=1&mt=8")!
UIApplication.shared.openURL(url)
}
}
|
mit
|
49c75dc47efb5fb129f251ff3a39fd90
| 24.125 | 96 | 0.565299 | 4.112532 | false | false | false | false |
CaptainTeemo/Saffron
|
Saffron/ProgressiveImage.swift
|
1
|
12473
|
//
// ProgressiveImage.swift
// Saffron
//
// Created by CaptainTeemo on 6/17/16.
// Copyright © 2016 Captain Teemo. All rights reserved.
//
import Foundation
import Accelerate
import ImageIO
// This progressiveImage idea is totally cribbed from PINRemoteImage(https://github.com/pinterest/PINRemoteImage) with one little modification which is I prefer dispatch_semaphore instead of NSLock.
final class ProgressiveImage {
var progressThresholds: [CGFloat] {
set {
lock()
_progressThresholds = newValue
unlock()
}
get {
lock()
let thresholds = _progressThresholds
unlock()
return thresholds
}
}
var estimatedRemainingTimeThreshold: Double {
set {
lock()
_estimatedRemainingTimeThreshold = newValue
unlock()
}
get {
lock()
let thresholds = _estimatedRemainingTimeThreshold
unlock()
return thresholds
}
}
var startTime: Double {
set {
lock()
_startTime = newValue
unlock()
}
get {
lock()
let time = _startTime
unlock()
return time
}
}
// var data: Data? {
// get {
// lock()
// let data = _mutableData?.copy() as? Data
// unlock()
// return data
// }
// }
fileprivate var _imageSource = CGImageSourceCreateIncremental(nil)
fileprivate var _size = CGSize.zero
fileprivate var _isProgressiveJPEG = true
fileprivate var _progressThresholds: [CGFloat] = [0.00, 0.20, 0.35, 0.50, 0.65, 0.80]
fileprivate var _currentThreshold = 0
fileprivate var _startTime = CACurrentMediaTime()
fileprivate var _estimatedRemainingTimeThreshold: Double = -1
fileprivate var _sosCount = 0
fileprivate var _scannedByte = 0
fileprivate var _mutableData: Data?
fileprivate var _expectedNumberOfBytes: Int64 = 0
fileprivate var _bytesPerSecond: Double {
get {
let length = CACurrentMediaTime() - _startTime
return Double(_mutableData!.count) / length
}
}
fileprivate var _estimatedRemainingTime: Double {
get {
if _expectedNumberOfBytes < 0 { return Double(CGFloat.greatestFiniteMagnitude) }
let remainingBytes = _expectedNumberOfBytes - _mutableData!.count
if remainingBytes == 0 { return 0 }
if _bytesPerSecond == 0 { return Double(CGFloat.greatestFiniteMagnitude) }
return Double(remainingBytes) / _bytesPerSecond
}
}
fileprivate var _semaphore = DispatchSemaphore(value: 1)
}
// MARK: - Public
extension ProgressiveImage {
func updateProgressiveImage(_ data: Data, expectedNumberOfBytes: Int64) {
lock()
if _mutableData == nil {
var bytesToAlloc = 0
if expectedNumberOfBytes > 0 {
bytesToAlloc = Int(expectedNumberOfBytes)
}
_mutableData = Data(capacity: bytesToAlloc)
_expectedNumberOfBytes = expectedNumberOfBytes
}
_mutableData!.append(data)
while !hasCompletedFirstScan() && _scannedByte < _mutableData!.count {
var startByte = _scannedByte
if startByte > 0 {
startByte -= 1
}
let (found, scannedByte) = scanForSOS(_mutableData! as Data, startByte: startByte)
if found {
_sosCount += 1
}
_scannedByte = scannedByte
}
let _ = _mutableData!.withUnsafeBytes {
CGImageSourceUpdateData(_imageSource, CFDataCreate(kCFAllocatorDefault, $0, _mutableData!.count), false)
}
// CGImageSourceUpdateData(_imageSource, CFDataCreate(kCFAllocatorDefault, _mutableData!.bytes.bindMemory(to: UInt8.self, capacity: _mutableData!.count), _mutableData!.count), false)
unlock()
}
func currentImage(_ blurred: Bool, maxProgressiveRenderSize: CGSize = CGSize(width: 1024, height: 1024), quality: CGFloat = 1) -> UIImage? {
lock()
if _currentThreshold == _progressThresholds.count {
unlock()
return nil
}
if _estimatedRemainingTimeThreshold > 0 && _estimatedRemainingTime < _estimatedRemainingTimeThreshold {
unlock()
return nil
}
if !hasCompletedFirstScan() {
unlock()
return nil
}
var currentImage: UIImage? = nil
if _size.width <= 0 || _size.height <= 0 {
if let imageProperties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, nil) as NSDictionary? {
var size = _size
if let width = imageProperties["\(kCGImagePropertyPixelWidth)"] , size.width <= 0 {
size.width = CGFloat(width as! NSNumber)
}
if let height = imageProperties["\(kCGImagePropertyPixelHeight)"] , size.height <= 0 {
size.height = CGFloat(height as! NSNumber)
}
_size = size
if let jpegProperties = imageProperties["\(kCGImagePropertyJFIFDictionary)"] as? NSDictionary,
let isProgressive = jpegProperties["\(kCGImagePropertyJFIFIsProgressive)"] as? NSNumber {
_isProgressiveJPEG = isProgressive.boolValue
}
}
}
if _size.width > maxProgressiveRenderSize.width || _size.height > maxProgressiveRenderSize.height {
unlock()
return nil
}
var progress: CGFloat = 0
if _expectedNumberOfBytes > 0 {
progress = CGFloat(_mutableData!.count) / CGFloat(_expectedNumberOfBytes)
}
if progress >= 0.99 {
unlock()
return nil
}
if _isProgressiveJPEG && _size.width > 0 && _size.height > 0 && progress > _progressThresholds[_currentThreshold] {
while _currentThreshold < _progressThresholds.count && progress > _progressThresholds[_currentThreshold] {
_currentThreshold += 1
}
if let image = CGImageSourceCreateImageAtIndex(_imageSource, 0, nil) {
if blurred {
currentImage = processImage(UIImage(cgImage: image), progress: progress)
} else {
currentImage = UIImage(cgImage: image)
}
}
}
unlock()
return currentImage
}
}
// MARK: - Private
extension ProgressiveImage {
fileprivate func scanForSOS(_ data: Data, startByte: Int) -> (Bool, Int) {
let scanMarker = UnsafeMutableRawPointer(mutating: [0xFF, 0xDA])
// var scanRange = NSRange()
// scanRange.location = startByte
// scanRange.length = data.count - scanRange.location
let scanRange: Range<Int> = startByte..<data.count
let sosRange = data.range(of: Data(bytes: UnsafeRawPointer(scanMarker), count: 2), options: .backwards, in: scanRange)
if let r = sosRange, !r.isEmpty {
return (true, (r.upperBound - r.lowerBound))
}
return (false, (scanRange.upperBound - scanRange.lowerBound))
}
fileprivate func hasCompletedFirstScan() -> Bool {
return _sosCount >= 2
}
fileprivate func processImage(_ inputImage: UIImage, progress: CGFloat) -> UIImage? {
guard let inputImageRef = inputImage.cgImage else { return nil }
var outputImage: UIImage? = nil
let inputSize = inputImage.size
guard inputSize.width >= 1 || inputSize.height >= 1 else { return nil }
let imageScale = inputImage.scale
var radius = (inputImage.size.width / 25) * max(0, 1 - progress)
radius *= imageScale
if radius < CGFloat(FLT_EPSILON) {
return inputImage
}
UIGraphicsBeginImageContextWithOptions(inputSize, true, imageScale)
if let context = UIGraphicsGetCurrentContext() {
context.scaleBy(x: 1, y: -1)
context.translateBy(x: 0, y: -inputSize.height)
var effectInBuffer = vImage_Buffer()
var scratchBuffer = vImage_Buffer()
var inputBuffer: vImage_Buffer
var outputBuffer: vImage_Buffer
var format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
.union(.byteOrder32Little), version: 0, decode: nil, renderingIntent: CGColorRenderingIntent.defaultIntent)
var error = vImageBuffer_InitWithCGImage(&effectInBuffer, &format, nil, inputImageRef, UInt32(kvImagePrintDiagnosticsToConsole))
if error == kvImageNoError {
error = vImageBuffer_Init(&scratchBuffer, effectInBuffer.height, effectInBuffer.width, format.bitsPerPixel, UInt32(kvImageNoFlags))
if error == kvImageNoError {
inputBuffer = effectInBuffer
outputBuffer = scratchBuffer
if radius - 2 < CGFloat(FLT_EPSILON) {
radius = 2
}
let d = radius * 3 * sqrt(2 * CGFloat(M_PI)) / 4 + 0.5
var wholeRadius = UInt32(floor(d / 2))
wholeRadius |= 1
let tempBufferSize = vImageBoxConvolve_ARGB8888(&inputBuffer, &outputBuffer, nil, 0, 0, wholeRadius, wholeRadius, nil, UInt32(kvImageGetTempBufferSize) | UInt32(kvImageEdgeExtend))
let tempBuffer: UnsafeMutableRawPointer? = malloc(tempBufferSize)
if tempBuffer != nil {
vImageBoxConvolve_ARGB8888(&inputBuffer, &outputBuffer, tempBuffer, 0, 0, wholeRadius, wholeRadius, nil, UInt32(kvImageEdgeExtend))
vImageBoxConvolve_ARGB8888(&outputBuffer, &inputBuffer, tempBuffer, 0, 0, wholeRadius, wholeRadius, nil, UInt32(kvImageEdgeExtend))
vImageBoxConvolve_ARGB8888(&inputBuffer, &outputBuffer, tempBuffer, 0, 0, wholeRadius, wholeRadius, nil, UInt32(kvImageEdgeExtend))
free(tempBuffer)
let temp = inputBuffer
inputBuffer = outputBuffer
outputBuffer = temp
if let effectCGImage = vImageCreateCGImageFromBuffer(&inputBuffer, &format, { userData, bufferData in
free(bufferData)
}, nil, UInt32(kvImageNoAllocate), nil) {
context.saveGState()
context.draw(effectCGImage.takeRetainedValue(), in: CGRect(x: 0, y: 0, width: inputSize.width, height: inputSize.height))
} else {
free(inputBuffer.data)
}
free(outputBuffer.data)
outputImage = UIGraphicsGetImageFromCurrentImageContext()
}
} else {
if scratchBuffer.data != nil {
free(scratchBuffer.data)
}
free(effectInBuffer.data)
}
} else {
if effectInBuffer.data != nil {
free(effectInBuffer.data)
}
}
}
UIGraphicsEndImageContext()
return outputImage
}
}
// MARK: - Lock
extension ProgressiveImage {
fileprivate func lock() {
let _ = _semaphore.wait(timeout: DispatchTime.distantFuture)
}
fileprivate func unlock() {
_semaphore.signal()
}
}
|
mit
|
3a4a531a551eb284dd75a17fa5549954
| 36.679758 | 200 | 0.547627 | 5.36892 | false | false | false | false |
powerytg/Accented
|
Accented/Core/Storage/Models/PhotoModel.swift
|
1
|
3433
|
//
// PhotoModel.swift
// Accented
//
// Photo view model
//
// Created by You, Tiangong on 4/22/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
import SwiftyJSON
class PhotoModel: ModelBase {
private var dateFormatter = DateFormatter()
var photoId : String!
var imageUrls = [ImageSize : String!]()
var width : CGFloat!
var height: CGFloat!
var title : String!
var desc : String?
var creationDate : Date?
var lens : String?
var camera : String?
var aperture : String?
var longitude : Double?
var latitude : Double?
var tags = [String]()
var user : UserModel!
var commentsCount : Int?
var voted : Bool!
var voteCount : Int?
var rating : Float?
var viewCount : Int?
override init() {
super.init()
}
init(json:JSON) {
super.init()
photoId = String(json["id"].int!)
modelId = photoId
// Image urls
for (_, imageJson):(String, JSON) in json["images"] {
guard imageJson["https_url"].string != nil else { continue }
// Parse size metadta
let imageSizeString = String(imageJson["size"].intValue)
if let size = ImageSize(rawValue: imageSizeString) {
imageUrls[size] = imageJson["https_url"].stringValue
}
}
// Original width and height
width = CGFloat(json["width"].intValue)
height = CGFloat(json["height"].intValue)
// Title
title = json["name"].stringValue
// Description
desc = json["description"].string
// Dates
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ"
let createdAt = json["created_at"].string!
creationDate = dateFormatter.date(from: createdAt)
// EXIF
camera = json["camera"].string
lens = json["lens"].string
aperture = json["aperture"].string
// Geolocation
longitude = json["longitude"].double
latitude = json["latitude"].double
// User
user = UserModel(json: json["user"])
StorageService.sharedInstance.putUserToCache(user)
// Tags
for (_, tagJSON):(String, JSON) in json["tags"] {
tags.append(tagJSON.string!)
}
// Like status
voted = json["voted"].boolValue
voteCount = json["votes_count"].int
rating = json["rating"].float
viewCount = json["times_viewed"].int
}
override func copy(with zone: NSZone? = nil) -> Any {
let clone = PhotoModel()
clone.modelId = self.modelId
clone.photoId = self.photoId
clone.imageUrls = self.imageUrls
clone.width = self.width
clone.height = self.height
clone.title = self.title
clone.desc = self.desc
clone.creationDate = self.creationDate
clone.camera = self.camera
clone.lens = self.lens
clone.aperture = self.aperture
clone.longitude = self.longitude
clone.latitude = self.latitude
clone.user = self.user.copy() as! UserModel
clone.tags = self.tags
clone.voted = self.voted
clone.voteCount = self.voteCount
clone.rating = self.rating
clone.viewCount = self.viewCount
return clone
}
}
|
mit
|
8ed06613ed62ca5a59845fbd52b6b20a
| 27.840336 | 72 | 0.568182 | 4.515789 | false | false | false | false |
JaleelNazir/MJTableImageSwift
|
MJTableImageLoading/AppDelegate.swift
|
1
|
6418
|
//
// AppDelegate.swift
// MJTableImageLoading
//
// Created by Mohamed Jaleel Nazir on 27/05/15.
// Copyright (c) 2015 Jaleel. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.Nyqmind.MJTableImageLoading" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MJTableImageLoading", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MJTableImageLoading.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
|
mit
|
01e61184be7a13d0bba7f608c0f3f39f
| 52.041322 | 290 | 0.700218 | 5.813406 | false | false | false | false |
lorentey/GlueKit
|
Sources/ArrayFilteringOnPredicate.swift
|
1
|
2631
|
//
// ArrayFilteringOnPredicate.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-09-26.
// Copyright © 2015–2017 Károly Lőrentey.
//
extension ObservableArrayType {
public func filter(_ isIncluded: @escaping (Element) -> Bool) -> AnyObservableArray<Element> {
return ArrayFilteringOnPredicate<Self>(parent: self, isIncluded: isIncluded).anyObservableArray
}
}
private final class ArrayFilteringOnPredicate<Parent: ObservableArrayType>: _BaseObservableArray<Parent.Element> {
public typealias Element = Parent.Element
public typealias Change = ArrayChange<Element>
private struct ParentSink: UniqueOwnedSink {
typealias Owner = ArrayFilteringOnPredicate
unowned(unsafe) let owner: Owner
func receive(_ update: ArrayUpdate<Parent.Element>) {
owner.applyParentUpdate(update)
}
}
private let parent: Parent
private let isIncluded: (Element) -> Bool
private var indexMapping: ArrayFilteringIndexmap<Element>
init(parent: Parent, isIncluded: @escaping (Element) -> Bool) {
self.parent = parent
self.isIncluded = isIncluded
self.indexMapping = ArrayFilteringIndexmap(initialValues: parent.value, isIncluded: isIncluded)
super.init()
parent.add(ParentSink(owner: self))
}
deinit {
parent.remove(ParentSink(owner: self))
}
func applyParentUpdate(_ update: ArrayUpdate<Element>) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
let filteredChange = self.indexMapping.apply(change)
if !filteredChange.isEmpty {
sendChange(filteredChange)
}
case .endTransaction:
endTransaction()
}
}
override var isBuffered: Bool {
return false
}
override subscript(index: Int) -> Element {
return parent[indexMapping.matchingIndices[index]]
}
override subscript(bounds: Range<Int>) -> ArraySlice<Element> {
precondition(0 <= bounds.lowerBound && bounds.lowerBound <= bounds.upperBound && bounds.upperBound <= count)
var result: [Element] = []
result.reserveCapacity(bounds.count)
for index in indexMapping.matchingIndices[bounds] {
result.append(parent[index])
}
return ArraySlice(result)
}
override var value: Array<Element> {
return indexMapping.matchingIndices.map { parent[$0] }
}
override var count: Int {
return indexMapping.matchingIndices.count
}
}
|
mit
|
da319b393e8e04b3b7c47207ea02b25d
| 29.870588 | 116 | 0.65282 | 4.710952 | false | false | false | false |
Takanu/Pelican
|
Sources/Pelican/API/Types/Stickers/StickerSet.swift
|
1
|
964
|
//
// StickerSet.swift
// Pelican
//
// Created by Takanu Kyriako on 21/12/2017.
//
import Foundation
/**
Represents a sticker set - a collection of stickers that are stored on the Telegram servers.
*/
public class StickerSet: Codable {
/// The username for the sticker set (?)
public var username: String
/// The name of the sticker set.
public var title: String
/// If true, this set contains sticker masks.
public var containsMasks: Bool
/// An array of all the stickers that this set contains.
public var stickers: [Sticker]
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case username = "name"
case title
case containsMasks = "contains_masks"
case stickers
}
init(withUsername username: String, title: String, containsMasks: Bool, stickers: [Sticker]) {
self.username = username
self.title = title
self.containsMasks = containsMasks
self.stickers = stickers
}
}
|
mit
|
23c63fb1d440cba5f49bd469f7ebd5eb
| 21.952381 | 95 | 0.712656 | 3.795276 | false | false | false | false |
ricardopereira/QuickActions
|
Source/QuickActions.swift
|
1
|
6220
|
//
// QuickActions.swift
// QuickActions
//
// Created by Ricardo Pereira on 20/02/16.
// Copyright © 2016 Ricardo Pereira. All rights reserved.
//
import UIKit
public enum ShortcutIcon: Int {
case compose
case play
case pause
case add
case location
case search
case share
case prohibit
case contact
case home
case markLocation
case favorite
case love
case cloud
case invitation
case confirmation
case mail
case message
case date
case time
case capturePhoto
case captureVideo
case task
case taskCompleted
case alarm
case bookmark
case shuffle
case audio
case update
case custom
@available(iOS 9.0, *)
func toApplicationShortcutIcon() -> UIApplicationShortcutIcon? {
if self == .custom {
NSException(name: NSExceptionName(rawValue: "Invalid option"), reason: "`Custom` type need to be used with `toApplicationShortcutIcon:imageName`", userInfo: nil).raise()
return nil
}
let icon = UIApplicationShortcutIcon.IconType(rawValue: self.rawValue) ?? UIApplicationShortcutIcon.IconType.confirmation
return UIApplicationShortcutIcon(type: icon)
}
@available(iOS 9.0, *)
func toApplicationShortcutIcon(_ imageName: String) -> UIApplicationShortcutIcon? {
if self == .custom {
return UIApplicationShortcutIcon(templateImageName: imageName)
}
else {
NSException(name: NSExceptionName(rawValue: "Invalid option"), reason: "Type need to be `Custom`", userInfo: nil).raise()
return nil
}
}
}
public protocol ShortcutType: RawRepresentable {}
public extension RawRepresentable where Self: ShortcutType {
init?(type: String) {
assert(type is RawValue)
// FIXME: try another solution to restrain the RawRepresentable as String
self.init(rawValue: type as! RawValue)
}
var value: String {
return self.rawValue as? String ?? ""
}
}
public struct Shortcut {
public let type: String
public let title: String
public let subtitle: String?
public let icon: ShortcutIcon?
public init<T: ShortcutType>(type: T, title: String, subtitle: String?, icon: ShortcutIcon?) {
self.type = type.value
self.title = title
self.subtitle = subtitle
self.icon = icon
}
}
public extension Shortcut {
@available(iOS 9.0, *)
init(shortcutItem: UIApplicationShortcutItem) {
if let range = shortcutItem.type.rangeOfCharacter(from: CharacterSet(charactersIn: "."), options: .backwards) {
type = String(shortcutItem.type[range.upperBound...])
}
else {
type = "unknown"
}
title = shortcutItem.localizedTitle
subtitle = shortcutItem.localizedSubtitle
// FIXME: shortcutItem.icon!.type isn't accessible
icon = nil
}
@available(iOS 9.0, *)
fileprivate func toApplicationShortcut(_ bundleIdentifier: String) -> UIApplicationShortcutItem {
return UIMutableApplicationShortcutItem(type: bundleIdentifier + "." + type, localizedTitle: title, localizedSubtitle: subtitle, icon: icon?.toApplicationShortcutIcon(), userInfo: nil)
}
}
@available(iOS 9.0, *)
public extension UIApplicationShortcutItem {
var toShortcut: Shortcut {
return Shortcut(shortcutItem: self)
}
}
public protocol QuickActionSupport {
@available(iOS 9.0, *)
func prepareForQuickAction<T: ShortcutType>(_ shortcutType: T)
}
open class QuickActions<T: ShortcutType> {
fileprivate let bundleIdentifier: String
public init(_ application: UIApplication, actionHandler: QuickActionSupport?, bundleIdentifier: String, shortcuts: [Shortcut], launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) {
self.bundleIdentifier = bundleIdentifier
if #available(iOS 9.0, *) {
install(shortcuts, toApplication: application)
}
if #available(iOS 9.0, *), let shortcutItem = launchOptions?[.shortcutItem] as? UIApplicationShortcutItem {
handle(actionHandler, shortcutItem: shortcutItem)
}
}
/// Install initial Quick Actions (app shortcuts)
@available(iOS 9.0, *)
fileprivate func install(_ shortcuts: [Shortcut], toApplication application: UIApplication) {
application.shortcutItems = shortcuts.map { $0.toApplicationShortcut(bundleIdentifier) }
}
@available(iOS 9.0, *)
@discardableResult
open func handle(_ actionHandler: QuickActionSupport?, shortcutItem: UIApplicationShortcutItem) -> Bool {
return handle(actionHandler, shortcut: shortcutItem.toShortcut)
}
open func handle(_ actionHandler: QuickActionSupport?, shortcut: Shortcut) -> Bool {
guard let viewController = actionHandler else { return false }
if #available(iOS 9.0, *) {
// FIXME: Can't use `shortcutType`: Segmentation fault: 11
//let shortcutType = T.init(type: shortcut.type)
viewController.prepareForQuickAction(T.init(type: shortcut.type)!)
return true
}
else {
return false
}
}
open func add(_ shortcuts: [Shortcut], toApplication application: UIApplication) {
if #available(iOS 9.0, *) {
var items = shortcuts.map { $0.toApplicationShortcut(bundleIdentifier) }
items.append(contentsOf: application.shortcutItems ?? [])
application.shortcutItems = items
}
}
open func add(_ shortcut: Shortcut, toApplication application: UIApplication) {
add([shortcut], toApplication: application)
}
open func remove(_ shortcut: Shortcut, toApplication application: UIApplication) {
if #available(iOS 9.0, *) {
if let index = application.shortcutItems?.firstIndex(of: shortcut.toApplicationShortcut(bundleIdentifier)) , index > -1 {
application.shortcutItems?.remove(at: index)
}
}
}
open func clear(_ application: UIApplication) {
if #available(iOS 9.0, *) {
application.shortcutItems = nil
}
}
}
|
mit
|
eff9607f1db68e6e45cd7ea36d8fb051
| 29.485294 | 193 | 0.656215 | 4.920095 | false | false | false | false |
apple/swift-corelibs-foundation
|
Sources/Foundation/Decimal.swift
|
1
|
85701
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2016 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
public var NSDecimalMaxSize: Int32 { 8 }
public var NSDecimalNoScale: Int32 { Int32(Int16.max) }
public struct Decimal {
fileprivate var __exponent: Int8
fileprivate var __lengthAndFlags: UInt8
fileprivate var __reserved: UInt16
public var _exponent: Int32 {
get {
return Int32(__exponent)
}
set {
__exponent = Int8(newValue)
}
}
// _length == 0 && _isNegative == 1 -> NaN.
public var _length: UInt32 {
get {
return UInt32((__lengthAndFlags & 0b0000_1111))
}
set {
guard newValue <= maxMantissaLength else {
fatalError("Attempt to set a length greater than capacity \(newValue) > \(maxMantissaLength)")
}
__lengthAndFlags =
(__lengthAndFlags & 0b1111_0000) |
UInt8(newValue & 0b0000_1111)
}
}
public var _isNegative: UInt32 {
get {
return UInt32(((__lengthAndFlags) & 0b0001_0000) >> 4)
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b1110_1111) |
(UInt8(newValue & 0b0000_0001 ) << 4)
}
}
public var _isCompact: UInt32 {
get {
return UInt32(((__lengthAndFlags) & 0b0010_0000) >> 5)
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b1101_1111) |
(UInt8(newValue & 0b0000_00001 ) << 5)
}
}
public var _reserved: UInt32 {
get {
return UInt32(UInt32(__lengthAndFlags & 0b1100_0000) << 10 | UInt32(__reserved))
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b0011_1111) |
UInt8(UInt32(newValue & (0b11 << 16)) >> 10)
__reserved = UInt16(newValue & 0b1111_1111_1111_1111)
}
}
public var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)
public init() {
self._mantissa = (0,0,0,0,0,0,0,0)
self.__exponent = 0
self.__lengthAndFlags = 0
self.__reserved = 0
}
public init(_exponent: Int32, _length: UInt32, _isNegative: UInt32, _isCompact: UInt32, _reserved: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)) {
precondition(_length <= 15)
self._mantissa = _mantissa
self.__exponent = Int8(_exponent)
self.__lengthAndFlags = UInt8(_length & 0b1111)
self.__reserved = 0
self._isNegative = _isNegative
self._isCompact = _isCompact
self._reserved = _reserved
}
}
extension Decimal {
public typealias RoundingMode = NSDecimalNumber.RoundingMode
public typealias CalculationError = NSDecimalNumber.CalculationError
}
public func pow(_ x: Decimal, _ y: Int) -> Decimal {
var x = x
var result = Decimal()
_ = NSDecimalPower(&result, &x, y, .plain)
return result
}
extension Decimal : Hashable, Comparable {
// (Used by `VariableLengthNumber` and `doubleValue`.)
fileprivate subscript(index: UInt32) -> UInt16 {
get {
switch index {
case 0: return _mantissa.0
case 1: return _mantissa.1
case 2: return _mantissa.2
case 3: return _mantissa.3
case 4: return _mantissa.4
case 5: return _mantissa.5
case 6: return _mantissa.6
case 7: return _mantissa.7
default: fatalError("Invalid index \(index) for _mantissa")
}
}
set {
switch index {
case 0: _mantissa.0 = newValue
case 1: _mantissa.1 = newValue
case 2: _mantissa.2 = newValue
case 3: _mantissa.3 = newValue
case 4: _mantissa.4 = newValue
case 5: _mantissa.5 = newValue
case 6: _mantissa.6 = newValue
case 7: _mantissa.7 = newValue
default: fatalError("Invalid index \(index) for _mantissa")
}
}
}
// (Used by `NSDecimalNumber` and `hash(into:)`.)
internal var doubleValue: Double {
if _length == 0 {
return _isNegative == 1 ? Double.nan : 0
}
var d = 0.0
for idx in (0..<min(_length, 8)).reversed() {
d = d * 65536 + Double(self[idx])
}
if _exponent < 0 {
for _ in _exponent..<0 {
d /= 10.0
}
} else {
for _ in 0..<_exponent {
d *= 10.0
}
}
return _isNegative != 0 ? -d : d
}
// The low 64 bits of the integer part.
// (Used by `uint64Value` and `int64Value`.)
private var _unsignedInt64Value: UInt64 {
// Quick check if number if has too many zeros before decimal point or too many trailing zeros after decimal point.
// Log10 (2^64) ~ 19, log10 (2^128) ~ 38
if _exponent < -38 || _exponent > 20 {
return 0
}
if _length == 0 || isZero || magnitude < (0 as Decimal) {
return 0
}
var copy = self.significand
if _exponent < 0 {
for _ in _exponent..<0 {
_ = divideByShort(©, 10)
}
} else if _exponent > 0 {
for _ in 0..<_exponent {
_ = multiplyByShort(©, 10)
}
}
let uint64 = UInt64(copy._mantissa.3) << 48 | UInt64(copy._mantissa.2) << 32 | UInt64(copy._mantissa.1) << 16 | UInt64(copy._mantissa.0)
return uint64
}
// A best-effort conversion of the integer value, trying to match Darwin for
// values outside of UInt64.min...UInt64.max.
// (Used by `NSDecimalNumber`.)
internal var uint64Value: UInt64 {
let value = _unsignedInt64Value
if !self.isNegative {
return value
}
if value == Int64.max.magnitude + 1 {
return UInt64(bitPattern: Int64.min)
}
if value <= Int64.max.magnitude {
var value = Int64(value)
value.negate()
return UInt64(bitPattern: value)
}
return value
}
// A best-effort conversion of the integer value, trying to match Darwin for
// values outside of Int64.min...Int64.max.
// (Used by `NSDecimalNumber`.)
internal var int64Value: Int64 {
let uint64Value = _unsignedInt64Value
if self.isNegative {
if uint64Value == Int64.max.magnitude + 1 {
return Int64.min
}
if uint64Value <= Int64.max.magnitude {
var value = Int64(uint64Value)
value.negate()
return value
}
}
return Int64(bitPattern: uint64Value)
}
public func hash(into hasher: inout Hasher) {
// FIXME: This is a weak hash. We should rather normalize self to a
// canonical member of the exact same equivalence relation that
// NSDecimalCompare implements, then simply feed all components to the
// hasher.
hasher.combine(doubleValue)
}
public static func ==(lhs: Decimal, rhs: Decimal) -> Bool {
if lhs.isNaN {
return rhs.isNaN
}
if lhs.__exponent == rhs.__exponent && lhs.__lengthAndFlags == rhs.__lengthAndFlags && lhs.__reserved == rhs.__reserved {
if lhs._mantissa.0 == rhs._mantissa.0 &&
lhs._mantissa.1 == rhs._mantissa.1 &&
lhs._mantissa.2 == rhs._mantissa.2 &&
lhs._mantissa.3 == rhs._mantissa.3 &&
lhs._mantissa.4 == rhs._mantissa.4 &&
lhs._mantissa.5 == rhs._mantissa.5 &&
lhs._mantissa.6 == rhs._mantissa.6 &&
lhs._mantissa.7 == rhs._mantissa.7 {
return true
}
}
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedSame
}
public static func <(lhs: Decimal, rhs: Decimal) -> Bool {
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedAscending
}
}
extension Decimal : CustomStringConvertible {
public init?(string: String, locale: Locale? = nil) {
let scan = Scanner(string: string)
var theDecimal = Decimal()
scan.locale = locale
if !scan.scanDecimal(&theDecimal) {
return nil
}
self = theDecimal
}
public var description: String {
var value = self
return NSDecimalString(&value, nil)
}
}
extension Decimal : Codable {
private enum CodingKeys : Int, CodingKey {
case exponent
case length
case isNegative
case isCompact
case mantissa
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let exponent = try container.decode(CInt.self, forKey: .exponent)
let length = try container.decode(CUnsignedInt.self, forKey: .length)
let isNegative = try container.decode(Bool.self, forKey: .isNegative)
let isCompact = try container.decode(Bool.self, forKey: .isCompact)
var mantissaContainer = try container.nestedUnkeyedContainer(forKey: .mantissa)
var mantissa: (CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort,
CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort) = (0,0,0,0,0,0,0,0)
mantissa.0 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.1 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.2 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.3 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.4 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.5 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.6 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.7 = try mantissaContainer.decode(CUnsignedShort.self)
self.init(_exponent: exponent,
_length: length,
_isNegative: CUnsignedInt(isNegative ? 1 : 0),
_isCompact: CUnsignedInt(isCompact ? 1 : 0),
_reserved: 0,
_mantissa: mantissa)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(_exponent, forKey: .exponent)
try container.encode(_length, forKey: .length)
try container.encode(_isNegative == 0 ? false : true, forKey: .isNegative)
try container.encode(_isCompact == 0 ? false : true, forKey: .isCompact)
var mantissaContainer = container.nestedUnkeyedContainer(forKey: .mantissa)
try mantissaContainer.encode(_mantissa.0)
try mantissaContainer.encode(_mantissa.1)
try mantissaContainer.encode(_mantissa.2)
try mantissaContainer.encode(_mantissa.3)
try mantissaContainer.encode(_mantissa.4)
try mantissaContainer.encode(_mantissa.5)
try mantissaContainer.encode(_mantissa.6)
try mantissaContainer.encode(_mantissa.7)
}
}
extension Decimal : ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self.init(value)
}
}
extension Decimal : ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.init(value)
}
}
extension Decimal : SignedNumeric {
public var magnitude: Decimal {
guard _length != 0 else { return self }
return Decimal(
_exponent: self._exponent, _length: self._length,
_isNegative: 0, _isCompact: self._isCompact,
_reserved: 0, _mantissa: self._mantissa)
}
public init?<T : BinaryInteger>(exactly source: T) {
let zero = 0 as T
if source == zero {
self = Decimal.zero
return
}
let negative: UInt32 = (T.isSigned && source < zero) ? 1 : 0
var mantissa = source.magnitude
var exponent: Int32 = 0
let maxExponent = Int8.max
while mantissa.isMultiple(of: 10) && (exponent < maxExponent) {
exponent += 1
mantissa /= 10
}
// If the mantissa still requires more than 128 bits of storage then it is too large.
if mantissa.bitWidth > 128 && (mantissa >> 128 != zero) { return nil }
let mantissaParts: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)
let loWord = UInt64(truncatingIfNeeded: mantissa)
var length = ((loWord.bitWidth - loWord.leadingZeroBitCount) + (UInt16.bitWidth - 1)) / UInt16.bitWidth
mantissaParts.0 = UInt16(truncatingIfNeeded: loWord >> 0)
mantissaParts.1 = UInt16(truncatingIfNeeded: loWord >> 16)
mantissaParts.2 = UInt16(truncatingIfNeeded: loWord >> 32)
mantissaParts.3 = UInt16(truncatingIfNeeded: loWord >> 48)
let hiWord = mantissa.bitWidth > 64 ? UInt64(truncatingIfNeeded: mantissa >> 64) : 0
if hiWord != 0 {
length = 4 + ((hiWord.bitWidth - hiWord.leadingZeroBitCount) + (UInt16.bitWidth - 1)) / UInt16.bitWidth
mantissaParts.4 = UInt16(truncatingIfNeeded: hiWord >> 0)
mantissaParts.5 = UInt16(truncatingIfNeeded: hiWord >> 16)
mantissaParts.6 = UInt16(truncatingIfNeeded: hiWord >> 32)
mantissaParts.7 = UInt16(truncatingIfNeeded: hiWord >> 48)
} else {
mantissaParts.4 = 0
mantissaParts.5 = 0
mantissaParts.6 = 0
mantissaParts.7 = 0
}
self = Decimal(_exponent: exponent, _length: UInt32(length), _isNegative: negative, _isCompact: 1, _reserved: 0, _mantissa: mantissaParts)
}
public static func +=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalAdd($0, $0, &rhs, .plain)
}
}
public static func -=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalSubtract($0, $0, &rhs, .plain)
}
}
public static func *=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalMultiply($0, $0, &rhs, .plain)
}
}
public static func /=(lhs: inout Decimal, rhs: Decimal) {
var rhs = rhs
_ = withUnsafeMutablePointer(to: &lhs) {
NSDecimalDivide($0, $0, &rhs, .plain)
}
}
public static func +(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer += rhs
return answer
}
public static func -(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer -= rhs
return answer
}
public static func *(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer *= rhs
return answer
}
public static func /(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer /= rhs
return answer
}
public mutating func negate() {
guard _length != 0 else { return }
_isNegative = _isNegative == 0 ? 1 : 0
}
}
extension Decimal {
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func add(_ other: Decimal) {
self += other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func subtract(_ other: Decimal) {
self -= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func multiply(by other: Decimal) {
self *= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func divide(by other: Decimal) {
self /= other
}
}
extension Decimal : Strideable {
public func distance(to other: Decimal) -> Decimal {
return other - self
}
public func advanced(by n: Decimal) -> Decimal {
return self + n
}
}
private extension Decimal {
// Creates a value with zero exponent.
// (Used by `_powersOfTen*`.)
init(_length: UInt32, _isCompact: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)) {
self.init(_exponent: 0, _length: _length, _isNegative: 0, _isCompact: _isCompact,
_reserved: 0, _mantissa: _mantissa)
}
}
private let _powersOfTen = [
/* 10**00 */ Decimal(_length: 1, _isCompact: 1, _mantissa: (0x0001,0,0,0,0,0,0,0)),
/* 10**01 */ Decimal(_length: 1, _isCompact: 0, _mantissa: (0x000a,0,0,0,0,0,0,0)),
/* 10**02 */ Decimal(_length: 1, _isCompact: 0, _mantissa: (0x0064,0,0,0,0,0,0,0)),
/* 10**03 */ Decimal(_length: 1, _isCompact: 0, _mantissa: (0x03e8,0,0,0,0,0,0,0)),
/* 10**04 */ Decimal(_length: 1, _isCompact: 0, _mantissa: (0x2710,0,0,0,0,0,0,0)),
/* 10**05 */ Decimal(_length: 2, _isCompact: 0, _mantissa: (0x86a0, 0x0001,0,0,0,0,0,0)),
/* 10**06 */ Decimal(_length: 2, _isCompact: 0, _mantissa: (0x4240, 0x000f,0,0,0,0,0,0)),
/* 10**07 */ Decimal(_length: 2, _isCompact: 0, _mantissa: (0x9680, 0x0098,0,0,0,0,0,0)),
/* 10**08 */ Decimal(_length: 2, _isCompact: 0, _mantissa: (0xe100, 0x05f5,0,0,0,0,0,0)),
/* 10**09 */ Decimal(_length: 2, _isCompact: 0, _mantissa: (0xca00, 0x3b9a,0,0,0,0,0,0)),
/* 10**10 */ Decimal(_length: 3, _isCompact: 0, _mantissa: (0xe400, 0x540b, 0x0002,0,0,0,0,0)),
/* 10**11 */ Decimal(_length: 3, _isCompact: 0, _mantissa: (0xe800, 0x4876, 0x0017,0,0,0,0,0)),
/* 10**12 */ Decimal(_length: 3, _isCompact: 0, _mantissa: (0x1000, 0xd4a5, 0x00e8,0,0,0,0,0)),
/* 10**13 */ Decimal(_length: 3, _isCompact: 0, _mantissa: (0xa000, 0x4e72, 0x0918,0,0,0,0,0)),
/* 10**14 */ Decimal(_length: 3, _isCompact: 0, _mantissa: (0x4000, 0x107a, 0x5af3,0,0,0,0,0)),
/* 10**15 */ Decimal(_length: 4, _isCompact: 0, _mantissa: (0x8000, 0xa4c6, 0x8d7e, 0x0003,0,0,0,0)),
/* 10**16 */ Decimal(_length: 4, _isCompact: 0, _mantissa: (0x0000, 0x6fc1, 0x86f2, 0x0023,0,0,0,0)),
/* 10**17 */ Decimal(_length: 4, _isCompact: 0, _mantissa: (0x0000, 0x5d8a, 0x4578, 0x0163,0,0,0,0)),
/* 10**18 */ Decimal(_length: 4, _isCompact: 0, _mantissa: (0x0000, 0xa764, 0xb6b3, 0x0de0,0,0,0,0)),
/* 10**19 */ Decimal(_length: 4, _isCompact: 0, _mantissa: (0x0000, 0x89e8, 0x2304, 0x8ac7,0,0,0,0)),
/* 10**20 */ Decimal(_length: 5, _isCompact: 0, _mantissa: (0x0000, 0x6310, 0x5e2d, 0x6bc7, 0x0005,0,0,0)),
/* 10**21 */ Decimal(_length: 5, _isCompact: 0, _mantissa: (0x0000, 0xdea0, 0xadc5, 0x35c9, 0x0036,0,0,0)),
/* 10**22 */ Decimal(_length: 5, _isCompact: 0, _mantissa: (0x0000, 0xb240, 0xc9ba, 0x19e0, 0x021e,0,0,0)),
/* 10**23 */ Decimal(_length: 5, _isCompact: 0, _mantissa: (0x0000, 0xf680, 0xe14a, 0x02c7, 0x152d,0,0,0)),
/* 10**24 */ Decimal(_length: 5, _isCompact: 0, _mantissa: (0x0000, 0xa100, 0xcced, 0x1bce, 0xd3c2,0,0,0)),
/* 10**25 */ Decimal(_length: 6, _isCompact: 0, _mantissa: (0x0000, 0x4a00, 0x0148, 0x1614, 0x4595, 0x0008,0,0)),
/* 10**26 */ Decimal(_length: 6, _isCompact: 0, _mantissa: (0x0000, 0xe400, 0x0cd2, 0xdcc8, 0xb7d2, 0x0052,0,0)),
/* 10**27 */ Decimal(_length: 6, _isCompact: 0, _mantissa: (0x0000, 0xe800, 0x803c, 0x9fd0, 0x2e3c, 0x033b,0,0)),
/* 10**28 */ Decimal(_length: 6, _isCompact: 0, _mantissa: (0x0000, 0x1000, 0x0261, 0x3e25, 0xce5e, 0x204f,0,0)),
/* 10**29 */ Decimal(_length: 7, _isCompact: 0, _mantissa: (0x0000, 0xa000, 0x17ca, 0x6d72, 0x0fae, 0x431e, 0x0001,0)),
/* 10**30 */ Decimal(_length: 7, _isCompact: 0, _mantissa: (0x0000, 0x4000, 0xedea, 0x4674, 0x9cd0, 0x9f2c, 0x000c,0)),
/* 10**31 */ Decimal(_length: 7, _isCompact: 0, _mantissa: (0x0000, 0x8000, 0x4b26, 0xc091, 0x2022, 0x37be, 0x007e,0)),
/* 10**32 */ Decimal(_length: 7, _isCompact: 0, _mantissa: (0x0000, 0x0000, 0xef81, 0x85ac, 0x415b, 0x2d6d, 0x04ee,0)),
/* 10**33 */ Decimal(_length: 7, _isCompact: 0, _mantissa: (0x0000, 0x0000, 0x5b0a, 0x38c1, 0x8d93, 0xc644, 0x314d,0)),
/* 10**34 */ Decimal(_length: 8, _isCompact: 0, _mantissa: (0x0000, 0x0000, 0x8e64, 0x378d, 0x87c0, 0xbead, 0xed09, 0x0001)),
/* 10**35 */ Decimal(_length: 8, _isCompact: 0, _mantissa: (0x0000, 0x0000, 0x8fe8, 0x2b87, 0x4d82, 0x72c7, 0x4261, 0x0013)),
/* 10**36 */ Decimal(_length: 8, _isCompact: 0, _mantissa: (0x0000, 0x0000, 0x9f10, 0xb34b, 0x0715, 0x7bc9, 0x97ce, 0x00c0)),
/* 10**37 */ Decimal(_length: 8, _isCompact: 0, _mantissa: (0x0000, 0x0000, 0x36a0, 0x00f4, 0x46d9, 0xd5da, 0xee10, 0x0785)),
/* 10**38 */ Decimal(_length: 8, _isCompact: 0, _mantissa: (0x0000, 0x0000, 0x2240, 0x098a, 0xc47a, 0x5a86, 0x4ca8, 0x4b3b))
/* 10**39 is on 9 shorts. */
]
private let _powersOfTenDividingUInt128Max = [
/* 10**00 dividing UInt128.max is deliberately omitted. */
/* 10**01 */ Decimal(_length: 8, _isCompact: 1, _mantissa: (0x9999, 0x9999, 0x9999, 0x9999, 0x9999, 0x9999, 0x9999, 0x1999)),
/* 10**02 */ Decimal(_length: 8, _isCompact: 1, _mantissa: (0xf5c2, 0x5c28, 0xc28f, 0x28f5, 0x8f5c, 0xf5c2, 0x5c28, 0x028f)),
/* 10**03 */ Decimal(_length: 8, _isCompact: 1, _mantissa: (0x1893, 0x5604, 0x2d0e, 0x9db2, 0xa7ef, 0x4bc6, 0x8937, 0x0041)),
/* 10**04 */ Decimal(_length: 8, _isCompact: 1, _mantissa: (0x0275, 0x089a, 0x9e1b, 0x295e, 0x10cb, 0xbac7, 0x8db8, 0x0006)),
/* 10**05 */ Decimal(_length: 7, _isCompact: 1, _mantissa: (0x3372, 0x80dc, 0x0fcf, 0x8423, 0x1b47, 0xac47, 0xa7c5,0)),
/* 10**06 */ Decimal(_length: 7, _isCompact: 1, _mantissa: (0x3858, 0xf349, 0xb4c7, 0x8d36, 0xb5ed, 0xf7a0, 0x10c6,0)),
/* 10**07 */ Decimal(_length: 7, _isCompact: 1, _mantissa: (0xec08, 0x6520, 0x787a, 0xf485, 0xabca, 0x7f29, 0x01ad,0)),
/* 10**08 */ Decimal(_length: 7, _isCompact: 1, _mantissa: (0x4acd, 0x7083, 0xbf3f, 0x1873, 0xc461, 0xf31d, 0x002a,0)),
/* 10**09 */ Decimal(_length: 7, _isCompact: 1, _mantissa: (0x5447, 0x8b40, 0x2cb9, 0xb5a5, 0xfa09, 0x4b82, 0x0004,0)),
/* 10**10 */ Decimal(_length: 6, _isCompact: 1, _mantissa: (0xa207, 0x5ab9, 0xeadf, 0x5ef6, 0x7f67, 0x6df3,0,0)),
/* 10**11 */ Decimal(_length: 6, _isCompact: 1, _mantissa: (0xf69a, 0xef78, 0x4aaf, 0xbcb2, 0xbff0, 0x0afe,0,0)),
/* 10**12 */ Decimal(_length: 6, _isCompact: 1, _mantissa: (0x7f0f, 0x97f2, 0xa111, 0x12de, 0x7998, 0x0119,0,0)),
/* 10**13 */ Decimal(_length: 6, _isCompact: 0, _mantissa: (0x0cb4, 0xc265, 0x7681, 0x6849, 0x25c2, 0x001c,0,0)),
/* 10**14 */ Decimal(_length: 6, _isCompact: 1, _mantissa: (0x4e12, 0x603d, 0x2573, 0x70d4, 0xd093, 0x0002,0,0)),
/* 10**15 */ Decimal(_length: 5, _isCompact: 1, _mantissa: (0x87ce, 0x566c, 0x9d58, 0xbe7b, 0x480e,0,0,0)),
/* 10**16 */ Decimal(_length: 5, _isCompact: 1, _mantissa: (0xda61, 0x6f0a, 0xf622, 0xaca5, 0x0734,0,0,0)),
/* 10**17 */ Decimal(_length: 5, _isCompact: 1, _mantissa: (0x4909, 0xa4b4, 0x3236, 0x77aa, 0x00b8,0,0,0)),
/* 10**18 */ Decimal(_length: 5, _isCompact: 1, _mantissa: (0xa0e7, 0x43ab, 0xd1d2, 0x725d, 0x0012,0,0,0)),
/* 10**19 */ Decimal(_length: 5, _isCompact: 1, _mantissa: (0xc34a, 0x6d2a, 0x94fb, 0xd83c, 0x0001,0,0,0)),
/* 10**20 */ Decimal(_length: 4, _isCompact: 1, _mantissa: (0x46ba, 0x2484, 0x4219, 0x2f39,0,0,0,0)),
/* 10**21 */ Decimal(_length: 4, _isCompact: 1, _mantissa: (0xd3df, 0x83a6, 0xed02, 0x04b8,0,0,0,0)),
/* 10**22 */ Decimal(_length: 4, _isCompact: 1, _mantissa: (0x7b96, 0x405d, 0xe480, 0x0078,0,0,0,0)),
/* 10**23 */ Decimal(_length: 4, _isCompact: 1, _mantissa: (0x5928, 0xa009, 0x16d9, 0x000c,0,0,0,0)),
/* 10**24 */ Decimal(_length: 4, _isCompact: 1, _mantissa: (0x88ea, 0x299a, 0x357c, 0x0001,0,0,0,0)),
/* 10**25 */ Decimal(_length: 3, _isCompact: 1, _mantissa: (0xda7d, 0xd0f5, 0x1ef2,0,0,0,0,0)),
/* 10**26 */ Decimal(_length: 3, _isCompact: 1, _mantissa: (0x95d9, 0x4818, 0x0318,0,0,0,0,0)),
/* 10**27 */ Decimal(_length: 3, _isCompact: 0, _mantissa: (0xdbc8, 0x3a68, 0x004f,0,0,0,0,0)),
/* 10**28 */ Decimal(_length: 3, _isCompact: 1, _mantissa: (0xaf94, 0xec3d, 0x0007,0,0,0,0,0)),
/* 10**29 */ Decimal(_length: 2, _isCompact: 1, _mantissa: (0xf7f5, 0xcad2,0,0,0,0,0,0)),
/* 10**30 */ Decimal(_length: 2, _isCompact: 1, _mantissa: (0x4bfe, 0x1448,0,0,0,0,0,0)),
/* 10**31 */ Decimal(_length: 2, _isCompact: 1, _mantissa: (0x3acc, 0x0207,0,0,0,0,0,0)),
/* 10**32 */ Decimal(_length: 2, _isCompact: 1, _mantissa: (0xec47, 0x0033,0,0,0,0,0,0)),
/* 10**33 */ Decimal(_length: 2, _isCompact: 1, _mantissa: (0x313a, 0x0005,0,0,0,0,0,0)),
/* 10**34 */ Decimal(_length: 1, _isCompact: 1, _mantissa: (0x84ec,0,0,0,0,0,0,0)),
/* 10**35 */ Decimal(_length: 1, _isCompact: 1, _mantissa: (0x0d4a,0,0,0,0,0,0,0)),
/* 10**36 */ Decimal(_length: 1, _isCompact: 0, _mantissa: (0x0154,0,0,0,0,0,0,0)),
/* 10**37 */ Decimal(_length: 1, _isCompact: 1, _mantissa: (0x0022,0,0,0,0,0,0,0)),
/* 10**38 */ Decimal(_length: 1, _isCompact: 1, _mantissa: (0x0003,0,0,0,0,0,0,0))
]
// The methods in this extension exist to match the protocol requirements of
// FloatingPoint, even if we can't conform directly.
//
// If it becomes clear that conformance is truly impossible, we can deprecate
// some of the methods (e.g. `isEqual(to:)` in favor of operators).
extension Decimal {
public static let greatestFiniteMagnitude = Decimal(
_exponent: 127,
_length: 8,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)
)
public static let leastNormalMagnitude = Decimal(
_exponent: -128,
_length: 1,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)
)
public static let leastNonzeroMagnitude = leastNormalMagnitude
@available(*, deprecated, message: "Use '-Decimal.greatestFiniteMagnitude' for least finite value or '0' for least finite magnitude")
public static let leastFiniteMagnitude = -greatestFiniteMagnitude
public static let pi = Decimal(
_exponent: -38,
_length: 8,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58)
)
@available(*, unavailable, message: "Decimal does not fully adopt FloatingPoint.")
public static var infinity: Decimal { fatalError("Decimal does not fully adopt FloatingPoint") }
@available(*, unavailable, message: "Decimal does not fully adopt FloatingPoint.")
public static var signalingNaN: Decimal { fatalError("Decimal does not fully adopt FloatingPoint") }
public static var quietNaN: Decimal {
return Decimal(
_exponent: 0, _length: 0, _isNegative: 1, _isCompact: 0,
_reserved: 0, _mantissa: (0, 0, 0, 0, 0, 0, 0, 0))
}
public static var nan: Decimal { quietNaN }
public static var radix: Int { 10 }
public init(_ value: UInt8) {
self.init(UInt64(value))
}
public init(_ value: Int8) {
self.init(Int64(value))
}
public init(_ value: UInt16) {
self.init(UInt64(value))
}
public init(_ value: Int16) {
self.init(Int64(value))
}
public init(_ value: UInt32) {
self.init(UInt64(value))
}
public init(_ value: Int32) {
self.init(Int64(value))
}
public init(_ value: UInt64) {
self = Decimal()
if value == 0 {
return
}
var compactValue = value
var exponent: Int32 = 0
while compactValue % 10 == 0 {
compactValue /= 10
exponent += 1
}
_isCompact = 1
_exponent = exponent
let wordCount = ((UInt64.bitWidth - compactValue.leadingZeroBitCount) + (UInt16.bitWidth - 1)) / UInt16.bitWidth
_length = UInt32(wordCount)
_mantissa.0 = UInt16(truncatingIfNeeded: compactValue >> 0)
_mantissa.1 = UInt16(truncatingIfNeeded: compactValue >> 16)
_mantissa.2 = UInt16(truncatingIfNeeded: compactValue >> 32)
_mantissa.3 = UInt16(truncatingIfNeeded: compactValue >> 48)
}
public init(_ value: Int64) {
self.init(value.magnitude)
if value < 0 {
_isNegative = 1
}
}
public init(_ value: UInt) {
self.init(UInt64(value))
}
public init(_ value: Int) {
self.init(Int64(value))
}
public init(_ value: Double) {
precondition(!value.isInfinite, "Decimal does not fully adopt FloatingPoint")
if value.isNaN {
self = Decimal.nan
} else if value == 0.0 {
self = Decimal()
} else {
self = Decimal()
let negative = value < 0
var val = negative ? -1 * value : value
var exponent: Int8 = 0
// Try to get val as close to UInt64.max whilst adjusting the exponent
// to reduce the number of digits after the decimal point.
while val < Double(UInt64.max - 1) {
guard exponent > Int8.min else {
self = Decimal.nan
return
}
val *= 10.0
exponent -= 1
}
while Double(UInt64.max) <= val {
guard exponent < Int8.max else {
self = Decimal.nan
return
}
val /= 10.0
exponent += 1
}
var mantissa: UInt64
let maxMantissa = Double(UInt64.max).nextDown
if val > maxMantissa {
// UInt64(Double(UInt64.max)) gives an overflow error; this is the largest
// mantissa that can be set.
mantissa = UInt64(maxMantissa)
} else {
mantissa = UInt64(val)
}
var i: UInt32 = 0
// This is a bit ugly but it is the closest approximation of the C
// initializer that can be expressed here.
while mantissa != 0 && i < NSDecimalMaxSize {
switch i {
case 0:
_mantissa.0 = UInt16(truncatingIfNeeded: mantissa)
case 1:
_mantissa.1 = UInt16(truncatingIfNeeded: mantissa)
case 2:
_mantissa.2 = UInt16(truncatingIfNeeded: mantissa)
case 3:
_mantissa.3 = UInt16(truncatingIfNeeded: mantissa)
case 4:
_mantissa.4 = UInt16(truncatingIfNeeded: mantissa)
case 5:
_mantissa.5 = UInt16(truncatingIfNeeded: mantissa)
case 6:
_mantissa.6 = UInt16(truncatingIfNeeded: mantissa)
case 7:
_mantissa.7 = UInt16(truncatingIfNeeded: mantissa)
default:
fatalError("initialization overflow")
}
mantissa = mantissa >> 16
i += 1
}
_length = i
_isNegative = negative ? 1 : 0
_isCompact = 0
_exponent = Int32(exponent)
self.compact()
}
}
public init(sign: FloatingPointSign, exponent: Int, significand: Decimal) {
self = significand
let error = withUnsafeMutablePointer(to: &self) {
NSDecimalMultiplyByPowerOf10($0, $0, Int16(clamping: exponent), .plain)
}
if error == .underflow { self = 0 }
// We don't need to check for overflow because `Decimal` cannot represent infinity.
if sign == .minus { negate() }
}
public init(signOf: Decimal, magnitudeOf magnitude: Decimal) {
self.init(
_exponent: magnitude._exponent,
_length: magnitude._length,
_isNegative: signOf._isNegative,
_isCompact: magnitude._isCompact,
_reserved: 0,
_mantissa: magnitude._mantissa)
}
public var exponent: Int {
return Int(_exponent)
}
public var significand: Decimal {
return Decimal(
_exponent: 0, _length: _length, _isNegative: 0, _isCompact: _isCompact,
_reserved: 0, _mantissa: _mantissa)
}
public var sign: FloatingPointSign {
return _isNegative == 0 ? FloatingPointSign.plus : FloatingPointSign.minus
}
public var ulp: Decimal {
guard isFinite else { return .nan }
let exponent: Int32
if isZero {
exponent = .min
} else {
let significand_ = significand
let shift =
_powersOfTenDividingUInt128Max.firstIndex { significand_ > $0 }
?? _powersOfTenDividingUInt128Max.count
exponent = _exponent &- Int32(shift)
}
return Decimal(
_exponent: max(exponent, -128), _length: 1, _isNegative: 0, _isCompact: 1,
_reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
public var nextUp: Decimal {
if _isNegative == 1 {
if _exponent > -128
&& (_mantissa.0, _mantissa.1, _mantissa.2, _mantissa.3) == (0x999a, 0x9999, 0x9999, 0x9999)
&& (_mantissa.4, _mantissa.5, _mantissa.6, _mantissa.7) == (0x9999, 0x9999, 0x9999, 0x1999) {
return Decimal(
_exponent: _exponent &- 1, _length: 8, _isNegative: 1, _isCompact: 1,
_reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff))
}
} else {
if _exponent < 127
&& (_mantissa.0, _mantissa.1, _mantissa.2, _mantissa.3) == (0xffff, 0xffff, 0xffff, 0xffff)
&& (_mantissa.4, _mantissa.5, _mantissa.6, _mantissa.7) == (0xffff, 0xffff, 0xffff, 0xffff) {
return Decimal(
_exponent: _exponent &+ 1, _length: 8, _isNegative: 0, _isCompact: 1,
_reserved: 0, _mantissa: (0x999a, 0x9999, 0x9999, 0x9999, 0x9999, 0x9999, 0x9999, 0x1999))
}
}
return self + ulp
}
public var nextDown: Decimal {
return -(-self).nextUp
}
/// The IEEE 754 "class" of this type.
public var floatingPointClass: FloatingPointClassification {
if _length == 0 && _isNegative == 1 {
return .quietNaN
} else if _length == 0 {
return .positiveZero
}
// NSDecimal does not really represent normal and subnormal in the same
// manner as the IEEE standard, for now we can probably claim normal for
// any nonzero, non-NaN values.
if _isNegative == 1 {
return .negativeNormal
} else {
return .positiveNormal
}
}
public var isCanonical: Bool { true }
/// `true` iff `self` is negative.
public var isSignMinus: Bool { _isNegative != 0 }
/// `true` iff `self` is +0.0 or -0.0.
public var isZero: Bool { _length == 0 && _isNegative == 0 }
/// `true` iff `self` is subnormal.
public var isSubnormal: Bool { false }
/// `true` iff `self` is normal (not zero, subnormal, infinity, or NaN).
public var isNormal: Bool { !isZero && !isInfinite && !isNaN }
/// `true` iff `self` is zero, subnormal, or normal (not infinity or NaN).
public var isFinite: Bool { !isNaN }
/// `true` iff `self` is infinity.
public var isInfinite: Bool { false }
/// `true` iff `self` is NaN.
public var isNaN: Bool { _length == 0 && _isNegative == 1 }
/// `true` iff `self` is a signaling NaN.
public var isSignaling: Bool { false }
/// `true` iff `self` is a signaling NaN.
public var isSignalingNaN: Bool { false }
public func isEqual(to other: Decimal) -> Bool {
return self.compare(to: other) == .orderedSame
}
public func isLess(than other: Decimal) -> Bool {
return self.compare(to: other) == .orderedAscending
}
public func isLessThanOrEqualTo(_ other: Decimal) -> Bool {
let comparison = self.compare(to: other)
return comparison == .orderedAscending || comparison == .orderedSame
}
public func isTotallyOrdered(belowOrEqualTo other: Decimal) -> Bool {
// Note: Decimal does not have -0 or infinities to worry about
if self.isNaN {
return false
}
if self < other {
return true
}
if other < self {
return false
}
// Fall through to == behavior
return true
}
@available(*, unavailable, message: "Decimal does not fully adopt FloatingPoint.")
public mutating func formTruncatingRemainder(dividingBy other: Decimal) { fatalError("Decimal does not fully adopt FloatingPoint") }
}
extension Decimal: _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSDecimalNumber {
return NSDecimalNumber(decimal: self)
}
public static func _forceBridgeFromObjectiveC(_ x: NSDecimalNumber, result: inout Decimal?) {
result = _unconditionallyBridgeFromObjectiveC(x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSDecimalNumber, result: inout Decimal?) -> Bool {
result = x.decimalValue
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDecimalNumber?) -> Decimal {
var result: Decimal?
guard let src = source else { return Decimal(0) }
guard _conditionallyBridgeFromObjectiveC(src, result: &result) else { return Decimal(0) }
return result!
}
}
// MARK: - End of conformances shared with Darwin overlay
fileprivate func divideByShort<T:VariableLengthNumber>(_ d: inout T, _ divisor:UInt16) -> (UInt16,NSDecimalNumber.CalculationError) {
if divisor == 0 {
d._length = 0
return (0,.divideByZero)
}
// note the below is not the same as from length to 0 by -1
var carry: UInt32 = 0
for i in (0..<d._length).reversed() {
let accumulator = UInt32(d[i]) + carry * (1<<16)
d[i] = UInt16(accumulator / UInt32(divisor))
carry = accumulator % UInt32(divisor)
}
d.trimTrailingZeros()
return (UInt16(carry),.noError)
}
fileprivate func multiplyByShort<T:VariableLengthNumber>(_ d: inout T, _ mul:UInt16) -> NSDecimalNumber.CalculationError {
if mul == 0 {
d._length = 0
return .noError
}
var carry: UInt32 = 0
// FIXME handle NSCalculationOverflow here?
for i in 0..<d._length {
let accumulator: UInt32 = UInt32(d[i]) * UInt32(mul) + carry
carry = accumulator >> 16
d[i] = UInt16(truncatingIfNeeded: accumulator)
}
if carry != 0 {
if d._length >= Decimal.maxSize {
return .overflow
}
d[d._length] = UInt16(truncatingIfNeeded: carry)
d._length += 1
}
return .noError
}
fileprivate func addShort<T:VariableLengthNumber>(_ d: inout T, _ add:UInt16) -> NSDecimalNumber.CalculationError {
var carry:UInt32 = UInt32(add)
for i in 0..<d._length {
let accumulator: UInt32 = UInt32(d[i]) + carry
carry = accumulator >> 16
d[i] = UInt16(truncatingIfNeeded: accumulator)
}
if carry != 0 {
if d._length >= Decimal.maxSize {
return .overflow
}
d[d._length] = UInt16(truncatingIfNeeded: carry)
d._length += 1
}
return .noError
}
public func NSDecimalIsNotANumber(_ dcm: UnsafePointer<Decimal>) -> Bool {
return dcm.pointee.isNaN
}
/*************** Operations ***********/
public func NSDecimalCopy(_ destination: UnsafeMutablePointer<Decimal>, _ source: UnsafePointer<Decimal>) {
destination.pointee.__lengthAndFlags = source.pointee.__lengthAndFlags
destination.pointee.__exponent = source.pointee.__exponent
destination.pointee.__reserved = source.pointee.__reserved
destination.pointee._mantissa = source.pointee._mantissa
}
public func NSDecimalCompact(_ number: UnsafeMutablePointer<Decimal>) {
number.pointee.compact()
}
// NSDecimalCompare:Compares leftOperand and rightOperand.
public func NSDecimalCompare(_ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>) -> ComparisonResult {
let left = leftOperand.pointee
let right = rightOperand.pointee
return left.compare(to: right)
}
fileprivate extension UInt16 {
func compareTo(_ other: UInt16) -> ComparisonResult {
if self < other {
return .orderedAscending
} else if self > other {
return .orderedDescending
} else {
return .orderedSame
}
}
}
fileprivate func mantissaCompare<T:VariableLengthNumber>(
_ left: T,
_ right: T) -> ComparisonResult {
if left._length > right._length {
return .orderedDescending
}
if left._length < right._length {
return .orderedAscending
}
let length = left._length // == right._length
for i in (0..<length).reversed() {
let comparison = left[i].compareTo(right[i])
if comparison != .orderedSame {
return comparison
}
}
return .orderedSame
}
fileprivate func fitMantissa(_ big: inout WideDecimal, _ exponent: inout Int32, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if big._length <= Decimal.maxSize {
return .noError
}
var remainder: UInt16 = 0
var previousRemainder: Bool = false
// Divide by 10 as much as possible
while big._length > Decimal.maxSize + 1 {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&big,10000)
exponent += 4
}
while big._length > Decimal.maxSize {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&big,10)
exponent += 1
}
// If we are on a tie, adjust with previous remainder.
// .50001 is equivalent to .6
if previousRemainder && (remainder == 0 || remainder == 5) {
remainder += 1
}
if remainder == 0 {
return .noError
}
// Round the result
switch roundingMode {
case .down:
break
case .bankers:
if remainder == 5 && (big[0] & 1) == 0 {
break
}
fallthrough
case .plain:
if remainder < 5 {
break
}
fallthrough
case .up:
let originalLength = big._length
// big._length += 1 ??
_ = addShort(&big,1)
if originalLength > big._length {
// the last digit is == 0. Remove it.
_ = divideByShort(&big, 10)
exponent += 1
}
}
return .lossOfPrecision;
}
fileprivate func integerMultiply<T:VariableLengthNumber>(_ big: inout T,
_ left: T,
_ right: Decimal) -> NSDecimalNumber.CalculationError {
if left._length == 0 || right._length == 0 {
big._length = 0
return .noError
}
if big._length == 0 || big._length > left._length + right._length {
big._length = min(big.maxMantissaLength,left._length + right._length)
}
big.zeroMantissa()
var carry: UInt16 = 0
for j in 0..<right._length {
var accumulator: UInt32 = 0
carry = 0
for i in 0..<left._length {
if i + j < big._length {
let bigij = UInt32(big[i+j])
accumulator = UInt32(carry) + bigij + UInt32(right[j]) * UInt32(left[i])
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
big[i+j] = UInt16(truncatingIfNeeded:accumulator)
} else if carry != 0 || (right[j] > 0 && left[i] > 0) {
return .overflow
}
}
if carry != 0 {
if left._length + j < big._length {
big[left._length + j] = carry
} else {
return .overflow
}
}
}
big.trimTrailingZeros()
return .noError
}
fileprivate func integerDivide<T:VariableLengthNumber>(_ r: inout T,
_ cu: T,
_ cv: Decimal) -> NSDecimalNumber.CalculationError {
// Calculate result = a / b.
// Result could NOT be a pointer to same space as a or b.
// resultLen must be >= aLen - bLen.
//
// Based on algorithm in The Art of Computer Programming, Volume 2,
// Seminumerical Algorithms by Donald E. Knuth, 2nd Edition. In addition
// you need to consult the erratas for the book available at:
//
// http://www-cs-faculty.stanford.edu/~uno/taocp.html
var u = WideDecimal(true)
var v = WideDecimal(true) // divisor
// Simple case
if cv.isZero {
return .divideByZero;
}
// If u < v, the result is approximately 0...
if cu._length < cv._length {
for i in 0..<cv._length {
if cu[i] < cv[i] {
r._length = 0
return .noError;
}
}
}
// Fast algorithm
if cv._length == 1 {
r = cu
let (_,error) = divideByShort(&r, cv[0])
return error
}
u.copyMantissa(from: cu)
v.copyMantissa(from: cv)
u._length = cu._length + 1
v._length = cv._length + 1
// D1: Normalize
// Calculate d such that d*highest_digit of v >= b/2 (0x8000)
//
// I could probably use something smarter to get d to be a power of 2.
// In this case the multiply below became only a shift.
let d: UInt32 = UInt32((1 << 16) / Int(cv[cv._length - 1] + 1))
// This is to make the whole algorithm work and u*d/v*d == u/v
_ = multiplyByShort(&u, UInt16(d))
_ = multiplyByShort(&v, UInt16(d))
u.trimTrailingZeros()
v.trimTrailingZeros()
// Set a zero at the leftmost u position if the multiplication
// does not have a carry.
if u._length == cu._length {
u[u._length] = 0
u._length += 1
}
v[v._length] = 0; // Set a zero at the leftmost v position.
// the algorithm will use it during the
// multiplication/subtraction phase.
// Determine the size of the quotient.
// It's an approximate value.
let ql:UInt16 = UInt16(u._length - v._length)
// Some useful constants for the loop
// It's used to determine the quotient digit as fast as possible
// The test vl > 1 is probably useless, since optimizations
// up there are taking over this case. I'll keep it, just in case.
let v1:UInt16 = v[v._length-1]
let v2:UInt16 = v._length > 1 ? v[v._length-2] : 0
// D2: initialize j
// On each pass, build a single value for the quotient.
for j in 0..<ql {
// D3: calculate q^
// This formula and test for q gives at most q+1; See Knuth for proof.
let ul = u._length
let tmp:UInt32 = UInt32(u[ul - UInt32(j) - UInt32(1)]) << 16 + UInt32(u[ul - UInt32(j) - UInt32(2)])
var q:UInt32 = tmp / UInt32(v1) // Quotient digit. could be a short.
var rtmp:UInt32 = tmp % UInt32(v1)
// This test catches all cases where q is really q+2 and
// most where it is q+1
if q == (1 << 16) || UInt32(v2) * q > (rtmp<<16) + UInt32(u[ul - UInt32(j) - UInt32(3)]) {
q -= 1
rtmp += UInt32(v1)
if (rtmp < (1 << 16)) && ( (q == (1 << 16) ) || ( UInt32(v2) * q > (rtmp<<16) + UInt32(u[ul - UInt32(j) - UInt32(3)])) ) {
q -= 1
rtmp += UInt32(v1)
}
}
// D4: multiply and subtract.
var mk:UInt32 = 0 // multiply carry
var sk:UInt32 = 1 // subtraction carry
var acc:UInt32
// We perform a multiplication and a subtraction
// during the same pass...
for i in 0...v._length {
let ul = u._length
let vl = v._length
acc = q * UInt32(v[i]) + mk // multiply
mk = acc >> 16 // multiplication carry
acc = acc & 0xffff;
acc = 0xffff + UInt32(u[ul - vl + i - UInt32(j) - UInt32(1)]) - acc + sk; // subtract
sk = acc >> 16;
u[ul - vl + i - UInt32(j) - UInt32(1)] = UInt16(truncatingIfNeeded:acc)
}
// D5: test remainder
// This test catches cases where q is still q + 1
if sk == 0 {
// D6: add back.
var k:UInt32 = 0 // Addition carry
// subtract one from the quotient digit
q -= 1
for i in 0...v._length {
let ul = u._length
let vl = v._length
acc = UInt32(v[i]) + UInt32(u[UInt32(ul) - UInt32(vl) + UInt32(i) - UInt32(j) - UInt32(1)]) + k
k = acc >> 16;
u[UInt32(ul) - UInt32(vl) + UInt32(i) - UInt32(j) - UInt32(1)] = UInt16(truncatingIfNeeded:acc)
}
// k must be == 1 here
}
r[UInt32(ql - j - UInt16(1))] = UInt16(q)
// D7: loop on j
}
r._length = UInt32(ql);
r.trimTrailingZeros()
return .noError;
}
fileprivate func integerMultiplyByPowerOf10<T:VariableLengthNumber>(_ result: inout T, _ left: T, _ p: Int) -> NSDecimalNumber.CalculationError {
var power = p
if power == 0 {
result = left
return .noError
}
let isNegative = power < 0
if isNegative {
power = -power
}
result = left
let maxpow10 = _powersOfTen.count - 1
var error:NSDecimalNumber.CalculationError = .noError
while power > maxpow10 {
var big = T()
power -= maxpow10
let p10 = _powersOfTen[maxpow10]
if !isNegative {
error = integerMultiply(&big,result,p10)
} else {
error = integerDivide(&big,result,p10)
}
if error != .noError && error != .lossOfPrecision {
return error;
}
for i in 0..<big._length {
result[i] = big[i]
}
result._length = big._length
}
var big = T()
// Handle the rest of the power (<= maxpow10)
let p10 = _powersOfTen[Int(power)]
if !isNegative {
error = integerMultiply(&big, result, p10)
} else {
error = integerDivide(&big, result, p10)
}
for i in 0..<big._length {
result[i] = big[i]
}
result._length = big._length
return error;
}
public func NSDecimalRound(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) {
NSDecimalCopy(result,number) // this is unnecessary if they are the same address, but we can't test that here
result.pointee.round(scale: scale,roundingMode: roundingMode)
}
// Rounds num to the given scale using the given mode.
// result may be a pointer to same space as num.
// scale indicates number of significant digits after the decimal point
public func NSDecimalNormalize(_ a: UnsafeMutablePointer<Decimal>, _ b: UnsafeMutablePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
var diffexp = Int(a.pointee.__exponent) - Int(b.pointee.__exponent)
var result = Decimal()
//
// If the two numbers share the same exponents,
// the normalisation is already done
//
if diffexp == 0 {
return .noError
}
//
// Put the smallest of the two in aa
//
var aa: UnsafeMutablePointer<Decimal>
var bb: UnsafeMutablePointer<Decimal>
if diffexp < 0 {
aa = b
bb = a
diffexp = -diffexp
} else {
aa = a
bb = b
}
//
// Build a backup for aa
//
var backup = Decimal()
NSDecimalCopy(&backup,aa)
//
// Try to multiply aa to reach the same exponent level than bb
//
if integerMultiplyByPowerOf10(&result, aa.pointee, diffexp) == .noError {
// Succeed. Adjust the length/exponent info
// and return no errorNSDecimalNormalize
aa.pointee.copyMantissa(from: result)
aa.pointee._exponent = bb.pointee._exponent
return .noError;
}
//
// Failed, restart from scratch
//
NSDecimalCopy(aa, &backup);
//
// What is the maximum pow10 we can apply to aa ?
//
let logBase10of2to16 = 4.81647993
let aaLength = aa.pointee._length
let maxpow10 = Int8(floor(Double(Decimal.maxSize - aaLength) * logBase10of2to16))
//
// Divide bb by this value
//
_ = integerMultiplyByPowerOf10(&result, bb.pointee, Int(maxpow10) - diffexp)
bb.pointee.copyMantissa(from: result)
bb.pointee._exponent -= (Int32(maxpow10) - Int32(diffexp))
//
// If bb > 0 multiply aa by the same value
//
if !bb.pointee.isZero {
_ = integerMultiplyByPowerOf10(&result, aa.pointee, Int(maxpow10))
aa.pointee.copyMantissa(from: result)
aa.pointee._exponent -= Int32(maxpow10)
} else {
bb.pointee._exponent = aa.pointee._exponent;
}
//
// the two exponents are now identical, but we've lost some digits in the operation.
//
return .lossOfPrecision;
}
public func NSDecimalAdd(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
if leftOperand.pointee.isZero {
NSDecimalCopy(result, rightOperand)
return .noError
} else if rightOperand.pointee.isZero {
NSDecimalCopy(result, leftOperand)
return .noError
} else {
var a = Decimal()
var b = Decimal()
var error:NSDecimalNumber.CalculationError = .noError
NSDecimalCopy(&a,leftOperand)
NSDecimalCopy(&b,rightOperand)
let normalizeError = NSDecimalNormalize(&a, &b,roundingMode)
if a.isZero {
NSDecimalCopy(result,&b)
return normalizeError
}
if b.isZero {
NSDecimalCopy(result,&a)
return normalizeError
}
result.pointee._exponent = a._exponent
if a.isNegative == b.isNegative {
var big = WideDecimal()
result.pointee.isNegative = a.isNegative
// No possible error here.
_ = integerAdd(&big,&a,&b)
if big._length > Decimal.maxSize {
var exponent:Int32 = 0
error = fitMantissa(&big, &exponent, roundingMode)
let newExponent = result.pointee._exponent + exponent
// Just to be sure!
if newExponent > Int32(Int8.max) {
result.pointee.setNaN()
return .overflow
}
result.pointee._exponent = newExponent
}
let length = min(Decimal.maxSize,big._length)
for i in 0..<length {
result.pointee[i] = big[i]
}
result.pointee._length = length
} else { // not the same sign
let comparison = mantissaCompare(a,b)
switch comparison {
case .orderedSame:
result.pointee.setZero()
case .orderedAscending:
_ = integerSubtract(&result.pointee,&b,&a)
result.pointee.isNegative = b.isNegative
case .orderedDescending:
_ = integerSubtract(&result.pointee,&a,&b)
result.pointee.isNegative = a.isNegative
}
}
result.pointee._isCompact = 0
NSDecimalCompact(result)
return error == .noError ? normalizeError : error
}
}
fileprivate func integerAdd(_ result: inout WideDecimal, _ left: inout Decimal, _ right: inout Decimal) -> NSDecimalNumber.CalculationError {
var idx: UInt32 = 0
var carry: UInt16 = 0
let maxIndex: UInt32 = min(left._length, right._length) // The highest index with bits set in both values
while idx < maxIndex {
let li = UInt32(left[idx])
let ri = UInt32(right[idx])
let sum = li + ri + UInt32(carry)
carry = UInt16(truncatingIfNeeded: sum >> 16)
result[idx] = UInt16(truncatingIfNeeded: sum)
idx += 1
}
while idx < left._length {
if carry != 0 {
let li = UInt32(left[idx])
let sum = li + UInt32(carry)
carry = UInt16(truncatingIfNeeded: sum >> 16)
result[idx] = UInt16(truncatingIfNeeded: sum)
idx += 1
} else {
while idx < left._length {
result[idx] = left[idx]
idx += 1
}
break
}
}
while idx < right._length {
if carry != 0 {
let ri = UInt32(right[idx])
let sum = ri + UInt32(carry)
carry = UInt16(truncatingIfNeeded: sum >> 16)
result[idx] = UInt16(truncatingIfNeeded: sum)
idx += 1
} else {
while idx < right._length {
result[idx] = right[idx]
idx += 1
}
break
}
}
result._length = idx
if carry != 0 {
result[idx] = carry
idx += 1
result._length = idx
}
if idx > Decimal.maxSize {
return .overflow
}
return .noError;
}
// integerSubtract: Subtract b from a, put the result in result, and
// modify resultLen to match the length of the result.
// Result may be a pointer to same space as a or b.
// resultLen must be >= Max(aLen,bLen).
// Could return NSCalculationOverflow if b > a. In this case 0 - result
// give b-a...
//
fileprivate func integerSubtract(_ result: inout Decimal, _ left: inout Decimal, _ right: inout Decimal) -> NSDecimalNumber.CalculationError {
var idx: UInt32 = 0
let maxIndex: UInt32 = min(left._length, right._length) // The highest index with bits set in both values
var borrow: UInt16 = 0
while idx < maxIndex {
let li = UInt32(left[idx])
let ri = UInt32(right[idx])
// 0x10000 is to borrow in advance to avoid underflow.
let difference: UInt32 = (0x10000 + li) - UInt32(borrow) - ri
result[idx] = UInt16(truncatingIfNeeded: difference)
// borrow = 1 if the borrow was used.
borrow = 1 - UInt16(truncatingIfNeeded: difference >> 16)
idx += 1
}
while idx < left._length {
if borrow != 0 {
let li = UInt32(left[idx])
let sum = 0xffff + li // + no carry
borrow = 1 - UInt16(truncatingIfNeeded: sum >> 16)
result[idx] = UInt16(truncatingIfNeeded: sum)
idx += 1
} else {
while idx < left._length {
result[idx] = left[idx]
idx += 1
}
break
}
}
while idx < right._length {
let ri = UInt32(right[idx])
let difference = 0xffff - ri + UInt32(borrow)
borrow = 1 - UInt16(truncatingIfNeeded: difference >> 16)
result[idx] = UInt16(truncatingIfNeeded: difference)
idx += 1
}
if borrow != 0 {
return .overflow
}
result._length = idx;
result.trimTrailingZeros()
return .noError;
}
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalSubtract(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
var r = rightOperand.pointee
r.negate()
return NSDecimalAdd(result, leftOperand, &r, roundingMode)
}
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalMultiply(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
if leftOperand.pointee.isZero || rightOperand.pointee.isZero {
result.pointee.setZero()
return .noError
}
var big = WideDecimal()
var calculationError:NSDecimalNumber.CalculationError = .noError
calculationError = integerMultiply(&big,WideDecimal(leftOperand.pointee),rightOperand.pointee)
result.pointee._isNegative = (leftOperand.pointee._isNegative + rightOperand.pointee._isNegative) % 2
var newExponent = leftOperand.pointee._exponent + rightOperand.pointee._exponent
if big._length > Decimal.maxSize {
var exponent:Int32 = 0
calculationError = fitMantissa(&big, &exponent, roundingMode)
newExponent += exponent
}
for i in 0..<big._length {
result.pointee[i] = big[i]
}
result.pointee._length = big._length
result.pointee._isCompact = 0
if newExponent > Int32(Int8.max) {
result.pointee.setNaN()
return .overflow
}
result.pointee._exponent = newExponent
NSDecimalCompact(result)
return calculationError
}
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalDivide(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
if rightOperand.pointee.isZero {
result.pointee.setNaN()
return .divideByZero
}
if leftOperand.pointee.isZero {
result.pointee.setZero()
return .noError
}
var a = Decimal()
var b = Decimal()
var big = WideDecimal()
var exponent:Int32 = 0
NSDecimalCopy(&a, leftOperand)
NSDecimalCopy(&b, rightOperand)
/* If the precision of the left operand is much smaller
* than that of the right operand (for example,
* 20 and 0.112314123094856724234234572), then the
* difference in their exponents is large and a lot of
* precision will be lost below. This is particularly
* true as the difference approaches 38 or larger.
* Normalizing here looses some precision on the
* individual operands, but often produces a more
* accurate result later. I chose 19 arbitrarily
* as half of the magic 38, so that normalization
* doesn't always occur. */
if (19 <= Int(a._exponent - b._exponent)) {
_ = NSDecimalNormalize(&a, &b, roundingMode);
/* We ignore the small loss of precision this may
* induce in the individual operands. */
/* Sometimes the normalization done previously is inappropriate and
* forces one of the operands to 0. If this happens, restore both. */
if a.isZero || b.isZero {
NSDecimalCopy(&a, leftOperand);
NSDecimalCopy(&b, rightOperand);
}
}
_ = integerMultiplyByPowerOf10(&big, WideDecimal(a), 38) // Trust me, it's 38 !
_ = integerDivide(&big, big, b)
_ = fitMantissa(&big, &exponent, .down)
let length = min(big._length,Decimal.maxSize)
for i in 0..<length {
result.pointee[i] = big[i]
}
result.pointee._length = length
result.pointee.isNegative = a._isNegative != b._isNegative
exponent = a._exponent - b._exponent - 38 + exponent
if exponent < Int32(Int8.min) {
result.pointee.setNaN()
return .underflow
}
if exponent > Int32(Int8.max) {
result.pointee.setNaN()
return .overflow;
}
result.pointee._exponent = Int32(exponent)
result.pointee._isCompact = 0
NSDecimalCompact(result)
return .noError
}
// Division could be silently inexact;
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalPower(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ power: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if number.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
NSDecimalCopy(result,number)
return result.pointee.power(UInt(power), roundingMode:roundingMode)
}
public func NSDecimalMultiplyByPowerOf10(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ power: Int16, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
NSDecimalCopy(result,number)
return result.pointee.multiply(byPowerOf10: power)
}
public func NSDecimalString(_ dcm: UnsafePointer<Decimal>, _ locale: Any?) -> String {
let ZERO: UInt8 = 0x30 // ASCII '0' == 0x30
let zeroString = String(Unicode.Scalar(ZERO)) // "0"
var copy = dcm.pointee
if copy.isNaN {
return "NaN"
}
if copy._length == 0 {
return zeroString
}
let decimalSeparatorReversed: String = {
// Short circuiting for common case that `locale` is `nil`
guard locale != nil else { return "." } // Defaulting to decimal point
var decimalSeparator: String? = nil
if let locale = locale as? Locale {
decimalSeparator = locale.decimalSeparator
} else if let dictionary = locale as? [NSLocale.Key: String] {
decimalSeparator = dictionary[NSLocale.Key.decimalSeparator]
} else if let dictionary = locale as? [String: String] {
decimalSeparator = dictionary[NSLocale.Key.decimalSeparator.rawValue]
}
guard let dc = decimalSeparator else { return "." } // Defaulting to decimal point
return String(dc.reversed())
}()
let resultCount =
(copy.isNegative ? 1 : 0) + // sign, obviously
39 + // mantissa is an 128bit, so log10(2^128) is approx 38.5 giving 39 digits max for the mantissa
(copy._exponent > 0 ? Int(copy._exponent) : decimalSeparatorReversed.count) // trailing zeroes or decimal separator
var result = ""
result.reserveCapacity(resultCount)
while copy._exponent > 0 {
result.append(zeroString)
copy._exponent -= 1
}
if copy._exponent == 0 {
copy._exponent = 1
}
while copy._length != 0 {
var remainder: UInt16 = 0
if copy._exponent == 0 {
result.append(decimalSeparatorReversed)
}
copy._exponent += 1
(remainder, _) = divideByShort(©, 10)
result.append(String(Unicode.Scalar(ZERO + UInt8(remainder))))
}
if copy._exponent <= 0 {
while copy._exponent != 0 {
result.append(zeroString)
copy._exponent += 1
}
result.append(decimalSeparatorReversed)
result.append(zeroString)
}
if copy._isNegative != 0 {
result.append("-")
}
return String(result.reversed())
}
private func multiplyBy10(_ dcm: inout Decimal, andAdd extra:Int) -> NSDecimalNumber.CalculationError {
let backup = dcm
if multiplyByShort(&dcm, 10) == .noError && addShort(&dcm, UInt16(extra)) == .noError {
return .noError
} else {
dcm = backup // restore the old values
return .overflow // this is the only possible error
}
}
fileprivate protocol VariableLengthNumber {
var _length: UInt32 { get set }
init()
subscript(index:UInt32) -> UInt16 { get set }
var isZero:Bool { get }
mutating func copyMantissa<T:VariableLengthNumber>(from other:T)
mutating func zeroMantissa()
mutating func trimTrailingZeros()
var maxMantissaLength: UInt32 { get }
}
extension Decimal: VariableLengthNumber {
var maxMantissaLength:UInt32 {
return Decimal.maxSize
}
fileprivate mutating func zeroMantissa() {
for i in 0..<Decimal.maxSize {
self[i] = 0
}
}
internal mutating func trimTrailingZeros() {
if _length > Decimal.maxSize {
_length = Decimal.maxSize
}
while _length != 0 && self[_length - 1] == 0 {
_length -= 1
}
}
fileprivate mutating func copyMantissa<T : VariableLengthNumber>(from other: T) {
if other._length > maxMantissaLength {
for i in maxMantissaLength..<other._length {
guard other[i] == 0 else {
fatalError("Loss of precision during copy other[\(i)] \(other[i]) != 0")
}
}
}
let length = min(other._length, maxMantissaLength)
for i in 0..<length {
self[i] = other[i]
}
self._length = length
self._isCompact = 0
}
}
// Provides a way with dealing with extra-length decimals, used for calculations
fileprivate struct WideDecimal : VariableLengthNumber {
var maxMantissaLength:UInt32 {
return _extraWide ? 17 : 16
}
fileprivate mutating func zeroMantissa() {
for i in 0..<maxMantissaLength {
self[i] = 0
}
}
fileprivate mutating func trimTrailingZeros() {
while _length != 0 && self[_length - 1] == 0 {
_length -= 1
}
}
init() {
self.init(false)
}
fileprivate mutating func copyMantissa<T : VariableLengthNumber>(from other: T) {
let length = other is Decimal ? min(other._length,Decimal.maxSize) : other._length
for i in 0..<length {
self[i] = other[i]
}
self._length = length
}
var isZero: Bool {
return _length == 0
}
var __length: UInt16
var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16,
UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)
// Most uses of this class use 16 shorts, but integer division uses 17 shorts
var _extraWide: Bool
var _length: UInt32 {
get {
return UInt32(__length)
}
set {
guard newValue <= maxMantissaLength else {
fatalError("Attempt to set a length greater than capacity \(newValue) > \(maxMantissaLength)")
}
__length = UInt16(newValue)
}
}
init(_ extraWide:Bool = false) {
__length = 0
_mantissa = (UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0))
_extraWide = extraWide
}
init(_ decimal:Decimal) {
self.__length = UInt16(decimal._length)
self._extraWide = false
self._mantissa = (decimal[0],decimal[1],decimal[2],decimal[3],decimal[4],decimal[5],decimal[6],decimal[7],UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0))
}
subscript(index:UInt32) -> UInt16 {
get {
switch index {
case 0: return _mantissa.0
case 1: return _mantissa.1
case 2: return _mantissa.2
case 3: return _mantissa.3
case 4: return _mantissa.4
case 5: return _mantissa.5
case 6: return _mantissa.6
case 7: return _mantissa.7
case 8: return _mantissa.8
case 9: return _mantissa.9
case 10: return _mantissa.10
case 11: return _mantissa.11
case 12: return _mantissa.12
case 13: return _mantissa.13
case 14: return _mantissa.14
case 15: return _mantissa.15
case 16 where _extraWide: return _mantissa.16 // used in integerDivide
default: fatalError("Invalid index \(index) for _mantissa")
}
}
set {
switch index {
case 0: _mantissa.0 = newValue
case 1: _mantissa.1 = newValue
case 2: _mantissa.2 = newValue
case 3: _mantissa.3 = newValue
case 4: _mantissa.4 = newValue
case 5: _mantissa.5 = newValue
case 6: _mantissa.6 = newValue
case 7: _mantissa.7 = newValue
case 8: _mantissa.8 = newValue
case 9: _mantissa.9 = newValue
case 10: _mantissa.10 = newValue
case 11: _mantissa.11 = newValue
case 12: _mantissa.12 = newValue
case 13: _mantissa.13 = newValue
case 14: _mantissa.14 = newValue
case 15: _mantissa.15 = newValue
case 16 where _extraWide: _mantissa.16 = newValue
default: fatalError("Invalid index \(index) for _mantissa")
}
}
}
func toDecimal() -> Decimal {
var result = Decimal()
result._length = self._length
for i in 0..<_length {
result[i] = self[i]
}
return result
}
}
// MARK: - Internal (Swifty) functions
extension Decimal {
fileprivate static let maxSize: UInt32 = UInt32(NSDecimalMaxSize)
fileprivate var isCompact: Bool {
get {
return _isCompact != 0
}
set {
_isCompact = newValue ? 1 : 0
}
}
fileprivate var isNegative: Bool {
get {
return _isNegative != 0
}
set {
_isNegative = newValue ? 1 : 0
}
}
fileprivate mutating func compact() {
if isCompact || isNaN || _length == 0 {
return
}
var newExponent = self._exponent
var remainder: UInt16 = 0
// Divide by 10 as much as possible
repeat {
(remainder,_) = divideByShort(&self,10)
newExponent += 1
} while remainder == 0
// Put the non-empty remainder in place
_ = multiplyByShort(&self,10)
_ = addShort(&self,remainder)
newExponent -= 1
// Set the new exponent
while newExponent > Int32(Int8.max) {
_ = multiplyByShort(&self,10)
newExponent -= 1
}
_exponent = newExponent
isCompact = true
}
fileprivate mutating func round(scale:Int, roundingMode:RoundingMode) {
// scale is the number of digits after the decimal point
var s = Int32(scale) + _exponent
if s == NSDecimalNoScale || s >= 0 {
return
}
s = -s
var remainder: UInt16 = 0
var previousRemainder = false
let negative = _isNegative != 0
var newExponent = _exponent + s
while s > 4 {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&self, 10000)
s -= 4
}
while s > 0 {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&self, 10)
s -= 1
}
// If we are on a tie, adjust with premdr. .50001 is equivalent to .6
if previousRemainder && (remainder == 0 || remainder == 5) {
remainder += 1;
}
if remainder != 0 {
if negative {
switch roundingMode {
case .up:
break
case .bankers:
if remainder == 5 && (self[0] & 1) == 0 {
remainder += 1
}
fallthrough
case .plain:
if remainder < 5 {
break
}
fallthrough
case .down:
_ = addShort(&self, 1)
}
if _length == 0 {
_isNegative = 0;
}
} else {
switch roundingMode {
case .down:
break
case .bankers:
if remainder == 5 && (self[0] & 1) == 0 {
remainder -= 1
}
fallthrough
case .plain:
if remainder < 5 {
break
}
fallthrough
case .up:
_ = addShort(&self, 1)
}
}
}
_isCompact = 0;
while newExponent > Int32(Int8.max) {
newExponent -= 1;
_ = multiplyByShort(&self, 10);
}
_exponent = newExponent;
self.compact();
}
internal func compare(to other:Decimal) -> ComparisonResult {
// NaN is a special case and is arbitrary ordered before everything else
// Conceptually comparing with NaN is bogus anyway but raising or
// always returning the same answer will confuse the sorting algorithms
if self.isNaN {
return other.isNaN ? .orderedSame : .orderedAscending
}
if other.isNaN {
return .orderedDescending
}
// Check the sign
if self._isNegative > other._isNegative {
return .orderedAscending
}
if self._isNegative < other._isNegative {
return .orderedDescending
}
// If one of the two is == 0, the other is bigger
// because 0 implies isNegative = 0...
if self.isZero && other.isZero {
return .orderedSame
}
if self.isZero {
return .orderedAscending
}
if other.isZero {
return .orderedDescending
}
var selfNormal = self
var otherNormal = other
_ = NSDecimalNormalize(&selfNormal, &otherNormal, .down)
let comparison = mantissaCompare(selfNormal,otherNormal)
if selfNormal._isNegative == 1 {
if comparison == .orderedDescending {
return .orderedAscending
} else if comparison == .orderedAscending {
return .orderedDescending
} else {
return .orderedSame
}
}
return comparison
}
fileprivate mutating func setNaN() {
_length = 0
_isNegative = 1
}
fileprivate mutating func setZero() {
_length = 0
_isNegative = 0
}
fileprivate mutating func multiply(byPowerOf10 power:Int16) -> CalculationError {
if isNaN {
return .overflow
}
if isZero {
return .noError
}
let newExponent = _exponent + Int32(power)
if newExponent < Int32(Int8.min) {
setNaN()
return .underflow
}
if newExponent > Int32(Int8.max) {
setNaN()
return .overflow
}
_exponent = newExponent
return .noError
}
fileprivate mutating func power(_ p:UInt, roundingMode:RoundingMode) -> CalculationError {
if isNaN {
return .overflow
}
var power = p
if power == 0 {
_exponent = 0
_length = 1
_isNegative = 0
self[0] = 1
_isCompact = 1
return .noError
} else if power == 1 {
return .noError
}
var temporary = Decimal(1)
var error:CalculationError = .noError
while power > 1 {
if power % 2 == 1 {
let previousError = error
var leftOp = temporary
error = NSDecimalMultiply(&temporary, &leftOp, &self, roundingMode)
if previousError != .noError { // FIXME is this the intent?
error = previousError
}
if error == .overflow || error == .underflow {
setNaN()
return error
}
power -= 1
}
if power != 0 {
let previousError = error
var leftOp = self
var rightOp = self
error = NSDecimalMultiply(&self, &leftOp, &rightOp, roundingMode)
if previousError != .noError { // FIXME is this the intent?
error = previousError
}
if error == .overflow || error == .underflow {
setNaN()
return error
}
power /= 2
}
}
let previousError = error
var rightOp = self
error = NSDecimalMultiply(&self, &temporary, &rightOp, roundingMode)
if previousError != .noError { // FIXME is this the intent?
error = previousError
}
if error == .overflow || error == .underflow {
setNaN()
return error
}
return error
}
}
// Could be silently inexact for float and double.
extension Scanner {
public func scanDecimal(_ dcm: inout Decimal) -> Bool {
if let result = scanDecimal() {
dcm = result
return true
} else {
return false
}
}
public func scanDecimal() -> Decimal? {
var result = Decimal.zero
let string = self._scanString
let length = string.length
var buf = _NSStringBuffer(string: string, start: self._scanLocation, end: length)
var tooBig = false
let ds = (locale as? Locale ?? Locale.current).decimalSeparator?.first ?? Character(".")
buf.skip(_skipSet)
var neg = false
var ok = false
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
ok = true
neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-")
buf.advance()
buf.skip(_skipSet)
}
// build the mantissa
while let numeral = decimalValue(buf.currentCharacter) {
ok = true
if tooBig || multiplyBy10(&result,andAdd:numeral) != .noError {
tooBig = true
if result._exponent == Int32(Int8.max) {
repeat {
buf.advance()
} while decimalValue(buf.currentCharacter) != nil
return nil
}
result._exponent += 1
}
buf.advance()
}
// get the decimal point
if let us = UnicodeScalar(buf.currentCharacter), Character(us) == ds {
ok = true
buf.advance()
// continue to build the mantissa
while let numeral = decimalValue(buf.currentCharacter) {
if tooBig || multiplyBy10(&result,andAdd:numeral) != .noError {
tooBig = true
} else {
if result._exponent == Int32(Int8.min) {
repeat {
buf.advance()
} while decimalValue(buf.currentCharacter) != nil
return nil
}
result._exponent -= 1
}
buf.advance()
}
}
if buf.currentCharacter == unichar(unicodeScalarLiteral: "e") || buf.currentCharacter == unichar(unicodeScalarLiteral: "E") {
ok = true
var exponentIsNegative = false
var exponent: Int32 = 0
buf.advance()
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") {
exponentIsNegative = true
buf.advance()
} else if buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
buf.advance()
}
while let numeral = decimalValue(buf.currentCharacter) {
exponent = 10 * exponent + Int32(numeral)
guard exponent <= 2*Int32(Int8.max) else {
return nil
}
buf.advance()
}
if exponentIsNegative {
exponent = -exponent
}
exponent += result._exponent
guard exponent >= Int32(Int8.min) && exponent <= Int32(Int8.max) else {
return nil
}
result._exponent = exponent
}
// No valid characters have been seen upto this point so error out.
guard ok == true else { return nil }
result.isNegative = neg
// if we get to this point, and have NaN, then the input string was probably "-0"
// or some variation on that, and normalize that to zero.
if result.isNaN {
result = Decimal(0)
}
result.compact()
self._scanLocation = buf.location
return result
}
// Copied from Scanner.swift
private func decimalValue(_ ch: unichar) -> Int? {
guard let s = UnicodeScalar(ch), s.isASCII else { return nil }
return Character(s).wholeNumberValue
}
}
|
apache-2.0
|
d2fbca811a50e2ea62a1923cf46d10f9
| 34.195483 | 233 | 0.571254 | 3.951722 | false | false | false | false |
roambotics/swift
|
test/SILGen/function_conversion.swift
|
2
|
37591
|
// RUN: %target-swift-emit-silgen -module-name function_conversion -primary-file %s | %FileCheck %s
// RUN: %target-swift-emit-ir -module-name function_conversion -primary-file %s
// Check SILGen against various FunctionConversionExprs emitted by Sema.
// ==== Representation conversions
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion7cToFuncyS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_guaranteed (Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @$sS2iIetCyd_S2iIegyd_TR
// CHECK: [[FUNC:%.*]] = partial_apply [callee_guaranteed] [[THUNK]](%0)
// CHECK: return [[FUNC]]
func cToFunc(_ arg: @escaping @convention(c) (Int) -> Int) -> (Int) -> Int {
return arg
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion8cToBlockyS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int
// CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]]
// CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int
// CHECK: return [[COPY]]
func cToBlock(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(block) (Int) -> Int {
return arg
}
// ==== Throws variance
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToThrowsyyyKcyycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @owned @callee_guaranteed () -> @error any Error
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> ()):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> () to $@callee_guaranteed () -> @error any Error
// CHECK: return [[FUNC]]
// CHECK: } // end sil function '$s19function_conversion12funcToThrowsyyyKcyycF'
func funcToThrows(_ x: @escaping () -> ()) -> () throws -> () {
return x
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12thinToThrowsyyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error any Error
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error any Error
// CHECK: return [[FUNC]] : $@convention(thin) () -> @error any Error
func thinToThrows(_ x: @escaping @convention(thin) () -> ()) -> @convention(thin) () throws -> () {
return x
}
// FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs
/*
func thinFunc() {}
func thinToThrows() {
let _: @convention(thin) () -> () = thinFunc
}
*/
// ==== Class downcasts and upcasts
class Feral {}
class Domesticated : Feral {}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned Domesticated) -> @owned @callee_guaranteed () -> @owned Feral {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> @owned Domesticated):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> @owned Domesticated to $@callee_guaranteed () -> @owned Feral
// CHECK: return [[FUNC]]
// CHECK: } // end sil function '$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF'
func funcToUpcast(_ x: @escaping () -> Domesticated) -> () -> Feral {
return x
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@guaranteed @callee_guaranteed (@guaranteed Feral) -> ()) -> @owned @callee_guaranteed (@guaranteed Domesticated) -> ()
// CHECK: bb0([[ARG:%.*]] :
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed (@guaranteed Feral) -> () to $@callee_guaranteed (@guaranteed Domesticated) -> (){{.*}}
// CHECK: return [[FUNC]]
func funcToUpcast(_ x: @escaping (Feral) -> ()) -> (Domesticated) -> () {
return x
}
// ==== Optionals
struct Trivial {
let n: Int8
}
class C {
let n: Int8
init(n: Int8) {
self.n = n
}
}
struct Loadable {
let c: C
var n: Int8 {
return c.n
}
init(n: Int8) {
c = C(n: n)
}
}
struct AddrOnly {
let a: Any
var n: Int8 {
return a as! Int8
}
init(n: Int8) {
a = n
}
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convOptionalTrivialyyAA0E0VADSgcF
func convOptionalTrivial(_ t1: @escaping (Trivial?) -> Trivial) {
// CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR
// CHECK: partial_apply
let _: (Trivial) -> Trivial? = t1
// CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR
// CHECK: partial_apply
let _: (Trivial?) -> Trivial? = t1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: [[ENUM:%.*]] = enum $Optional<Trivial>
// CHECK-NEXT: apply %1([[ENUM]])
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR : $@convention(thin) (Optional<Trivial>, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: apply %1(%0)
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalLoadableyyAA0E0VADSgcF
func convOptionalLoadable(_ l1: @escaping (Loadable?) -> Loadable) {
// CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_AcDIeggo_TR
// CHECK: partial_apply
let _: (Loadable) -> Loadable? = l1
// CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR
// CHECK: partial_apply
let _: (Loadable?) -> Loadable? = l1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR : $@convention(thin) (@guaranteed Optional<Loadable>, @guaranteed @callee_guaranteed (@guaranteed Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable>
// CHECK: apply %1(%0)
// CHECK-NEXT: enum $Optional<Loadable>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalAddrOnlyyyAA0eF0VADSgcF
func convOptionalAddrOnly(_ a1: @escaping (AddrOnly?) -> AddrOnly) {
// CHECK: function_ref @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR
// CHECK: partial_apply
let _: (AddrOnly?) -> AddrOnly? = a1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR : $@convention(thin) (@in_guaranteed Optional<AddrOnly>, @guaranteed @callee_guaranteed (@in_guaranteed Optional<AddrOnly>) -> @out AddrOnly) -> @out Optional<AddrOnly>
// CHECK: [[TEMP:%.*]] = alloc_stack $AddrOnly
// CHECK-NEXT: apply %2([[TEMP]], %1)
// CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [init] {{.*}} : $*AddrOnly
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: tuple ()
// CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly
// CHECK-NEXT: return
// ==== Existentials
protocol Q {
var n: Int8 { get }
}
protocol P : Q {}
extension Trivial : P {}
extension Loadable : P {}
extension AddrOnly : P {}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion22convExistentialTrivial_2t3yAA0E0VAA1Q_pc_AeaF_pSgctF
func convExistentialTrivial(_ t2: @escaping (Q) -> Trivial, t3: @escaping (Q?) -> Trivial) {
// CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR
// CHECK: partial_apply
let _: (Trivial) -> P = t2
// CHECK: function_ref @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR
// CHECK: partial_apply
let _: (Trivial?) -> P = t3
// CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR
// CHECK: partial_apply
let _: (P) -> P = t2
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (@in_guaranteed any Q) -> Trivial) -> @out any P
// CHECK: alloc_stack $any Q
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR
// CHECK: switch_enum
// CHECK: bb1([[TRIVIAL:%.*]] : $Trivial):
// CHECK: init_existential_addr
// CHECK: init_enum_data_addr
// CHECK: copy_addr
// CHECK: inject_enum_addr
// CHECK: bb2:
// CHECK: inject_enum_addr
// CHECK: bb3:
// CHECK: apply
// CHECK: init_existential_addr
// CHECK: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR : $@convention(thin) (@in_guaranteed any P, @guaranteed @callee_guaranteed (@in_guaranteed any Q) -> Trivial) -> @out any P
// CHECK: [[TMP:%.*]] = alloc_stack $any Q
// CHECK-NEXT: open_existential_addr immutable_access %1 : $*any P
// CHECK-NEXT: init_existential_addr [[TMP]] : $*any Q
// CHECK-NEXT: copy_addr {{.*}} to [init] {{.*}}
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: destroy_addr
// CHECK: return
// ==== Existential metatypes
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion23convExistentialMetatypeyyAA7TrivialVmAA1Q_pXpSgcF
func convExistentialMetatype(_ em: @escaping (Q.Type?) -> Trivial.Type) {
// CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR
// CHECK: partial_apply
let _: (Trivial.Type) -> P.Type = em
// CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR
// CHECK: partial_apply
let _: (Trivial.Type?) -> P.Type = em
// CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR
// CHECK: partial_apply
let _: (P.Type) -> P.Type = em
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR : $@convention(thin) (@thin Trivial.Type, @guaranteed @callee_guaranteed (Optional<@thick any Q.Type>) -> @thin Trivial.Type) -> @thick any P.Type
// CHECK: [[META:%.*]] = metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype [[META]] : $@thick Trivial.Type, $@thick any Q.Type
// CHECK-NEXT: enum $Optional<@thick any Q.Type>
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick any P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR : $@convention(thin) (Optional<@thin Trivial.Type>, @guaranteed @callee_guaranteed (Optional<@thick any Q.Type>) -> @thin Trivial.Type) -> @thick any P.Type
// CHECK: switch_enum %0 : $Optional<@thin Trivial.Type>
// CHECK: bb1([[META:%.*]] : $@thin Trivial.Type):
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick any Q.Type
// CHECK-NEXT: enum $Optional<@thick any Q.Type>
// CHECK: bb2:
// CHECK-NEXT: enum $Optional<@thick any Q.Type>
// CHECK: bb3({{.*}}):
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick any P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR : $@convention(thin) (@thick any P.Type, @guaranteed @callee_guaranteed (Optional<@thick any Q.Type>) -> @thin Trivial.Type) -> @thick any P.Type
// CHECK: open_existential_metatype %0 : $@thick any P.Type to $@thick (@opened({{.*}}, any P) Self).Type
// CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}, any P) Self).Type, $@thick any Q.Type
// CHECK-NEXT: enum $Optional<@thick any Q.Type>
// CHECK-NEXT: apply %1
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick any P.Type
// CHECK-NEXT: return
// ==== Class metatype upcasts
class Parent {}
class Child : Parent {}
// Note: we add a Trivial => Trivial? conversion here to force a thunk
// to be generated
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion18convUpcastMetatype_2c5yAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_AEmAGmSg_AJtctF
func convUpcastMetatype(_ c4: @escaping (Parent.Type, Trivial?) -> Child.Type,
c5: @escaping (Parent.Type?, Trivial?) -> Child.Type) {
// CHECK: function_ref @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c4
// CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c5
// CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR
// CHECK: partial_apply
let _: (Child.Type?, Trivial) -> Parent.Type? = c5
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<@thick Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR : $@convention(thin) (Optional<@thick Child.Type>, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<@thick Parent.Type>
// CHECK: unchecked_trivial_bit_cast %0 : $Optional<@thick Child.Type> to $Optional<@thick Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<@thick Parent.Type>
// CHECK: return
// ==== Function to existential -- make sure we maximally abstract it
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convFuncExistentialyyS2icypcF : $@convention(thin) (@guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> ()
// CHECK: bb0([[ARG:%.*]] :
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR :
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[ARG_COPY]])
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$s19function_conversion19convFuncExistentialyyS2icypcF'
func convFuncExistential(_ f1: @escaping (Any) -> (Int) -> Int) {
let _: (@escaping (Int) -> Int) -> Any = f1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> @out Any {
// CHECK: [[EXISTENTIAL:%.*]] = alloc_stack $Any
// CHECK: [[COPIED_VAL:%.*]] = copy_value
// CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR
// CHECK-NEXT: [[PA:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[COPIED_VAL]])
// CHECK-NEXT: [[CF:%.*]] = convert_function [[PA]]
// CHECK-NEXT: init_existential_addr [[EXISTENTIAL]] : $*Any, $(Int) -> Int
// CHECK-NEXT: store [[CF]]
// CHECK-NEXT: apply
// CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR
// CHECK-NEXT: partial_apply
// CHECK-NEXT: convert_function
// CHECK-NEXT: init_existential_addr %0 : $*Any, $(Int) -> Int
// CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 for <Int, Int>
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS2iIegyd_S2iIegnr_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> Int) -> @out Int
// CHECK: [[LOADED:%.*]] = load [trivial] %1 : $*Int
// CHECK-NEXT: apply %2([[LOADED]])
// CHECK-NEXT: store {{.*}} to [trivial] %0
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK: return [[VOID]]
// ==== Class-bound archetype upcast
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion29convClassBoundArchetypeUpcast{{[_0-9a-zA-Z]*}}F
func convClassBoundArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent) -> (T, Trivial)) {
// CHECK: function_ref @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR
// CHECK: partial_apply
let _: (T) -> (Parent, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR : $@convention(thin) <T where T : Parent> (@guaranteed T, @guaranteed @callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)) -> (@owned Parent, Optional<Trivial>)
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T, [[CLOSURE:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)):
// CHECK: [[CASTED_ARG:%.*]] = upcast [[ARG]] : $T to $Parent
// CHECK: [[RESULT:%.*]] = apply %1([[CASTED_ARG]])
// CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[RESULT]]
// CHECK: [[LHS_CAST:%.*]] = upcast [[LHS]] : $T to $Parent
// CHECK: [[RHS_OPT:%.*]] = enum $Optional<Trivial>, #Optional.some!enumelt, [[RHS]]
// CHECK: [[RESULT:%.*]] = tuple ([[LHS_CAST]] : $Parent, [[RHS_OPT]] : $Optional<Trivial>)
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR'
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion37convClassBoundMetatypeArchetypeUpcast{{[_0-9a-zA-Z]*}}F
func convClassBoundMetatypeArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent.Type) -> (T.Type, Trivial)) {
// CHECK: function_ref @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR
// CHECK: partial_apply
let _: (T.Type) -> (Parent.Type, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR : $@convention(thin) <T where T : Parent> (@thick T.Type, @guaranteed @callee_guaranteed (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>)
// CHECK: bb0([[META:%.*]] :
// CHECK: upcast %0 : $@thick T.Type
// CHECK-NEXT: apply
// CHECK-NEXT: destructure_tuple
// CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// ==== Make sure we destructure one-element tuples
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convTupleScalar_2f22f3yyAA1Q_pc_yAaE_pcySi_SitSgctF
// CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR
// CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR
// CHECK: function_ref @$sSi_SitSgIegy_S2iIegyy_TR
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR : $@convention(thin) (@in_guaranteed any P, @guaranteed @callee_guaranteed (@in_guaranteed any Q) -> ()) -> ()
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sSi_SitSgIegy_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (Optional<(Int, Int)>) -> ()) -> ()
func convTupleScalar(_ f1: @escaping (Q) -> (),
f2: @escaping (_ parent: Q) -> (),
f3: @escaping (_ tuple: (Int, Int)?) -> ()) {
let _: (P) -> () = f1
let _: (P) -> () = f2
let _: ((Int, Int)) -> () = f3
}
func convTupleScalarOpaque<T>(_ f: @escaping (T...) -> ()) -> ((_ args: T...) -> ())? {
return f
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> @owned @callee_guaranteed (Int) -> Optional<(Int, Int)>
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)):
// CHECK: [[FN:%.*]] = copy_value [[ARG]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @$sS3iIegydd_S2i_SitSgIegyd_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[FN]])
// CHECK-NEXT: return [[THUNK]]
// CHECK-NEXT: } // end sil function '$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF'
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS3iIegydd_S2i_SitSgIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> Optional<(Int, Int)>
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)):
// CHECK: [[RESULT:%.*]] = apply %1(%0)
// CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Int)
// CHECK-NEXT: [[OPTIONAL:%.*]] = enum $Optional<(Int, Int)>, #Optional.some!enumelt, [[RESULT]]
// CHECK-NEXT: return [[OPTIONAL]]
// CHECK-NEXT: } // end sil function '$sS3iIegydd_S2i_SitSgIegyd_TR'
func convTupleToOptionalDirect(_ f: @escaping (Int) -> (Int, Int)) -> (Int) -> (Int, Int)? {
return f
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF : $@convention(thin) <T> (@guaranteed @callee_guaranteed @substituted <τ_0_0, τ_0_1, τ_0_2> (@in_guaranteed τ_0_0) -> (@out τ_0_1, @out τ_0_2) for <T, T, T>) -> @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_1 == (τ_0_2, τ_0_3)> (@in_guaranteed τ_0_0) -> @out Optional<(τ_0_2, τ_0_3)> for <T, (T, T), T, T>
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed @substituted <τ_0_0, τ_0_1, τ_0_2> (@in_guaranteed τ_0_0) -> (@out τ_0_1, @out τ_0_2) for <T, T, T>):
// CHECK: [[FN:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[FN_CONV:%.*]] = convert_function [[FN]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @$sxxxIegnrr_xx_xtSgIegnr_lTR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<T>([[FN_CONV]])
// CHECK-NEXT: [[THUNK_CONV:%.*]] = convert_function [[THUNK]]
// CHECK-NEXT: return [[THUNK_CONV]]
// CHECK-NEXT: } // end sil function '$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF'
// CHECK: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sxxxIegnrr_xx_xtSgIegnr_lTR : $@convention(thin) <T> (@in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)) -> @out Optional<(T, T)>
// CHECK: bb0(%0 : $*Optional<(T, T)>, %1 : $*T, %2 : @guaranteed $@callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)):
// CHECK: [[OPTIONAL:%.*]] = init_enum_data_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 1
// CHECK-NEXT: apply %2([[LEFT]], [[RIGHT]], %1)
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK: return [[VOID]]
func convTupleToOptionalIndirect<T>(_ f: @escaping (T) -> (T, T)) -> (T) -> (T, T)? {
return f
}
// ==== Make sure we support AnyHashable erasure
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convAnyHashable1tyx_tSHRzlF
// CHECK: function_ref @$s19function_conversion15convAnyHashable1tyx_tSHRzlFSbs0dE0V_AEtcfU_
// CHECK: function_ref @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR : $@convention(thin) <T where T : Hashable> (@in_guaranteed T, @in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed AnyHashable, @in_guaranteed AnyHashable) -> Bool) -> Bool
// CHECK: alloc_stack $AnyHashable
// CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF
// CHECK: apply {{.*}}<T>
// CHECK: alloc_stack $AnyHashable
// CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF
// CHECK: apply {{.*}}<T>
// CHECK: return
func convAnyHashable<T : Hashable>(t: T) {
let fn: (T, T) -> Bool = {
(x: AnyHashable, y: AnyHashable) in x == y
}
}
// ==== Convert exploded tuples to Any or Optional<Any>
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12convTupleAnyyyyyc_Si_SitycyypcyypSgctF
// CHECK: function_ref @$sIeg_ypIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sIeg_ypSgIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sS2iIegdd_ypIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sS2iIegdd_ypSgIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sypIegn_S2iIegyy_TR
// CHECK: partial_apply
// CHECK: function_ref @$sypSgIegn_S2iIegyy_TR
// CHECK: partial_apply
func convTupleAny(_ f1: @escaping () -> (),
_ f2: @escaping () -> (Int, Int),
_ f3: @escaping (Any) -> (),
_ f4: @escaping (Any?) -> ()) {
let _: () -> Any = f1
let _: () -> Any? = f1
let _: () -> Any = f2
let _: () -> Any? = f2
let _: ((Int, Int)) -> () = f3
let _: ((Int, Int)) -> () = f4
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sIeg_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Any
// CHECK: init_existential_addr %0 : $*Any, $()
// CHECK-NEXT: apply %1()
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sIeg_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Optional<Any>
// CHECK: [[ENUM_PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Optional<Any>, #Optional.some!enumelt
// CHECK-NEXT: init_existential_addr [[ENUM_PAYLOAD]] : $*Any, $()
// CHECK-NEXT: apply %1()
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<Any>, #Optional.some!enumelt
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Any
// CHECK: [[ANY_PAYLOAD:%.*]] = init_existential_addr %0
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RESULT:%.*]] = apply %1()
// CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]]
// CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Optional<Any> {
// CHECK: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr %0
// CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[OPTIONAL_PAYLOAD]]
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RESULT:%.*]] = apply %1()
// CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]]
// CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sypIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> ()) -> ()
// CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]]
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: apply %2([[ANY_VALUE]])
// CHECK-NEXT: tuple ()
// CHECK-NEXT: destroy_addr [[ANY_VALUE]]
// CHECK-NEXT: dealloc_stack [[ANY_VALUE]]
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sypSgIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Optional<Any>) -> ()) -> ()
// CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]]
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: [[OPTIONAL_VALUE:%.*]] = alloc_stack $Optional<Any>
// CHECK-NEXT: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL_VALUE]]
// CHECK-NEXT: copy_addr [take] [[ANY_VALUE]] to [init] [[OPTIONAL_PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[OPTIONAL_VALUE]]
// CHECK-NEXT: apply %2([[OPTIONAL_VALUE]])
// CHECK-NEXT: tuple ()
// CHECK-NEXT: destroy_addr [[OPTIONAL_VALUE]]
// CHECK-NEXT: dealloc_stack [[OPTIONAL_VALUE]]
// CHECK-NEXT: dealloc_stack [[ANY_VALUE]]
// CHECK-NEXT: return
// ==== Support collection subtyping in function argument position
protocol Z {}
class A: Z {}
func foo_arr<T: Z>(type: T.Type, _ fn: ([T]?) -> Void) {}
func foo_map<T: Z>(type: T.Type, _ fn: ([Int: T]) -> Void) {}
func rdar35702810() {
let fn_arr: ([Z]?) -> Void = { _ in }
let fn_map: ([Int: Z]) -> Void = { _ in }
// CHECK: function_ref @$ss15_arrayForceCastySayq_GSayxGr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
// CHECK: apply %5<A, any Z>(%4) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
foo_arr(type: A.self, fn_arr)
// CHECK: function_ref @$ss17_dictionaryUpCastySDyq0_q1_GSDyxq_GSHRzSHR0_r2_lF : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: apply %2<Int, A, Int, any Z>(%0) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: apply %1(%4) : $@callee_guaranteed (@guaranteed Dictionary<Int, any Z>) -> ()
foo_map(type: A.self, fn_map)
}
protocol X: Hashable {}
class B: X {
func hash(into hasher: inout Hasher) {}
static func == (lhs: B, rhs: B) -> Bool { return true }
}
func bar_arr<T: X>(type: T.Type, _ fn: ([T]?) -> Void) {}
func bar_map<T: X>(type: T.Type, _ fn: ([T: Int]) -> Void) {}
func bar_set<T: X>(type: T.Type, _ fn: (Set<T>) -> Void) {}
func rdar35702810_anyhashable() {
let fn_arr: ([AnyHashable]?) -> Void = { _ in }
let fn_map: ([AnyHashable: Int]) -> Void = { _ in }
let fn_set: (Set<AnyHashable>) -> Void = { _ in }
// CHECK: [[FN:%.*]] = function_ref @$sSays11AnyHashableVGSgIegg_Say19function_conversion1BCGSgIegg_TR : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> ()
// CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Optional<Array<B>>) -> () to $@noescape @callee_guaranteed (@guaranteed Optional<Array<B>>) -> ()
bar_arr(type: B.self, fn_arr)
// CHECK: [[FN:%.*]] = function_ref @$sSDys11AnyHashableVSiGIegg_SDy19function_conversion1BCSiGIegg_TR : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> ()
// CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () to $@noescape @callee_guaranteed (@guaranteed Dictionary<B, Int>) -> ()
bar_map(type: B.self, fn_map)
// CHECK: [[FN:%.*]] = function_ref @$sShys11AnyHashableVGIegg_Shy19function_conversion1BCGIegg_TR : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> ()
// CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Set<B>) -> () to $@noescape @callee_guaranteed (@guaranteed Set<B>) -> ()
bar_set(type: B.self, fn_set)
}
// ==== Function conversion with parameter substToOrig reabstraction.
struct FunctionConversionParameterSubstToOrigReabstractionTest {
typealias SelfTy = FunctionConversionParameterSubstToOrigReabstractionTest
class Klass: Error {}
struct Foo<T> {
static func enum1Func(_ : (T) -> Foo<Error>) -> Foo<Error> {
// Just to make it compile.
return Optional<Foo<Error>>.none!
}
}
static func bar<T>(t: T) -> Foo<T> {
// Just to make it compile.
return Optional<Foo<T>>.none!
}
static func testFunc() -> Foo<Error> {
return Foo<Klass>.enum1Func(SelfTy.bar)
}
}
// CHECK: sil {{.*}} [ossa] @$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR
// CHECK: [[TUPLE:%.*]] = apply %4(%2, %3) : $@noescape @callee_guaranteed (@guaranteed String, @guaranteed String) -> (@owned String, @owned String)
// CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: [[ADDR:%.*]] = alloc_stack $String
// CHECK: store [[LHS]] to [init] [[ADDR]] : $*String
// CHECK: [[CVT:%.*]] = function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF : $@convention(thin) <τ_0_0 where τ_0_0 : Hashable> (@in_guaranteed τ_0_0) -> @out AnyHashable
// CHECK: apply [[CVT]]<String>(%0, [[ADDR]])
// CHECK: } // end sil function '$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR'
func dontCrash() {
let userInfo = ["hello": "world"]
let d = [AnyHashable: Any](uniqueKeysWithValues: userInfo.map { ($0.key, $0.value) })
}
struct Butt<T> {
var foo: () throws -> T
}
@_silgen_name("butt")
func butt() -> Butt<Any>
func foo() throws -> Any {
return try butt().foo()
}
|
apache-2.0
|
e5e89526802451543be3490e83829d29
| 53.476052 | 441 | 0.641045 | 3.303468 | false | false | false | false |
VladislavJevremovic/Atom-Attack
|
AtomAttack Shared/Sources/Game/Extensions/SKTexture+Gradient.swift
|
1
|
1375
|
//
// SKTexture+Gradient.swift
// Atom Attack
//
// Copyright © 2015-2021 Vladislav Jevremović. All rights reserved.
//
import SpriteKit
extension SKTexture {
class func textureWithVerticalGradient(
size: CGSize,
topColor: CIColor,
bottomColor: CIColor
) -> SKTexture? {
let imageContext = CIContext(options: nil)
guard let gradientFilter = CIFilter(name: "CILinearGradient") else {
return nil
}
gradientFilter.setDefaults()
let startVector = CIVector(x: size.width / 2, y: 0)
gradientFilter.setValue(startVector, forKey: "inputPoint0")
let endVector = CIVector(x: size.width / 2, y: size.height)
gradientFilter.setValue(endVector, forKey: "inputPoint1")
gradientFilter.setValue(bottomColor, forKey: "inputColor0")
gradientFilter.setValue(topColor, forKey: "inputColor1")
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
guard
let outputImage = gradientFilter.outputImage,
let cgImage = imageContext.createCGImage(outputImage, from: rect) else {
return nil
}
#if os(iOS)
return SKTexture(image: UIImage(cgImage: cgImage))
#elseif os(OSX)
return SKTexture(image: NSImage(cgImage: cgImage, size: .zero))
#endif
}
}
|
mit
|
b365f57f036988b11279d9352260ebac
| 29.511111 | 84 | 0.634377 | 4.290625 | false | false | false | false |
linchanlau/Swift-PM25
|
PM25/SCLAlertView.swift
|
3
|
11020
|
//
// SCLAlertView.swift
// SCLAlertView Example
//
// Created by Viktor Radchenko on 6/5/14.
// Copyright (c) 2014 Viktor Radchenko. All rights reserved.
//
import Foundation
import UIKit
// Pop Up Styles
enum SCLAlertViewStyle: Int {
case Success
case Error
case Notice
case Warning
case Info
}
// Allow alerts to be closed/renamed in a chainable manner
// Example: SCLAlertView().showSuccess(self, title: "Test", subTitle: "Value").Close()
class SCLAlertViewResponder {
let alertview: SCLAlertView
// Initialisation and Title/Subtitle/Close functions
init(alertview: SCLAlertView) { self.alertview = alertview }
func setTitle(title: String) { self.alertview.labelView.text = title; }
func setSubTitle(subTitle: String) { self.alertview.labelViewDescription.text = subTitle; }
func Close() { self.alertview.doneButtonAction() }
}
// The Main Class
class SCLAlertView : UIView {
let kDefaultShadowOpacity: CGFloat = 0.7;
let kCircleHeight: CGFloat = 56.0;
let kCircleTopPosition: CGFloat = -12; // Should not be defined here. Make it dynamic
let kCircleBackgroundTopPosition: CGFloat = -15; // Should not be defined here. Make it dynamic
let kCircleHeightBackground: CGFloat = 62.0;
let kCircleIconHeight: CGFloat = 20.0;
let kWindowWidth: CGFloat = 240.0;
let kWindowHeight: CGFloat = 228.0;
// Font
let kDefaultFont: NSString = "HelveticaNeue"
// Members declaration
var labelView: UILabel
var labelViewDescription: UILabel
var shadowView: UIView
var contentView: UIView
var circleView: UIView
var circleViewBackground: UIView
var circleIconImageView: UIImageView
var doneButton: UIButton
var rootViewController: UIViewController
var durationTimer: NSTimer!
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
override init () {
// Content View
self.contentView = UIView(frame: CGRectMake(0, kCircleHeight / 4, kWindowWidth, kWindowHeight))
self.contentView.backgroundColor = UIColor(white: 1, alpha: 1);
self.contentView.layer.cornerRadius = 5;
self.contentView.layer.masksToBounds = true;
self.contentView.layer.borderWidth = 0.5;
// Circle View
self.circleView = UIView(frame: CGRectMake(kWindowWidth / 2 - kCircleHeight / 2, kCircleTopPosition, kCircleHeight, kCircleHeight))
self.circleView.layer.cornerRadius = self.circleView.frame.size.height / 2;
// Circle View Background
self.circleViewBackground = UIView(frame: CGRectMake(kWindowWidth / 2 - kCircleHeightBackground / 2, kCircleBackgroundTopPosition, kCircleHeightBackground, kCircleHeightBackground))
self.circleViewBackground.layer.cornerRadius = self.circleViewBackground.frame.size.height / 2;
self.circleViewBackground.backgroundColor = UIColor.whiteColor()
// Circle View Image
self.circleIconImageView = UIImageView(frame: CGRectMake(kCircleHeight / 2 - kCircleIconHeight / 2, kCircleHeight / 2 - kCircleIconHeight / 2, kCircleIconHeight, kCircleIconHeight))
self.circleView.addSubview(self.circleIconImageView)
// Title
self.labelView = UILabel(frame: CGRectMake(12, kCircleHeight / 2 + 22, kWindowWidth - 24, 40))
self.labelView.numberOfLines = 1
self.labelView.textAlignment = NSTextAlignment.Center
self.labelView.font = UIFont(name: kDefaultFont, size: 20)
self.contentView.addSubview(self.labelView)
// Subtitle
self.labelViewDescription = UILabel(frame: CGRectMake(12, 84, kWindowWidth - 24, 80))
self.labelViewDescription.numberOfLines = 3
self.labelViewDescription.textAlignment = NSTextAlignment.Center
self.labelViewDescription.font = UIFont(name: kDefaultFont, size: 14)
self.contentView.addSubview(self.labelViewDescription)
// Shadow View
self.shadowView = UIView(frame: UIScreen.mainScreen().bounds)
self.shadowView.backgroundColor = UIColor.blackColor()
// Done Button
self.doneButton = UIButton(frame: CGRectMake(12, kWindowHeight - 52, kWindowWidth - 24, 40))
self.doneButton.layer.cornerRadius = 3
self.doneButton.layer.masksToBounds = true
self.doneButton.setTitle("Done", forState: UIControlState.Normal)
self.doneButton.titleLabel!.font = UIFont(name: kDefaultFont, size: 14)
self.contentView.addSubview(self.doneButton)
// Root view controller
self.rootViewController = UIViewController()
// Superclass initiation
super.init(frame: CGRectMake(((320 - kWindowWidth) / 2), 0 - kWindowHeight, kWindowWidth, kWindowHeight))
// Show notice on screen
self.addSubview(self.contentView)
self.addSubview(self.circleViewBackground)
self.addSubview(self.circleView)
// Colours
self.contentView.backgroundColor = UIColorFromRGB(0xFFFFFF)
self.labelView.textColor = UIColorFromRGB(0x4D4D4D)
self.labelViewDescription.textColor = UIColorFromRGB(0x4D4D4D)
self.contentView.layer.borderColor = UIColorFromRGB(0xCCCCCC).CGColor
// On complete.
self.doneButton.addTarget(self, action: Selector("doneButtonAction"), forControlEvents: UIControlEvents.TouchUpInside)
}
// showTitle(view, title, subTitle, style)
func showTitle(view: UIViewController, title: String, subTitle: String, style: SCLAlertViewStyle) -> SCLAlertViewResponder {
return showTitle(view, title: title, subTitle: subTitle, duration: 2.0, completeText: nil, style: style)
}
// showSuccess(view, title, subTitle)
func showSuccess(view: UIViewController, title: String, subTitle: String) -> SCLAlertViewResponder {
return showTitle(view, title: title, subTitle: subTitle, duration: 2.0, completeText: nil, style: SCLAlertViewStyle.Success);
}
// showError(view, title, subTitle)
func showError(view: UIViewController, title: String, subTitle: String) -> SCLAlertViewResponder {
return showTitle(view, title: title, subTitle: subTitle, duration: 2.0, completeText: nil, style: SCLAlertViewStyle.Error);
}
// showNotice(view, title, subTitle)
func showNotice(view: UIViewController, title: String, subTitle: String) -> SCLAlertViewResponder {
return showTitle(view, title: title, subTitle: subTitle, duration: 2.0, completeText: nil, style: SCLAlertViewStyle.Notice);
}
// showWarning(view, title, subTitle)
func showWarning(view: UIViewController, title: String, subTitle: String) -> SCLAlertViewResponder {
return showTitle(view, title: title, subTitle: subTitle, duration: 2.0, completeText: nil, style: SCLAlertViewStyle.Warning);
}
// showInfo(view, title, subTitle)
func showInfo(view: UIViewController, title: String, subTitle: String) -> SCLAlertViewResponder {
return showTitle(view, title: title, subTitle: subTitle, duration: 2.0, completeText: nil, style: SCLAlertViewStyle.Info);
}
// showTitle(view, title, subTitle, duration, style)
func showTitle(view:UIViewController, title: String, subTitle: String, duration: NSTimeInterval?, completeText: String?, style: SCLAlertViewStyle) -> SCLAlertViewResponder {
self.alpha = 0;
self.rootViewController = view
self.rootViewController.view.addSubview(self.shadowView)
self.rootViewController.view.addSubview(self)
// Complete text
if(completeText != nil) {
self.doneButton.setTitle(completeText, forState: UIControlState.Normal)
}
// Alert colour/icon
var viewColor: UIColor = UIColor()
var iconImageName: NSString = ""
// Icon style
switch(style) {
case SCLAlertViewStyle.Success:
viewColor = UIColorFromRGB(0x22B573);
iconImageName = "notification-success"
case SCLAlertViewStyle.Error:
viewColor = UIColorFromRGB(0xC1272D);
iconImageName = "notification-error"
case SCLAlertViewStyle.Notice:
viewColor = UIColorFromRGB(0x727375)
iconImageName = "notification-notice"
case SCLAlertViewStyle.Warning:
viewColor = UIColorFromRGB(0xFFD110);
iconImageName = "notification-warning"
case SCLAlertViewStyle.Info:
viewColor = UIColorFromRGB(0x2866BF);
iconImageName = "notification-info"
default:
println("default")
}
// Title
if ((title as NSString).length > 0 ) {
self.labelView.text = title;
}
// Subtitle
if ((subTitle as NSString).length > 0) {
self.labelViewDescription.text = subTitle;
}
// Alert view colour and images
self.doneButton.backgroundColor = viewColor;
self.circleView.backgroundColor = viewColor;
self.circleIconImageView.image = UIImage(named: iconImageName)
// Adding duration
if (duration != nil && duration > 0) {
durationTimer?.invalidate()
durationTimer = NSTimer.scheduledTimerWithTimeInterval(duration!, target: self, selector: Selector("hideView"), userInfo: nil, repeats: false)
}
// Animate in the alert view
UIView.animateWithDuration(0.2, animations: {
self.shadowView.alpha = self.kDefaultShadowOpacity
self.frame.origin.y = self.rootViewController.view.center.y - 100;
self.alpha = 1;
}, completion: { finished in
UIView.animateWithDuration(0.2, animations: {
self.center = self.rootViewController.view.center;
}, completion: { finished in })
})
// Chainable objects
return SCLAlertViewResponder(alertview: self)
}
// When click 'Done' button, hide view.
func doneButtonAction() { hideView(); }
// Close SCLAlertView
func hideView() {
UIView.animateWithDuration(0.2, animations: {
self.shadowView.alpha = 0;
self.alpha = 0;
}, completion: { finished in
self.shadowView.removeFromSuperview()
self.removeFromSuperview()
})
}
// Helper function to convert from RGB to UIColor
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
|
mit
|
49b094cb2b4dea97c49cc32d9f5137b0
| 40.904943 | 189 | 0.653448 | 4.810127 | false | false | false | false |
qx/PageMenu
|
Demos/Demo 5/PageMenuDemoSegmentedControl/PageMenuDemoSegmentedControl/ViewController.swift
|
1
|
5642
|
//
// ViewController.swift
// PageMenuDemoSegmentedControl
//
// Created by Niklas Fahl on 1/20/15.
// Copyright (c) 2015 Niklas Fahl. All rights reserved.
//
import UIKit
class ViewController: UIViewController, CAPSPageMenuDelegate {
var pageMenu : CAPSPageMenu?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "PAGE MENU"
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
// MARK: - Scroll menu setup
// Initialize view controllers to display and place in array
var controllerArray : [UIViewController] = []
let controller1 : TestTableViewController = TestTableViewController(nibName: "TestTableViewController", bundle: nil)
controller1.parentNavigationController = self.navigationController
controller1.title = "FAVORITES"
controllerArray.append(controller1)
let controller2 : RecentsTableViewController = RecentsTableViewController(nibName: "RecentsTableViewController", bundle: nil)
controller2.title = "RECENTS"
controller2.parentNavigationController = self.navigationController
controllerArray.append(controller2)
let controller3 : RecentsTableViewController = RecentsTableViewController(nibName: "RecentsTableViewController", bundle: nil)
controller3.title = "FRIENDS"
controller3.parentNavigationController = self.navigationController
controllerArray.append(controller3)
let controller4 : RecentsTableViewController = RecentsTableViewController(nibName: "RecentsTableViewController", bundle: nil)
controller4.title = "OTHERS"
controller4.parentNavigationController = self.navigationController
controllerArray.append(controller4)
// Customize menu (Optional)
let parameters: [CAPSPageMenuOption] = [
.MenuItemSeparatorWidth(4.3),
.ScrollMenuBackgroundColor(UIColor.whiteColor()),
.ViewBackgroundColor(UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)),
.BottomMenuHairlineColor(UIColor(red: 20.0/255.0, green: 20.0/255.0, blue: 20.0/255.0, alpha: 0.1)),
.SelectionIndicatorColor(UIColor(red: 18.0/255.0, green: 150.0/255.0, blue: 225.0/255.0, alpha: 1.0)),
.MenuMargin(20.0),
.MenuHeight(40.0),
.SelectedMenuItemLabelColor(UIColor(red: 18.0/255.0, green: 150.0/255.0, blue: 225.0/255.0, alpha: 1.0)),
.UnselectedMenuItemLabelColor(UIColor(red: 40.0/255.0, green: 40.0/255.0, blue: 40.0/255.0, alpha: 1.0)),
.MenuItemFont(UIFont(name: "HelveticaNeue-Medium", size: 14.0)!),
.UseMenuLikeSegmentedControl(true),
.MenuItemSeparatorRoundEdges(true),
.SelectionIndicatorHeight(2.0),
.MenuItemSeparatorPercentageHeight(0.1)
]
// Initialize scroll menu
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 0.0, self.view.frame.width, self.view.frame.height), pageMenuOptions: parameters)
// Optional delegate
pageMenu!.delegate = self
self.view.addSubview(pageMenu!.view)
}
// Uncomment below for some navbar color animation fun using the new delegate functions
func didMoveToPage(controller: UIViewController, index: Int) {
print("did move to page")
// var color : UIColor = UIColor(red: 18.0/255.0, green: 150.0/255.0, blue: 225.0/255.0, alpha: 1.0)
// var navColor : UIColor = UIColor(red: 17.0/255.0, green: 64.0/255.0, blue: 107.0/255.0, alpha: 1.0)
//
// if index == 1 {
// color = UIColor.orangeColor()
// navColor = color
// } else if index == 2 {
// color = UIColor.grayColor()
// navColor = color
// } else if index == 3 {
// color = UIColor.purpleColor()
// navColor = color
// }
//
// UIView.animateWithDuration(0.5, animations: { () -> Void in
// self.navigationController!.navigationBar.barTintColor = navColor
// }) { (completed) -> Void in
// print("did fade")
// }
}
func willMoveToPage(controller: UIViewController, index: Int) {
print("will move to page")
// var color : UIColor = UIColor(red: 18.0/255.0, green: 150.0/255.0, blue: 225.0/255.0, alpha: 1.0)
// var navColor : UIColor = UIColor(red: 17.0/255.0, green: 64.0/255.0, blue: 107.0/255.0, alpha: 1.0)
//
// if index == 1 {
// color = UIColor.orangeColor()
// navColor = color
// } else if index == 2 {
// color = UIColor.grayColor()
// navColor = color
// } else if index == 3 {
// color = UIColor.purpleColor()
// navColor = color
// }
//
// UIView.animateWithDuration(0.5, animations: { () -> Void in
// self.navigationController!.navigationBar.barTintColor = navColor
// }) { (completed) -> Void in
// print("did fade")
// }
}
}
|
bsd-3-clause
|
6b61675f7d3bd82607bf65021dd50304
| 45.254098 | 170 | 0.586671 | 4.44602 | false | false | false | false |
shelleyweiss/softsurvey
|
SoftSurvey/SoftSurvey.swift
|
1
|
2731
|
//
// SoftSurvey.swift
// SoftSurvey
//
// Created by shelley weiss on 3/26/15.
// Copyright (c) 2015 shelley weiss. All rights reserved.
//
import UIKit
class SoftSurvey<T:SoftQuestion> {
var count: Int = 0
var head: Node<T> = Node<T>()
var tail: Node<T> = Node<T>()
init() {
}
func isEmpty() -> Bool {
return self.count == 0
}
func enqueue(value: T) {
var node = Node<T>(value: value)
if self.isEmpty() {
self.head = node
self.tail = node
} else {
node.next = self.head
self.head.prev = node
self.head = node
}
self.count++
}
func dequeue() -> T? {
if self.isEmpty() {
return nil
} else if self.count == 1 {
var temp: Node<T> = self.tail
self.count--
return temp.value
} else {
var temp: Node<T> = self.tail
self.tail = self.tail.prev!
self.count--
return temp.value
}
}
func upload() -> String? {
let path = NSBundle.mainBundle().pathForResource("jsonData", ofType: "json")
let jsonData = NSData(contentsOfMappedFile: path!)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
var soft : NSArray = jsonResult["softQuestion"] as! NSArray
//traditional C-style
for var index = 0; index < soft.count; ++index {
if let question: AnyObject = ((soft)[index] as? NSDictionary)?["question"] {
var softnode = T(value: index+1 as Int, text: question as! String)
//enqueue(softnode)
if let answerArray: NSArray = (((soft)[index] as? NSDictionary)?["answer"] as? NSArray)
{
for item in answerArray { // loop through data items
let obj = item as! NSDictionary
for (key, value) in obj
{
softnode.pushAnswer(value as! String)
// softnode.pushMultiple(value as String)
}
}
}
else
{
//println("none")
}
enqueue(softnode)
}
}
return nil
}
};
|
artistic-2.0
|
03ad9d4dfd7ef89499c2b12489cec4a2
| 25.269231 | 166 | 0.444892 | 4.894265 | false | false | false | false |
Zhendeshede/weiboBySwift
|
新浪微博/新浪微博/RelayTableViewCell.swift
|
1
|
2124
|
//
// RelayTableViewCell.swift
// 新浪微博
//
// Created by 李旭飞 on 15/10/20.
// Copyright © 2015年 lee. All rights reserved.
//
import UIKit
let textWidth:CGFloat = 300
class RelayTableViewCell: WeiboTableViewCell {
override var statuses:WeiboData?{
didSet{
let name = statuses?.retweeted_status?.user?.name
let text = statuses?.retweeted_status?.text
relayLabel.text = " @ \(name) # \(text) "
}
}
override func setupInterface(){
super.setupInterface()
contentView.insertSubview(backButton, belowSubview: pictureView)
contentView.insertSubview(relayLabel, aboveSubview: backButton)
backButton.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: nil,offset:CGPoint(x: -margin, y: margin))
backButton.ff_AlignVertical(type: ff_AlignType.TopRight, referView: bottomView, size: nil)
///转发文字
relayLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: backButton, size: nil, offset: CGPoint(x: margin, y: margin))
let constraintsList = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: relayLabel, size: CGSize(width: textWidth, height: textWidth), offset: CGPoint(x: 0, y: margin))
pictureWidthCon = pictureView.ff_Constraint(constraintsList, attribute: NSLayoutAttribute.Width)
pictureHeightCon = pictureView.ff_Constraint(constraintsList, attribute: NSLayoutAttribute.Height)
pictureTopCon = pictureView.ff_Constraint(constraintsList, attribute: NSLayoutAttribute.Top)
}
private lazy var relayLabel:UILabel = {
let label = UILabel(color: UIColor.blackColor(), fontSize: 15)
label.numberOfLines=0
label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width-2 * margin
return label
}()
private lazy var backButton:UIButton = {
let but = UIButton()
but.backgroundColor=UIColor(white: 0.95, alpha: 1.0)
return but
}()
}
|
mit
|
ebafdb68b423bfd39061abf9635841bd
| 31.292308 | 193 | 0.660791 | 4.563043 | false | false | false | false |
wwu-pi/md2-framework
|
de.wwu.md2.framework/res/resources/ios/lib/util/MD2UIUtil.swift
|
1
|
3167
|
//
// UIUtil.swift
// md2-ios-library
//
// Created by Christoph Rieger on 03.08.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
import UIKit
/// Utility class for view-related functions
class MD2UIUtil {
/**
Transform the CGRect object of view elements to a dimension object for easier handling.
:param: bounds The rectangle object.
:returns: The dimension object.
*/
static func CGRectToDimension(bounds: CGRect) -> MD2Dimension {
let dimension = MD2Dimension(
x: Float(bounds.origin.x),
y: Float(bounds.origin.y),
width: Float(bounds.size.width),
height: Float(bounds.size.height))
return dimension
}
/**
Transform the CGSize object of view elements to a dimension object for easier handling.
:param: size The size object.
:returns: The dimension object.
*/
static func CGSizeToDimension(size: CGSize) -> MD2Dimension {
let dimension = MD2Dimension(
x: Float(0),
y: Float(0),
width: Float(size.width),
height: Float(size.height))
return dimension
}
/**
Transform the dimension object to a CGRect object to set within a view element.
:param: dimension The dimension object.
:returns: The rectangle object.
*/
static func dimensionToCGRect(dimension: MD2Dimension) -> CGRect {
let rect = CGRect(x: Double(dimension.x),
y: Double(dimension.y),
width: Double(dimension.width),
height: Double(dimension.height))
return rect
}
/**
Transform the dimension object to a CGSize object.
:param: dimension The dimension object.
:returns: The size object.
*/
static func dimensionToCGSize(dimension: MD2Dimension) -> CGSize {
let size = CGSize(
width: Double(dimension.width),
height: Double(dimension.height))
return size
}
/**
Show a message in an overlay popup.
:param: message The message to show.
:param: title The popup title.
*/
static func showMessage(message: String, title: String) {
var alertView = UIAlertView()
alertView.title = title
alertView.addButtonWithTitle(MD2ViewConfig.TOOLTIP_BUTTON)
alertView.message = message
alertView.show()
}
/**
Return the inner dimensions of a view element by applying the gutter margin to an outer margin.
:param: outerDimension The outer dimension object.
:returns: The inner dimension.
*/
static func innerDimensionsWithGutter(outerDimensions: MD2Dimension) -> MD2Dimension {
return outerDimensions + MD2Dimension(
x: MD2ViewConfig.GUTTER,
y: MD2ViewConfig.GUTTER,
width: -2 * MD2ViewConfig.GUTTER,
height: -2 * MD2ViewConfig.GUTTER)
}
}
|
apache-2.0
|
d7ddaa5257629c306905ee48c1079eeb
| 29.451923 | 103 | 0.579728 | 4.769578 | false | false | false | false |
haifengkao/NightWatch
|
Example/NightWatch/JsonExtension.swift
|
1
|
2984
|
//
// JsonExtension.swift
// UbikeTracer
//
// Created by nickLin on 2017/7/21.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
extension Data {
@nonobjc var arrayDic : [[String:Any]]?{
do {
return try JSONSerialization.jsonObject(with: self, options: .mutableContainers ) as? [[String:Any]]
} catch let error as NSError {
print(msg:error)
}
return nil
}
@nonobjc var dic : [String:Any]?{
do {
return try JSONSerialization.jsonObject(with: self, options: .mutableContainers ) as? [String:Any]
} catch let error as NSError {
print(msg:error)
}
return nil
}
@nonobjc var array : [Any]?{
do {
return try JSONSerialization.jsonObject(with: self, options: .mutableContainers ) as? [Any]
} catch let error as NSError {
print(msg:error)
}
return nil
}
@nonobjc var string : String? {
return String(data: self, encoding: .utf8)
}
}
extension Dictionary {
@nonobjc var json:Data?{
guard JSONSerialization.isValidJSONObject(self) else { return nil }
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return jsonData
} catch {
return nil
}
}
}
extension Array {
@nonobjc var json:Data?{
guard JSONSerialization.isValidJSONObject(self) else { return nil }
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return jsonData
} catch {
return nil
}
}
}
extension String {
@nonobjc var ArrayDic : [[String:Any]]?{
return self.data?.arrayDic
}
@nonobjc var Array : [Any]?{
return self.data?.array
}
@nonobjc var Dic : [String:Any]?{
return self.data?.dic
}
@nonobjc var data : Data?{
return self.data(using: .utf8)
}
}
extension Collection where Self : ExpressibleByDictionaryLiteral{
func log(file: String = #file,method: String = #function,line: Int = #line){
Swift.print("\((file as NSString).lastPathComponent)[\(line)], \(method) : 總共有 key / Value \(count) 筆")
enumerated().forEach{print($0)}
}
}
extension Array where Element : Collection , Element: ExpressibleByDictionaryLiteral {
func log(file: String = #file,method: String = #function,line: Int = #line){
Swift.print("\((file as NSString).lastPathComponent)[\(line)], \(method) : 總共有 \(count) 筆")
enumerated().forEach
{
print("第 \($0.offset) 筆")
print("總共有 key / Value \($0.element.count) 筆")
$0.element.forEach
{
print($0)
}
print("-------------------\n")
}
}
}
|
mit
|
643e3fe71c44d34ff8e3c522593a8325
| 25.366071 | 112 | 0.558754 | 4.317251 | false | false | false | false |
tlax/GaussSquad
|
GaussSquad/Model/LinearEquations/Solution/Steps/MLinearEquationsSolutionStepError.swift
|
1
|
1224
|
import UIKit
class MLinearEquationsSolutionStepError:MLinearEquationsSolutionStep
{
private let kHeaderHeight:CGFloat = 45
init(
equations:[MLinearEquationsSolutionEquation],
descr:String)
{
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:14),
NSForegroundColorAttributeName:UIColor.squadRed]
let attributesSubtitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.medium(size:13),
NSForegroundColorAttributeName:UIColor.black]
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let stringTitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("MLinearEquationsSolutionStepError_title", comment:""),
attributes:attributesTitle)
let stringSubtitle:NSAttributedString = NSAttributedString(
string:descr,
attributes:attributesSubtitle)
mutableString.append(stringTitle)
mutableString.append(stringSubtitle)
super.init(
title:mutableString,
equations:equations,
headerHeight:kHeaderHeight)
}
}
|
mit
|
ddce1d185d9fb4a0a05f92781ad3f812
| 35 | 92 | 0.675654 | 6.12 | false | true | false | false |
Yalantis/Koloda
|
Pod/Classes/KolodaView/KolodaCardStorage.swift
|
2
|
1204
|
//
// KolodaCardStorage.swift
// Pods
//
// Created by Eugene Andreyev on 3/30/16.
//
//
import Foundation
import UIKit
extension KolodaView {
func createCard(at index: Int, frame: CGRect? = nil) -> DraggableCardView {
let cardView = generateCard(frame ?? frameForTopCard())
configureCard(cardView, at: index)
return cardView
}
func generateCard(_ frame: CGRect) -> DraggableCardView {
let cardView = DraggableCardView(frame: frame)
cardView.delegate = self
return cardView
}
func configureCard(_ card: DraggableCardView, at index: Int) {
let contentView = dataSource!.koloda(self, viewForCardAt: index)
card.configure(contentView, overlayView: dataSource?.koloda(self, viewForCardOverlayAt: index))
//Reconfigure drag animation constants from Koloda instance.
if let rotationMax = self.rotationMax {
card.rotationMax = rotationMax
}
if let rotationAngle = self.rotationAngle {
card.rotationAngle = rotationAngle
}
if let scaleMin = self.scaleMin {
card.scaleMin = scaleMin
}
}
}
|
mit
|
f37bf222e6f566d9b64c02a61f815b02
| 26.363636 | 103 | 0.627907 | 4.703125 | false | true | false | false |
neonichu/Wunderschnell
|
Phone App/PayPalClient.swift
|
1
|
5882
|
//
// PayPalClient.swift
// WatchButton
//
// Created by Boris Bügling on 09/05/15.
// Copyright (c) 2015 Boris Bügling. All rights reserved.
//
import Alamofire
// Somehow using `NSURLAuthenticationChallenge` didn't work against the PayPal API, either 😭
private struct AuthRequest: URLRequestConvertible {
private let clientId: String
private let clientSecret: String
private let code: String
private let grantAttributeName: String
private let grantType: String
var URLRequest: NSURLRequest {
if let URL = NSURL(string: "https://api.sandbox.paypal.com/v1/oauth2/token") {
let URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.HTTPMethod = Method.POST.rawValue
let parameters = [ "grant_type": grantType, "response_type": "token", "redirect_uri": "urn:ietf:wg:oauth:2.0:oob", grantAttributeName: code ]
let auth = String(format: "%@:%@", clientId, clientSecret).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let header = auth.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
URLRequest.setValue("Basic \(header)", forHTTPHeaderField: "Authorization")
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
fatalError("Broken Authentication URL...")
}
}
/// Implementation of https://github.com/paypal/PayPal-iOS-SDK/blob/master/docs/future_payments_server.md because we want no server. 😎
public class PayPalClient {
let baseURL = "https://api.sandbox.paypal.com/v1"
let clientId: String
let clientSecret: String
let code: String
let metadataId: String
var refreshToken: String?
var token: String?
/// For inital OAuth, pass futurePaymentCode and metadataId. When refreshing, pass refreshToken.
public init(clientId: String, clientSecret: String, code: String, metadataId: String = "") {
self.clientId = clientId
self.clientSecret = clientSecret
self.code = code
self.metadataId = metadataId
}
private func createActualPayment(description: String, _ currency: String, _ amount: String, _ completion: (paymentId: String) -> Void) {
let parameters: [String:AnyObject] = [ "intent":"authorize", "payer":["payment_method":"paypal"], "transactions": [ [ "amount": [ "currency": currency, "total": amount ], "description": description ] ]]
Alamofire.request(payPalRequest("payments/payment", .POST, parameters))
.responseJSON { (_, _, JSON, _) in
if let JSON = JSON as? [String:AnyObject], transactions = JSON["transactions"] as? [[String:AnyObject]], relatedResources = transactions.first?["related_resources"] as? [[String:AnyObject]], authorization = relatedResources.first?["authorization"] as? [String:AnyObject], id = authorization["id"] as? String {
completion(paymentId: id)
} else {
fatalError("Did not receive ID for payment")
}
}
}
private func payPalRequest(endpoint: String, _ method: Alamofire.Method, _ parameters: [String: AnyObject]?) -> URLRequestConvertible {
assert(token != nil, "")
if let token = token, URL = NSURL(string: "\(baseURL)/\(endpoint)") {
let URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.HTTPMethod = method.rawValue
URLRequest.setValue(metadataId, forHTTPHeaderField: "PayPal-Client-Metadata-Id")
URLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let encoding = Alamofire.ParameterEncoding.JSON
return encoding.encode(URLRequest, parameters: parameters).0
}
fatalError("Could not create valid request.")
}
private func requestOAuthToken(completion: () -> ()) {
let grantAttributeName = metadataId == "" ? "refresh_token" : "code"
let grantType = metadataId == "" ? "refresh_token" : "authorization_code"
Alamofire.request(AuthRequest(clientId: clientId, clientSecret: clientSecret, code: code, grantAttributeName: grantAttributeName, grantType: grantType))
.responseJSON { (_, _, JSON, _) in
if let JSON = JSON as? [String:AnyObject] {
if let refreshToken = JSON["refresh_token"] as? String {
self.refreshToken = refreshToken
}
if let token = JSON["access_token"] as? String {
self.token = token
completion()
} else {
fatalError("No `access_token` received: \(JSON)")
}
}
}
}
public func createPayment(description: String, _ currency: String, _ amount: String, completion: (paymentId: String) -> Void) {
requestOAuthToken() {
self.createActualPayment(description, currency, amount, completion)
}
}
public func pay(paymentId: String, _ currency: String, _ amount: String, completion: (paid: Bool) -> Void) {
requestOAuthToken() {
let URL = "payments/authorization/\(paymentId)/capture"
let parameters: [String: AnyObject] = [ "amount": [ "currency": currency, "total": amount ], "is_final_capture": true]
Alamofire.request(self.payPalRequest(URL, .POST, parameters))
.responseJSON { (_, _, JSON, _) in
//println(JSON)
if let JSON = JSON as? [String:AnyObject], amount = JSON["amount"] as? [String:AnyObject] {
completion(paid: true)
} else {
completion(paid: false)
}
}
}
}
}
|
mit
|
9c4e2b560af003b697e6a37c6ed233f7
| 44.184615 | 325 | 0.616956 | 4.787286 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Models/CoreData/CoreDataMigrations/CoreDataStructuralMigrations.swift
|
1
|
4527
|
//
// CoreDataStructuralMigrations.swift
//
// Created by Emily Ivie on 2/9/17.
// Based on https://gist.github.com/kean/28439b29532993b620497621a4545789
// Copyright (c) 2016 Alexander Grebenyuk (github.com/kean).
// The MIT License (MIT)
//
import CoreData
public struct CoreDataStructuralMigrations {
/// Warning: Keep in sync with currently selected migration. If they don't match, fatal error.
private var migrationNames = [
"CoreData",
"CoreData20170208",
"CoreData20180204",
"CoreData20190609",
]
private let storeName: String
private let storeUrl: URL
init(storeName: String, storeUrl: URL) {
self.storeName = storeName
self.storeUrl = storeUrl
}
func run() throws {
guard FileManager.default.fileExists(atPath: storeUrl.path) else {
// we have no prior persistent data, so no migrations to run...
return
}
let storeDirectory = Bundle.main.url(forResource: storeName, withExtension: "momd")?.lastPathComponent
var migrationMoms: [NSManagedObjectModel] = try migrationNames.map {
return try managedObjectModel(forName: $0, bundle: Bundle.main, directory: storeDirectory)
}.filter({ $0 != nil }).map({ $0! })
migrationMoms = try reduceMomsToPendingChanges(moms: migrationMoms)
if migrationMoms.count > 1, let startMom = migrationMoms.first {
_ = try migrationMoms[1..<migrationMoms.count].reduce(startMom) { (sourceMom, destinationMom) in
try migrateStore(from: sourceMom, to: destinationMom)
return destinationMom
}
}
}
private func managedObjectModel(
forName name: String,
bundle: Bundle,
directory: String?
) throws -> NSManagedObjectModel? {
let omoUrl = bundle.url(forResource: name, withExtension: "omo", subdirectory: directory)
let momUrl = bundle.url(forResource: name, withExtension: "mom", subdirectory: directory)
guard let url = omoUrl ?? momUrl else {
if directory != nil {
return try managedObjectModel(forName: name, bundle: bundle, directory: nil)
} else {
throw CoreDataMigration.MigrationError.missingModels
}
}
return NSManagedObjectModel(contentsOf: url)
}
private func reduceMomsToPendingChanges(moms: [NSManagedObjectModel]) throws -> [NSManagedObjectModel] {
let meta = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: NSSQLiteStoreType, at: storeUrl)
guard let index = moms.firstIndex(where: {
$0.isConfiguration(withName: nil, compatibleWithStoreMetadata: meta)
}) else {
throw CoreDataMigration.MigrationError.incompatibleModels
}
return Array(moms[index..<moms.count])
}
private func migrateStore(
from sourceMom: NSManagedObjectModel,
to destinationMom: NSManagedObjectModel
) throws {
// Prepare temp directory
let dir = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
defer {
_ = try? FileManager.default.removeItem(at: dir)
}
// Perform migration
let mapping = try findMapping(from: sourceMom, to: destinationMom)
let destinationUrl = dir.appendingPathComponent(storeUrl.lastPathComponent)
let manager = NSMigrationManager(sourceModel: sourceMom, destinationModel: destinationMom)
try autoreleasepool {
try manager.migrateStore(
from: storeUrl,
sourceType: NSSQLiteStoreType,
options: nil,
with: mapping,
toDestinationURL: destinationUrl,
destinationType: NSSQLiteStoreType,
destinationOptions: nil
)
}
// Replace source store
let psc = NSPersistentStoreCoordinator(managedObjectModel: destinationMom)
try psc.replacePersistentStore(
at: storeUrl,
destinationOptions: nil,
withPersistentStoreFrom: destinationUrl,
sourceOptions: nil,
ofType: NSSQLiteStoreType
)
}
private func findMapping(
from sourceMom: NSManagedObjectModel,
to destinationMom: NSManagedObjectModel
) throws -> NSMappingModel {
if let mapping = NSMappingModel(
from: Bundle.allBundles,
forSourceModel: sourceMom,
destinationModel: destinationMom
) {
return mapping // found custom mapping
}
return try NSMappingModel.inferredMappingModel(
forSourceModel: sourceMom,
destinationModel: destinationMom
)
}
private func remove(oldStoreUrl: URL?) -> Bool {
guard let oldStoreUrl = oldStoreUrl else { return true }
do {
try FileManager.default.removeItem(at: oldStoreUrl)
return true
} catch {
print("Failed to delete old store")
}
return false
}
}
|
mit
|
9038aa82f3fd2a749c2aad5d1b3ad2ec
| 31.106383 | 113 | 0.739563 | 3.84949 | false | false | false | false |
jamesjmtaylor/weg-ios
|
wegUnitTests/repoUnitTests.swift
|
1
|
895
|
//
// repoUnitTests.swift
// wegUnitTests
//
// Created by Taylor, James on 10/2/18.
// Copyright © 2018 James JM Taylor. All rights reserved.
//
import XCTest
import Mockingjay
@testable import weg_ios
class repoUnitTests: XCTestCase {
override func setUp() {
super.setUp()
let url = Bundle(for: type(of: self)).url(forResource: "getAllResponse", withExtension: "json")!
let data = try! Data(contentsOf: url)
let getAllUrl = EquipmentRepository.getAllUrl()
// stub(http(.get, uri: getAllUrl), jsonData(data))
}
func testExample() {
EquipmentRepository.getEquipment { (error) in
if let error = error {
XCTFail(error)
}
let equipment = EquipmentRepository.getEquipmentFromDatabase()
XCTAssert(!(equipment?.isEmpty ?? true)) //Should not be empty
}
}
}
|
mit
|
990c3b3adbc337ed5116666641074936
| 26.9375 | 104 | 0.620805 | 4.17757 | false | true | false | false |
coodly/TalkToCloud
|
Sources/TalkToCloud/Commander.swift
|
1
|
2653
|
/*
* Copyright 2016 Coodly 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
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public class Commander<C: Command> {
private let arguments: [String]
private let containerId: String
public init(containerId: String, arguments: [String]) {
self.arguments = arguments
self.containerId = containerId
}
public func run() {
Logging.log("Run \(String(describing: C.self))")
Logging.log("Arguments: \(arguments)")
let command = C()
#if os(Linux)
let fetch = CommandLineFetch()
#else
let fetch = SynchronousSystemFetch()
#endif
let config = Configuration(containerId: containerId)
if var consumer = command as? ContainerConsumer {
consumer.container = containerFromArguments(config: config, fetch: fetch)!
}
if var consumer = command as? DevelopmentConsumer {
consumer.developmentContainer = config.developmentContainer(with: fetch)
}
if var consumer = command as? ProductionConsumer {
consumer.productionContainer = config.productionContainer(with: fetch)
}
var remaining = arguments
remaining.removeFirst()
let toRemove = ["--production", "--development"]
for remove in toRemove {
if let index = remaining.firstIndex(of: remove) {
remaining.remove(at: index)
}
}
Logging.log("Command arguments: \(remaining)")
command.execute(with: remaining)
}
private func containerFromArguments(config: Configuration, fetch: NetworkFetch) -> CloudContainer? {
if arguments.contains("--production") {
return config.productionContainer(with: fetch)
} else if arguments.contains("--development") {
return config.developmentContainer(with: fetch)
} else {
Logging.log("No environment defined. We will crash now 8-|")
return nil
}
}
}
|
apache-2.0
|
dcf22ae2085cacc5deb58ff835968d12
| 33.454545 | 104 | 0.637392 | 4.894834 | false | true | false | false |
ps2/rileylink_ios
|
MinimedKit/PumpEvents/ResumePumpEvent.swift
|
1
|
946
|
//
// ResumePumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 3/8/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct ResumePumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public let wasRemotelyTriggered: Bool
public init?(availableData: Data, pumpModel: PumpModel) {
length = 7
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
wasRemotelyTriggered = availableData[5] & 0b01000000 != 0
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "Resume",
"wasRemotelyTriggered": wasRemotelyTriggered,
]
}
}
|
mit
|
4beac86ad59f345da6dffbd53ea6707b
| 24.540541 | 75 | 0.625397 | 4.772727 | false | false | false | false |
PlanTeam/BSON
|
Sources/BSON/Helpers/ByteBuffer+Helpers.swift
|
1
|
1281
|
import NIO
extension ByteBuffer {
func getDouble(at offset: Int) -> Double? {
guard let int = getInteger(at: offset, endianness: .little, as: UInt64.self) else {
return nil
}
return Double(bitPattern: int)
}
func getObjectId(at offset: Int) -> ObjectId? {
guard
let timestamp = getInteger(at: offset + 0, endianness: .big, as: UInt32.self),
let random = getInteger(at: offset + 4, endianness: .big, as: UInt64.self)
else {
return nil
}
return ObjectId(timestamp: timestamp, random: random)
}
func getByte(at offset: Int) -> UInt8? {
return self.getInteger(at: offset, endianness: .little, as: UInt8.self)
}
/// Returns the first index at which `byte` appears, starting from the reader position
func firstRelativeIndexOf(startingAt: Int) -> Int? {
withUnsafeReadableBytes { buffer -> Int? in
var i = startingAt
let count = buffer.count
while i < count {
if buffer[i] == 0 {
return i - startingAt
}
i += 1
}
return nil
}
}
}
|
mit
|
5fdb3d27f8e1d47b868c630b6fe5500f
| 28.113636 | 91 | 0.517564 | 4.494737 | false | false | false | false |
erinshihshih/ETripTogether
|
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQNSArray+Sort.swift
|
3
|
2410
|
//
// IQNSArray+Sort.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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
/**
UIView.subviews sorting category.
*/
internal extension Array {
///--------------
/// MARK: Sorting
///--------------
/**
Returns the array by sorting the UIView's by their tag property.
*/
internal func sortedArrayByTag() -> [Element] {
return sort({ (obj1 : Element, obj2 : Element) -> Bool in
let view1 = obj1 as! UIView
let view2 = obj2 as! UIView
return (view1.tag < view2.tag)
})
}
/**
Returns the array by sorting the UIView's by their tag property.
*/
internal func sortedArrayByPosition() -> [Element] {
return sort({ (obj1 : Element, obj2 : Element) -> Bool in
let view1 = obj1 as! UIView
let view2 = obj2 as! UIView
let x1 = CGRectGetMinX(view1.frame)
let y1 = CGRectGetMinY(view1.frame)
let x2 = CGRectGetMinX(view2.frame)
let y2 = CGRectGetMinY(view2.frame)
if y1 != y2 {
return y1 < y2
} else {
return x1 < x2
}
})
}
}
|
mit
|
6b43f871deab3318e08a877b70c8cf44
| 32.472222 | 80 | 0.618257 | 4.564394 | false | false | false | false |
telldus/telldus-live-mobile-v3
|
ios/DeviceActionShortcutExtension/DeviceActionShortcutIntentHandler.swift
|
1
|
2482
|
//
// DeviceActionShortcutIntentHandler.swift
// DeviceActionShortcutExtension
//
// Created by Rimnesh Fernandez on 15/02/21.
// Copyright © 2021 Telldus Technologies AB. All rights reserved.
//
import Foundation
import UIKit
import DeviceActionShortcut
final class DeviceActionShortcutIntentHandler: NSObject, DeviceActionShortcutIntentHandling {
@available(iOS 12.0, *)
func handle(intent: DeviceActionShortcutIntent, completion: @escaping (DeviceActionShortcutIntentResponse) -> Void) {
let dataDict = Utilities().getAuthData()
guard dataDict != nil
else {
completion(DeviceActionShortcutIntentResponse(code: .failure, userActivity: nil))
return
}
let pro = dataDict?["pro"] as? Int
let _isBasicUser = SharedUtils().isBasicUser(pro: pro)
if _isBasicUser {
completion(DeviceActionShortcutIntentResponse(code: .basic, userActivity: nil))
return;
}
guard let deviceId = intent.deviceId else {
completion(DeviceActionShortcutIntentResponse(code: .failure, userActivity: nil))
return
}
let method = intent.method
let fetcher = Fetcher();
if method == "2048" {
let thermostatValue = intent.thermostatValue
fetcher.deviceSetStateThermostat(deviceId: deviceId, stateValue: thermostatValue!) { (status) in
guard status == "success" else {
completion(DeviceActionShortcutIntentResponse(code: .failure, userActivity: nil))
return
}
completion(DeviceActionShortcutIntentResponse(code: .success, userActivity: nil))
}
} else if method == "1024" {
let rgbValue = intent.rgbValue
fetcher.deviceSetStateRGB(deviceId: deviceId, stateValue: rgbValue!) { (status) in
guard status == "success" else {
completion(DeviceActionShortcutIntentResponse(code: .failure, userActivity: nil))
return
}
completion(DeviceActionShortcutIntentResponse(code: .success, userActivity: nil))
}
} else {
let dimValue = intent.dimValue
fetcher.deviceSetState(deviceId: deviceId, method: method!, stateValue: dimValue) { (status) in
guard status == "success" else {
completion(DeviceActionShortcutIntentResponse(code: .failure, userActivity: nil))
return
}
completion(DeviceActionShortcutIntentResponse(code: .success, userActivity: nil))
}
}
}
}
|
gpl-3.0
|
d1930c1cade4d1bc855a490e97442864
| 32.527027 | 119 | 0.674728 | 4.971944 | false | false | false | false |
liuduoios/HLDBadgeControls
|
HLDBadgeControlsDemo/HLDBadgeControlsDemo/ViewController.swift
|
1
|
1417
|
//
// ViewController.swift
// HLDBadgeControlsDemo
//
// Created by 刘铎 on 15/9/9.
// Copyright © 2015年 Derek Liu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let smallRedDot = HLDSmallRedDot()
smallRedDot.frame = CGRect(origin: CGPoint(x: 100, y: 100), size: smallRedDot.frame.size)
view.addSubview(smallRedDot)
let badgeView = HLDBadgeView()
badgeView.frame = CGRect(origin: CGPoint(x: 200, y: 100), size: badgeView.frame.size)
badgeView.autoHideWhenZero = true
badgeView.setCount(344)
view.addSubview(badgeView)
let button = UIButton(type: .RoundedRect)
button.frame = CGRectMake(100, 200, 100, 30)
button.backgroundColor = UIColor.blueColor()
view.addSubview(button)
button.hld_setBadgeCount(90)
let cell = UITableViewCell(frame: CGRect(x: 200, y: 200, width: 150, height: 44))
cell.contentView.backgroundColor = UIColor.yellowColor()
view.addSubview(cell)
cell.hld_setCellBadgeCount(20)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
553c85d0ab885255c039e83e12223a7e
| 29.652174 | 97 | 0.646099 | 4.208955 | false | false | false | false |
dvSection8/dvSection8
|
dvSection8/Classes/Utils/_DVForceUpdate.swift
|
1
|
3164
|
//
// AppVersion.swift
// Rush
//
// Created by MJ Roldan on 31/07/2017.
// Copyright © 2017 Mark Joel Roldan. All rights reserved.
//
import Foundation
/*public enum iTunesLookUp: String {
case ph = "https://itunes.apple.com/ph/lookup?id="
case all = "https://itunes.apple.com/lookup?id="
}
public struct _DVForceUpdate {
private lazy var api: DVAPI = {
return DVAPI()
}()
var itunesID: Any? = nil
var lookUpTerritory: String? = nil
public init(itunesID id: Any? = nil, territory lookUp: iTunesLookUp) {
self.itunesID = id
self.lookUpTerritory = lookUp.rawValue
}
/**
Set content-type in HTTP header
*/
fileprivate func contentType() -> String {
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
return contentType
}
/**
This function will result block for lookup itunes api to get the json data
*/
public func getAppStoreDetails(_ value: @escaping ResponseSuccessBlock, failed: @escaping ResponseFailedBlock) {
let url = URL(string: "\(self.lookUpTerritory ?? "")" + "\(self.itunesID ?? "")")
let headers = ["content-Type": self.contentType()]
let requests = DVAPIRequests(.post, url: url, parameters: nil, headers: headers)
self.api.request(requests, success: { (results) in
if let results = results["results"] as? [Any] {
if results.count > 0 {
if let dict = results[0] as? JSONDictionary {
value(dict)
}
}
}
}, failed: { (errorCode) in
failed(errorCode)
})
}
/**
check the current app store version and current installed app version
*/
public func checkAppVersion(_ update: @escaping () -> ()) {
self.getAppStoreDetails({ (result) in
// get installed app version
if let appStoreVersion = result["version"] as? String {
let deviceAppVersion = DVDeviceManager().appVersion
print("appStoreVersion: \(appStoreVersion), deviceAppVersion: \(deviceAppVersion)")
// get each version number
let asvComponents = appStoreVersion.components(separatedBy: ".")
let davComponents = deviceAppVersion.components(separatedBy: ".")
var isOutOfVersion = false
// check if current app store version and app version has not equal
for v in 0..<min(asvComponents.count, davComponents.count) {
let asv :String = asvComponents[v]
let dav :String = davComponents[v]
if asv != dav {
isOutOfVersion = (dav < asv)
break
}
}
// the app version is out to date
if isOutOfVersion {
update()
}
}
}) {_ in
// Failed
}
}
}*/
|
mit
|
324c6ed3f270fac9162bbd617ee5afc1
| 33.758242 | 116 | 0.548214 | 4.584058 | false | false | false | false |
dropbox/SwiftyDropbox
|
Source/SwiftyDropbox/Shared/Handwritten/OAuth/OAuthUtils.swift
|
1
|
3006
|
///
/// Copyright (c) 2020 Dropbox, Inc. All rights reserved.
///
import Foundation
/// Contains utility methods used in auth flow. e.g. method to construct URL query.
enum OAuthUtils {
static func createPkceCodeFlowParams(for authSession: OAuthPKCESession) -> [URLQueryItem] {
var params = [URLQueryItem]()
if let scopeString = authSession.scopeRequest?.scopeString {
params.append(URLQueryItem(name: OAuthConstants.scopeKey, value: scopeString))
}
if let scopeRequest = authSession.scopeRequest, scopeRequest.includeGrantedScopes {
params.append(
URLQueryItem(name: OAuthConstants.includeGrantedScopesKey, value: scopeRequest.scopeType.rawValue)
)
}
let pkceData = authSession.pkceData
params.append(contentsOf: [
URLQueryItem(name: OAuthConstants.codeChallengeKey, value: pkceData.codeChallenge),
URLQueryItem(name: OAuthConstants.codeChallengeMethodKey, value: pkceData.codeChallengeMethod),
URLQueryItem(name: OAuthConstants.tokenAccessTypeKey, value: authSession.tokenAccessType),
URLQueryItem(name: OAuthConstants.responseTypeKey, value: authSession.responseType),
])
return params
}
/// Extracts auth response parameters from URL and removes percent encoding.
/// Response parameters from DAuth via the Dropbox app are in the query component.
static func extractDAuthResponseFromUrl(_ url: URL) -> [String: String] {
extractQueryParamsFromUrlString(url.absoluteString)
}
/// Extracts auth response parameters from URL and removes percent encoding.
/// Response parameters OAuth 2 code flow (RFC6749 4.1.2) are in the query component.
static func extractOAuthResponseFromCodeFlowUrl(_ url: URL) -> [String: String] {
extractQueryParamsFromUrlString(url.absoluteString)
}
/// Extracts auth response parameters from URL and removes percent encoding.
/// Response parameters from OAuth 2 token flow (RFC6749 4.2.2) are in the fragment component.
static func extractOAuthResponseFromTokenFlowUrl(_ url: URL) -> [String: String] {
guard let urlComponents = URLComponents(string: url.absoluteString),
let responseString = urlComponents.fragment else {
return [:]
}
// Create a query only URL string and extract its individual query parameters.
return extractQueryParamsFromUrlString("?\(responseString)")
}
/// Extracts query parameters from URL and removes percent encoding.
private static func extractQueryParamsFromUrlString(_ urlString: String) -> [String: String] {
guard let urlComponents = URLComponents(string: urlString),
let queryItems = urlComponents.queryItems else {
return [:]
}
return queryItems.reduce(into: [String: String]()) { result, queryItem in
result[queryItem.name] = queryItem.value
}
}
}
|
mit
|
2bccbabbcffc3989d2b93523b047a3a8
| 46.714286 | 114 | 0.694278 | 4.960396 | false | false | false | false |
adamnemecek/SortedArray.swift
|
Sources/SortedSlice.swift
|
1
|
2265
|
//
// SortedSlice.swift
// SortedCollection
//
// Created by Adam Nemecek on 4/29/17.
// Copyright © 2017 Adam Nemecek. All rights reserved.
//
public struct SortedSlice<Element : Comparable> : MutableCollection, Equatable, RandomAccessCollection,
RangeReplaceableCollection, CustomStringConvertible, ExpressibleByArrayLiteral {
public typealias Base = SortedArray<Element>
public typealias Index = Base.Index
public private(set) var startIndex : Index
public private(set) var endIndex : Index
private(set) internal var base : Base
public init() {
self = []
}
public init(arrayLiteral literal: Element...) {
base = SortedArray(literal)
startIndex = base.startIndex
endIndex = base.endIndex
}
internal init(base: Base, range: CountableRange<Index>) {
self.base = base
startIndex = range.lowerBound
endIndex = range.upperBound
}
internal init(base: Base, range: Range<Index>) {
self.base = base
startIndex = range.lowerBound
endIndex = range.upperBound
}
public var description: String {
return base.content[indices].description
}
public func index(after i: Index) -> Index {
return base.index(after: i)
}
public func index(before i: Index) -> Index {
return base.index(before: i)
}
public subscript(index: Index) -> Element {
get {
return base[index]
}
set {
base[index] = newValue
}
}
public func sort() {
return
}
public func sorted() -> [Element] {
return Array(self)
}
public static func ==(lhs: SortedSlice, rhs: SortedSlice) -> Bool {
return lhs.count == rhs.count && lhs.elementsEqual(rhs)
}
mutating
public func replaceSubrange<C : Collection>(_ subrange: Range<Index>, with newElements: C) where C.Iterator.Element == Element {
base.replaceSubrange(subrange, with: [])
newElements.forEach {
base.append($0)
}
let i = indices.clamped(to: base.indices)
startIndex = i.lowerBound
endIndex = i.upperBound
}
}
|
mit
|
1465167dd91f3a7000d9d6f674d35cd4
| 24.727273 | 132 | 0.600265 | 4.639344 | false | false | false | false |
vowed21/HWSwiftyViewPager
|
HWSwiftyViewPagerDemo/HWSwiftyViewPagerDemo/AppDelegate.swift
|
1
|
6157
|
//
// AppDelegate.swift
// HWSwiftyViewPagerDemo
//
// Created by HyunWoo Kim on 2016. 1. 19..
// Copyright © 2016년 KokohApps. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.kokohapps.ios.HWSwiftyViewPagerDemo" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "HWSwiftyViewPagerDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
36d88d3c1d93c732c45a25b40434418e
| 54.441441 | 291 | 0.718557 | 5.789276 | false | false | false | false |
damoyan/BYRClient
|
FromScratch/View/ArticleHeader.swift
|
1
|
1603
|
//
// ArticleHeader.swift
// FromScratch
//
// Created by Yu Pengyang on 12/23/15.
// Copyright © 2015 Yu Pengyang. All rights reserved.
//
import UIKit
class ArticleHeader: UITableViewHeaderFooterView {
@IBOutlet weak var avatar: BYRImageView!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var positionLabel: UILabel!
@IBAction func onReply(sender: UIButton) {
print("reply")
}
override func prepareForReuse() {
super.prepareForReuse()
avatar.byr_reset()
idLabel.text = nil
nameLabel.text = nil
}
func update(article: ArticleCellData) {
if let url = article.article.user?.faceURL {
avatar.byr_setImageWithURLString(url)
} else {
avatar.image = UIImage(named: "default_avatar")
}
idLabel.text = article.article.user?.id
nameLabel.text = article.article.user?.userName
if let position = article.article.position {
positionLabel.text = {
switch position {
case 0:
return "楼主"
case 1:
return "沙发"
case 2:
return "板凳"
default:
return "\(position)楼"
}
}()
} else {
positionLabel.text = nil
}
}
deinit {
avatar.stopAnimating()
avatar.animationImages = nil
avatar.image = nil
print("deinit header")
}
}
|
mit
|
7a4b74344a634cb0a425b718014a1d1f
| 25.032787 | 59 | 0.537154 | 4.563218 | false | false | false | false |
doubleencore/XcodeIssueGenerator
|
XcodeIssueGenerator/ArgumentParser.swift
|
1
|
4913
|
//
// ArgumentParser.swift
//
// Copyright (c) 2016 POSSIBLE Mobile (https://possiblemobile.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
class ArgumentParser {
// MARK: - Static
struct K {
static let InsufficientArgumentsMessage = "Insufficient arguments provided for option."
static let CouldNotMakeExcludeDirectoryMessage = "Could not make exclude directory. Directories should be relative to the project file which is the same as being relative to ($SRCROOT)."
}
static func printUsage(_ executableName: String) {
print("Usage:")
print("\t\(executableName) -w warning tags -e error tags -b build configuration -x exclude directories")
}
// MARK: - ArgumentParser
// MARK: Lifetime
init(sourceRoot: String) {
self.sourceRoot = sourceRoot
}
// MARK: Internal
let sourceRoot: String
var warningTags: [String]?
var errorTags: [String]?
var buildConfig: String?
var excludeURLs = [URL]()
/**
Parse arguments into warning tags, error tags, build configuration, and exclude URLs.
- parameter arguments: An array of argument strings.
- returns: Bool indicating if we met the minimum argument requirements.
*/
func parse(_ arguments: [String]) -> Bool {
var argumentsGenerator = arguments.makeIterator()
while let arg = argumentsGenerator.next() {
switch arg {
case "-w":
if let next = argumentsGenerator.next() {
warningTags = split(list: next)
} else {
print(K.InsufficientArgumentsMessage)
}
case "-e":
if let next = argumentsGenerator.next() {
errorTags = split(list: next)
} else {
print(K.InsufficientArgumentsMessage)
}
case "-b":
if let next = argumentsGenerator.next() {
buildConfig = next
} else {
print(K.InsufficientArgumentsMessage)
}
case "-x":
if let next = argumentsGenerator.next() {
let excludePaths = split(list: next)
excludeURLs.append(contentsOf: makeURLs(from: excludePaths))
} else {
print(K.InsufficientArgumentsMessage)
}
default:
break
}
}
// Minimum requirements are we have warning tags or error tags and also a build configuration.
if (warningTags?.isEmpty == false || errorTags?.isEmpty == false) && buildConfig?.isEmpty == false {
return true
} else {
return false
}
}
// MARK: Private
/**
Split a comma-delimited string into an Array of strings.
- parameter list: Lists should be comma-separated strings: "TODO,FIXME"
- returns: Array of strings with whitespace trimmed.
*/
private func split(list: String?) -> [String]? {
guard let list = list else { return nil }
let components = list.components(separatedBy: ",")
return components.map { $0.trimmingCharacters(in: CharacterSet.whitespaces) }
}
private func makeURLs(from excludePaths: [String]?) -> [URL] {
guard let excludePaths = excludePaths else { return [] }
var excludeURLs = [URL]()
for excludePath in excludePaths {
let fullExcludePath = "\(sourceRoot)/\(excludePath)"
if FileManager.isDirectory(fullExcludePath) {
excludeURLs.append(URL(fileURLWithPath: fullExcludePath))
} else {
print(K.CouldNotMakeExcludeDirectoryMessage)
}
}
return excludeURLs
}
}
|
mit
|
cd50e3a847cb28d35a63eae91b1feaef
| 33.356643 | 194 | 0.615306 | 4.917918 | false | false | false | false |
brokenseal/iOS-exercises
|
Team Treehouse/RestaurantFinder/RestaurantFinder/RestaurantListController.swift
|
1
|
6370
|
//
// MasterViewController.swift
// RestaurantFinder
//
// Created by Pasan Premaratne on 5/4/16.
// Copyright © 2017 Davide Callegar. All rights reserved.
//
import UIKit
import MapKit
let DEFAULT_COORDINATE = Coordinate(latitude: 40.759106, longitude: -73.985185)
class RestaurantListController: UITableViewController, UISearchBarDelegate {
let foursquareClient = FoursquareClient(
clientID: "5O53IDZJAWB12DFHH1WFEYL2I1I3L0BTYQPHZUGJZYFL5IO4",
clientSecret: "DXVEG1PDN0NMSOOZRRLJTWXTAON4RUL3GJSXAZVVEKHP40A3"
)
let locationManager = LocationManager()
var lastReceivedCoordinate: Coordinate = DEFAULT_COORDINATE
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var searchBar: UISearchBar!
var venues: [Venue] = [] {
didSet {
tableView.reloadData()
addMapAnnotations()
}
}
var mapManager: SimpleMapManager? {
guard let map = map else { return nil }
return SimpleMapManager(map, regionRadius: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupLocationManager()
}
private func setupLocationManager(){
locationManager.on(.locationFix) { [weak self] coordinate in
self?.lastReceivedCoordinate = coordinate as! Coordinate
self?.updateRestaurants(withCoordinate: coordinate as! Coordinate, query: nil)
}
locationManager.on(.locationError) { [weak self] error in
guard let uiViewController = self else { return }
let intError = error as! Error
SimpleAlert.default(
title: "Localization Error",
message: intError.localizedDescription
).show(using: uiViewController)
}
locationManager.on(.permissionUpdate) { [weak self] status in
let intStatus = status as! CLAuthorizationStatus
guard let uiViewController = self else { return }
if intStatus == .denied {
SimpleAlert.default(
title: "Localization Permission Required",
message: "Without the permission to use your localization services, this app won't work"
).show(using: uiViewController)
}
}
locationManager.getPermission()
locationManager.startListeningForLocationChanges()
}
private func updateRestaurants(withCoordinate coordinate: Coordinate, query: String?){
refreshControl?.beginRefreshing()
foursquareClient.fetchRestaurantsFor(
coordinate,
category: .food(nil),
query: query ?? searchBar.text
//searchRadius: ,
//limit: ,
) { result in
switch result {
case .success(let venues):
self.venues = venues
case .failure(let error):
SimpleAlert.default(
title: "Error retrieving restaurant data",
message: error.localizedDescription
).show(using: self)
}
self.refreshControl?.endRefreshing()
}
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
let venue = venues[indexPath.row]
controller.venue = venue
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return venues.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantCell", for: indexPath) as! RestaurantCell
let venue = venues[indexPath.row]
cell.setup(title: venue.name, checkinCount: venue.checkins.description, category: venue.categoryName)
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
@IBAction func refreshRestaurantData(_ sender: AnyObject) {
self.updateRestaurants(withCoordinate: lastReceivedCoordinate, query: nil)
}
func addMapAnnotations(){
guard let mapManager = mapManager else { return }
let pins: [Pin] = venues.filter { venue in
return venue.location?.coordinate != nil
}.map { venue in
let coordinate = (venue.location?.coordinate)!
return Pin(
title: venue.name,
latitude: coordinate.latitude,
longitude: coordinate.longitude
)
}
mapManager.removeAllPins()
mapManager.addPins(pinsData: pins)
mapManager.showRegion(
latitude: lastReceivedCoordinate.latitude,
longitude: lastReceivedCoordinate.longitude
)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let text = searchBar.text {
searchBar.resignFirstResponder()
updateRestaurants(withCoordinate: lastReceivedCoordinate, query: text)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
updateRestaurants(withCoordinate: lastReceivedCoordinate, query: nil)
}
}
|
mit
|
a2bc3bb742d479ba4855be9cceb36c89
| 35.1875 | 122 | 0.628356 | 5.320802 | false | false | false | false |
codepgq/LearningSwift
|
CustomPullToRefresh/CustomPullToRefresh/ViewController.swift
|
1
|
2064
|
//
// ViewController.swift
// CustomPullToRefresh
//
// Created by ios on 16/9/26.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
class ViewController: UIViewController ,UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
/// 数据源
private lazy var dataSource : TBDataSource = {
let source = TBDataSource.cellIdentifierWith("iconCell", data: [["😂", "🤗", "😳", "😌", "😊"],["😂", "🤗", "😳", "😌", "😊"],["😂", "🤗", "😳", "😌", "😊"]], style: TBSectionStyle.Section_Has, cell: { (cell: AnyObject, item: AnyObject) -> () in
let newCell = cell as! UITableViewCell
let newItem = item as! String
newCell.textLabel!.text = newItem
newCell.textLabel?.font = UIFont(name: "Apple Color Emoji", size: 40)
newCell.textLabel?.textAlignment = NSTextAlignment.Center
})
return source
}()
private lazy var refreshControl : CustomRefreshView = CustomRefreshView.addViewsForNib("RefreshContents")
private var isAnimating : Bool = false
var timer: NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = dataSource
tableView.delegate = self
tableView.rowHeight = 60
tableView.addSubview(refreshControl)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if refreshControl.refreshing {
if !isAnimating {
doSomething()
refreshControl.startAnimation()
}
}
}
/**
开启定时器
*/
private func doSomething() {
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: #selector(ViewController.endedOfWork), userInfo: nil, repeats: true)
}
/**
定时器结束,关闭动画
*/
@objc private func endedOfWork() {
refreshControl.endRefreshing()
timer.invalidate()
timer = nil
}
}
|
apache-2.0
|
d92480900c84a4e7dc61b1e145cf86f8
| 28.117647 | 237 | 0.592424 | 4.987406 | false | false | false | false |
samodom/UIKitSwagger
|
UIKitSwagger/Spinner/SpinnerStateManager.swift
|
1
|
3512
|
//
// SpinnerStateManager.swift
// UIKitSwagger
//
// Created by Sam Odom on 1/23/15.
// Copyright (c) 2015 Swagger Soft. All rights reserved.
//
import UIKit
/**
State enumeration representing the managed state of a `UIActivityIndicatorView`.
- `Detached`: The manager does not currently have a spinner attached to it.
- `Stopped`: The manager has a spinner, but it is not supposed to be animated.
- `Started(Int)`: The manager has a spinner, is supposed to be animating, and is using a client count represented by the associated integer.
*/
public enum SpinnerState {
case Detached
case Stopped
case Started(Int)
}
/**
Class that helps manage mutliple concurrent client tasks that use a `UIActivityIndicatorView`.
*/
public class SpinnerStateManager {
/**
The current state of the manager concerning attachment to a spinner and its expected animation state.
- note: This value cannot be modified directly. Instead, the state is managed internally through the assignment of the spinner and by start/stop events.
*/
public private(set) var currentState = SpinnerState.Detached
/**
The instance of `UIActivityIndicatorView` that is attached to the manager, if any.
*/
weak public var spinner: UIActivityIndicatorView? {
didSet {
matchNewSpinnerState()
}
}
/**
Designated initializer for a `SpinnerStateManager`.
- parameter spinner: An instance of `UIActivityIndicatorView` to be managed.
- note: If a spinner is provided during initialization, the manager's state will be either `Stopped` or `Started(1)`, depending on the animation state of the spinner.
*/
public init(_ spinner: UIActivityIndicatorView? = nil) {
self.spinner = spinner
matchNewSpinnerState()
}
/**
Begins animating an attached spinner, if any, or increases the client count of a spinner that is already animating.
- note: If a spinner is not attached to the manager, the start event is ignored.
*/
public func start() {
spinner?.startAnimating()
switch currentState {
case .Stopped:
currentState = .Started(1)
case .Started(let clientCount):
currentState = .Started(clientCount + 1)
case .Detached:
break
}
}
/**
Stop animating an attached spinner, if any, if it is currently animating and has a client count of 1.
- note: If it is animating and has multiple clients, the client count is decreased by one (1) and the spinner will continue to animate. If a spinner is not attached to the manager, the stop event is ignored.
*/
public func stop() {
removeClient()
}
private func removeClient() {
switch currentState {
case .Started(let clients) where clients == 1:
currentState = .Stopped
case .Started(let clients):
currentState = .Started(clients - 1)
default:
break
}
stopAnimatingIfNeeded()
}
private func stopAnimatingIfNeeded() {
switch currentState {
case .Started(_):
break
default:
spinner?.stopAnimating()
}
}
private func matchNewSpinnerState() {
if spinner == nil {
currentState = .Detached
}
else if spinner!.isAnimating() {
currentState = .Started(1)
}
else {
currentState = .Stopped
}
}
}
|
mit
|
f47710a86793306782ef0cee2d9e1270
| 29.017094 | 212 | 0.644647 | 4.871012 | false | false | false | false |
ChristianKienle/Bold
|
Bold/QueryResult.swift
|
1
|
3592
|
import Foundation
/**
A query result is returned by executeQuery(query:(arguments:)). The result of a query can either be a success (.Success) or a failure (.Failure). If the result is .Success then it has an associated result set (see ResultSet). If the result is .Failure then it has an associcated error (see Error).
You can use for-in to iterate over the query result:
let queryResult = db.executeQuery(query)
for row in queryResult {
// work with the row
}
In the above example row is an instance of Row. If the query result is .Failure the above code is still valid but the code block of the for-in-loop is simply not executed. If the above for-loop iterates over every row in the query result it is closed automatically for you after the last iteration. If you are not using for-in to iterate over the complete result set then you have to close it manually.
You can use isSuccess and isFailure to find out whether the query contains a result or an error.
*/
public enum QueryResult {
/**
Represents a successful query.
*/
case success(ResultSet)
/**
Represents a failed query.
*/
case failure(Error)
/**
Is used to determine if the query was successful.
:returns: true if the query was successful (then you can be sure that resultSet is non-nil), otherwise false.
*/
public var isSuccess: Bool {
return resultSet != nil
}
/**
Is used to determine if the query failed.
:returns: true if the query failed (then you can be sure that the error is non-nil), otherwise false.
*/
public var isFailure: Bool {
return !isSuccess
}
/**
Is used to determine get to the actual result set (see ResultSet).
:returns: a result set if the query succeeded, otherwise nil.
*/
public var resultSet: ResultSet? {
switch self {
case .success(let result): return result
default: return nil
}
}
/**
Is used to get the error if the executed query failed.
:returns: an error if the query failed, otherwise nil.
*/
public var error: Error? {
switch self {
case .failure(let error): return error
default: return nil
}
}
/**
Is used to close the underlying result set. If there is no result set then false is returned. This means that you can safely call this method even if there is no result set.
:returns: true if there was a result set and it has been closed, otherwise false.
*/
public func closeResultSet() -> Bool {
guard let resultSet = self.resultSet else {
return false
}
return resultSet.close()
}
public typealias Consumer = (_ resultSet: ResultSet) -> (Void)
public func consumeResultSet(_ consumer: Consumer) {
guard let resultSet = resultSet else {
return
}
consumer(resultSet)
}
public func consumeResultSetAndClose(_ consumer: Consumer) {
consumeResultSet { set in
consumer(set)
let _ = set.close()
}
}
}
public struct QueryResultGenerator : IteratorProtocol {
public typealias Element = Row
let queryResult: QueryResult
init(queryResult: QueryResult) {
self.queryResult = queryResult
}
public func next() -> Element? {
guard let resultSet = queryResult.resultSet else {
return nil
}
guard resultSet.next() else {
let _ = resultSet.close()
return nil
}
return resultSet.row
}
}
extension QueryResult : Sequence {
public typealias GeneratorType = QueryResultGenerator
public func makeIterator() -> GeneratorType {
return QueryResultGenerator(queryResult:self)
}
}
|
mit
|
2addccf27f19a241786e3f8a13598ac6
| 28.442623 | 403 | 0.688753 | 4.445545 | false | false | false | false |
suominentoni/nearest-departures
|
HSL Nearest Departures/NextDepartureCell.swift
|
1
|
1236
|
import Foundation
import UIKit
import NearestDeparturesDigitransit
class NextDepartureCell: UITableViewCell {
@IBOutlet weak var code: UILabel!
@IBOutlet weak var time: UILabel!
@IBOutlet weak var destination: UILabel!
var codeWidthConstraint: NSLayoutConstraint?
func setDepartureData(departure: Departure, codeLabelWidth: CGFloat) {
if let codeShort = departure.line.codeShort,
let destination = departure.line.destination {
self.code.text = codeShort
if(self.codeWidthConstraint != nil) {
self.contentView.removeConstraint(self.codeWidthConstraint!)
}
self.codeWidthConstraint = self.code.widthAnchor.constraint(equalToConstant: codeLabelWidth)
self.contentView.addConstraint(self.codeWidthConstraint!)
self.destination.text = destination
self.accessibilityLabel = "\(NSLocalizedString("LINE", comment: "")) \(codeShort), \(NSLocalizedString("DESTINATION", comment: "")) \(destination), \(departure.formattedDepartureTime().string)"
} else {
self.code.text = departure.line.codeLong
}
self.time.attributedText = departure.formattedDepartureTime()
}
}
|
mit
|
61920fec7404d45d75a801a07e5581a5
| 44.777778 | 205 | 0.690129 | 5.107438 | false | false | false | false |
WatchBuilder/AEXML
|
AEXML/Namespaces.swift
|
1
|
5983
|
//
// AEXMLExtensions.swift
// WatchBuilder
//
// Created by William Kent on 5/27/15.
// Copyright (c) 2015 William Kent. All rights reserved.
//
import Foundation
public extension AEXMLElement {
// XMLNamespaceURLsByPrefix, defaultXMLNamespaceURL, getXMLNamespacePrefixForURL(),
// and getXMLNamespaceURLForPrefix() all call the same method on their parent,
// if any, before returning nil.
public var localName: String {
get {
let parts = name.components(separatedBy: ":")
assert(parts.count == 1 || parts.count == 2, "Malformed XML tag")
if parts.count == 1 { return name }
return parts[1];
}
}
public var XMLNamespaceURLsByPrefix: [String: String] {
get {
var retval = [String: String]()
for (key, value) in attributes {
let prefix = "xmlns:"
let stringKey = key as! String
if stringKey.hasPrefix(prefix) {
let trimmedKey = stringKey.substring(from: stringKey.characters.index(stringKey.startIndex, offsetBy: (prefix as NSString).length))
retval[trimmedKey] = value as? String
}
}
for (key, value) in (parent?.XMLNamespaceURLsByPrefix ?? [:]) {
retval[key] = value
}
return retval
}
}
public var elementXMLNamespaceURL: String? {
get {
let parts = name.components(separatedBy: ":")
if parts.count == 1 {
return defaultXMLNamespaceURL
} else if parts.count == 2 {
return getXMLNamespaceURLForPrefix(parts[0])
} else {
fatalError("Malformed XML tag name")
}
}
}
public var defaultXMLNamespaceURL: String? {
get {
if let URL: AnyObject = attributes["xmlns"] {
return URL as? String
} else {
return parent?.defaultXMLNamespaceURL
}
}
set {
if let newValue = newValue {
attributes["xmlns"] = newValue as NSString
} else {
attributes.removeValue(forKey: "xmlns")
}
}
}
public func getXMLNamespacePrefixForURL(_ URL: String) -> String? {
for (key, value) in XMLNamespaceURLsByPrefix {
if value == URL {
return key
}
}
return parent?.getXMLNamespacePrefixForURL(URL)
}
public func getXMLNamespaceURLForPrefix(_ prefix: String) -> String? {
if let URL = XMLNamespaceURLsByPrefix[prefix] {
return URL
} else {
return parent?.getXMLNamespaceURLForPrefix(prefix)
}
}
public func setXMLNamespace(prefix: String, URL: String) {
attributes["xmlns:\(prefix)"] = URL
}
public func clearXMLNamespaceMapping(prefix: String) {
attributes.removeValue(forKey: "xmlns:\(prefix)")
}
public func containsXMLNamespaceMapping(prefix: String) -> Bool {
if prefix == "" { return defaultXMLNamespaceURL != nil }
return XMLNamespaceURLsByPrefix.keys.contains(prefix)
}
public func containsXMLNamespaceMapping(namespaceURL: String) -> Bool {
if namespaceURL == defaultXMLNamespaceURL { return true }
return XMLNamespaceURLsByPrefix.values.contains(namespaceURL)
}
public func child(elementName: String, namespaceURL: String) -> AEXMLElement? {
if let defaultXMLNamespaceURL = defaultXMLNamespaceURL {
if defaultXMLNamespaceURL == namespaceURL {
for child in children {
if child.name == elementName {
return child
}
}
}
}
for (prefix, href) in XMLNamespaceURLsByPrefix {
if namespaceURL == href {
let annotatedName = "\(prefix):\(elementName)"
for child in children {
if child.name == annotatedName {
return child
}
}
}
}
return nil
}
public func attribute(name: String, namespaceURL: String) -> String? {
if let defaultXMLNamespaceURL = defaultXMLNamespaceURL {
if defaultXMLNamespaceURL == namespaceURL {
return attributes[name] as? String
}
}
for (prefix, href) in XMLNamespaceURLsByPrefix {
if namespaceURL == href {
let annotatedName = "\(prefix):\(name)"
for (attrName, attrValue) in attributes {
if attrName == annotatedName {
return attrValue as? String
}
}
}
}
return nil
}
public func setAttribute(name: String, namespaceURL: String, value: String) {
if let defaultXMLNamespaceURL = defaultXMLNamespaceURL {
if defaultXMLNamespaceURL == namespaceURL {
attributes[name] = value
}
}
for (prefix, href) in XMLNamespaceURLsByPrefix {
if namespaceURL == href {
attributes["\(prefix):\(name)"] = value
}
}
// If this point is reached, the namespaceURL was not matched to a prefix.
// In this case, create one using an automatically generated name.
var index = 0
while containsXMLNamespaceMapping(prefix: "ns\(index)") {
index += 1
}
setXMLNamespace(prefix: "ns\(index)", URL: namespaceURL)
return attributes["ns\(index):\(name)"] = value
}
public func addChild(name: String, namespaceURL: String, value: String? = nil, attributes: [NSObject : AnyObject] = [NSObject : AnyObject]()) -> AEXMLElement {
if let defaultXMLNamespaceURL = defaultXMLNamespaceURL {
if defaultXMLNamespaceURL == namespaceURL {
return addChild(name: name, value: value, attributes: attributes)
}
}
for (prefix, href) in XMLNamespaceURLsByPrefix {
if namespaceURL == href {
return addChild(name: "\(prefix):\(name)", value: value, attributes: attributes)
}
}
// If this point is reached, the namespaceURL was not matched to a prefix.
// In this case, create one using an automatically generated name.
var index = 0
while containsXMLNamespaceMapping(prefix: "ns\(index)") {
index += 1
}
setXMLNamespace(prefix: "ns\(index)", URL: namespaceURL)
return addChild(name: "ns\(index):\(name)", value: value, attributes: attributes)
}
public convenience init(name: String, namespaceURL: String, relativeToElement parent: AEXMLElement) {
let prefix = parent.getXMLNamespacePrefixForURL(namespaceURL)
if let prefix = prefix {
self.init("\(prefix):\(name)")
} else {
var index = 0
while parent.containsXMLNamespaceMapping(prefix: "ns\(index)") { index += 1 }
self.init("ns\(index):\(name)")
setXMLNamespace(prefix: "ns\(index)", URL: namespaceURL)
}
}
}
|
mit
|
0019ec46bda1f69b0b33f8ebf1088304
| 26.195455 | 160 | 0.685609 | 3.582635 | false | false | false | false |
JesusAntonioGil/OnTheMap
|
OnTheMap/Data/RequestClient/RequestClient.swift
|
1
|
5267
|
//
// RequestClient.swift
// OnTheMap
//
// Created by Jesús Antonio Gil on 28/03/16.
// Copyright © 2016 Jesús Antonio Gil. All rights reserved.
//
import UIKit
@objc protocol RequestClientDelegate {
func requestClientSuccess(data: AnyObject)
func requestClientError(error: NSError)
}
class RequestClient: NSObject {
var delegate: RequestClientDelegate?
//MARK: PUBLIC
func request(endpoint: URLEndpoint) {
switch endpoint {
case .Login(_), .Logout():
requestUdacity(endpoint)
case .StudentLocations(), .UpdateStudentLocetion(_):
requestParse(endpoint)
}
}
//MARK: PRIVATE
private func requestUdacity(endpoint: URLEndpoint) {
let target = URLProvider(endpoint: endpoint)
let request = NSMutableURLRequest(URL: urlWithParams(target.url, parameters: target.paramenters))
request.HTTPMethod = target.method
if(target.method != "DELETE") {
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = httpBody(target.body)
} else {
let sharedCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
var xsrfCookie: NSHTTPCookie? = nil
for cookie in sharedCookieStorage.cookies! {
if cookie.name == "XSRF-TOKEN" {
xsrfCookie = cookie
}
}
if let xsrfCookie = xsrfCookie {
request.setValue(xsrfCookie.value, forHTTPHeaderField: "X-XSRF-TOKEN")
}
}
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if(error != nil) {
self.delegate?.requestClientError(error!)
return
}
let newData = data!.subdataWithRange(NSMakeRange(5, data!.length - 5))
print(NSString(data: newData, encoding: NSUTF8StringEncoding))
do {
let jsonDict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(newData, options: .AllowFragments) as! NSDictionary
if (jsonDict.valueForKey("error") != nil) {
self.delegate?.requestClientError(NSError(domain: "OnTheMap", code: jsonDict.valueForKey("status") as! NSInteger, userInfo: [NSLocalizedDescriptionKey: jsonDict.valueForKey("error")!]))
} else {
self.delegate?.requestClientSuccess(jsonDict)
}
} catch {
self.delegate?.requestClientError(NSError(domain: "OnTheMap", code: 500, userInfo: [NSLocalizedDescriptionKey: "Error read json"]))
}
}
task.resume()
}
private func requestParse(endpoint: URLEndpoint) {
let target = URLProvider(endpoint: endpoint)
let request = NSMutableURLRequest(URL: urlWithParams(target.url, parameters: target.paramenters))
request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = target.method
if(target.method == "PUT") {
request.HTTPBody = httpBody(target.body)
}
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if (error != nil) {
self.delegate?.requestClientError(error!)
return
}
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
do {
let jsonDict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary
if (jsonDict.valueForKey("error") != nil) {
self.delegate?.requestClientError(NSError(domain: "OnTheMap", code: 900 , userInfo: [NSLocalizedDescriptionKey: jsonDict.valueForKey("error")!]))
} else {
self.delegate?.requestClientSuccess(jsonDict)
}
} catch {
self.delegate?.requestClientError(NSError(domain: "OnTheMap", code: 500, userInfo: [NSLocalizedDescriptionKey: "Error read json"]))
}
}
task.resume()
}
private func urlWithParams(url: NSURL, parameters: [String]!) -> NSURL {
var stringUrl = url.absoluteString
if(parameters != nil) {
for param in parameters {
stringUrl = stringUrl.stringByAppendingString("/\(param)")
}
}
return NSURL(string: stringUrl)!
}
private func httpBody(body: String!) -> NSData? {
if(body != nil) {
return body.dataUsingEncoding(NSUTF8StringEncoding)
}
return nil
}
}
|
mit
|
ac1670ac4b3c4c274214f750f5225015
| 36.870504 | 205 | 0.592135 | 5.032505 | false | false | false | false |
devinross/curry-fire
|
Examples/Examples/BounceAnimatorViewController.swift
|
1
|
1979
|
//
// BounceAnimatorViewController.swift
// Created by Devin Ross on 9/13/16.
//
/*
curryfire || https://github.com/devinross/curry-fire
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
class BounceAnimatorViewController: UIViewController {
var animator : UIDynamicAnimator?
override func loadView() {
super.loadView()
self.view.backgroundColor = UIColor.white
let block = UIView(frame: CGRectCenteredInRect(self.view.bounds, 100, 100), backgroundColor: UIColor.random(), cornerRadius: 10)
block.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin]
block.layer.shouldRasterize = true
block.layer.rasterizationScale = UIScreen.main.scale
self.view.addSubview(block)
let bounce = TKBounceBehavior(items: [block])
bounce.bounceDirection = CGVector(dx: 3, dy: 0)
animator = UIDynamicAnimator(referenceView: self.view)
animator?.addBehavior(bounce)
self.view .addTapGesture { (sender) in
bounce.bounce()
}
}
}
|
mit
|
1babb2e893f3256db427e02927a17801
| 29.446154 | 130 | 0.767559 | 4.228632 | false | false | false | false |
TVGSoft/Architecture-iOS
|
Model/Service/AuthenticateServiceImpl.swift
|
1
|
1987
|
//
// AuthenticateServiceImpl.swift
// Model
//
// Created by Giáp Trần on 9/1/16.
// Copyright © 2016 TVG Soft, Inc. All rights reserved.
//
import SwiftyJSON
public class AuthenticateServiceImpl: Service, AuthenticateService {
// MARK: AuthenticateService implement
public func signIn(email: String, password: String, completionHandler: (Response<User>) -> Void) {
let parameters = [ "email" : email,
"password" : password ]
apiHelper.post(.SignIn, parameters: parameters) { [unowned self] (json, error) in
self.handleJson(
json,
error: error,
completionHandler: completionHandler
)
}
}
public func signUp(email: String, password: String, name: String, completionHandler: (Response<User>) -> Void) {
let parameters = [ "email" : email,
"password" : password,
"name" : name ]
apiHelper.post(.SignUp, parameters: parameters) { [unowned self] (json, error) in
self.handleJson(
json,
error: error,
completionHandler: completionHandler
)
}
}
// MARK - Private method
private func handleJson(json: JSON?, error: NSError?, completionHandler: (Response<User>) -> Void) {
let response = Response<User>()
if let hasJon = json {
response.fromJson(hasJon)
if response.isSuccess {
User.fromJson(hasJon["data"], output: &response.data)
} else {
response.error = NSError(domain: response.message!, code: 0, userInfo: nil)
}
}
if let hasError = error {
response.error = hasError
}
completionHandler(response)
}
}
|
mit
|
684ce5907f3cdd29cd2c4e5bda5ddbe8
| 29.060606 | 116 | 0.518911 | 4.920596 | false | false | false | false |
piresbruno/LogKit
|
LogKit/LogKit.swift
|
1
|
2345
|
//
// LogKit.swift
// LogKit
//
// Created by Bruno Pires on 26/05/16.
// Copyright © 2016 Bruno Pires. All rights reserved.
//
import Foundation
public class LogKit {
private static let instance = LogKit()
private var level:LogLevel = .disabled
public class func setup(level:LogLevel){
self.instance.level = level
}
/// *Writes in the debug console the data*
///
/// - parameters:
/// - level: LogLevel wanted
/// - message: message to be written in the debug console
/// - returns: Void
public class func log(level:LogLevel,
message:Any,
_ path: String = #file,
_ function: String = #function,
_ lineNumber: Int = #line){
let filePath = path.components(separatedBy: "/")
.last!
.replacingOccurrences(of: "swift", with: function)
.replacingOccurrences(of:"()", with: "")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss:SSS"
if self.instance.level >= level && level != .disabled{
print("\(level.description.uppercased()) | \(dateFormatter.string(from: NSDate() as Date)) [\(filePath):\(lineNumber)]: \(message)")
}
}
}
//MARK: LogLevel enum and Comparable protocol implementation
public enum LogLevel: Int, Comparable {
case disabled = 0
case error = 1
case warning = 2
case info = 3
case debug = 4
case verbose = 5
var description: String {
switch self {
case .disabled:
return "Disabled"
case .error:
return " Error"
case .warning:
return "Warning"
case .info:
return " Info"
case .debug:
return " Debug"
case .verbose:
return "Verbose"
}
}
}
public func >(lhs: LogLevel, rhs: LogLevel) -> Bool{
return lhs.rawValue > rhs.rawValue
}
public func <(lhs: LogLevel, rhs: LogLevel) -> Bool{
return lhs.rawValue < rhs.rawValue
}
public func >=(lhs: LogLevel, rhs: LogLevel) -> Bool{
return lhs.rawValue >= rhs.rawValue
}
public func <=(lhs: LogLevel, rhs: LogLevel) -> Bool{
return lhs.rawValue <= rhs.rawValue
}
|
apache-2.0
|
6d1011d477fe3c0b013585005d75f625
| 25.337079 | 144 | 0.554181 | 4.406015 | false | false | false | false |
string-team/analytics-ios
|
AnalyticsTests/HTTPClientTest.swift
|
1
|
7945
|
//
// HTTPClientTest.swift
// Analytics
//
// Created by Tony Xiao on 9/16/16.
// Copyright © 2016 Segment. All rights reserved.
//
import Quick
import Nimble
import Nocilla
import Analytics
class HTTPClientTest: QuickSpec {
override func spec() {
var client: SEGHTTPClient!
beforeEach {
LSNocilla.sharedInstance().start()
client = SEGHTTPClient(requestFactory: nil)
}
afterEach {
LSNocilla.sharedInstance().clearStubs()
LSNocilla.sharedInstance().stop()
}
describe("defaultRequestFactory") {
it("preserves url") {
let factory = SEGHTTPClient.defaultRequestFactory()
let url = URL(string: "https://api.segment.io/v1/batch")
let request = factory(url!)
expect(request.url) == url
}
}
describe("settingsForWriteKey") {
it("succeeds for 2xx response") {
_ = stubRequest("GET", "https://cdn-settings.segment.com/v1/projects/foo/settings" as NSString)!
.withHeaders(["Accept-Encoding" : "gzip" ])!
.andReturn(200)!
.withHeaders(["Content-Type" : "application/json"])!
.withBody("{\"integrations\":{\"Segment.io\":{\"apiKey\":\"foo\"}},\"plan\":{\"track\":{}}}" as NSString)
var done = false
let task = client.settings(forWriteKey: "foo", completionHandler: { success, settings in
expect(success) == true
expect((settings as? NSDictionary)) == [
"integrations": [
"Segment.io": [
"apiKey":"foo"
]
],
"plan":[
"track": [:]
]
] as NSDictionary
done = true
})
expect(task.state).toEventually(equal(URLSessionTask.State.completed))
expect(done).toEventually(beTrue())
}
it("fails for non 2xx response") {
_ = stubRequest("GET", "https://cdn-settings.segment.com/v1/projects/foo/settings" as NSString)!
.withHeaders(["Accept-Encoding" : "gzip" ])!
.andReturn(400)!
.withHeaders(["Content-Type" : "application/json" ])!
.withBody("{\"integrations\":{\"Segment.io\":{\"apiKey\":\"foo\"}},\"plan\":{\"track\":{}}}" as NSString)
var done = false
client.settings(forWriteKey: "foo", completionHandler: { success, settings in
expect(success) == false
expect(settings).to(beNil())
done = true
})
expect(done).toEventually(beTrue())
}
it("fails for json error") {
_ = stubRequest("GET", "https://cdn-settings.segment.com/v1/projects/foo/settings" as NSString)!
.withHeaders(["Accept-Encoding":"gzip"])!
.andReturn(200)!
.withHeaders(["Content-Type":"application/json"])!
.withBody("{\"integrations" as NSString)
var done = false
client.settings(forWriteKey: "foo", completionHandler: { success, settings in
expect(success) == false
expect(settings).to(beNil())
done = true
})
expect(done).toEventually(beTrue())
}
}
describe("upload") {
it("does not ask to retry for json error") {
let batch: [String: Any] = [
// Dates cannot be serialized as is so the json serialzation will fail.
"sentAt": NSDate(),
"batch": [["type": "track", "event": "foo"]],
]
var done = false
let task = client.upload(batch, forWriteKey: "bar", forEndpoint: "endp") { retry in
expect(retry) == false
done = true
}
expect(task).to(beNil())
expect(done).toEventually(beTrue())
}
let batch: [String: Any] = ["sentAt":"2016-07-19'T'19:25:06Z", "batch":[["type":"track", "event":"foo"]]]
it("does not ask to retry for 2xx response") {
_ = stubRequest("POST", "https://api.segment.io/v1/batch" as NSString)!
.withJsonGzippedBody(batch as AnyObject)
.withWriteKey("bar")
.andReturn(200)
var done = false
let task = client.upload(batch, forWriteKey: "bar", forEndpoint: "endp") { retry in
expect(retry) == false
done = true
}
expect(done).toEventually(beTrue())
expect(task.state).toEventually(equal(URLSessionTask.State.completed))
}
it("asks to retry for 3xx response") {
_ = stubRequest("POST", "https://api.segment.io/v1/batch" as NSString)!
.withJsonGzippedBody(batch as AnyObject)
.withWriteKey("bar")
.andReturn(304)
var done = false
let task = client.upload(batch, forWriteKey: "bar", forEndpoint: "endp") { retry in
expect(retry) == true
done = true
}
expect(done).toEventually(beTrue())
expect(task.state).toEventually(equal(URLSessionTask.State.completed))
}
it("does not ask to retry for 4xx response") {
_ = stubRequest("POST", "https://api.segment.io/v1/batch" as NSString)!
.withJsonGzippedBody(batch as AnyObject)
.withWriteKey("bar")
.andReturn(401)
var done = false
let task = client.upload(batch, forWriteKey: "bar", forEndpoint: "endp") { retry in
expect(retry) == false
done = true
}
expect(done).toEventually(beTrue())
expect(task.state).toEventually(equal(URLSessionTask.State.completed))
}
it("asks to retry for 5xx response") {
_ = stubRequest("POST", "https://api.segment.io/v1/batch" as NSString)!
.withJsonGzippedBody(batch as AnyObject)
.withWriteKey("bar")
.andReturn(504)
var done = false
let task = client.upload(batch, forWriteKey: "bar", forEndpoint: "endp") { retry in
expect(retry) == true
done = true
}
expect(done).toEventually(beTrue())
expect(task.state).toEventually(equal(URLSessionTask.State.completed))
}
}
describe("attribution") {
it("fails for json error") {
let device = [
// Dates cannot be serialized as is so the json serialzation will fail.
"sentAt": NSDate(),
]
var done = false
let task = client.attribution(withWriteKey: "bar", forDevice: device) { success, properties in
expect(success) == false
done = true
}
expect(task).to(beNil())
expect(done).toEventually(beTrue())
}
let context: [String: Any] = [
"os": [
"name": "iPhone OS",
"version" : "8.1.3",
],
"ip": "8.8.8.8",
]
it("succeeds for 2xx response") {
_ = stubRequest("POST", "https://mobile-service.segment.com/v1/attribution" as NSString)!
.withWriteKey("foo")
.andReturn(200)!
.withBody("{\"provider\": \"mock\"}" as NSString)
var done = false
let task = client.attribution(withWriteKey: "foo", forDevice: context) { success, properties in
expect(success) == true
expect(properties as? [String: String]) == [
"provider": "mock"
]
done = true
}
expect(task.state).toEventually(equal(URLSessionTask.State.completed))
expect(done).toEventually(beTrue())
}
it("fails for non 2xx response") {
_ = stubRequest("POST", "https://mobile-service.segment.com/v1/attribution" as NSString)!
.withWriteKey("foo")
.andReturn(404)!
.withBody("not found" as NSString)
var done = false
let task = client.attribution(withWriteKey: "foo", forDevice: context) { success, properties in
expect(success) == false
expect(properties).to(beNil())
done = true
}
expect(task.state).toEventually(equal(URLSessionTask.State.completed))
expect(done).toEventually(beTrue())
}
}
}
}
|
mit
|
b47369f9c6c38458831b73f48b30b7b9
| 33.689956 | 115 | 0.566213 | 4.250401 | false | false | false | false |
douShu/weiboInSwift
|
weiboInSwift/weiboInSwift/Classes/Module/Home(首页)/HomeTableViewController.swift
|
1
|
11926
|
//
// HomeTableViewController.swift
// weiboInSwift
//
// Created by 逗叔 on 15/9/6.
// Copyright © 2015年 逗叔. All rights reserved.
//
import UIKit
class HomeTableViewController: BaseTableViewController, StatusCellDelegate {
// MARK: - ----------------------------- 属性 -----------------------------
/// 点击图片的缩影
var indexPath: NSIndexPath?
/// 转场动画的iconView
var iconView = UIImageView()
/// 选中的cell上面的图片
var pictView: PictureView?
/// 是否是 modal 的标识
var isPresend = false
/// 数据
private var statuses: [Status]? {
didSet{
tableView.reloadData()
}
}
private lazy var refreshlabel: UILabel = {
let h: CGFloat = 44
let l: UILabel = UILabel(frame: CGRect(x: 0, y: -2 * h, width: self.view.bounds.width, height: h))
l.backgroundColor = UIColor.orangeColor()
l.textColor = UIColor.whiteColor()
l.textAlignment = NSTextAlignment.Center
self.navigationController?.navigationBar.insertSubview(l, atIndex: 0)
return l
}()
// MARK: - ----------------------------- 构造方法 -----------------------------
override func viewDidLoad() {
super.viewDidLoad()
/// 设置登录界面
if UserAccount.sharedUserAccount == nil {
visitLoginView?.setupLoginImageView(true, imgName: "visitordiscover_feed_image_smallicon", message: "关注一些人,回这里看看有什么惊喜")
return
}
/// 设置tableview
setupTableview()
/// 加载数据
loadData()
/// 接受点击配图的通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "photoBrowser:", name: DSPictureViewCellSelectPhotoNotification, object: nil)
}
/// 设置tableview
private func setupTableview() {
// 注册cell
tableView.registerClass(NormalCell.self, forCellReuseIdentifier: StatusCellID.NormalCell.rawValue)
tableView.registerClass(RetweetCell.self, forCellReuseIdentifier: StatusCellID.RetweetCell.rawValue)
tableView.rowHeight = 300
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
// 设置下拉刷新控件
refreshControl = DSRefreshControl()
refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
}
/// 注销通知
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - ----------------------------- 单元格选中了http超链接文字 -----------------------------
func statusCellDidSelectedLinkText(text: String) {
guard let url = NSURL(string: text) else {
print("没有有效的url")
return
}
let vc = WebViewController()
vc.url = url
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
}
// MARK: - ----------------------------- 显示大配图 -----------------------------
func photoBrowser(n: NSNotification) {
/// modal 浏览图片控制器
/// 从自定义的通知中拿取参数, 一定要进行判断
guard let largerPictureURLs = n.userInfo![DSPictureViewCellSelectPhotoURLKEY] as? [NSURL] else {
print("没有传递largerPictureURLs")
return
}
guard let indexPath = n.userInfo![DSPictureViewCellSelectPhotoIndexKEY] as? NSIndexPath else {
print("没有传递indexPath")
return
}
guard let pictView = n.object as? PictureView else {
print("图像不存在")
return
}
/// 记录点击的是哪个collectingView
self.pictView = pictView
self.indexPath = indexPath
/// 1> 自定义转场动画
let vc = PhotoBrowserController(largerPictureURLs: largerPictureURLs, index: indexPath.item)
vc.modalPresentationStyle = UIModalPresentationStyle.Custom
vc.transitioningDelegate = self
/// 2> 转场动画的View
iconView.sd_setImageWithURL(largerPictureURLs[indexPath.item])
presentViewController(vc, animated: true, completion: nil)
}
// MARK: - ----------------------------- 刷新加载数据 -----------------------------
private var pullUpRefreshFlag = false
func loadData() {
// 开始刷新
refreshControl?.beginRefreshing()
var since_id = statuses?.first?.id ?? 0
var max_id = 0
if pullUpRefreshFlag {
since_id = 0
max_id = statuses?.last?.id ?? 0
}
Status.loadLists(since_id, max_id: max_id) { (lists, error) -> () in
// 结束刷新
self.refreshControl?.endRefreshing()
// 对下拉刷新标记进行复位
self.pullUpRefreshFlag = false
if error != nil {
print(error)
return
}
let count = lists?.count ?? 0
if since_id > 0 {
self.showPullDownTip(count)
}
if count == 0 {
return
}
if since_id > 0 { // 做下拉刷下
self.statuses = lists! + self.statuses!
} else if max_id > 0 { // 做上拉刷新
self.statuses = self.statuses! + lists!
} else {
self.statuses = lists
}
}
}
/// 显示刷新了几条微博
///
/// - parameter count: 微博数
private func showPullDownTip(count: Int) {
/// UIView的动画底层是通过layer来实现的
if refreshlabel.layer.animationForKey("position") != nil {
print("正在刷新, 请耐心等待")
return
}
refreshlabel.text = "刷新到\(count)条微博"
let rect = refreshlabel.frame
UIView.animateWithDuration(2.0, animations: { () -> Void in
// 自动反转
UIView.setAnimationRepeatAutoreverses(true)
self.refreshlabel.frame = CGRectOffset(self.refreshlabel.frame, 0, 3 * 44)
}) { (_) -> Void in
self.refreshlabel.frame = rect
// l.removeFromSuperview()
}
}
// MARK: - ----------------------------- 数据源方法 -----------------------------
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statuses?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let status = statuses![indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellID.cellID(status), forIndexPath: indexPath) as! StatusCell
if indexPath.row == (statuses?.count)! - 1 {
pullUpRefreshFlag = true
loadData()
}
cell.status = status
cell.statusDelegate = self
return cell
}
// MARK: - ----------------------------- 代理方法 -----------------------------
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let status = statuses![indexPath.row]
if let h = status.rowHeight {
return h
}
// 返回高度
let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellID.cellID(status)) as! StatusCell
status.rowHeight = cell.rowHeight(status)
return status.rowHeight!
}
}
// MARK: - ----------------------------- 自定义转场的协议 -----------------------------
extension HomeTableViewController: UIViewControllerTransitioningDelegate {
/// 返回提供转场动画的遵守: UIViewControllerTransitioningDelegate 协议的对象
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresend = true
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresend = false
return self
}
}
// MARK: - ----------------------------- 自定义转场动画 -----------------------------
extension HomeTableViewController: UIViewControllerAnimatedTransitioning {
/// 转场动画时常
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 1
}
/**
transitionContext 提供了转场动画需要的元素
completeTransition(true) 动画结束后必须调用的
containerView() 容器视图
viewForKey 获取到转场的视图
*/
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
if isPresend {
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
transitionContext.containerView()?.addSubview(iconView)
let fromRect = pictView!.cellScreenFrame(self.indexPath!)
let toRect = pictView!.cellFulScreenFrame(self.indexPath!)
iconView.frame = fromRect
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
self.iconView.frame = toRect
}) { (_) -> Void in
self.iconView.removeFromSuperview()
/// 添加目标视图
transitionContext.containerView()?.addSubview(toView!)
transitionContext.completeTransition(true)
}
return
}
print("毛关系")
/// 获取照片查看器控制器
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserController
/// 获取微博中对应cell的位置
let indexPath = fromVC.currentImageViewIndexPath()
let rect = pictView!.cellScreenFrame(indexPath)
/// 获取照片视图
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
/// 获取图像视图
let iv = fromVC.currentImageView()
iv.center = fromView!.center
let scale = fromView!.transform.a
iv.transform = CGAffineTransformScale(iv.transform, scale, scale)
transitionContext.containerView()?.addSubview(iv)
fromView?.removeFromSuperview()
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
iv.frame = rect
}, completion: { (_) -> Void in
iv.removeFromSuperview()
transitionContext.completeTransition(true)
})
}
}
|
mit
|
6e3b4b48f2f596313b8c543dec6160f7
| 28.882353 | 217 | 0.53396 | 5.793157 | false | false | false | false |
gottesmm/swift
|
test/attr/attr_override.swift
|
6
|
16460
|
// RUN: %target-typecheck-verify-swift
@override // expected-error {{'override' can only be specified on class members}} {{1-11=}} expected-error {{'override' is a declaration modifier, not an attribute}} {{1-2=}}
func virtualAttributeCanNotBeUsedInSource() {}
class MixedKeywordsAndAttributes { // expected-note {{in declaration of 'MixedKeywordsAndAttributes'}}
// expected-error@+1 {{expected declaration}} expected-error@+1 {{consecutive declarations on a line must be separated by ';'}} {{11-11=;}}
override @inline(never) func f1() {}
}
class DuplicateOverrideBase {
func f1() {}
class func cf1() {}
class func cf2() {}
class func cf3() {}
class func cf4() {}
}
class DuplicateOverrideDerived : DuplicateOverrideBase {
override override func f1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override override class func cf1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf2() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
class override override func cf3() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf4() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
}
class A {
func f0() { }
func f1() { } // expected-note{{overridden declaration is here}}
var v1: Int { return 5 }
var v2: Int { return 5 } // expected-note{{overridden declaration is here}}
var v4: String { return "hello" }// expected-note{{attempt to override property here}}
var v5: A { return self }
var v6: A { return self }
var v7: A { // expected-note{{attempt to override property here}}
get { return self }
set { }
}
var v8: Int = 0 // expected-note {{attempt to override property here}}
var v9: Int { return 5 } // expected-note{{attempt to override property here}}
subscript (i: Int) -> String { // expected-note{{potential overridden subscript 'subscript' here}}
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden subscript 'subscript' here}}
get {
return "hello"
}
set {
}
}
subscript (i: Int8) -> A { // expected-note{{potential overridden subscript 'subscript' here}}
get { return self }
}
subscript (i: Int16) -> A { // expected-note{{attempt to override subscript here}} expected-note{{potential overridden subscript 'subscript' here}}
get { return self }
set { }
}
func overriddenInExtension() {} // expected-note {{overridden declaration is here}}
}
class B : A {
override func f0() { }
func f1() { } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
override func f2() { } // expected-error{{method does not override any method from its superclass}}
override var v1: Int { return 5 }
var v2: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}
override var v3: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
override var v4: Int { return 5 } // expected-error{{property 'v4' with type 'Int' cannot override a property with type 'String'}}
// Covariance
override var v5: B { return self }
override var v6: B {
get { return self }
set { }
}
override var v7: B { // expected-error{{cannot override mutable property 'v7' of type 'A' with covariant type 'B'}}
get { return self }
set { }
}
// Stored properties
override var v8: Int { return 5 } // expected-error {{cannot override mutable property with read-only property 'v8'}}
override var v9: Int // expected-error{{cannot override with a stored property 'v9'}}
override subscript (i: Int) -> String {
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{3-3=override }}
get {
return "hello"
}
set {
}
}
override subscript (f: Float) -> String { // expected-error{{subscript does not override any subscript from its superclass}}
get {
return "hello"
}
set {
}
}
// Covariant
override subscript (i: Int8) -> B {
get { return self }
}
override subscript (i: Int16) -> B { // expected-error{{cannot override mutable subscript of type '(Int16) -> B' with covariant type '(Int16) -> A'}}
get { return self }
set { }
}
override init() { }
override deinit { } // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
override typealias Inner = Int // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
}
extension B {
override func overriddenInExtension() {} // expected-error{{declarations in extensions cannot override yet}}
}
struct S {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
extension S {
override func ef() {} // expected-error{{method does not override any method from its superclass}}
}
enum E {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
protocol P {
override func f() // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
override func f() { } // expected-error{{'override' can only be specified on class members}} {{1-10=}}
// Invalid 'override' on declarations inside closures.
var rdar16654075a = {
override func foo() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
var rdar16654075b = {
class A {
override func foo() {} // expected-error{{method does not override any method from its superclass}}
}
}
var rdar16654075c = { () -> () in
override func foo() {} // expected-error {{'override' can only be specified on class members}} {{3-12=}}
()
}
var rdar16654075d = { () -> () in
class A {
override func foo() {} // expected-error {{method does not override any method from its superclass}}
}
A().foo()
}
var rdar16654075e = { () -> () in
class A {
func foo() {}
}
class B : A {
override func foo() {}
}
A().foo()
}
class C {
init(string: String) { } // expected-note{{overridden declaration is here}}
required init(double: Double) { } // expected-note 3{{overridden required initializer is here}}
convenience init() { self.init(string: "hello") } // expected-note{{attempt to override convenience initializer here}}
}
class D1 : C {
override init(string: String) { super.init(string: string) }
required init(double: Double) { }
convenience init() { self.init(string: "hello") }
}
class D2 : C {
init(string: String) { super.init(string: string) } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
// FIXME: Would like to remove the space after 'override' as well.
required override init(double: Double) { } // expected-warning{{'override' is implied when overriding a required initializer}} {{12-21=}}
override convenience init() { self.init(string: "hello") } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class D3 : C {
override init(string: String) { super.init(string: string) }
override init(double: Double) { } // expected-error{{use the 'required' modifier to override a required initializer}}{{3-11=required}}
}
class D4 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required override init(string: String) { super.init(string: string) }
required init(double: Double) { }
}
class D5 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required convenience override init(string: String) { self.init(double: 5.0) }
required init(double: Double) { }
}
class D6 : C {
init(double: Double) { } // expected-error{{'required' modifier must be present on all overrides of a required initializer}} {{3-3=required }}
}
// rdar://problem/18232867
class C_empty_tuple {
init() { }
}
class D_empty_tuple : C_empty_tuple {
override init(foo:()) { } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class C_with_let {
let x = 42 // expected-note {{attempt to override property here}}
}
class D_with_let : C_with_let {
override var x : Int { get { return 4 } set {} } // expected-error {{cannot override immutable 'let' property 'x' with the getter of a 'var'}}
}
// <rdar://problem/21311590> QoI: Inconsistent diagnostics when no constructor is available
class C21311590 {
override init() {} // expected-error {{initializer does not override a designated initializer from its superclass}}
}
class B21311590 : C21311590 {}
_ = C21311590()
_ = B21311590()
class MismatchOptionalBase {
func param(_: Int?) {}
func paramIUO(_: Int!) {}
func result() -> Int { return 0 }
func fixSeveralTypes(a: Int?, b: Int!) -> Int { return 0 }
func functionParam(x: ((Int) -> Int)?) {}
func tupleParam(x: (Int, Int)?) {}
func compositionParam(x: (P1 & P2)?) {}
func nameAndTypeMismatch(label: Int?) {}
func ambiguousOverride(a: Int, b: Int?) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
func ambiguousOverride(a: Int?, b: Int) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
var prop: Int = 0 // expected-note {{attempt to override property here}}
var optProp: Int? // expected-note {{attempt to override property here}}
var getProp: Int { return 0 } // expected-note {{attempt to override property here}}
var getOptProp: Int? { return nil }
init(param: Int?) {}
init() {} // expected-note {{non-failable initializer 'init()' overridden here}}
subscript(a: Int?) -> Void { // expected-note {{attempt to override subscript here}}
get { return () }
set {}
}
subscript(b: Void) -> Int { // expected-note {{attempt to override subscript here}}
get { return 0 }
set {}
}
subscript(get a: Int?) -> Void {
return ()
}
subscript(get b: Void) -> Int {
return 0
}
subscript(ambiguous a: Int, b: Int?) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
subscript(ambiguous a: Int?, b: Int) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
}
protocol P1 {}
protocol P2 {}
class MismatchOptional : MismatchOptionalBase {
override func param(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{29-29=?}}
override func paramIUO(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int!' with non-optional type 'Int'}} {{32-32=?}}
override func result() -> Int? { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}}
override func fixSeveralTypes(a: Int, b: Int) -> Int! { return nil }
// expected-error@-1 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{39-39=?}}
// expected-error@-2 {{cannot override instance method parameter of type 'Int!' with non-optional type 'Int'}} {{47-47=?}}
// expected-error@-3 {{cannot override instance method result type 'Int' with optional type 'Int!'}} {{55-56=}}
override func functionParam(x: @escaping (Int) -> Int) {} // expected-error {{cannot override instance method parameter of type '((Int) -> Int)?' with non-optional type '(Int) -> Int'}} {{34-34=(}} {{56-56=)?}}
override func tupleParam(x: (Int, Int)) {} // expected-error {{cannot override instance method parameter of type '(Int, Int)?' with non-optional type '(Int, Int)'}} {{41-41=?}}
override func compositionParam(x: P1 & P2) {} // expected-error {{cannot override instance method parameter of type '(P1 & P2)?' with non-optional type 'P1 & P2'}} {{37-37=(}} {{44-44=)?}}
override func nameAndTypeMismatch(_: Int) {}
// expected-error@-1 {{argument names for method 'nameAndTypeMismatch' do not match those of overridden method 'nameAndTypeMismatch(label:)'}} {{37-37=label }}
// expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{43-43=?}}
override func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} {{none}}
override func ambiguousOverride(a: Int, b: Int) {} // expected-error {{method does not override any method from its superclass}} {{none}}
override var prop: Int? { // expected-error {{property 'prop' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
get { return nil }
set {}
}
override var optProp: Int { // expected-error {{cannot override mutable property 'optProp' of type 'Int?' with covariant type 'Int'}} {{none}}
get { return 0 }
set {}
}
override var getProp: Int? { return nil } // expected-error {{property 'getProp' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
override var getOptProp: Int { return 0 } // okay
override init(param: Int) {} // expected-error {{cannot override initializer parameter of type 'Int?' with non-optional type 'Int'}}
override init?() {} // expected-error {{failable initializer 'init()' cannot override a non-failable initializer}} {{none}}
override subscript(a: Int) -> Void { // expected-error {{cannot override mutable subscript of type '(Int) -> Void' with covariant type '(Int?) -> Void'}}
get { return () }
set {}
}
override subscript(b: Void) -> Int? { // expected-error {{cannot override mutable subscript of type '(Void) -> Int?' with covariant type '(Void) -> Int'}}
get { return nil }
set {}
}
override subscript(get a: Int) -> Void { // expected-error {{cannot override subscript index of type 'Int?' with non-optional type 'Int'}} {{32-32=?}}
return ()
}
override subscript(get b: Void) -> Int? { // expected-error {{cannot override subscript element type 'Int' with optional type 'Int?'}} {{41-42=}}
return nil
}
override subscript(ambiguous a: Int?, b: Int?) -> Void { // expected-error {{declaration 'subscript(ambiguous:_:)' cannot override more than one superclass declaration}}
return ()
}
override subscript(ambiguous a: Int, b: Int) -> Void { // expected-error {{subscript does not override any subscript from its superclass}}
return ()
}
}
class MismatchOptional2 : MismatchOptionalBase {
override func result() -> Int! { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int!'}} {{32-33=}}
// None of these are overrides because we didn't say 'override'. Since they're
// not exact matches, they shouldn't result in errors.
func param(_: Int) {}
func ambiguousOverride(a: Int, b: Int) {}
// This is covariant, so we still assume it's meant to override.
func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}}
}
class MismatchOptional3 : MismatchOptionalBase {
override func result() -> Optional<Int> { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Optional<Int>'}} {{none}}
}
// Make sure we remap the method's innermost generic parameters
// to the correct depth
class GenericBase<T> {
func doStuff<U>(t: T, u: U) {}
init<U>(t: T, u: U) {}
}
class ConcreteSub : GenericBase<Int> {
override func doStuff<U>(t: Int, u: U) {}
override init<U>(t: Int, u: U) {}
}
class ConcreteBase {
init<U>(t: Int, u: U) {}
func doStuff<U>(t: Int, u: U) {}
}
class GenericSub<T> : ConcreteBase {
override init<U>(t: Int, u: U) {}
override func doStuff<U>(t: Int, u: U) {}
}
|
apache-2.0
|
013ec452aa080bf80afdeb9c362e9481
| 39.244499 | 212 | 0.671567 | 3.922784 | false | false | false | false |
JohnEstropia/CoreStore
|
Sources/NSManagedObjectContext+Querying.swift
|
2
|
19039
|
//
// NSManagedObjectContext+Querying.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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
import CoreData
// MARK: - NSManagedObjectContext
extension NSManagedObjectContext: FetchableSource, QueryableSource {
// MARK: FetchableSource
@nonobjc
public func fetchExisting<O: DynamicObject>(_ object: O) -> O? {
let rawObject = object.cs_toRaw()
if rawObject.objectID.isTemporaryID {
do {
try withExtendedLifetime(self) { (context: NSManagedObjectContext) -> Void in
try context.obtainPermanentIDs(for: [rawObject])
}
}
catch {
Internals.log(
CoreStoreError(error),
"Failed to obtain permanent ID for object."
)
return nil
}
}
do {
let existingRawObject = try self.existingObject(with: rawObject.objectID)
if existingRawObject === rawObject {
return object
}
return object.runtimeType().cs_fromRaw(object: existingRawObject)
}
catch {
Internals.log(
CoreStoreError(error),
"Failed to load existing \(Internals.typeName(object)) in context."
)
return nil
}
}
@nonobjc
public func fetchExisting<O: DynamicObject>(_ objectID: NSManagedObjectID) -> O? {
do {
let existingObject = try self.existingObject(with: objectID)
return O.cs_fromRaw(object: existingObject)
}
catch _ {
return nil
}
}
@nonobjc
public func fetchExisting<O: DynamicObject, S: Sequence>(_ objects: S) -> [O] where S.Iterator.Element == O {
return objects.compactMap({ self.fetchExisting($0.cs_id()) })
}
@nonobjc
public func fetchExisting<O: DynamicObject, S: Sequence>(_ objectIDs: S) -> [O] where S.Iterator.Element == NSManagedObjectID {
return objectIDs.compactMap({ self.fetchExisting($0) })
}
@nonobjc
public func fetchOne<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> O? {
return try self.fetchOne(from, fetchClauses)
}
@nonobjc
public func fetchOne<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> O? {
let fetchRequest = Internals.CoreStoreFetchRequest<NSManagedObject>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .managedObjectResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
return try self.fetchOne(fetchRequest).flatMap(from.entityClass.cs_fromRaw)
}
@nonobjc
public func fetchOne<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> B.ObjectType? {
return try self.fetchOne(clauseChain.from, clauseChain.fetchClauses)
}
@nonobjc
public func fetchAll<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> [O] {
return try self.fetchAll(from, fetchClauses)
}
@nonobjc
public func fetchAll<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> [O] {
let fetchRequest = Internals.CoreStoreFetchRequest<NSManagedObject>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .managedObjectResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
let entityClass = from.entityClass
return try self.fetchAll(fetchRequest).map(entityClass.cs_fromRaw)
}
@nonobjc
public func fetchAll<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> [B.ObjectType] {
return try self.fetchAll(clauseChain.from, clauseChain.fetchClauses)
}
@nonobjc
public func fetchCount<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> Int {
return try self.fetchCount(from, fetchClauses)
}
@nonobjc
public func fetchCount<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> Int {
let fetchRequest = Internals.CoreStoreFetchRequest<NSNumber>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.resultType = .countResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
return try self.fetchCount(fetchRequest)
}
@nonobjc
public func fetchCount<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> Int {
return try self.fetchCount(clauseChain.from, clauseChain.fetchClauses)
}
@nonobjc
public func fetchObjectID<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? {
return try self.fetchObjectID(from, fetchClauses)
}
@nonobjc
public func fetchObjectID<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? {
let fetchRequest = Internals.CoreStoreFetchRequest<NSManagedObjectID>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .managedObjectIDResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
return try self.fetchObjectID(fetchRequest)
}
@nonobjc
public func fetchObjectID<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> NSManagedObjectID? {
return try self.fetchObjectID(clauseChain.from, clauseChain.fetchClauses)
}
@nonobjc
public func fetchObjectIDs<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] {
return try self.fetchObjectIDs(from, fetchClauses)
}
@nonobjc
public func fetchObjectIDs<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] {
let fetchRequest = Internals.CoreStoreFetchRequest<NSManagedObjectID>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .managedObjectIDResultType
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
return try self.fetchObjectIDs(fetchRequest)
}
@nonobjc
public func fetchObjectIDs<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> [NSManagedObjectID] {
return try self.fetchObjectIDs(clauseChain.from, clauseChain.fetchClauses)
}
@nonobjc
internal func fetchObjectIDs(_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObjectID>) throws -> [NSManagedObjectID] {
var fetchResults: [NSManagedObjectID]?
var fetchError: Error?
self.performAndWait {
do {
fetchResults = try self.fetch(fetchRequest.dynamicCast())
}
catch {
fetchError = error
}
}
if let fetchResults = fetchResults {
return fetchResults
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing fetch request."
)
throw coreStoreError
}
// MARK: QueryableSource
@nonobjc
public func queryValue<O, U: QueryableAttributeType>(_ from: From<O>, _ selectClause: Select<O, U>, _ queryClauses: QueryClause...) throws -> U? {
return try self.queryValue(from, selectClause, queryClauses)
}
@nonobjc
public func queryValue<O, U: QueryableAttributeType>(_ from: From<O>, _ selectClause: Select<O, U>, _ queryClauses: [QueryClause]) throws -> U? {
let fetchRequest = Internals.CoreStoreFetchRequest<NSDictionary>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
selectClause.applyToFetchRequest(fetchRequest.staticCast())
queryClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
return try self.queryValue(selectClause.selectTerms, fetchRequest: fetchRequest)
}
@nonobjc
public func queryValue<B>(_ clauseChain: B) throws -> B.ResultType? where B: QueryChainableBuilderType, B.ResultType: QueryableAttributeType {
return try self.queryValue(clauseChain.from, clauseChain.select, clauseChain.queryClauses)
}
@nonobjc
public func queryAttributes<O>(_ from: From<O>, _ selectClause: Select<O, NSDictionary>, _ queryClauses: QueryClause...) throws -> [[String: Any]] {
return try self.queryAttributes(from, selectClause, queryClauses)
}
@nonobjc
public func queryAttributes<O>(_ from: From<O>, _ selectClause: Select<O, NSDictionary>, _ queryClauses: [QueryClause]) throws -> [[String: Any]] {
let fetchRequest = Internals.CoreStoreFetchRequest<NSDictionary>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
selectClause.applyToFetchRequest(fetchRequest.staticCast())
queryClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
return try self.queryAttributes(fetchRequest)
}
public func queryAttributes<B>(_ clauseChain: B) throws -> [[String : Any]] where B : QueryChainableBuilderType, B.ResultType == NSDictionary {
return try self.queryAttributes(clauseChain.from, clauseChain.select, clauseChain.queryClauses)
}
// MARK: FetchableSource, QueryableSource
@nonobjc
public func unsafeContext() -> NSManagedObjectContext {
return self
}
// MARK: Deleting
@nonobjc
internal func deleteAll<O>(_ from: From<O>, _ deleteClauses: [FetchClause]) throws -> Int {
let fetchRequest = Internals.CoreStoreFetchRequest<NSManagedObject>()
try from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .managedObjectResultType
fetchRequest.returnsObjectsAsFaults = true
fetchRequest.includesPropertyValues = false
deleteClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
return try self.deleteAll(fetchRequest)
}
}
// MARK: - NSManagedObjectContext (Internal)
extension NSManagedObjectContext {
// MARK: Fetching
@nonobjc
internal func fetchOne<O: NSManagedObject>(_ fetchRequest: Internals.CoreStoreFetchRequest<O>) throws -> O? {
var fetchResults: [O]?
var fetchError: Error?
self.performAndWait {
do {
fetchResults = try self.fetch(fetchRequest.staticCast())
}
catch {
fetchError = error
}
}
if let fetchResults = fetchResults {
return fetchResults.first
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing fetch request."
)
throw coreStoreError
}
@nonobjc
internal func fetchAll<O: NSManagedObject>(_ fetchRequest: Internals.CoreStoreFetchRequest<O>) throws -> [O] {
var fetchResults: [O]?
var fetchError: Error?
self.performAndWait {
do {
fetchResults = try self.fetch(fetchRequest.staticCast())
}
catch {
fetchError = error
}
}
if let fetchResults = fetchResults {
return fetchResults
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing fetch request."
)
throw coreStoreError
}
@nonobjc
internal func fetchCount(_ fetchRequest: Internals.CoreStoreFetchRequest<NSNumber>) throws -> Int {
var count = 0
var countError: Error?
self.performAndWait {
do {
count = try self.count(for: fetchRequest.staticCast())
}
catch {
countError = error
}
}
if count == NSNotFound {
let coreStoreError = CoreStoreError(countError)
Internals.log(
coreStoreError,
"Failed executing count request."
)
throw coreStoreError
}
return count
}
@nonobjc
internal func fetchObjectID(_ fetchRequest: Internals.CoreStoreFetchRequest<NSManagedObjectID>) throws -> NSManagedObjectID? {
var fetchResults: [NSManagedObjectID]?
var fetchError: Error?
self.performAndWait {
do {
fetchResults = try self.fetch(fetchRequest.staticCast())
}
catch {
fetchError = error
}
}
if let fetchResults = fetchResults {
return fetchResults.first
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing fetch request."
)
throw coreStoreError
}
// MARK: Querying
@nonobjc
internal func queryValue<O, U: QueryableAttributeType>(_ selectTerms: [SelectTerm<O>], fetchRequest: Internals.CoreStoreFetchRequest<NSDictionary>) throws -> U? {
var fetchResults: [Any]?
var fetchError: Error?
self.performAndWait {
do {
fetchResults = try self.fetch(fetchRequest.staticCast())
}
catch {
fetchError = error
}
}
if let fetchResults = fetchResults {
if let rawResult = fetchResults.first as? NSDictionary,
let rawObject = rawResult[selectTerms.first!.keyPathString] as? U.QueryableNativeType {
return Select<O, U>.ReturnType.cs_fromQueryableNativeType(rawObject)
}
return nil
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing fetch request."
)
throw coreStoreError
}
@nonobjc
internal func queryValue<O>(_ selectTerms: [SelectTerm<O>], fetchRequest: Internals.CoreStoreFetchRequest<NSDictionary>) throws -> Any? {
var fetchResults: [Any]?
var fetchError: Error?
self.performAndWait {
do {
fetchResults = try self.fetch(fetchRequest.staticCast())
}
catch {
fetchError = error
}
}
if let fetchResults = fetchResults {
if let rawResult = fetchResults.first as? NSDictionary,
let rawObject = rawResult[selectTerms.first!.keyPathString] {
return rawObject
}
return nil
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing fetch request."
)
throw coreStoreError
}
@nonobjc
internal func queryAttributes(_ fetchRequest: Internals.CoreStoreFetchRequest<NSDictionary>) throws -> [[String: Any]] {
var fetchResults: [Any]?
var fetchError: Error?
self.performAndWait {
do {
fetchResults = try self.fetch(fetchRequest.staticCast())
}
catch {
fetchError = error
}
}
if let fetchResults = fetchResults {
return NSDictionary.cs_fromQueryResultsNativeType(fetchResults)
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing fetch request."
)
throw coreStoreError
}
// MARK: Deleting
@nonobjc
internal func deleteAll<O: NSManagedObject>(_ fetchRequest: Internals.CoreStoreFetchRequest<O>) throws -> Int {
var numberOfDeletedObjects: Int?
var fetchError: Error?
self.performAndWait {
autoreleasepool {
do {
let fetchResults = try self.fetch(fetchRequest.staticCast())
for object in fetchResults {
self.delete(object)
}
numberOfDeletedObjects = fetchResults.count
}
catch {
fetchError = error
}
}
}
if let numberOfDeletedObjects = numberOfDeletedObjects {
return numberOfDeletedObjects
}
let coreStoreError = CoreStoreError(fetchError)
Internals.log(
coreStoreError,
"Failed executing delete request."
)
throw coreStoreError
}
}
|
mit
|
b2c0e88b732ec618e39ea6801ab8d239
| 31.158784 | 166 | 0.586196 | 5.612618 | false | false | false | false |
mathewsanders/Mustard
|
Playgrounds/Source/Tokenizing Dates.playground/Sources/DateTokenizer.swift
|
1
|
2726
|
//
// DateTokenizer.swift
//
//
// Created by Mathew Sanders on 1/2/17.
//
//
import Swift
import Mustard
infix operator ~=
func ~= (option: CharacterSet, input: UnicodeScalar) -> Bool {
return option.contains(input)
}
final public class DateTokenizer: TokenizerType, DefaultTokenizerType {
// private properties
private let _template = "00/00/00"
private var _position: String.UnicodeScalarIndex
private var _dateText: String
private var _date: Date?
// public property
// called when we access `DateToken.defaultTokenizer`
public required init() {
_position = _template.unicodeScalars.startIndex
_dateText = ""
}
// formatters are expensive, so only instantiate once for all DateTokens
public static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yy"
return dateFormatter
}()
public func tokenCanTake(_ scalar: UnicodeScalar) -> Bool {
guard _position < _template.unicodeScalars.endIndex else {
// we've matched all of the template
return false
}
switch (_template.unicodeScalars[_position], scalar) {
case ("\u{0030}", CharacterSet.decimalDigits), // match with a decimal digit
("\u{002F}", "\u{002F}"): // match with the '/' character
_position = _template.unicodeScalars.index(after: _position) // increment the template position
_dateText.unicodeScalars.append(scalar) // add scalar to text matched so far
return true
default:
return false
}
}
public func tokenIsComplete() -> Bool {
if _position == _template.unicodeScalars.endIndex,
let date = DateTokenizer.dateFormatter.date(from: _dateText) {
// we've reached the end of the template
// and the date text collected so far represents a valid
// date format (e.g. not 99/99/99)
_date = date
return true
}
else {
return false
}
}
// reset the tokenizer for matching new date
public func prepareForReuse() {
_dateText = ""
_date = nil
_position = _template.unicodeScalars.startIndex
}
public struct DateToken: TokenType {
public let text: String
public let range: Range<String.Index>
public let date: Date
}
public func makeToken(text: String, range: Range<String.Index>) -> DateToken {
return DateToken(text: text, range: range, date: _date!)
}
}
|
mit
|
1449df73bd3e5fc70438ecafd37ccce9
| 28.956044 | 107 | 0.594277 | 4.816254 | false | false | false | false |
BalestraPatrick/HomeKitty
|
Sources/App/Controllers/HomeKitAppController.swift
|
1
|
7073
|
//
// Copyright © 2018 HomeKitty. All rights reserved.
//
import Foundation
import Vapor
import HTTP
import FluentPostgreSQL
import Leaf
import Fluent
final class HomeKitAppController {
init(router: Router) {
router.get("apps", use: apps)
router.get("apps", Int.parameter, use: app)
router.get("apps", Int.parameter, "report", use: report)
router.get("apps", "contribute", use: contribute)
router.post("apps", "contribute", use: submit)
}
func apps(_ req: Request) throws -> Future<View> {
let categories = try QueryHelper.categories(request: req)
let apps = try QueryHelper.apps(request: req)
let sidemenuCounts = QueryHelper.sidemenuCounts(request: req)
return flatMap(to: View.self, categories, apps, sidemenuCounts) { categories, apps, sidemenuCounts in
let data = AppsResponse(apps: apps,
categories: categories,
accessoryCount: sidemenuCounts.accessoryCount,
manufacturerCount: sidemenuCounts.manufacturerCount,
appCount: sidemenuCounts.appCount,
noApps: sidemenuCounts.appCount == 0)
let leaf = try req.view()
return leaf.render("Apps/apps", data)
}
}
func app(_ req: Request) throws -> Future<View> {
let paramId: Int = try req.parameters.next()
let categories = try QueryHelper.categories(request: req)
let app = try QueryHelper.app(request: req, id: paramId)
let sidemenuCounts = QueryHelper.sidemenuCounts(request: req)
return app.flatMap { app in
guard let app = app else { throw Abort(.badRequest) }
return flatMap(to: View.self, categories, sidemenuCounts) { categories, sidemenuCounts in
let data = AppResponse(app: app,
categories: categories,
accessoryCount: sidemenuCounts.accessoryCount,
manufacturerCount: sidemenuCounts.manufacturerCount,
appCount: sidemenuCounts.appCount)
let leaf = try req.view()
return leaf.render("Apps/app", data)
}
}
}
// MARK: - Report
func report(_ req: Request) throws -> Future<View> {
let appId: Int = try req.parameters.next()
let accessories = try QueryHelper.accessories(request: req).all()
let apps = try QueryHelper.apps(request: req)
return flatMap(to: View.self, accessories, apps) { (accessories, apps) in
guard let app = apps.filter({ $0.id == appId }).first else { throw Abort(.badRequest) }
let leaf = try req.view()
let responseData = ReportResponse(accessories: accessories.map { $0.0 },
apps: apps,
accessoryToReport: nil,
appToReport: app,
contactTopic: .appIssue)
return leaf.render("report", responseData)
}
}
// MARK: - Contribute
func contribute(_ req: Request) throws -> Future<View> {
let manufacturers = try QueryHelper.manufacturers(request: req)
let categories = try QueryHelper.categories(request: req)
let bridges = try QueryHelper.bridges(request: req)
let regions = try QueryHelper.regions(request: req)
return flatMap(to: View.self, manufacturers, categories, bridges, regions, { (manufacturers, categories, bridges, regions) in
let data = ContributeResponse(categories: categories,
manufacturers: manufacturers,
bridges: bridges.map { Accessory.AccessoryResponse(accessory: $0.0, manufacturer: $0.1) },
regions: regions)
let leaf = try req.view()
return leaf.render("Apps/contribute", data)
})
}
func submit(_ req: Request) throws -> Future<View> {
return try req.content.decode(ContributionRequest.self).flatMap { contributionRequest in
return HomeKitApp.query(on: req)
.filter(\HomeKitApp.appStoreLink == contributionRequest.appStoreLink).first()
.flatMap { app in
let leaf = try req.make(TemplateRenderer.self)
if app?.approved == false {
return leaf.render("contributeSuccess")
}
if app?.id != nil {
throw Abort(.badRequest, reason: "This app already exists")
}
return HomeKitApp(name: contributionRequest.name,
subtitle: contributionRequest.subtitle,
price: Double(contributionRequest.price?.replacingOccurrences(of: "$", with: "").replacingOccurrences(of: ",", with: ".") ?? ""),
appStoreLink: contributionRequest.appStoreLink,
appStoreIcon: contributionRequest.appIcon,
publisher: contributionRequest.publisher,
websiteLink: contributionRequest.websiteLink)
.create(on: req)
.flatMap { _ in
return leaf.render("contributeSuccess")
}
}
}
}
struct ContributeResponse: Content {
let categories: [Category]
let manufacturers: [Manufacturer]
let bridges: [Accessory.AccessoryResponse]
let regions: [Region]
}
private struct AppsResponse: Codable {
let apps: [HomeKitApp]
let categories: [Category]
let accessoryCount: Int
let manufacturerCount: Int
let appCount: Int
let noApps: Bool
}
private struct AppResponse: Codable {
let pageTitle = "App Details"
let app: HomeKitApp
let categories: [Category]
let accessoryCount: Int
let manufacturerCount: Int
let appCount: Int
}
private struct ContributionRequest: Content {
let name: String
let subtitle: String?
let price: String?
let appIcon: String
let appStoreLink: String
let recaptchaResponse: String
let publisher: String
let websiteLink: String
enum CodingKeys: String, CodingKey {
case name
case subtitle
case price
case appIcon = "app_icon"
case appStoreLink = "appStore_link"
case publisher
case websiteLink = "website_link"
case recaptchaResponse = "g-recaptcha-response"
}
}
}
|
mit
|
24554e4d56dac9c4ec87b3dc7bb1c9a1
| 39.411429 | 167 | 0.546946 | 5.098774 | false | false | false | false |
WeHUD/app
|
weHub-ios/Gzone_App/Gzone_App/ContactViewController.swift
|
1
|
4095
|
//
// ContactViewController.swift
// Gzone_App
//
// Created by Lyes Atek on 04/07/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import UIKit
class ContactViewController : UIViewController, UITableViewDataSource,UITableViewDelegate{
@IBOutlet var tableView: UITableView!
var followers : [User] = []
var avatars : [UIImage] = []
let cellIdentifier = "FriendsSearchCustomCell"
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(UINib(nibName: "FriendsSearchTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier)
self.tableView.estimatedRowHeight = UITableViewAutomaticDimension
self.tableView.rowHeight = 90.0
self.tableView.dataSource = self
self.tableView.delegate = self
self.getUsers()
self.tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Home", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ProfilUser") as! ProfilUserViewController
controller.user = self.followers[(self.tableView.indexPathForSelectedRow?.row)!]
navigationController?.pushViewController(controller, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.followers.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "FriendsSearchCustomCell") as! FriendsSearchTableViewCell
let follower = followers[indexPath.row]
cell.userNameLbl.text = follower.username
cell.userReplyLbl.text = "@" + follower.username
cell.userAvatarImageView.image = self.avatars[indexPath.row]
cell.UnfollowAction = { (cell) in self.unfollowAction(followerId: follower._id, row: tableView.indexPath(for: cell)!.row, indexPath: indexPath)}
// cell.followBtn = { (cell) in self.unfollowAction(followerId: follower._id, row: tableView.indexPath(for: cell)!.row, indexPath: indexPath)
return cell
}
func unfollowAction(followerId : String, row : Int,indexPath : IndexPath){
let followerWB = WBFollower()
followerWB.deleteFollowerUser(userId: AuthenticationService.sharedInstance.currentUser!._id, followerId: followerId,accessToken: AuthenticationService.sharedInstance.accessToken!){
(result: Bool) in
DispatchQueue.main.async(execute: {
self.getUsers()
})
print(result)
}
}
func refreshTableView(){
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
func getUsers()->Void{
let userWB : WBUser = WBUser()
userWB.getFollowedUser(accessToken: AuthenticationService.sharedInstance.accessToken!, userId : AuthenticationService.sharedInstance.currentUser!._id,offset: "0") {
(result: [User]) in
self.followers = result
self.imageFromUrl(followers: self.followers)
self.refreshTableView()
}
}
func imageFromUrl(followers : [User]){
self.avatars.removeAll()
for follower in followers {
let imageUrlString = follower.avatar
let imageUrl:URL = URL(string: imageUrlString!)!
let imageData:NSData = NSData(contentsOf: imageUrl)!
self.avatars.append(UIImage(data: imageData as Data)!)
}
}
}
|
bsd-3-clause
|
46e9fb788784c77f3dcaa36f477efc18
| 33.116667 | 188 | 0.637763 | 5.221939 | false | false | false | false |
DeFrenZ/BonBon
|
Sources/Observable.swift
|
1
|
7995
|
/// A reference wrapper around a mutable value. An object can subscribe for
/// updates to this value with a function, which will have both the states of
/// the transition as arguments. It's not mandatory to unsubscribe to the
/// updates as no strong reference is kept and if a subscribed object gets
/// deallocated it automatically gets unsubsribed.
///
/// - warning: The observer doesn't listen to the wrapped value changes, so if
/// `Observed` has reference semantics notifications of its update will be
/// given only when the reference gets updated, and not when the referenced
/// value does.
/// - seealso: [Observer Pattern]
/// (https://en.wikipedia.org/wiki/Observer_pattern)
public final class Observable<Observed> {
// MARK: Private implementation
private var actionsPerObject: [ObjectIdentifier: UpdateAction] = [:]
private var actions: AnySequence<UpdateAction> {
return .init(actionsPerObject.values)
}
private func addObserver(with identifier: ObjectIdentifier, onUpdate: @escaping UpdateAction) {
actionsPerObject[identifier] = onUpdate
}
private func removeObserver(with identifier: ObjectIdentifier) {
actionsPerObject[identifier] = nil
}
private func notifyObservers(from oldValue: Observed, to newValue: Observed) {
actions.forEach { $0(oldValue, newValue) }
}
// MARK: Public interface
/// The type of the function that gets called back on updates.
/// - note: `from` and `to` are not necessarily different. Use
/// `subscribe(_:onChange:)` if you want to ensure that.
///
/// - parameter from: The wrapped value before the update.
/// - parameter to: The wrapped value after the update.
public typealias UpdateAction = (_ from: Observed, _ to: Observed) -> Void
/// The wrapped value of which updates are tracked by the `Observable`
/// object and notified to its observers. Can be read and changed by
/// anyone.
public var value: Observed {
didSet { notifyObservers(from: oldValue, to: value) }
}
/// Create a new `Observable` wrapping the given `value`.
///
/// - parameter value: The initial value from which changes will be
/// observed.
public init(_ value: Observed) {
self.value = value
}
/// Subscribe to updates on the wrapped value by calling the passed function
/// every time that happens. The subscription is referenced to through the
/// given object, which is not strongly referenced, so that needs to stay
/// alive for the subscription to continue and must be used to unsubscribe.
/// - note: `onUpdate` will be called whenever the wrapped value gets set,
/// even if the value didn't change. It doesn't get called when you
/// subscribe to it.
/// - warning: Only one subscription per object per `Observable` is allowed.
/// Subscribing again with the same object for updates will
/// automatically remove the previous subscription. If you want to
/// subscribe with separate callbacks from the same context, use two
/// different objects for them.
/// - seealso: `subscribe(_:onChange:)`
///
/// - parameter observer: The object that owns the subscription. It can be
/// hold only one subscription per `Observable`. If this gets
/// deallocated then it is automatically unsubscribed.
/// - parameter onUpdate: The function that will get called on every update
/// of the wrapped value.
public func subscribe(_ observer: AnyObject, onUpdate: @escaping UpdateAction) {
let identifier = ObjectIdentifier(observer)
let autoreleasingOnUpdate: UpdateAction = { [weak self, weak observer] oldValue, newValue in
guard let _self = self else { return }
guard observer != nil else {
_self.removeObserver(with: identifier)
return
}
onUpdate(oldValue, newValue)
}
addObserver(with: identifier, onUpdate: autoreleasingOnUpdate)
}
/// Unsubscribe the given object from further updates to the wrapped value.
///
/// - parameter observer: The object that was used to subscribe to updates
/// in the first place.
public func unsubscribe(_ observer: AnyObject) {
let identifier = ObjectIdentifier(observer)
removeObserver(with: identifier)
}
}
// MARK: - Type-constrained extensions
extension Observable where Observed: Equatable {
/// Subscribe to changes on the wrapped value with the passed function, but
/// only when it gets set to a different value. That's the only difference
/// from a classic subscription.
/// - seealso: `subscribe(_:onUpdate:)`
///
/// - parameter observer: The object that owns the subscription.
/// - parameter onChange: The function that will get called on every update
/// of the wrapped value to a different value.
public func subscribe(_ observer: AnyObject, onChange: @escaping UpdateAction) {
subscribe(observer, onUpdate: { oldValue, newValue in
guard newValue != oldValue else { return }
onChange(oldValue, newValue)
})
}
}
// MARK: - Functional extensions
extension Observable {
/// Create a new `Observable` object that always keeps the same value as
/// this one, transformed through the given function. The updates are given
/// referring to the transformed value, and changes are determined in terms
/// of the result of the transformation.
///
/// - parameter transform: The transform between the value on this object
/// and the resulting one.
/// - parameter value: The `value` of this that gets transformed.
/// - returns: Another `Observable`, which notifies its subscribers of
/// updates on its transformed value.
public func map <T> (_ transform: @escaping (_ value: Observed) -> T) -> Observable<T> {
let mappedObservable: Observable<T> = .init(transform(value))
subscribe(mappedObservable, onUpdate: { [weak mappedObservable] oldValue, newValue in
mappedObservable?.value = transform(newValue)
})
return mappedObservable
}
/// Create a new `Observable` object that alwyas keeps the value of the one
/// resulting from applying the given `transform` on this one. The updates
/// are given referring to the transformed value, and changes are determined
/// in terms of the result of the transformation.
/// - seealso: `map`
///
/// - parameter transform: The transform between the value on this object
/// and a new `Observable`.
/// - parameter value: The `value` of this that gets transformed.
/// - returns: Another `Observable`, which is created from applying
/// `transform` on the current `value`, but which keeps track of future
/// changes of it.
public func flatMap <T> (_ transform: @escaping (_ value: Observed) -> Observable<T>) -> Observable<T> {
return map({ transform($0).value })
}
}
// MARK: - ==
extension Observable where Observed: Equatable {
/// Returns a `Bool` value indicating whether two `Observable` objects wrap
/// the same value.
/// - note: This check doesn't consider who is observing the objects. If you
/// want to check whether two variables refer to the same object, use
/// `===` instead.
///
/// - parameter lhs: The object on the left hand side of the operator.
/// - parameter rhs: The object on the right hand side of the operator.
/// - returns: `true` if the two objects wrap the same value, `false`
/// otherwise.
public static func == (_ lhs: Observable, _ rhs: Observable) -> Bool {
return lhs.value == rhs.value
}
/// Returns a `Bool` value indicating whether two `Observable` objects don't
/// wrap the same value.
/// - seealso: `Observable.==`
///
/// - parameter lhs: The object on the left hand side of the operator.
/// - parameter rhs: The object on the right hand side of the operator.
/// - returns: `false` if the two objects wrap the same value, `true`
/// otherwise.
public static func != (_ lhs: Observable, _ rhs: Observable) -> Bool {
return !(lhs == rhs)
}
}
// MARK: -
/// An empty reference. It's only purpose is to be used to subscribe to an
/// `Observable` when there's no more fitting object to use as the observer.
public final class SubscriptionOwner {
public init() {}
}
|
mit
|
f4942295e00db3bb63d58f873da6ad91
| 40.21134 | 105 | 0.711445 | 3.926817 | false | false | false | false |
ali-zahedi/AZViewer
|
AZViewer/AZRefreshControl.swift
|
1
|
3170
|
//
// AZRefreshControl.swift
// AZViewer
//
// Created by Ali Zahedi on 2/19/1396 AP.
// Copyright © 1396 AP Ali Zahedi. All rights reserved.
//
import UIKit
public class AZRefreshControl: UIRefreshControl{
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
// MARK: Public
public var loader: AZLoader{
return self.loaderView.loader
}
public var text: String = "" {
didSet{
self.title.text = self.text
}
}
public var title: AZLabel = AZLabel()
public var dateFormat: String = "HH:mm:ss dd/MMMM/yyyy" {
didSet{
self.formatterPersian.dateFormat = self.dateFormat
}
}
// MARK: Private
fileprivate var loaderView: AZView = AZView()
fileprivate var formatterPersian: DateFormatter!
// MARK: Init
override public init() {
super.init()
self.defaultInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.defaultInit()
}
// MARK: Override
public override func beginRefreshing() {
super.beginRefreshing()
self.loader.isActive = true
let date = Date()
self.title.text = self.formatterPersian.string(from: date)
}
public override func endRefreshing() {
super.endRefreshing()
self.loader.isActive = false
}
// MARK: Function
fileprivate func defaultInit(){
// fix color
self.tintColor = UIColor.clear
// add view
for v in [loaderView, title] as [UIView]{
v.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(v)
}
// persian formatter
self.prepareFormatterPersian()
// loader
self.prepareLoader()
// title
self.prepareTitleLabel()
}
}
// prepare
extension AZRefreshControl{
//loader
fileprivate func prepareLoader(){
self.loader.blurIsHidden = true
self.loader.horizontalAlignment = .middle
_ = self.loaderView.aZConstraints.parent(parent: self).top().right().left().height(to: self, multiplier: 0.7)
}
//tilte
fileprivate func prepareTitleLabel(){
_ = self.title.aZConstraints.parent(parent: self).top(to: self.loaderView, toAttribute: .bottom).right().left().bottom()
self.title.font = AZStyle.shared.sectionRefreshControlFont
self.title.textColor = AZStyle.shared.sectionRefreshControlColor
self.title.textAlignment = .center
}
// calender
fileprivate func prepareFormatterPersian(){
self.formatterPersian = DateFormatter()
self.formatterPersian.dateFormat = self.dateFormat
self.formatterPersian.locale = Locale(identifier:"fa_IR")
// self.formatterPersian.dateStyle = .l
self.formatterPersian.calendar = Calendar(identifier: .persian)
}
}
|
apache-2.0
|
1308a7685ee96119168894c83d028d4e
| 25.855932 | 128 | 0.60934 | 4.715774 | false | false | false | false |
BobbyRenTech/BRLazyPagedScrollView
|
Example/BRLazyPagedScrollView/BrowserViewController.swift
|
1
|
3947
|
//
// BrowserViewController.swift
// DialDemo
//
// Created by Bobby Ren on 5/15/15.
// Copyright (c) 2015 FwdCommit. All rights reserved.
//
import UIKit
class BrowserViewController: BRLazyPagedScrollViewController, UIScrollViewDelegate {
// @IBOutlet weak var myScrollView: UIScrollView!
var currentPageNumber: Int = 0
var maxPages: Int = 10
var allPages: [Int:PageViewController] = [Int:PageViewController]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController!.navigationBar.backgroundColor = UIColor.clearColor()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let width_ratio:CGFloat = 0.8
self.setupScrollViewWithPageWidth(self.view.frame.size.width * width_ratio, size: CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 100), border:30)
self.setupPages()
}
override func loadCurrentPage() {
var controller: PageViewController? = allPages[self.currentPageNumber]
if controller == nil {
controller = storyboard!.instantiateViewControllerWithIdentifier("PageViewController") as? PageViewController
controller!.setNumber(self.currentPageNumber)
self.allPages[self.currentPageNumber] = controller
}
self.currentPage = controller
super.loadCurrentPage()
println("current page \(controller!.currentNumber) offset \(controller!.view.frame.origin.x) scroll content \(scrollView.contentOffset.x) \(scrollView.contentOffset.y)")
}
override func loadLeftPage() {
if !self.canGoLeft() {
return;
}
var controller: PageViewController? = allPages[self.currentPageNumber-1]
if controller == nil {
controller = storyboard!.instantiateViewControllerWithIdentifier("PageViewController") as? PageViewController
controller!.setNumber(self.currentPageNumber-1)
self.allPages[self.currentPageNumber-1] = controller
}
self.leftPage = controller
super.loadLeftPage()
println("<-left page \(controller!.currentNumber) offset \(controller!.view.frame.origin.x)")
}
override func loadRightPage() {
if !self.canGoRight() {
return;
}
var controller: PageViewController? = allPages[self.currentPageNumber+1]
if controller == nil {
controller = storyboard!.instantiateViewControllerWithIdentifier("PageViewController") as? PageViewController
controller!.setNumber(self.currentPageNumber+1)
self.allPages[self.currentPageNumber+1] = controller
}
self.rightPage = controller
super.loadRightPage()
println("->right page \(controller!.currentNumber) offset \(controller!.view.frame.origin.x)")
}
override func canGoLeft() -> Bool {
return self.currentPageNumber > 0
}
override func canGoRight() -> Bool {
return self.currentPageNumber < maxPages - 1
}
override func pageLeft() {
self.currentPageNumber = self.currentPageNumber - 1
super.pageLeft()
}
override func pageRight() {
self.currentPageNumber = self.currentPageNumber + 1
super.pageRight()
}
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
|
88b64b4079415b75c0bded2d20b55d08
| 34.558559 | 177 | 0.664049 | 5.034439 | false | false | false | false |
ahoppen/swift
|
test/SILGen/literals.swift
|
16
|
25028
|
// RUN: %target-swift-emit-silgen %s | %FileCheck %s
func takesOptionalFunction(_: (() -> ())?) {}
struct CustomNull : ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func takesANull(_: CustomNull) {}
// CHECK-LABEL: sil hidden [ossa] @$s8literals4testyyF : $@convention(thin) () -> ()
func test() {
// CHECK: [[NIL:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.none!enumelt
// CHECK: [[FN:%.*]] = function_ref @$s8literals21takesOptionalFunctionyyyycSgF
// CHECK: apply [[FN]]([[NIL]])
_ = takesOptionalFunction(nil)
// CHECK: [[METATYPE:%.*]] = metatype $@thin CustomNull.Type
// CHECK: [[NIL_FN:%.*]] = function_ref @$s8literals10CustomNullV10nilLiteralACyt_tcfC
// CHECK: [[NIL:%.*]] = apply [[NIL_FN]]([[METATYPE]])
// CHECK: [[FN:%.*]] = function_ref @$s8literals10takesANullyyAA10CustomNullVF
// CHECK: apply [[FN]]([[NIL]])
_ = takesANull(nil)
}
class CustomStringClass : ExpressibleByStringLiteral {
required init(stringLiteral value: String) {}
required init(extendedGraphemeClusterLiteral value: String) {}
required init(unicodeScalarLiteral value: String) {}
}
class CustomStringSubclass : CustomStringClass {}
// CHECK-LABEL: sil hidden [ossa] @$s8literals27returnsCustomStringSubclassAA0cdE0CyF : $@convention(thin) () -> @owned CustomStringSubclass
// CHECK: [[METATYPE:%.*]] = metatype $@thick CustomStringSubclass.Type
// CHECK: [[UPCAST:%.*]] = upcast [[METATYPE]] : $@thick CustomStringSubclass.Type to $@thick CustomStringClass.Type
// CHECK: [[CTOR:%.*]] = class_method [[UPCAST]] : $@thick CustomStringClass.Type, #CustomStringClass.init!allocator : (CustomStringClass.Type) -> (String) -> CustomStringClass, $@convention(method) (@owned String, @thick CustomStringClass.Type) -> @owned CustomStringClass
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]({{%.*}}, [[UPCAST]])
// CHECK: [[DOWNCAST:%.*]] = unchecked_ref_cast [[RESULT]] : $CustomStringClass to $CustomStringSubclass
// CHECK: return [[DOWNCAST]]
func returnsCustomStringSubclass() -> CustomStringSubclass {
return "hello world"
}
class TakesArrayLiteral<Element> : ExpressibleByArrayLiteral {
required init(arrayLiteral elements: Element...) {}
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals18returnsCustomArrayAA05TakesD7LiteralCySiGyF : $@convention(thin) () -> @owned TakesArrayLiteral<Int>
// CHECK: [[TMP:%.*]] = apply %2(%0, %1) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 2
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Int>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: store [[TMP:%.*]] to [trivial] [[POINTER]]
// CHECK: [[IDX1:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[POINTER1:%.*]] = index_addr [[POINTER]] : $*Int, [[IDX1]] : $Builtin.Word
// CHECK: store [[TMP:%.*]] to [trivial] [[POINTER1]]
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Int>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Int>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Int>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Int>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
func returnsCustomArray() -> TakesArrayLiteral<Int> {
// Use temporary to simplify generated_sil
let tmp = 77
return [tmp, tmp]
}
class Klass {}
// CHECK-LABEL: sil hidden [ossa] @$s8literals24returnsClassElementArrayAA05TakesE7LiteralCyAA5KlassCGyF : $@convention(thin) () -> @owned TakesArrayLiteral<Klass>
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Klass>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: [[KLASS_METATYPE:%.*]] = metatype $@thick Klass.Type
// CHECK: [[CTOR:%.*]] = function_ref @$s8literals5KlassCACycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: [[TMP:%.*]] = apply [[CTOR]]([[KLASS_METATYPE]]) : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: store [[TMP]] to [init] [[POINTER]]
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Klass>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Klass>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Klass>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Klass>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
func returnsClassElementArray() -> TakesArrayLiteral<Klass> {
return [Klass()]
}
struct Foo<T> {
var t: T
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals30returnsAddressOnlyElementArray1tAA05TakesF7LiteralCyAA3FooVyxGGAH_tlF : $@convention(thin) <T> (@in_guaranteed Foo<T>) -> @owned TakesArrayLiteral<Foo<T>>
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo<T>>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: copy_addr %0 to [initialization] [[POINTER]] : $*Foo<T>
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Foo<T>>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo<T>>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo<T>>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo<T>>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
func returnsAddressOnlyElementArray<T>(t: Foo<T>) -> TakesArrayLiteral<Foo<T>> {
return [t]
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals3FooV20returnsArrayFromSelfAA05TakesD7LiteralCyACyxGGyF : $@convention(method) <T> (@in_guaranteed Foo<T>) -> @owned TakesArrayLiteral<Foo<T>>
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo<T>>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: copy_addr %0 to [initialization] [[POINTER]] : $*Foo<T>
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Foo<T>>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo<T>>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo<T>>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo<T>>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
extension Foo {
func returnsArrayFromSelf() -> TakesArrayLiteral<Foo<T>> {
return [self]
}
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals3FooV28returnsArrayFromMutatingSelfAA05TakesD7LiteralCyACyxGGyF : $@convention(method) <T> (@inout Foo<T>) -> @owned TakesArrayLiteral<Foo<T>>
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo<T>>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] %0 : $*Foo<T>
// CHECK: copy_addr [[ACCESS]] to [initialization] [[POINTER]] : $*Foo<T>
// CHECK: end_access [[ACCESS]] : $*Foo<T>
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Foo<T>>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo<T>>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo<T>>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo<T>>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
extension Foo {
mutating func returnsArrayFromMutatingSelf() -> TakesArrayLiteral<Foo<T>> {
return [self]
}
}
struct Foo2 {
var k: Klass
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals23returnsNonTrivialStructAA17TakesArrayLiteralCyAA4Foo2VGyF : $@convention(thin) () -> @owned TakesArrayLiteral<Foo2>
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<Foo2>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: [[METATYPE_FOO2:%.*]] = metatype $@thin Foo2.Type
// CHECK: [[METATYPE_KLASS:%.*]] = metatype $@thick Klass.Type
// CHECK: [[CTOR:%.*]] = function_ref @$s8literals5KlassCACycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: [[K:%.*]] = apply [[CTOR]]([[METATYPE_KLASS]]) : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: [[CTOR:%.*]] = function_ref @$s8literals4Foo2V1kAcA5KlassC_tcfC : $@convention(method) (@owned Klass, @thin Foo2.Type) -> @owned Foo2
// CHECK: [[TMP:%.*]] = apply [[CTOR]]([[K]], [[METATYPE_FOO2]]) : $@convention(method) (@owned Klass, @thin Foo2.Type) -> @owned Foo2
// store [[TMP]] to [init] [[POINTER]] : $*Foo2
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Foo2>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<Foo2>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<Foo2>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Foo2>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
func returnsNonTrivialStruct() -> TakesArrayLiteral<Foo2> {
return [Foo2(k: Klass())]
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals16NestedLValuePathV11wrapInArrayyyF : $@convention(method) (@inout NestedLValuePath) -> ()
// CHECK: [[METATYPE_NESTED:%.*]] = metatype $@thin NestedLValuePath.Type
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<NestedLValuePath>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] %0 : $*NestedLValuePath
// CHECK: [[OTHER_FN:%.*]] = function_ref @$s8literals16NestedLValuePathV21otherMutatingFunctionACyF : $@convention(method) (@inout NestedLValuePath) -> @owned NestedLValuePath
// CHECK: [[TMP:%.*]] = apply [[OTHER_FN]]([[ACCESS]]) : $@convention(method) (@inout NestedLValuePath) -> @owned NestedLValuePath
// CHECK: end_access [[ACCESS]] : $*NestedLValuePath
// CHECK: store [[TMP]] to [init] [[POINTER]] : $*NestedLValuePath
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<NestedLValuePath>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<NestedLValuePath>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<NestedLValuePath>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[ARR_RESULT:%.*]] = apply [[CTOR]]<NestedLValuePath>([[FIN_ARR]], [[METATYPE]])
// CHECK: [[CTOR:%.*]] = function_ref @$s8literals16NestedLValuePathV3arrAcA17TakesArrayLiteralCyACG_tcfC : $@convention(method) (@owned TakesArrayLiteral<NestedLValuePath>, @thin NestedLValuePath.Type) -> @owned NestedLValuePath
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]([[ARR_RESULT]], [[METATYPE_NESTED]]) : $@convention(method) (@owned TakesArrayLiteral<NestedLValuePath>, @thin NestedLValuePath.Type) -> @owned NestedLValuePath
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] %0 : $*NestedLValuePath
// CHECK: assign [[RESULT]] to [[ACCESS]] : $*NestedLValuePath
// CHECK: end_access [[ACCESS]] : $*NestedLValuePath
// CHECK: [[VOID:%.*]] = tuple ()
// CHECK: return [[VOID]] : $()
struct NestedLValuePath {
var arr: TakesArrayLiteral<NestedLValuePath>
mutating func wrapInArray() {
self = NestedLValuePath(arr: [self.otherMutatingFunction()])
}
mutating func otherMutatingFunction() -> NestedLValuePath {
return self
}
}
protocol WrapsSelfInArray {}
// CHECK-LABEL: sil hidden [ossa] @$s8literals16WrapsSelfInArrayPAAE04wrapdE0AA05TakesE7LiteralCyAaB_pGyF : $@convention(method) <Self where Self : WrapsSelfInArray> (@inout Self) -> @owned TakesArrayLiteral<WrapsSelfInArray>
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<WrapsSelfInArray>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] %0 : $*Self
// CHECK: [[EXISTENTIAL:%.*]] = init_existential_addr [[POINTER]] : $*WrapsSelfInArray, $Self
// CHECK: copy_addr [[ACCESS]] to [initialization] [[EXISTENTIAL]] : $*Self
// CHECK: end_access [[ACCESS]] : $*Self
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<WrapsSelfInArray>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesArrayLiteral<WrapsSelfInArray>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesArrayLiteral<WrapsSelfInArray>.Type, #TakesArrayLiteral.init!allocator : <Element> (TakesArrayLiteral<Element>.Type) -> (Element...) -> TakesArrayLiteral<Element>, $@convention(method)
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<WrapsSelfInArray>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
extension WrapsSelfInArray {
mutating func wrapInArray() -> TakesArrayLiteral<WrapsSelfInArray> {
return [self]
}
}
protocol FooProtocol {
init()
}
func makeThrowing<T : FooProtocol>() throws -> T { return T() }
func makeBasic<T : FooProtocol>() -> T { return T() }
// CHECK-LABEL: sil hidden [ossa] @$s8literals15throwingElementSayxGyKAA11FooProtocolRzlF : $@convention(thin) <T where T : FooProtocol> () -> (@owned Array<T>, @error Error)
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 2
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<T>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]]
// CHECK: [[FN:%.*]] = function_ref @$s8literals9makeBasicxyAA11FooProtocolRzlF : $@convention(thin)
// CHECK: [[TMP:%.*]] = apply [[FN]]<T>([[POINTER]])
// CHECK: [[IDX:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[POINTER1:%.*]] = index_addr [[POINTER]] : $*T, [[IDX]] : $Builtin.Word
// CHECK: [[FN:%.*]] = function_ref @$s8literals12makeThrowingxyKAA11FooProtocolRzlF : $@convention(thin)
// CHECK: try_apply [[FN]]<T>([[POINTER1]]) : {{.*}} normal bb1, error bb2
// CHECK: bb1([[TMP:%.*]] : $()):
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<T>([[ARR]])
// CHECK: return [[FIN_ARR]]
// CHECK: bb2([[ERR:%.*]] : @owned $Error):
// CHECK: destroy_addr [[POINTER]] : $*T
// CHECK: [[DEALLOC:%.*]] = function_ref @$ss29_deallocateUninitializedArrayyySayxGnlF
// CHECK: [[TMP:%.*]] = apply [[DEALLOC]]<T>([[ARR]])
// CHECK: throw [[ERR]] : $Error
func throwingElement<T : FooProtocol>() throws -> [T] {
return try [makeBasic(), makeThrowing()]
}
class TakesDictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral {
required init(dictionaryLiteral elements: (Key, Value)...) {}
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals23returnsCustomDictionaryAA05TakesD7LiteralCyS2iGyF : $@convention(thin) () -> @owned TakesDictionaryLiteral<Int, Int> {
// CHECK: [[TMP:%.*]] = apply %2(%0, %1) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[ARRAY_LENGTH:%.*]] = integer_literal $Builtin.Word, 2
// CHECK: // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [[ALLOCATE_VARARGS:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARR_TMP:%.*]] = apply [[ALLOCATE_VARARGS]]<(Int, Int)>([[ARRAY_LENGTH]])
// CHECK: ([[ARR:%.*]], [[ADDRESS:%.*]]) = destructure_tuple [[ARR_TMP]]
// CHECK: [[TUPLE_ADDR:%.*]] = pointer_to_address %9 : $Builtin.RawPointer to [strict] $*(Int, Int)
// CHECK: [[KEY_ADDR:%.*]] = tuple_element_addr [[TUPLE_ADDR]] : $*(Int, Int), 0
// CHECK: [[VALUE_ADDR:%.*]] = tuple_element_addr [[TUPLE_ADDR]] : $*(Int, Int), 1
// CHECK: store [[TMP]] to [trivial] [[KEY_ADDR]] : $*Int
// CHECK: store [[TMP]] to [trivial] [[VALUE_ADDR]] : $*Int
// CHECK: [[IDX1:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [[TUPLE_ADDR1:%.*]] = index_addr [[TUPLE_ADDR]] : $*(Int, Int), [[IDX1]] : $Builtin.Word
// CHECK: [[KEY_ADDR:%.*]] = tuple_element_addr [[TUPLE_ADDR1]] : $*(Int, Int), 0
// CHECK: [[VALUE_ADDR:%.*]] = tuple_element_addr [[TUPLE_ADDR1]] : $*(Int, Int), 1
// CHECK: store [[TMP]] to [trivial] [[KEY_ADDR]] : $*Int
// CHECK: store [[TMP]] to [trivial] [[VALUE_ADDR]] : $*Int
// CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<(Int, Int)>([[ARR]])
// CHECK: [[METATYPE:%.*]] = metatype $@thick TakesDictionaryLiteral<Int, Int>.Type
// CHECK: [[CTOR:%.*]] = class_method [[METATYPE]] : $@thick TakesDictionaryLiteral<Int, Int>.Type, #TakesDictionaryLiteral.init!allocator : <Key, Value> (TakesDictionaryLiteral<Key, Value>.Type) -> ((Key, Value)...) -> TakesDictionaryLiteral<Key, Value>, $@convention(method) <τ_0_0, τ_0_1> (@owned Array<(τ_0_0, τ_0_1)>, @thick TakesDictionaryLiteral<τ_0_0, τ_0_1>.Type) -> @owned TakesDictionaryLiteral<τ_0_0, τ_0_1>
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]<Int, Int>([[FIN_ARR]], [[METATYPE]])
// CHECK: return [[RESULT]]
func returnsCustomDictionary() -> TakesDictionaryLiteral<Int, Int> {
// Use temporary to simplify generated_sil
let tmp = 77
return [tmp: tmp, tmp : tmp]
}
struct Color: _ExpressibleByColorLiteral {
init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) {}
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals16makeColorLiteralAA0C0VyF : $@convention(thin) () -> Color {
// CHECK: [[COLOR_METATYPE:%.*]] = metatype $@thin Color.Type
// CHECK: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF5BA5E353F7CEE|0x3FFFADD2F1A9FBE76C8B}}
// CHECK: [[METATYPE:%.*]] = metatype $@thin Float.Type
// CHECK: [[FN:%.*]] = function_ref @$sSf20_builtinFloatLiteralSfBf{{64|80}}__tcfC
// CHECK: [[R:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Float.Type) -> Float
// CHECK: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0xBFB2F1A9FBE76C8B|0xBFFB978D4FDF3B645A1D}}
// CHECK: [[METATYPE:%.*]] = metatype $@thin Float.Type
// CHECK: [[FN:%.*]] = function_ref @$sSf20_builtinFloatLiteralSfBf{{64|80}}__tcfC
// CHECK: [[G:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Float.Type) -> Float
// CHECK: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0xBF889374BC6A7EFA|0xBFF8C49BA5E353F7CED9}}
// CHECK: [[METATYPE:%.*]] = metatype $@thin Float.Type
// CHECK: [[FN:%.*]] = function_ref @$sSf20_builtinFloatLiteralSfBf{{64|80}}__tcfC
// CHECK: [[B:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Float.Type) -> Float
// CHECK: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF0000000000000|0x3FFF8000000000000000}}
// CHECK: [[METATYPE:%.*]] = metatype $@thin Float.Type
// CHECK: [[FN:%.*]] = function_ref @$sSf20_builtinFloatLiteralSfBf{{64|80}}__tcfC
// CHECK: [[A:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Float.Type) -> Float
// CHECK: [[FN:%.*]] = function_ref @$s8literals5ColorV16_colorLiteralRed5green4blue5alphaACSf_S3ftcfC : $@convention(method) (Float, Float, Float, Float, @thin Color.Type) -> Color
// CHECK: [[LIT:%.*]] = apply [[FN]]([[R]], [[G]], [[B]], [[A]], [[COLOR_METATYPE]]) : $@convention(method) (Float, Float, Float, Float, @thin Color.Type) -> Color
// CHECK: return [[LIT]] : $Color
func makeColorLiteral() -> Color {
return #colorLiteral(red: 1.358, green: -0.074, blue: -0.012, alpha: 1.0)
}
struct Image: _ExpressibleByImageLiteral {
init(imageLiteralResourceName: String) {}
}
func makeTmpString() -> String { return "" }
// CHECK-LABEL: sil hidden [ossa] @$s8literals16makeImageLiteralAA0C0VyF : $@convention(thin) () -> Image
// CHECK: [[METATYPE:%.*]] = metatype $@thin Image.Type
// CHECK: [[FN:%.*]] = function_ref @$s8literals13makeTmpStringSSyF : $@convention(thin) () -> @owned String
// CHECK: [[STR:%.*]] = apply [[FN]]() : $@convention(thin) () -> @owned String
// CHECK: [[FN:%.*]] = function_ref @$s8literals5ImageV24imageLiteralResourceNameACSS_tcfC : $@convention(method) (@owned String, @thin Image.Type) -> Image
// CHECK: [[LIT:%.*]] = apply [[FN]]([[STR]], [[METATYPE]]) : $@convention(method) (@owned String, @thin Image.Type) -> Image
// CHECK: return [[LIT]] : $Image
func makeImageLiteral() -> Image {
return #imageLiteral(resourceName: makeTmpString())
}
struct FileReference: _ExpressibleByFileReferenceLiteral {
init(fileReferenceLiteralResourceName: String) {}
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals24makeFileReferenceLiteralAA0cD0VyF : $@convention(thin) () -> FileReference
// CHECK: [[METATYPE:%.*]] = metatype $@thin FileReference.Type
// CHECK: [[FN:%.*]] = function_ref @$s8literals13makeTmpStringSSyF : $@convention(thin) () -> @owned String
// CHECK: [[STR:%.*]] = apply [[FN]]() : $@convention(thin) () -> @owned String
// CHECK: [[FN:%.*]] = function_ref @$s8literals13FileReferenceV04fileC19LiteralResourceNameACSS_tcfC
// CHECK: [[LIT:%.*]] = apply [[FN]]([[STR]], [[METATYPE]]) : $@convention(method) (@owned String, @thin FileReference.Type) -> FileReference
// CHECK: return [[LIT]] : $FileReference
func makeFileReferenceLiteral() -> FileReference {
return #fileLiteral(resourceName: makeTmpString())
}
class ReferenceColor<T> { required init() {} }
protocol Silly {
init()
init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float)
}
extension Silly {
init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) {
self.init()
}
}
extension ReferenceColor : Silly, _ExpressibleByColorLiteral {}
func makeColorLiteral<T>() -> ReferenceColor<T> {
return #colorLiteral(red: 1.358, green: -0.074, blue: -0.012, alpha: 1.0)
}
// CHECK-LABEL: sil hidden [ossa] @$s8literals16makeColorLiteralAA09ReferenceC0CyxGylF : $@convention(thin) <T> () -> @owned ReferenceColor<T>
// CHECK: [[FN:%.*]] = function_ref @$s8literals5SillyPAAE16_colorLiteralRed5green4blue5alphaxSf_S3ftcfC : $@convention(method) <τ_0_0 where τ_0_0 : Silly> (Float, Float, Float, Float, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: apply [[FN]]<ReferenceColor<T>>(
|
apache-2.0
|
e04ce589b0520319a75ddff1bc9cd1b4
| 61.849246 | 419 | 0.66047 | 3.551107 | false | false | false | false |
BambooHR/ALTextInputBar
|
ALTextInputBar/ALTextInputBar.swift
|
1
|
9034
|
//
// ALTextInputBar.swift
// ALTextInputBar
//
// Created by Alex Littlejohn on 2015/04/24.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
public class ALTextInputBar: ALKeyboardObservingInputBar, ALTextViewDelegate {
public weak var delegate: ALTextInputBarDelegate?
/// Used for the intrinsic content size for autolayout
public var defaultHeight: CGFloat = 44
/// If true the right button will always be visible else it will only show when there is text in the text view
public var alwaysShowRightButton = false
/// The horizontal padding between the view edges and its subviews
public var horizontalPadding: CGFloat = 0
/// The horizontal spacing between subviews
public var horizontalSpacing: CGFloat = 5
/// Convenience set and retrieve the text view text
public var text: String! {
get {
return textView.text
}
set(newValue) {
textView.text = newValue
textView.delegate?.textViewDidChange?(textView)
}
}
/**
This view will be displayed on the left of the text view.
If this view is nil nothing will be displayed, and the text view will fill the space
*/
public var leftView: UIView? {
willSet(newValue) {
if newValue == nil {
if let view = leftView {
view.removeFromSuperview()
}
}
}
didSet {
if let view = leftView {
addSubview(view)
}
}
}
/**
This view will be displayed on the right of the text view.
If this view is nil nothing will be displayed, and the text view will fill the space
If alwaysShowRightButton is false this view will animate in from the right when the text view has content
*/
public var rightView: UIView? {
willSet(newValue) {
if newValue == nil {
if let view = rightView {
view.removeFromSuperview()
}
}
}
didSet {
if let view = rightView {
addSubview(view)
}
}
}
/// The text view instance
public let textView: ALTextView = {
let _textView = ALTextView()
_textView.textContainerInset = UIEdgeInsetsMake(1, 0, 1, 0);
_textView.textContainer.lineFragmentPadding = 0
_textView.maxNumberOfLines = defaultNumberOfLines()
_textView.placeholder = "Type here"
_textView.placeholderColor = UIColor.lightGrayColor()
_textView.font = UIFont.systemFontOfSize(14)
_textView.textColor = UIColor.darkGrayColor()
_textView.backgroundColor = UIColor.clearColor()
// This changes the caret color
_textView.tintColor = UIColor.lightGrayColor()
return _textView
}()
private var showRightButton = false
private var showLeftButton = false
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
addSubview(textView)
textView.textViewDelegate = self
backgroundColor = UIColor.groupTableViewBackgroundColor()
}
// MARK: - View positioning and layout -
override public func intrinsicContentSize() -> CGSize {
return CGSizeMake(UIViewNoIntrinsicMetric, defaultHeight)
}
override public func layoutSubviews() {
super.layoutSubviews()
let size = frame.size
let height = floor(size.height)
var leftViewSize = CGSizeZero
var rightViewSize = CGSizeZero
if let view = leftView {
leftViewSize = view.bounds.size
let leftViewX: CGFloat = horizontalPadding
let leftViewVerticalPadding = (defaultHeight - leftViewSize.height) / 2
let leftViewY: CGFloat = height - (leftViewSize.height + leftViewVerticalPadding)
view.frame = CGRectMake(leftViewX, leftViewY, leftViewSize.width, leftViewSize.height)
}
if let view = rightView {
rightViewSize = view.bounds.size
let rightViewVerticalPadding = (defaultHeight - rightViewSize.height) / 2
var rightViewX = size.width
let rightViewY = height - (rightViewSize.height + rightViewVerticalPadding)
if showRightButton || alwaysShowRightButton {
rightViewX -= (rightViewSize.width + horizontalPadding)
}
view.frame = CGRectMake(rightViewX, rightViewY, rightViewSize.width, rightViewSize.height)
}
let textViewPadding = (defaultHeight - textView.minimumHeight) / 2
var textViewX = horizontalPadding
let textViewY = textViewPadding
let textViewHeight = textView.expectedHeight
var textViewWidth = size.width - (horizontalPadding + horizontalPadding)
if leftViewSize.width > 0 {
textViewX += leftViewSize.width + horizontalSpacing
textViewWidth -= leftViewSize.width + horizontalSpacing
}
if (showRightButton || alwaysShowRightButton) && rightViewSize.width > 0 {
textViewWidth -= (horizontalSpacing + rightViewSize.width)
}
textView.frame = CGRectMake(textViewX, textViewY, textViewWidth, textViewHeight)
}
public func updateViews(animated: Bool) {
if animated {
// :discussion: Honestly not sure about the best way to calculated the ideal spring animation duration
// however these values seem to work for Slack
// possibly replace with facebook/pop but that opens another can of worms
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: .CurveEaseInOut, animations: {
self.setNeedsLayout()
self.layoutIfNeeded()
}, completion: nil)
} else {
setNeedsLayout()
layoutIfNeeded()
}
}
// MARK: - ALTextViewDelegate -
public final func textViewHeightChanged(textView: ALTextView, newHeight: CGFloat) {
let padding = defaultHeight - textView.minimumHeight
let height = padding + newHeight
if UIDevice.floatVersion() < 8.0 {
frame.size.height = height
setNeedsLayout()
layoutIfNeeded()
}
for c in constraints() {
var constraint = c as! NSLayoutConstraint
if constraint.firstAttribute == NSLayoutAttribute.Height && constraint.firstItem as! NSObject == self {
constraint.constant = height < defaultHeight ? defaultHeight : height
}
}
}
public final func textViewDidChange(textView: UITextView) {
var shouldShowButton = textView.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0
if showRightButton != shouldShowButton && !alwaysShowRightButton {
showRightButton = shouldShowButton
updateViews(true)
}
if let d = delegate, m = d.textViewDidChange {
m(self.textView)
}
}
public func textViewShouldBeginEditing(textView: UITextView) -> Bool {
var beginEditing: Bool = true
if let d = delegate, m = d.textViewShouldEndEditing {
beginEditing = m(self.textView)
}
return beginEditing
}
public func textViewShouldEndEditing(textView: UITextView) -> Bool {
var endEditing = true
if let d = delegate, m = d.textViewShouldEndEditing {
endEditing = m(self.textView)
}
return endEditing
}
public func textViewDidBeginEditing(textView: UITextView) {
if let d = delegate, m = d.textViewDidBeginEditing {
m(self.textView)
}
}
public func textViewDidEndEditing(textView: UITextView) {
if let d = delegate, m = d.textViewDidEndEditing {
m(self.textView)
}
}
public func textViewDidChangeSelection(textView: UITextView) {
if let d = delegate, m = d.textViewDidChangeSelection {
m(self.textView)
}
}
public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
var shouldChange = true
if text == "\n" {
if let d = delegate, m = d.textViewShouldReturn {
shouldChange = m(self.textView)
}
}
return shouldChange
}
}
|
mit
|
3456891bbd91cb2ad6656c82f811bc9d
| 31.970803 | 150 | 0.595971 | 5.653317 | false | false | false | false |
Paladinfeng/Weibo-Swift
|
Weibo/Weibo/Classes/View/Discover/View/PFSearchTitleView.swift
|
1
|
2285
|
//
// PFSearchTitleView.swift
// Weibo
//
// Created by Paladinfeng on 15/12/5.
// Copyright © 2015年 Paladinfeng. All rights reserved.
//
import UIKit
class PFSearchTitleView: UIView,UITextFieldDelegate {
@IBOutlet weak var searchField: UITextField!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var rightCons: NSLayoutConstraint!
class func searchView()->PFSearchTitleView {
return NSBundle.mainBundle().loadNibNamed("PFSearchTitleView", owner: nil, options: nil).last as! PFSearchTitleView
}
@IBAction func didClickCancel(sender: UIButton) {
searchField.resignFirstResponder()
searchField.text = ""
self.rightCons.constant = 0
UIView.animateWithDuration(0.25) { () -> Void in
self.searchField.layoutIfNeeded()
}
}
override func awakeFromNib() {
self.searchField.delegate = self
self.searchField.placeholder = "大家都在搜: 主要是气质"
// self.searchField.background = UIImage(named: "searchbar_textfield_background")
// //leftView 添加方式1
// let leftView = UIView(frame: CGRect(x: 0, y: 0, width: frame.height, height: frame.height))
//
// let imgView = UIImageView(image: (UIImage(named: "searchbar_textfield_search_icon")))
//
// imgView.sizeToFit()
//
// imgView.center = leftView.center
//
// leftView.addSubview(imgView)
//方式2
let leftView = UIImageView(image: (UIImage(named: "searchbar_textfield_search_icon")))
leftView.frame = CGRectMake(0, 0, frame.height, frame.height)
leftView.contentMode = .Center
// leftView.backgroundColor = UIColor.redColor()
self.searchField.leftView = leftView
self.searchField.leftViewMode = .Always
}
func textFieldDidBeginEditing(textField: UITextField) {
self.rightCons.constant = self.cancelBtn.frame.width + 8
UIView.animateWithDuration(0.25) { () -> Void in
self.searchField.layoutIfNeeded()
}
}
}
|
mit
|
a1e487df9a3ed84ee71774e5ecc12726
| 26.439024 | 123 | 0.591111 | 4.677755 | false | false | false | false |
rdavid8/iosweek3
|
PicFeed/PicFeed/Filters.swift
|
1
|
2129
|
//
// Filters.swift
// PicFeed
//
// Created by Ryan David on 2/16/16.
// Copyright © 2016 Ryan David. All rights reserved.
//
import UIKit
typealias FiltersCompletion = (theImage: UIImage?) -> ()
class Filters
{
private class func filter(name: String, image: UIImage, completion: FiltersCompletion)
{
NSOperationQueue().addOperationWithBlock { () -> Void in
guard let filter = CIFilter(name: name) else { fatalError("Check filter spelling") } //CIFilter will returnoptional. name is parameter for filter
filter.setValue(CIImage(image: image), forKey: kCIInputImageKey) //setting an input image for that image
//GPU CONTEXT
let options = [kCIContextWorkingColorSpace : NSNull()]
let EAGContext = EAGLContext(API: .OpenGLES2)
let GPUContext = CIContext(EAGLContext: EAGContext, options: options)
//Get the final image. output image of the filter
guard let outputImage = filter.outputImage else { fatalError("Y no image?") }
let CGImage = GPUContext.createCGImage(outputImage, fromRect: outputImage.extent)
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
completion(theImage: UIImage(CGImage: CGImage))
})
}
}
class func bw(image: UIImage, completion: FiltersCompletion)
{
self.filter("CIPhotoEffectMono", image: image, completion: completion)
}
class func st(image: UIImage, completion: FiltersCompletion)
{
self.filter("CISepiaTone", image: image, completion: completion)
}
class func mc(image: UIImage, completion: FiltersCompletion)
{
self.filter("CIColorMonochrome", image: image, completion: completion)
}
class func px(image: UIImage, completion: FiltersCompletion)
{
self.filter("CIPixellate", image: image, completion: completion)
}
class func ls(image: UIImage, completion: FiltersCompletion)
{
self.filter("CILineScreen", image: image, completion: completion)
}
}
|
mit
|
8d1433756e7b4c899d0cc68d8da7d009
| 36.333333 | 157 | 0.647556 | 4.697572 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.