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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bradhilton/SwiftTable | SwiftTable/Table/MultiTable/MultiTable+Interface.swift | 1 | 13352 | //
// MultiTable+Interface.swift
// SwiftTable
//
// Created by Bradley Hilton on 2/15/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
extension MultiTable {
public var style: UITableView.Style {
return _parent.style
}
public var rowHeight: CGFloat {
get {
return _parent.rowHeight
}
set {
parent?.rowHeight = newValue
}
}
public var sectionHeaderHeight: CGFloat {
get {
return _parent.sectionHeaderHeight
}
set {
parent?.sectionHeaderHeight = newValue
}
}
public var sectionFooterHeight: CGFloat {
get {
return _parent.sectionFooterHeight
}
set {
parent?.sectionFooterHeight = newValue
}
}
public var estimatedRowHeight: CGFloat {
get {
return _parent.estimatedRowHeight
}
set {
parent?.estimatedRowHeight = newValue
}
}
public var estimatedSectionHeaderHeight: CGFloat {
get {
return _parent.estimatedSectionHeaderHeight
}
set {
parent?.estimatedSectionHeaderHeight = newValue
}
}
public var estimatedSectionFooterHeight: CGFloat {
get {
return _parent.estimatedSectionFooterHeight
}
set {
parent?.estimatedSectionFooterHeight = newValue
}
}
public var separatorInset: UIEdgeInsets {
get {
return _parent.separatorInset
}
set {
parent?.separatorInset = newValue
}
}
public var backgroundView: UIView? {
get {
return parent?.backgroundView
}
set {
parent?.backgroundView = newValue
}
}
public func reloadData() {
parent?.reloadData()
}
public func reloadSectionIndexTitles() {
parent?.reloadSectionIndexTitles()
}
public func numberOfSectionsInTable(_ table: TableSource) -> Int {
return table.numberOfSections
}
public func numberOfRowsInSection(_ section: Int, inTable table: TableSource) -> Int {
return table.numberOfRowsInSection(section)
}
public func rectForSection(_ section: Int, inTable table: TableSource) -> CGRect {
return _parent.rectForSection(sectionFromTable(table, section: section), inTable: self)
}
public func rectForHeaderInSection(_ section: Int, inTable table: TableSource) -> CGRect {
return _parent.rectForHeaderInSection(sectionFromTable(table, section: section), inTable: self)
}
public func rectForFooterInSection(_ section: Int, inTable table: TableSource) -> CGRect {
return _parent.rectForFooterInSection(sectionFromTable(table, section: section), inTable: self)
}
public func rectForRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource) -> CGRect {
return _parent.rectForRowAtIndexPath(indexPathFromTable(table, indexPath: indexPath), inTable: self)
}
public func indexPathForRowAtPoint(_ point: CGPoint, inTable table: TableSource) -> IndexPath? {
return optionalIndexPathForTable(table, indexPath: parent?.indexPathForRowAtPoint(point, inTable: self))
}
public func indexPathForCell(_ cell: UITableViewCell, inTable table: TableSource) -> IndexPath? {
return optionalIndexPathForTable(table, indexPath: parent?.indexPathForCell(cell, inTable: self))
}
public func indexPathsForRowsInRect(_ rect: CGRect, inTable table: TableSource) -> [IndexPath]? {
return indexPathsForTable(table, indexPaths: parent?.indexPathsForRowsInRect(rect, inTable: self))
}
public func cellForRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource) -> UITableViewCell? {
return parent?.cellForRowAtIndexPath(indexPathFromTable(table, indexPath: indexPath), inTable: self)
}
public var visibleCells: [UITableViewCell] {
return _parent.visibleCells
}
public func indexPathsForVisibleRowsInTable(_ table: TableSource) -> [IndexPath]? {
return indexPathsForTable(table, indexPaths: parent?.indexPathsForVisibleRowsInTable(self))
}
public func headerViewForSection(_ section: Int, inTable table: TableSource) -> UITableViewHeaderFooterView? {
return parent?.headerViewForSection(sectionFromTable(table, section: section), inTable: self)
}
public func footerViewForSection(_ section: Int, inTable table: TableSource) -> UITableViewHeaderFooterView? {
return parent?.footerViewForSection(sectionFromTable(table, section: section), inTable: self)
}
public func scrollToRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource, atScrollPosition scrollPosition: UITableView.ScrollPosition, animated: Bool) {
parent?.scrollToRowAtIndexPath(indexPathFromTable(table, indexPath: indexPath), inTable: self, atScrollPosition: scrollPosition, animated: animated)
}
public func scrollToNearestSelectedRowAtScrollPosition(_ scrollPosition: UITableView.ScrollPosition, animated: Bool) {
parent?.scrollToNearestSelectedRowAtScrollPosition(scrollPosition, animated: animated)
}
public func beginUpdates() {
parent?.beginUpdates()
}
public func endUpdates() {
parent?.endUpdates()
}
public func insertSections(_ sections: IndexSet, inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
parent?.insertSections(indexSetFromTable(table, indexSet: sections), inTable: self, withRowAnimation: animation)
}
public func deleteSections(_ sections: IndexSet, inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
parent?.deleteSections(indexSetFromTable(table, indexSet: sections), inTable: self, withRowAnimation: animation)
}
public func reloadSections(_ sections: IndexSet, inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
parent?.reloadSections(indexSetFromTable(table, indexSet: sections), inTable: self, withRowAnimation: animation)
}
public func moveSection(_ section: Int, toSection newSection: Int, inTable table: TableSource) {
parent?.moveSection(sectionFromTable(table, section: section), toSection: sectionFromTable(table, section: newSection), inTable: self)
}
public func insertRowsAtIndexPaths(_ indexPaths: [IndexPath], inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
parent?.insertRowsAtIndexPaths(indexPathsFromTable(table, indexPaths: indexPaths), inTable: self, withRowAnimation: animation)
}
public func deleteRowsAtIndexPaths(_ indexPaths: [IndexPath], inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
parent?.deleteRowsAtIndexPaths(indexPathsFromTable(table, indexPaths: indexPaths), inTable: self, withRowAnimation: animation)
}
public func reloadRowsAtIndexPaths(_ indexPaths: [IndexPath], inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
parent?.reloadRowsAtIndexPaths(indexPathsFromTable(table, indexPaths: indexPaths), inTable: self, withRowAnimation: animation)
}
public func moveRowAtIndexPath(_ indexPath: IndexPath, toIndexPath newIndexPath: IndexPath, inTable table: TableSource) {
parent?.moveRowAtIndexPath(indexPathFromTable(table, indexPath: indexPath), toIndexPath: indexPathFromTable(table, indexPath: newIndexPath), inTable: self)
}
public var editing: Bool {
get {
return _parent.editing
}
set {
parent?.editing = newValue
}
}
public func setEditing(_ editing: Bool, animated: Bool) {
parent?.setEditing(editing, animated: animated)
}
public var allowsSelection: Bool {
get {
return _parent.allowsSelection
}
set {
parent?.allowsSelection = newValue
}
}
public var allowsSelectionDuringEditing: Bool {
get {
return _parent.allowsSelectionDuringEditing
}
set {
parent?.allowsSelectionDuringEditing = newValue
}
}
public var allowsMultipleSelection: Bool {
get {
return _parent.allowsMultipleSelection
}
set {
parent?.allowsMultipleSelection = newValue
}
}
public var allowsMultipleSelectionDuringEditing: Bool {
get {
return _parent.allowsMultipleSelectionDuringEditing
}
set {
parent?.allowsMultipleSelectionDuringEditing = newValue
}
}
public func indexPathForSelectedRowInTable(_ table: TableSource) -> IndexPath? {
return optionalIndexPathForTable(table, indexPath: parent?.indexPathForSelectedRowInTable(self))
}
public func indexPathsForSelectedRowsInTable(_ table: TableSource) -> [IndexPath]? {
return indexPathsForTable(table, indexPaths: parent?.indexPathsForSelectedRowsInTable(self))
}
public func selectRowAtIndexPath(_ indexPath: IndexPath?, inTable table: TableSource, animated: Bool, scrollPosition: UITableView.ScrollPosition) {
let mappedIndexPath: IndexPath? = indexPath != nil ? indexPathFromTable(table, indexPath: indexPath!) : nil
parent?.selectRowAtIndexPath(mappedIndexPath, inTable: self, animated: animated, scrollPosition: scrollPosition)
}
public func deselectRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource, animated: Bool) {
parent?.deselectRowAtIndexPath(indexPathFromTable(table, indexPath: indexPath), inTable: self, animated: animated)
}
public var sectionIndexMinimumDisplayRowCount: Int {
get {
return _parent.sectionIndexMinimumDisplayRowCount
}
set {
parent?.sectionIndexMinimumDisplayRowCount = newValue
}
}
public var sectionIndexColor: UIColor? {
get {
return parent?.sectionIndexColor
}
set {
parent?.sectionIndexColor = newValue
}
}
public var sectionIndexBackgroundColor: UIColor? {
get {
return parent?.sectionIndexBackgroundColor
}
set {
parent?.sectionIndexBackgroundColor = newValue
}
}
public var sectionIndexTrackingBackgroundColor: UIColor? {
get {
return parent?.sectionIndexTrackingBackgroundColor
}
set {
parent?.sectionIndexTrackingBackgroundColor = newValue
}
}
public var separatorStyle: UITableViewCell.SeparatorStyle {
get {
return _parent.separatorStyle
}
set {
parent?.separatorStyle = newValue
}
}
public var separatorColor: UIColor? {
get {
return parent?.separatorColor
}
set {
parent?.separatorColor = newValue
}
}
public var separatorEffect: UIVisualEffect? {
get {
return parent?.separatorEffect
}
set {
parent?.separatorEffect = newValue
}
}
public var tableHeaderView: UIView? {
get {
return parent?.tableHeaderView
}
set {
parent?.tableHeaderView = newValue
}
}
public var tableFooterView: UIView? {
get {
return parent?.tableFooterView
}
set {
parent?.tableFooterView = newValue
}
}
public func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell? {
return parent?.dequeueReusableCellWithIdentifier(identifier)
}
public func dequeueReusableCellWithIdentifier(_ identifier: String, forIndexPath indexPath: IndexPath, inTable table: TableSource) -> UITableViewCell {
return _parent.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPathFromTable(table, indexPath: indexPath), inTable: self)
}
public func dequeueReusableHeaderFooterViewWithIdentifier(_ identifier: String) -> UITableViewHeaderFooterView? {
return parent?.dequeueReusableHeaderFooterViewWithIdentifier(identifier)
}
public func registerNib(_ nib: UINib?, forCellReuseIdentifier identifier: String) {
parent?.registerNib(nib, forCellReuseIdentifier: identifier)
}
public func registerClass(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
parent?.registerClass(cellClass, forCellReuseIdentifier: identifier)
}
public func registerNib(_ nib: UINib?, forHeaderFooterViewReuseIdentifier identifier: String) {
parent?.registerNib(nib, forHeaderFooterViewReuseIdentifier: identifier)
}
public func registerClass(_ aClass: AnyClass?, forHeaderFooterViewReuseIdentifier identifier: String) {
parent?.registerClass(aClass, forHeaderFooterViewReuseIdentifier: identifier)
}
}
| mit | c8103037e29d55353d8a736b00fe63f5 | 34.507979 | 169 | 0.663171 | 5.912755 | false | false | false | false |
leopardpan/SwiftGen | SwiftGen.playground/Pages/ColorEnums-Demo.xcplaygroundpage/Contents.swift | 1 | 1648 | import UIKit
//: #### SwiftGenStoryboardEnumBuilder Usage Example
let enumBuilder = SwiftGenColorEnumBuilder()
if let colorsFile = NSBundle.mainBundle().pathForResource("colors", ofType: "txt") {
try enumBuilder.parseTextFile(colorsFile)
}
print(enumBuilder.build())
/* Note that you can ask the builder to also generate a string initializer
that takes a Hex string: "convenience init(hexString: String)" */
// print(enumBuilder.build(generateStringInit: true))
//: #### Code Generated by the Builder
// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
import UIKit
extension UIColor {
convenience init(rgbaValue: UInt32) {
let red = CGFloat((rgbaValue >> 24) & 0xff) / 255.0
let green = CGFloat((rgbaValue >> 16) & 0xff) / 255.0
let blue = CGFloat((rgbaValue >> 8) & 0xff) / 255.0
let alpha = CGFloat((rgbaValue ) & 0xff) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
extension UIColor {
enum Name : UInt32 {
case Translucent = 0xffffffcc
case ArticleBody = 0x339666ff
case Cyan = 0xff66ccff
case ArticleTitle = 0x33fe66ff
}
convenience init(named name: Name) {
self.init(rgbaValue: name.rawValue)
}
}
//: #### Usage Example
UIColor(named: .ArticleTitle)
UIColor(named: .ArticleBody)
UIColor(named: .ArticleBody)
UIColor(named: .Translucent)
/* Only possible if you used `enumBuilder.build(generateStringInit: true)` to generate the enum */
//let orange = UIColor(hexString: "#ffcc88")
let lightGreen = UIColor(rgbaValue: 0x00ff88ff)
| mit | b66d189feb82ec4477d1df9aac99b685 | 25.983607 | 98 | 0.676792 | 3.810185 | false | false | false | false |
Imgur/IMGTreeTableViewController | IMGTreeTableViewDemo/IMGSampleTreeConstructor.swift | 1 | 2331 | //
// IMGSampleTreeConstructor.swift
// SwiftTreeTable
//
// Created by Geoff MacDonald on 3/26/15.
// Copyright (c) 2015 Geoff MacDonald. All rights reserved.
//
import UIKit
import IMGTreeTableView
class IMGCommentNode: IMGTreeNode, NSCopying {
var comment: String?
override var description : String {
return "Node: \(comment!)"
}
override func copyWithZone(zone: NSZone) -> AnyObject {
var copy = super.copyWithZone(zone) as! IMGCommentNode
copy.comment = comment
return copy
}
}
class IMGCommentModel : NSObject {
var replies: [IMGCommentModel]?
var comment: String?
}
class IMGSampleTreeConstructor: NSObject, IMGTreeConstructorDelegate {
let sampleDepth = 8
let sampleSiblings = 3
func sampleCommentTree() -> IMGTree {
var comments: [IMGCommentModel] = []
for i in 0..<sampleSiblings {
//make up some root level comments
let comment = IMGCommentModel()
comment.comment = "Root: \(i)"
comment.replies = sampleComments(0)
comments.append(comment)
}
let tree = IMGTree.tree(fromRootArray: comments, withConstructerDelegate: self)
return tree
}
func sampleComments(depth: Int) -> [IMGCommentModel]? {
//make up some comments for some depth
var comments: [IMGCommentModel] = []
for i in 0..<sampleSiblings {
let comment = IMGCommentModel()
comment.comment = "\(depth) \(i+1)"
if depth < sampleDepth {
//recursive up to a point
comment.replies = sampleComments(depth+1)
}
comments.append(comment)
}
return comments
}
//MARK: IMGTreeConstructorDelegate
func classForNode() -> IMGTreeNode.Type {
return IMGCommentNode.self
}
func childrenForNodeObject(object: AnyObject) -> [AnyObject]? {
let commentObject = object as! IMGCommentModel
return commentObject.replies
}
func configureNode(node: IMGTreeNode, modelObject: AnyObject) {
let commentNode = node as! IMGCommentNode
let model = modelObject as! IMGCommentModel
commentNode.comment = model.comment
}
}
| mit | 5adf045d62c8bec1cfc8e7b9c5da18f4 | 27.084337 | 87 | 0.610897 | 4.357009 | false | false | false | false |
charleshkang/Weatherr | C4QWeather/C4QWeather/WeatherViewController.swift | 1 | 2486 | //
// WeatherViewController
// C4QWeather
//
// Created by Charles Kang on 11/21/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import UIKit
class WeatherViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet weak var convertTemperatureButton: UIButton!
@IBOutlet weak var tableView: UITableView!
// MARK: Private Properties
fileprivate let weatherRequester = WeatherRequester()
fileprivate var allWeather = [Weather]()
fileprivate var beenConverted = false
// MARK: Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
refreshWeather()
}
// MARK: Action Methods
fileprivate func refreshWeather() {
weatherRequester.getWeather { weather in
switch weather {
case.success(let weatherObjects):
main {
self.allWeather = weatherObjects
self.tableView.reloadData()
}
case.failure(let error):
let alertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
}
}
}
@IBAction func convertTemperatureAction(_ sender: AnyObject) {
if !beenConverted {
beenConverted = true
convertTemperatureButton.setTitle("Convert to Farenheit", for: UIControlState())
} else {
beenConverted = false
convertTemperatureButton.setTitle("Convert to Celsius", for: UIControlState())
}
tableView.reloadData()
}
}
//MARK: UITableViewDataSource Functions
extension WeatherViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allWeather.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constant.weatherCellIdentifier, for: indexPath) as! WeatherTableViewCell
let weather = allWeather[indexPath.row]
if !beenConverted {
cell.configureFahrenheit(With: weather)
} else {
cell.configureCelsius(With: weather)
}
return cell
}
}
| mit | 4f7a4c8f3f1f06b975d38e0781d4c3f8 | 30.455696 | 137 | 0.632193 | 5.413943 | false | false | false | false |
franklinsch/usagi | iOS/usagi-iOS/usagi-iOS/ScrollingTabAnimation.swift | 1 | 2551 | //
// ScrollingTabBarUtils.swift
// ScrollingTabBarUtils
//
// Created by Franklin Schrans on 24/12/2015.
// Copyright © 2015 Franklin Schrans. All rights reserved.
//
import UIKit
class ScrollingTabBarControllerDelegate: NSObject, UITabBarControllerDelegate {
func tabBarController(tabBarController: UITabBarController, animationControllerForTransitionFromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ScrollingTransitionAnimator(tabBarController: tabBarController, lastIndex: tabBarController.selectedIndex)
}
}
class ScrollingTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
weak var transitionContext: UIViewControllerContextTransitioning?
var tabBarController: UITabBarController!
var lastIndex = 0
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.4
}
init(tabBarController: UITabBarController, lastIndex: Int) {
self.tabBarController = tabBarController
self.lastIndex = lastIndex
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
let containerView = transitionContext.containerView()
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
containerView?.addSubview(toViewController!.view)
var viewWidth = CGRectGetWidth(toViewController!.view.bounds)
if tabBarController.selectedIndex < lastIndex {
viewWidth = -viewWidth
}
toViewController!.view.transform = CGAffineTransformMakeTranslation(viewWidth, 0)
UIView.animateWithDuration(self.transitionDuration((self.transitionContext)), delay: 0.0, usingSpringWithDamping: 1.2, initialSpringVelocity: 2.5, options: .TransitionNone, animations: {
toViewController!.view.transform = CGAffineTransformIdentity
fromViewController!.view.transform = CGAffineTransformMakeTranslation(-viewWidth, 0)
}, completion: { _ in
self.transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled())
fromViewController!.view.transform = CGAffineTransformIdentity
})
}
} | mit | d4f3e7f2544b1f71031e0ef360ce45fa | 44.553571 | 225 | 0.747059 | 7.005495 | false | false | false | false |
Verchen/Swift-Project | JinRong/JinRong/Classes/Authentication(认证)/View/ContactsCell.swift | 1 | 2109 | //
// ContactsCell.swift
// JinRong
//
// Created by 乔伟成 on 2017/7/18.
// Copyright © 2017年 乔伟成. All rights reserved.
//
import UIKit
class ContactsCell: UITableViewCell {
let name = UILabel()
let relation = UILabel()
let phoneNum = UILabel()
let update = UILabel()
var newModel : ContactsModel!
var model: ContactsModel {
get {
return self.newModel
}
set {
newModel = newValue
name.text = newModel.name
relation.text = newModel.relationId?.description
phoneNum.text = newModel.tel
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
setupUI()
}
func setupUI() -> Void {
name.sizeToFit()
name.frame = CGRect(x: 10, y: 10, width: name.frame.width, height: name.frame.height)
contentView.addSubview(name)
relation.textColor = UIColor.lightGray
relation.font = UIFont.systemFont(ofSize: 16)
relation.sizeToFit()
relation.frame = CGRect(x: name.frame.maxX + 5, y: name.frame.maxY - relation.frame.height, width: relation.frame.width, height: relation.frame.height)
contentView.addSubview(relation)
phoneNum.sizeToFit()
phoneNum.frame = CGRect(x: 10, y: name.frame.maxY + 10, width: phoneNum.frame.width, height: phoneNum.frame.height)
contentView.addSubview(phoneNum)
update.text = "修改"
update.frame = CGRect(x: UIScreen.main.bounds.width - 70, y: 0, width: 70, height: 70)
update.backgroundColor = UIColor.theme
update.textAlignment = .center
update.textColor = UIColor.white
contentView.addSubview(update)
}
}
| mit | e17f9352dadad5cd5155985b10e59e4e | 28.43662 | 159 | 0.605742 | 4.390756 | false | false | false | false |
kopto/KRActivityIndicatorView | KRActivityIndicatorView/KRActivityIndicatorAnimationBallTrianglePath.swift | 1 | 5545 | //
// KRActivityIndicatorAnimationBallTrianglePath.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// 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 Cocoa
class KRActivityIndicatorAnimationBallTrianglePath: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let circleSize = size.width / 5
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 2
let timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut)
// Animation
let animation = CAKeyframeAnimation(keyPath:"transform")
animation.keyTimes = [0, 0.33, 0.66, 1]
animation.timingFunctions = [timingFunction, timingFunction, timingFunction]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Top-center circle
let topCenterCircle = KRActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values:["{0,0}", "{hx,fy}", "{-hx,fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
topCenterCircle.frame = CGRect(x: x + size.width / 2 - circleSize / 2, y: y, width: circleSize, height: circleSize)
topCenterCircle.add(animation, forKey: "animation")
layer.addSublayer(topCenterCircle)
// Bottom-left circle
let bottomLeftCircle = KRActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{hx,-fy}", "{fx,0}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
bottomLeftCircle.frame = CGRect(x: x, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomLeftCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomLeftCircle)
// Bottom-right circle
let bottomRightCircle = KRActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{-fx,0}", "{-hx,-fy}", "{0,0}"], deltaX: deltaX, deltaY:deltaY)
bottomRightCircle.frame = CGRect(x: x + size.width - circleSize, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomRightCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomRightCircle)
}
func changeAnimation(_ animation: CAKeyframeAnimation, values rawValues: [String], deltaX: CGFloat, deltaY: CGFloat) {
let values = NSMutableArray(capacity: 5)
for rawValue in rawValues {
//let point = CGPointFromString(translateString(rawValue, deltaX: deltaX, deltaY: deltaY))
let point = NSPointFromString(translateString(rawValue, deltaX: deltaX, deltaY: deltaY))
values.add(NSValue(caTransform3D: CATransform3DMakeTranslation(point.x, point.y, 0)))
}
animation.values = values as [AnyObject]
}
func translateString(_ valueString: String, deltaX: CGFloat, deltaY: CGFloat) -> String {
let valueMutableString = NSMutableString(string: valueString)
let fullDeltaX = 2 * deltaX
let fullDeltaY = 2 * deltaY
var range = NSMakeRange(0, valueMutableString.length)
valueMutableString.replaceOccurrences(of: "hx", with: "\(deltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fx", with: "\(fullDeltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "hy", with: "\(deltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fy", with: "\(fullDeltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
return valueMutableString as String
}
}
| mit | f3fd5f782db2681ae1064413b80fc0b7 | 52.317308 | 144 | 0.694319 | 4.691201 | false | false | false | false |
imobilize/Molib | Molib/Classes/Utils/CommonClosures.swift | 1 | 362 | import Foundation
import UIKit
public typealias VoidCompletion = () -> Void
public typealias BoolCompletion = (_ success: Bool) -> Void
public typealias ErrorCompletion = (_ errorOptional: Error?) -> Void
public typealias VoidOptionalCompletion = (() -> Void)?
public typealias DataResponseCompletion = (_ dataOptional: Data?, _ errorOptional: Error?) -> Void
| apache-2.0 | 26ead22cd9534f7176f4f9d2ef16b595 | 39.222222 | 98 | 0.751381 | 4.891892 | false | false | false | false |
MA806P/SwiftDemo | SwiftTestDemo/SwiftTestDemo/AdvancedOperators.swift | 1 | 5544 | //
// AdvancedOperators.swift
// SwiftTestDemo
//
// Created by MA806P on 2018/9/15.
// Copyright © 2018年 myz. All rights reserved.
//
import Foundation
/*
Swift 中的算术运算符默认不会溢出。溢出被捕获后是作为错误进行处理的。
如果想使用溢出行为,请使用 Swift 的第二种算术运算符集,比如加号溢出操作符( &+ )。所有的溢出运算符都以 ( & ) 符开头。
Swift 允许你自定义中缀、前缀、后缀,和赋值运算符,来自定义优先级和关联值。
这些操作符可以像任意的预定义操作符一样在你的代码中使用,你甚至可以扩展已经存在的类型类支持你自定义的运算符。
按位取反运算符
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // 等于 11110000
let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits & lastSixBits // 等于 00111100
let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits // 等于 11111110
按位异或运算符 ,或者 按位互斥或运算符 将两个数的二进制数进行比较。
返回一个新值,当两个操作数对应的二进制数不同时,新值对应的二进制数置为 1 ,相同时置为 0 :
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits // 等于 00010001
按位偏移:
let shiftBits: UInt8 = 4 // 00000100 在二进制中
shiftBits << 1 // 00001000
shiftBits << 2 // 00010000
shiftBits << 5 // 10000000
shiftBits << 6 // 00000000
shiftBits >> 2 // 00000001
溢出运算符
如果你向一个整型的常量或者变量中插入一个它容纳不了的数值,Swift 默认会报错,而不会允许生成一个无效的数。
Int16 整型可以容纳从 -32768 到 32767 之间的有符号整型值。当你试图往一个 Int16 类型的常量或者变量里设置一个超出这个范围的值时,就会导致错误:
var potentialOverflow = Int16.max
// potentialOverflow 等于 32767,是 Int16 能容纳的最大值
potentialOverflow += 1
// 这行代码会导致错误
当你特别期望在出现溢出情况时,能够截取有效的二进制数,你可以选择这个操作而不是抛出一个错误。
Swift 为整型计算的溢出操作提供了三个算数 溢出运算符 可供选择。这几个运算符都是以 (&)开头:
溢出加法运算符 (&+)
溢出减法运算符 (&-)
溢出乘法运算符 (&*)
var unsignedOverflow = UInt8.max
// unsignedOverflow 等于 255, 是 UInt8 能容纳的最大值
unsignedOverflow = unsignedOverflow &+ 1
// unsignedOverflow 现在等于 0
var unsignedOverflow = UInt8.min
// unsignedOverflow 等于 0, 是 UInt8 能容纳的最小值
unsignedOverflow = unsignedOverflow &- 1
// unsignedOverflow 现在等于 255
var signedOverflow = Int8.min
// signedOverflow 等于 -128, Int8 能容纳的最小值
signedOverflow = signedOverflow &- 1
// signedOverflow 现在等于 127
优先级
2 + 3 % 4 * 5
// 这个表达式等于 17
2 + ((3 % 4) * 5) = 2 + (3 * 5) = 17
运算符方法
类和结构体可以提供现有运算符的自有实现。也可以称为 重载 运算符。
struct Vector2D {
var x = 0.0, y = 0.0
}
extension Vector2D {
static func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
}
前缀和后缀运算符 -b
extension Vector2D {
static prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
}
复合赋值运算符 +=
extension Vector2D {
static func += (left: inout Vector2D, right: Vector2D) {
left = left + right
}
}
等价运算符 == !=
extension Vector2D: Equatable {
static func == (left: Vector2D, right: Vector2D) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
}
自定义运算符
使用 operator 关键字在全局级别声明新运算符,并使用 prefix,infix 和 postfix 修饰符标记:
extension Vector2D {
static prefix func +++ (vector: inout Vector2D) -> Vector2D {
vector += vector
return vector
}
}
var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
let afterDoubling = +++toBeDoubled
// toBeDoubled 的值为 (2.0, 8.0)
// afterDoubling 的值也为 (2.0, 8.0)
自定义中缀运算符均属于优先级组。优先级组指定运算符相对于其它中缀运算符的优先级
未明确放入优先级组的自定义中缀运算符将被放入默认优先级组,其优先级高于三元条件运算符。
以下示例定义了一个名为 +- 的新自定义中缀运算符,它属于优先级组 AdditionPrecedence:
infix operator +-: AdditionPrecedence
extension Vector2D {
static func +- (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
}
let firstVector = Vector2D(x: 1.0, y: 2.0)
let secondVector = Vector2D(x: 3.0, y: 4.0)
let plusMinusVector = firstVector +- secondVector
// plusMinusVector 是一个 Vector2D 实例,其值为 (4.0, -2.0)
该运算符将两个向量的 x 值相加,并从第一个向量中减去第二个向量的 y 值。
因为它本质上是一个「加法」运算符,所以它被添加到了与加法中缀运算符(例如 + 和 - )相同的优先级组。
*/
| apache-2.0 | f18829288c9f5df7efbc1e84683b09c3 | 21.815476 | 85 | 0.690321 | 2.570758 | false | false | false | false |
russbishop/swift | stdlib/public/SDK/Dispatch/Time.swift | 1 | 3406 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// dispatch/time.h
// DISPATCH_TIME_NOW: ok
// DISPATCH_TIME_FOREVER: ok
public struct DispatchTime {
public let rawValue: dispatch_time_t
public static func now() -> DispatchTime {
let t = __dispatch_time(0, 0)
return DispatchTime(rawValue: t)
}
public static let distantFuture = DispatchTime(rawValue: ~0)
private init(rawValue: dispatch_time_t) {
self.rawValue = rawValue
}
}
public struct DispatchWallTime {
public let rawValue: dispatch_time_t
public static func now() -> DispatchWallTime {
return DispatchWallTime(rawValue: __dispatch_walltime(nil, 0))
}
public static let distantFuture = DispatchWallTime(rawValue: ~0)
private init(rawValue: dispatch_time_t) {
self.rawValue = rawValue
}
public init(time: timespec) {
var t = time
self.rawValue = __dispatch_walltime(&t, 0)
}
}
@available(*, deprecated, renamed: "DispatchWallTime")
public typealias DispatchWalltime = DispatchWallTime
public enum DispatchTimeInterval {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
internal var rawValue: UInt64 {
switch self {
case .seconds(let s): return UInt64(s) * NSEC_PER_SEC
case .milliseconds(let ms): return UInt64(ms) * NSEC_PER_MSEC
case .microseconds(let us): return UInt64(us) * NSEC_PER_USEC
case .nanoseconds(let ns): return UInt64(ns)
}
}
}
public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime {
let t = __dispatch_time(time.rawValue, Int64(interval.rawValue))
return DispatchTime(rawValue: t)
}
public func -(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime {
let t = __dispatch_time(time.rawValue, -Int64(interval.rawValue))
return DispatchTime(rawValue: t)
}
public func +(time: DispatchTime, seconds: Double) -> DispatchTime {
let t = __dispatch_time(time.rawValue, Int64(seconds * Double(NSEC_PER_SEC)))
return DispatchTime(rawValue: t)
}
public func -(time: DispatchTime, seconds: Double) -> DispatchTime {
let t = __dispatch_time(time.rawValue, Int64(-seconds * Double(NSEC_PER_SEC)))
return DispatchTime(rawValue: t)
}
public func +(time: DispatchWallTime, interval: DispatchTimeInterval) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, Int64(interval.rawValue))
return DispatchWallTime(rawValue: t)
}
public func -(time: DispatchWallTime, interval: DispatchTimeInterval) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, -Int64(interval.rawValue))
return DispatchWallTime(rawValue: t)
}
public func +(time: DispatchWallTime, seconds: Double) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, Int64(seconds * Double(NSEC_PER_SEC)))
return DispatchWallTime(rawValue: t)
}
public func -(time: DispatchWallTime, seconds: Double) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, Int64(-seconds * Double(NSEC_PER_SEC)))
return DispatchWallTime(rawValue: t)
}
| apache-2.0 | 5c6ed9d311202140b067f395eeeddd4d | 30.537037 | 91 | 0.702877 | 3.792873 | false | false | false | false |
harshalrj25/AnimatableReload | AnimatableReload/Classes/AnimatableReload.swift | 1 | 3067 | //
// AnimatableReload.swift
// Pods
//
// Created by iOSDev1 on 18/04/17.
//
//
import Foundation
public class AnimatableReload{
public class func reload(tableView:UITableView,animationDirection:String) {
tableView.reloadData()
tableView.layoutIfNeeded()
let cells = tableView.visibleCells
var index = 0
let tableHeight: CGFloat = tableView.bounds.size.height
for i in cells {
let cell: UITableViewCell = i as UITableViewCell
switch animationDirection {
case "up":
cell.transform = CGAffineTransform(translationX: 0, y: -tableHeight)
break
case "down":
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
break
case "left":
cell.transform = CGAffineTransform(translationX: tableHeight, y: 0)
break
case "right":
cell.transform = CGAffineTransform(translationX: -tableHeight, y: 0)
break
default:
cell.transform = CGAffineTransform(translationX: tableHeight, y: 0)
break
}
UIView.animate(withDuration: 1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseIn, animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0);
}, completion: nil)
index += 1
}
}
public class func reload(collectionView:UICollectionView,animationDirection:String) {
collectionView.reloadData()
collectionView.layoutIfNeeded()
let cells = collectionView.visibleCells
var index = 0
let tableHeight: CGFloat = collectionView.bounds.size.height
for i in cells {
let cell: UICollectionViewCell = i as UICollectionViewCell
switch animationDirection {
case "up":
cell.transform = CGAffineTransform(translationX: 0, y: -tableHeight)
break
case "down":
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
break
case "left":
cell.transform = CGAffineTransform(translationX: tableHeight, y: 0)
break
case "right":
cell.transform = CGAffineTransform(translationX: -tableHeight, y: 0)
break
default:
cell.transform = CGAffineTransform(translationX: tableHeight, y: 0)
break
}
UIView.animate(withDuration: 1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseIn, animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0);
}, completion: nil)
index += 1
}
}
}
| mit | 1bcca8a96a63a7d7b82cebaa114e97dd | 37.822785 | 170 | 0.556896 | 5.536101 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-security | Sample/BMSSecuritySample/BMSSecuritySample/AppDelegate.swift | 1 | 4135 | //
// AppDelegate.swift
// GoogleMCA
//
// Created by Ilan Klein on 15/02/2016.
// Copyright © 2016 ibm. All rights reserved.
//
import UIKit
import BMSCore
import BMSSecurity
///In order for the app to work you need to do the following things:
///1. In this file : Enter your Bluemix's app data (Url, GUID and region) and your app's protected resource's path
///2. In this file : Enter the protected Resource's realm
///3. In this file (line 37) : Enter challenge's answer recognized by your backend app
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private let backendURL = "{ENTER YOUR BACKANDURL}"
private let backendGUID = "{ENTER YOUR GUID}"
internal static let customResourceURL = "{ENTER THE PATH TO YOUR PROTECTED RESOURCE (e.g. /protectedResource)" // any protected resource
private static let customRealm = "{PROTECTED RESOURCE'S REALM}" // auth realm
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
BMSClient.sharedInstance.initializeWithBluemixAppRoute(backendURL, bluemixAppGUID: backendGUID, bluemixRegion: "your region, choose from BMSClient.REGION_XXX or add your own")
//Auth delegate for handling custom challenge
class MyAuthDelegate : AuthenticationDelegate {
func onAuthenticationChallengeReceived(authContext: AuthenticationContext, challenge: AnyObject){
print("onAuthenticationChallengeReceived")
let answer = "{Your challenge answer. Should be of type [String:AnyObject]?}"
authContext.submitAuthenticationChallengeAnswer(answer)
}
func onAuthenticationSuccess(info: AnyObject?) {
print("onAuthenticationSuccess")
}
func onAuthenticationFailure(info: AnyObject?){
print("onAuthenticationFailure")
}
}
let delegate = MyAuthDelegate()
let mcaAuthManager = MCAAuthorizationManager.sharedInstance
BMSClient.sharedInstance.authorizationManager = MCAAuthorizationManager.sharedInstance
do {
try mcaAuthManager.registerAuthenticationDelegate(delegate, realm: AppDelegate.customRealm)
} catch {
print("error with register: \(error)")
}
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:.
}
}
| apache-2.0 | cdd812a7bd149270a4cc62b52edc09ba | 49.414634 | 285 | 0.712143 | 5.432326 | false | false | false | false |
ScalaInc/exp-ios-sdk | ExpSwift/Classes/ContentNode.swift | 1 | 3590 | //
// ContentNode.swift
// Pods
//
// Created by Cesar on 9/23/15.
//
//
import Foundation
import PromiseKit
import Alamofire
public final class ContentNode: Model,ResponseObject,ResponseCollection {
var children: [ContentNode] = []
public let uuid: String
public let subtype: CONTENT_TYPES
public enum CONTENT_TYPES : String {
case APP = "scala:content:app"
case FILE = "scala:content:file"
case FOLDER = "scala:content:folder"
case URL = "scala:content:url"
case UNKNOWN = ""
}
required public init?(response: HTTPURLResponse?, representation: Any?) {
if let representation = representation as? [String: AnyObject] {
self.uuid = representation["uuid"] as! String
self.subtype = CONTENT_TYPES(rawValue: representation["subtype"] as! String)!
} else {
self.uuid = ""
self.subtype = CONTENT_TYPES.UNKNOWN
}
super.init(response: response, representation: representation)
// remove children from document
document["children"] = nil
}
/**
Get Children from Node
@return Promise<[Content]>.
*/
public func getChildren() ->Promise<[ContentNode]>{
if (!children.isEmpty) {
return Promise<[ContentNode]> { fulfill, reject in
fulfill(children)
}
} else {
return Promise { fulfill, reject in
Alamofire.request(Router.getContent(uuid) )
.responseObject { (response: DataResponse<ContentNode>) in
switch response.result{
case .success(let data):
self.children = data.children
fulfill(self.children)
case .failure(let error):
return reject(error)
}
}
}
}
}
/**
Get Url
@return String.
*/
public func getUrl () -> String? {
let rt = auth?.get("restrictedToken") as! String
switch(self.subtype) {
case .FILE:
let escapeUrl = (self.document["path"]! as! String).addingPercentEscapes(using: String.Encoding.utf8)!
return "\(hostUrl)/api/delivery\(escapeUrl)?_rt=\(rt)"
case .APP:
let escapeUrl = (self.document["path"]! as! String).addingPercentEscapes(using: String.Encoding.utf8)!
return "\(hostUrl)/api/delivery\(escapeUrl)/index.html?_rt=\(rt)"
case .URL:
return self.document["url"] as? String
default:
return nil
}
}
/**
Get Url to a file variant
@return String.
*/
public func getVariantUrl (_ name: String) -> String? {
if(CONTENT_TYPES.FILE == self.subtype && hasVariant(name)){
if let url = getUrl() {
let rt = auth?.get("restrictedToken") as! String
let variant = name.addingPercentEscapes(using: String.Encoding.utf8)!
return "\(url)?variant=\(variant)&_rt=\(rt)"
}
}
return nil
}
public func hasVariant(_ name: String) -> Bool {
if let variants = self.document["variants"] as? [[String:AnyObject]] {
for variant in variants {
if(variant["name"] as! String == name){
return true
}
}
}
return false;
}
}
| mit | 23093cc39a18e4e5152ff098e6012b2c | 28.42623 | 114 | 0.52507 | 4.780293 | false | false | false | false |
VictorNouvellet/Player | Player/Player/Category/UIImageView+Player.swift | 1 | 991 | //
// UIImageView+Player.swift
// Player
//
// Created by Victor Nouvellet on 10/12/17.
// Copyright © 2017 Victor Nouvellet. All rights reserved.
//
import UIKit
extension UIImageView {
func setImageFromURL(url: String?) {
self.image = UIImage(named: "AppIcon")
guard let safeUrlString = url, let safeUrl = URL(string: safeUrlString) else {
return
}
URLSession.shared.dataTask(with: safeUrl) { (data, response, error) in
if error != nil {
log.error("Failed fetching image: \(error.debugDescription)")
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
log.error("Error with HTTPURLResponse or statusCode")
return
}
DispatchQueue.main.async {
self.image = UIImage(data: data!)
}
}.resume()
}
}
| bsd-3-clause | f65c1559c1836ba991dbf440968f40da | 28.117647 | 96 | 0.549495 | 4.759615 | false | false | false | false |
netease-app/NIMSwift | Example/NIMSwift/Classes/IM/Session/IMPersonalCardController.swift | 1 | 6963 | //
// IMPersonalCardController.swift
// NIMSwift
//
// 个人资料页面
//
// Created by 衡成飞 on 6/7/17.
// Copyright © 2017 qianwang365. All rights reserved.
//
import UIKit
class IMPersonalCardController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var tableView:UITableView!
var headerView:UIView!
var footerView:UIView!
//传入参数(IM的account)
var userId:String!
fileprivate var userInfo:NIMUser?
fileprivate var user:NIMUser?
fileprivate var isAdded:Bool = false
deinit {
NIMSDK.shared().userManager.remove(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setupNav()
setupDelegate()
requestUserInfo()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupTableView()
}
func setupNav(){
self.navigationItem.title = "详细资料"
}
func setupDelegate(){
NIMSDK.shared().userManager.add(self)
}
func setupTableView(){
tableView.tableHeaderView?.height = 100.0
tableView.tableFooterView?.height = 150
headerView = tableView.tableHeaderView
footerView = tableView.tableFooterView
let friendButton = footerView.subviews.flatMap{$0 as? UIButton}.filter{$0.tag == 0}.first
let deleteButton = footerView.subviews.flatMap{$0 as? UIButton}.filter{$0.tag == 1}.first
let isMe = self.userId == NIMSDK.shared().loginManager.currentAccount() ? true:false
let isMyfriend = NIMSDK.shared().userManager.isMyFriend(self.userId)
deleteButton?.isHidden = !isMyfriend
deleteButton?.addTarget(self, action: #selector(didClickDeleteFriend), for: .touchUpInside)
if isMe || isMyfriend {
self.isAdded = true
friendButton?.setTitle("发消息", for: .normal)
friendButton?.addTarget(self, action: #selector(didClickSendMessage), for: .touchUpInside)
}else{
self.isAdded = false
friendButton?.setTitle("加为好友", for: .normal)
friendButton?.addTarget(self, action: #selector(didClickAddFriend), for: .touchUpInside)
}
}
func refresh(){
let info = NIMKit.shared().info(byUser: userId, option: nil)
if let h = info?.avatarUrlString,NSURL(string: h.encodingUrlQueryAllowed()) != nil {
headerView.subviews.flatMap{$0 as? UIImageView}.first?.cf_setImage(url:NSURL(string:h.encodingUrlQueryAllowed())! , placeHolderImage: UIImage(named:"avator_default"))
}
headerView.subviews.flatMap{$0 as? UILabel}.forEach{ v in
if v.tag == 0 {
if let alias = user?.alias {
v.text = alias
}else{
v.text = user?.userInfo?.nickName
}
}else if v.tag == 1 {
v.text = self.userId
}
}
self.tableView.reloadData()
}
func requestUserInfo(){
self.view.showHUDProgress()
NIMSDK.shared().userManager.fetchUserInfos([userId]) { (user, error) in
self.view.hiddenAllMessage()
if error != nil {
self.view.showHUDMsg(msg: "获取用户信息失败")
}else if user != nil{
self.user = user![0]
self.refresh()
}
}
}
// 删除好友
func didClickDeleteFriend(){
let act = UIAlertController(title: "删除好友", message: "删除好友后,将同时解除双方的好友关系", preferredStyle: .alert)
act.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
act.addAction(UIAlertAction(title: "确定", style: .default, handler: {_ in
self.view.showHUDProgress()
NIMSDK.shared().userManager.deleteFriend(self.userId, completion: { (error) in
self.view.hiddenAllMessage()
if error != nil {
print(error!)
self.view.showHUDMsg(msg: "删除失败")
}else{
self.navigationController?.popViewController(animated: true)
}
})
}))
self.present(act, animated: true, completion: nil)
}
// 发送消息
func didClickSendMessage(){
let session = NIMSession.init(self.userId, type: .P2P)
let vc = IMSessionController(session: session)!
self.navigationController?.pushViewController(vc, animated: true)
let nav = self.navigationController
nav?.viewControllers = [nav!.viewControllers[0],vc]
}
// 添加好友
func didClickAddFriend(){
let vc = self.storyboard?.instantiateViewController(withIdentifier: "IMAddFriendVerifyController") as! IMAddFriendVerifyController
vc.userOrTeamId = userId
vc.type = 0
self.navigationController?.pushViewController(vc, animated: true)
}
// MARK: - UITableViewDataSource,UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 && !self.isAdded{
return 0
}
return 60
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "remark cell", for: indexPath)
if let alias = user?.alias {
cell.contentView.subviews.first?.subviews.flatMap{$0 as? UILabel}.filter{$0.tag == 1}.first?.text = alias
}
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "search cell", for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "IMPersonalRemarkController") as! IMPersonalRemarkController
vc.user = self.user!
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
// MARK: - NIMUserManagerDelegate
extension IMPersonalCardController:NIMUserManagerDelegate{
func onUserInfoChanged(_ user: NIMUser) {
self.refresh()
}
func onFriendChanged(_ user: NIMUser) {
self.refresh()
}
func onBlackListChanged() {
self.refresh()
}
func onMuteListChanged() {
self.refresh()
}
}
| mit | d42d4d33c4c66554e2affe4e97ac6319 | 31.28436 | 178 | 0.591603 | 4.727273 | false | false | false | false |
rockgarden/swift_language | Playground/Temp.playground/Pages/Higher Order Functions.xcplaygroundpage/Contents.swift | 1 | 13584 | //: [Previous](@previous)
//: # HIGH ORDER FUNCTIONS 高阶函数
import UIKit
var array = [1,2,3,4,5]
//: ## Map
//: each value in array become another value (can become different type also)
let mapped = array.map { (value) -> Int in
return value + 1
}
let mappedShort = array.map({ "\($0) in String"})
mappedShort
/*:
## flatMap
support optional and squence of sequence
过滤nil, map不过滤
*/
var multidimentionalArray: [[Int]?] = [[1,2], [3,5], [4], nil]
let flatmapped: [[Int]?] = multidimentionalArray.flatMap { (array) in
return array?.count > 1 ? array : []
}
let flatmappedShort = multidimentionalArray.flatMap({ $0 }) //Remove nil
flatmappedShort
var flatMapX2 = array.flatMap{$0 * 2}
var images = array.flatMap{UIImage(named:"\($0).png")}
images.count
let persons: [[String: AnyObject]] = [["name": "Carl Saxon", "city": "New York, NY", "age": 44],
["name": "Travis Downing", "city": "El Segundo, CA", "age": 34],
["name": "Liz Parker", "city": "San Francisco, CA", "age": 32],
["name": "John Newden", "city": "New Jersey, NY", "age": 21],
["name": "Hector Simons", "city": "San Diego, CA", "age": 37],
["name": "Brian Neo", "age": 27]] //注意这家伙没有 city 键值
func infoFromState(state state: String, persons: [[String: AnyObject]])
-> Int {
// 先进行 flatMap 后进行 filter 筛选
// $0["city"] 是一个可选值,对于那些没有 city 属性的项返回 nil
// componentsSeparatedByString 处理键值,例如 "New York, NY"
// 最后返回的 ["New York","NY"],last 取到最后的 NY
return persons.flatMap( { $0["city"]?.componentsSeparatedByString(", ").last })
.filter({$0 == state})
.count
}
infoFromState(state: "CA", persons: persons)
//: ## Filter
//: each value in array must passed a rule to append itself into newly made array
let filtered = array.filter { (value) -> Bool in
return value >= 4
}
let filteredShort = array.filter({ $0 > 2 })
filteredShort
// 验证在字符串中是否存在指定单词
let words = ["Swift", "iOS", "cocoa", "OSX", "tvOS"]
let tweet = "This is an example about Swift"
let valid = words.filter({tweet.containsString($0)}).isEmpty
valid
words.contains(tweet.containsString)
tweet.characters
.split(" ")
.lazy
.map(String.init)
.contains(Set(words).contains)
/*:
## Reduce
combining the elements of an array to a single value
Reduce 是 map、flatMap 或 filter 的一种扩展的形式。Reduce 的基础思想是将一个序列转换为一个不同类型的数据,期间通过一个累加器(Accumulator)来持续记录递增状态。为了实现这个方法,我们会向 reduce 方法中传入一个用于处理序列中每个元素的结合(Combinator)闭包 / 函数 / 方法。
*/
// 0 is starting value
let reduced = array.reduce(0) { (value1, value2) -> Int in
value1 + value2
}
let reducedShort = array.reduce(0, combine: ({ $0 + $1 }))
reducedShort
// 初始值 initial 为 0,每次遍历数组元素,执行 + 操作, + 作为一个 combinator 函数是有效的,它仅仅是对 lhs(Left-hand side,等式左侧) 和 rhs(Right-hand side,等式右侧) 做加法处理,最后返回结果值.
array.reduce(0, combine: +)
// "test" is starting value
let reduced1 = array.reduce("test", combine: ({ "\($0)\($1)"}))
reduced1
// Can be mathematics function
// 初始值 initial 为 1,每次遍历数组元素,执行 * 操作
array.reduce(1, combine: *)
// 反转数组: $0 指累加器(accumulator),$1 指遍历数组得到的一个元素
let reduced2 = array.reduce([Int](), combine: { [$1] + $0 })
reduced2
func combinator(accumulator: Int, current: Int) -> Int {
return accumulator + current*current
}
array.reduce(0, combine: combinator)
/* 划分(Partition)处理
为元组定义个别名,此外 Acc 也是闭包传入的 accumulator 的类型
*/
typealias Acc = (l: [Int], r: [Int])
func partition(lst: [Int], criteria: (Int) -> Bool) -> Acc {
return lst.reduce((l: [Int](), r: [Int]()), combine: { (ac: Acc, o: Int) -> Acc in
if criteria(o) {
return (l: ac.l + [o], r: ac.r)
} else {
return (r: ac.r + [o], l: ac.l)
}
})
}
var resultPartition = partition([1, 2, 3, 4, 5, 6, 7, 8, 9], criteria: { $0 % 2 == 0 })
resultPartition
/* Minimum
返回列表中的最小项。
*/
array.minElement()
// 初始值为 Int.max,传入闭包为 min:求两个数的最小值
// min 闭包传入两个参数:1. 初始值 2. 遍历列表时的当前元素
// 倘若当前元素小于初始值,初始值就会替换成当前元素
// 示意写法: initial = min(initial, elem)
array.reduce(Int.max, combine: min)
/* Unique
剔除列表中重复的元素。当然,最好的解决方式是使用集合(Set)。
*/
[1, 2, 5, 1, 7].reduce([], combine: { (a: [Int], b: Int) -> [Int] in
if a.contains(b) {
return a
} else {
return a + [b]
}
})
/*:
### Group By 分组
遍历整个列表,通过一个鉴别函数对列表中元素进行分组,将分组后的列表作为结果值返回。
问题中的鉴别函数返回值类型需要遵循 Hashable 协议,这样我们才能拥有不同的键值。此外保留元素的排序,而组内元素排序则不一定被保留下来。*/
func groupby<T, H: Hashable>(items: [T], f: (T) -> H) -> [H: [T]] {
return items.reduce([:], combine: { (acc: [H: [T]], o: T) -> [H: [T]] in
var ac = acc
// o 为遍历序列的当前元素
let h = f(o) // 通过 f 函数得到 o 对应的键值
if var c = ac[h] { // 说明 o 对应的键值已经存在,只需要更新键值对应的数组元素即可
c.append(o)
ac.updateValue(c, forKey: h)
} else { // 说明 o 对应的键值不存在,需要为字典新增一个键值,对应值为 [o]
ac.updateValue([o], forKey: h)
}
return ac
})
}
(groupby([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], f: { $0 % 3 }))
// prints: [2: [2, 5, 8, 11], 0: [3, 6, 9, 12], 1: [1, 4, 7, 10]]
(groupby(["Carl", "Cozy", "Bethlehem", "Belem", "Brand", "Zara"], f: { $0.characters.first! }))
// prints: ["C" : ["Carl" , "Cozy"] , "B" : ["Bethlehem" , "Belem" , "Brand"] , "Z" : ["Zara"]]
/* Interpose
函数给定一个 items 数组,每隔 count 个元素插入 element 元素,返回结果值。
下面的实现确保了 element 仅在中间插入,而不会添加到数组尾部。
*/
func interpose<T>(items: [T], element: T, count: Int = 1) -> [T] {
// cur 为当前遍历元素的索引值 cnt 为计数器,当值等于 count 时又重新置 1
typealias Acc = (ac: [T], cur: Int, cnt: Int)
return items.reduce((ac: [], cur: 0, cnt: 1), combine: { (a: Acc, o: T) -> Acc in
switch a {
// 此时遍历的当前元素为序列中的最后一个元素
case let (ac, cur, _) where (cur+1) == items.count: return (ac + [o], 0, 0)
// 满足插入条件
case let (ac, cur, c) where c == count:
return (ac + [o, element], cur + 1, 1)
// 执行下一步
case let (ac, cur, c):
return (ac + [o], cur + 1, c + 1)
}
}).ac
}
(interpose([1, 2, 3, 4, 5], element: 9))
// : [1, 9, 2, 9, 3, 9, 4, 9, 5]
(interpose([1, 2, 3, 4, 5], element: 9, count: 2))
// : [1, 2, 9, 3, 4, 9, 5]
/* Interdig
该函数允许你有选择从两个序列中挑选元素合并成为一个新序列返回。
*/
func interdig<T>(list1: [T], list2: [T]) -> [T] {
// Zip2Sequence 返回 [(list1, list2)] 是一个数组,类型为元组
// 也就解释了为什么 combinator 闭包的类型是 (ac: [T], o: (T, T)) -> [T]
return Zip2Sequence(list1, list2).reduce([], combine: { (ac: [T], o: (T, T)) -> [T] in
return ac + [o.0, o.1]
})
}
(interdig([1, 3, 5], list2: [2, 4, 6]))
// : [1, 2, 3, 4, 5, 6]
/* Chunk
该函数返回原数组分解成长度为 n 后的多个数组.
*/
func chunk<T>(list: [T], length: Int) -> [[T]] {
typealias Acc = (stack: [[T]], cur: [T], cnt: Int)
let l = list.reduce((stack: [], cur: [], cnt: 0), combine: { (ac: Acc, o: T) -> Acc in
if ac.cnt == length {
return (stack: ac.stack + [ac.cur], cur: [o], cnt: 1)
} else {
return (stack: ac.stack, cur: ac.cur + [o], cnt: ac.cnt + 1)
}
})
return l.stack + [l.cur]
}
(chunk([1, 2, 3, 4, 5, 6, 7], length: 2))
// : [[1, 2], [3, 4], [5, 6], [7]]
// 函数中使用一个更为复杂的 accumulator,包含了 stack、current list 以及 count 。
/*:
### Reduce 实现
重新定义一个 map 函数
*/
func rmap(elements: [Int], transform: (Int) -> Int) -> [Int] {
return elements.reduce([Int](), combine: { (acc: [Int], obj: Int) -> [Int] in
var accvar = acc //内部定义, 最好外部定义
accvar.append(transform(obj))
return accvar
})
}
var resultRmap = (rmap([1, 2, 3, 4], transform: { $0 * 3}))
resultRmap
/*
首先,elements 序列调用 reduce 方法:elements.reduce...。
然后,我们传入初始值给累加器(Accumulator),即一个 Int 类型空数组([Int]())。
接着,我们传入 combinator 闭包,它接收两个参数:第一个参数为 accumulator,即 acc: [Int];第二个参数为从序列中取得的当前对象 obj: Int(对序列进行遍历,每次取到其中的一个对象 obj)。
combinator 闭包对 obj 做变换处理,然后添加到累加器 accumulator 中。
最后返回 accumulator 对象。
相比较调用 map 方法,这种实现代码看起来有点冗余。
*/
func rmapA(elements: [Int], transform: (Int) -> Int) -> [Int] {
// $0 表示第一个传入参数,$1 表示第二个传入参数,依次类推...
return elements.reduce([Int](), combine: {$0 + [transform($1)]})
}
var resultRmapA = (rmapA([1, 2, 3, 4], transform: { $0 * 3}))
resultRmapA
/*
+ 运算符能够对两个序列进行加法操作。因此 [0, 1, 2] + [transform(4)] 表达式将左序列和右序列进行相加,其中右序列由转换后的元素构成。
这里有个地方需要引起注意:[0, 1, 2] + [4] 执行速度要慢于 [0, 1, 2].append(4)。倘若你正在处理庞大的列表,应取代集合 + 集合的方式,转而使用一个可变的 accumulator 变量进行递增:rmap 效率更高。
*/
func rflatMap(elements: [Int], transform: (Int) -> Int?) -> [Int] {
return elements.reduce([Int](), combine: {
guard let m = transform($1)
else { return $0 }
return $0 + [m]})
}
var resultRflatMap = (rflatMap([1, 2, 3, 4], transform: { guard $0 != 3 else { return nil }; return $0 * 3}))
resultRflatMap
func rFilter(elements: [Int], filter: (Int) -> Bool) -> [Int] {
return elements.reduce([Int](),
combine: { guard filter($1) else { return $0 }
return $0 + [$1]})
}
var resultRFilter = (rFilter([1, 3, 4, 6], filter: { $0 % 2 == 0}))
resultRFilter
/*:
## Reduce vs. 链式结构
reduce 除了较强的灵活性之外,还具有另一个优势:通常情况下,map 和 filter 所组成的链式结构会引入性能上的问题,因为它们需要多次遍历你的集合才能最终得到结果值,这种操作往往伴随着性能损失:
*/
// 这里要遍历 3次
array = Array(0...100)
array.map({ $0 + 3}).filter({ $0 % 2 == 0}).reduce(0, combine: +)
// 这里只需要遍历 1 次序列
array.reduce(0, combine: { (ac: Int, r: Int) -> Int in
if (r + 3) % 2 == 0 {
return ac + r + 3
} else {
return ac
}
})
// reduce效率接近for-loop
var ux = 0
for i in array {
if (i + 3) % 2 == 0 {
ux += (i + 3)
}
}
array.map({ $0 + 3}).reverse().prefix(3)
// 0.027 Seconds
array.reduce([], combine: { (ac: [Int], r: Int) -> [Int] in
var acvar = ac
acvar.insert(r + 3, atIndex: 0)
return acvar
}).prefix(3)
// 2.927 Seconds,因为从 reduce 的语义上来说,传入闭包的参数(如果可变的话,即 mutated),会对底层序列的每个元素都产生一份 copy,这意味着 accumulator 参数 ac 将为 0…10000 范围内的每个元素都执行一次复制操作。
/*
## reduce infoFromState 函数
*/
func infoFromStateReduce(state state: String, persons: [[String: AnyObject]])
-> (count: Int, age: Float) {
// 在函数内定义别名让函数更加简洁
typealias Acc = (count: Int, age: Float)
// reduce 结果暂存为临时的变量
let u = persons.reduce((count: 0, age: 0.0)) {
(ac: Acc, p) -> Acc in
// 获取地区和年龄
guard let personState = (p["city"] as? String)?.componentsSeparatedByString(", ").last,
personAge = p["age"] as? Int
// 确保选出来的是来自正确的洲
where personState == state
// 如果缺失年龄或者地区,又或者上者比较结果不等,返回
else { return ac }
// 最终累加计算人数和年龄
return (count: ac.count + 1, age: ac.age + Float(personAge))
}
// 我们的结果就是上面的人数和除以人数后的平均年龄
return (age: u.age / Float(u.count), count: u.count)
}
infoFromStateReduce(state: "CA", persons: persons)
//: [Next](@next)
| mit | 79d3c1d44248057b4b0c7c73f4d51601 | 33.126582 | 170 | 0.573628 | 2.730127 | false | false | false | false |
huangboju/AsyncDisplay_Study | AsyncDisplay/RainForest/PageController.swift | 1 | 1312 | //
// PageController.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/4/20.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import AsyncDisplayKit
class PageController: UIViewController {
let pagerNode = ASPagerNode()
let allAnimals = [
RainforestCardInfo.birdCards(),
RainforestCardInfo.mammalCards(),
RainforestCardInfo.reptileCards()
]
override func viewDidLoad() {
super.viewDidLoad()
pagerNode.setDataSource(self)
view.addSubnode(pagerNode)
automaticallyAdjustsScrollViewInsets = false
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
pagerNode.frame = CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64)
}
}
// MARK: - ASPagerDataSource
extension PageController: ASPagerDataSource {
func pagerNode(_ pagerNode: ASPagerNode, nodeAt index: Int) -> ASCellNode {
let animals = allAnimals[index]
let node = ASCellNode(viewControllerBlock: { () -> UIViewController in
return AnimalTableNodeController(animals: animals!)
}, didLoad: nil)
return node
}
func numberOfPages(in pagerNode: ASPagerNode) -> Int {
return allAnimals.count
}
}
| mit | cd1533827aa15d94dd1a098be1b39862 | 23.942308 | 104 | 0.653816 | 4.381757 | false | false | false | false |
cristianames92/PortalView | Sources/UIKit/PortalTableView.swift | 1 | 6609 | //
// PortalTableView.swift
// PortalView
//
// Created by Guido Marucci Blas on 2/14/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import UIKit
public final class PortalTableView<MessageType, CustomComponentRendererType: UIKitCustomComponentRenderer>: UITableView, UITableViewDataSource, UITableViewDelegate
where CustomComponentRendererType.MessageType == MessageType {
public let mailbox = Mailbox<MessageType>()
public var isDebugModeEnabled: Bool = false
fileprivate let customComponentRenderer: CustomComponentRendererType
fileprivate let layoutEngine: LayoutEngine
fileprivate let items: [TableItemProperties<MessageType>]
// Used to cache cell actual height after rendering table
// item component. Caching cell height is usefull when
// cells have dynamic height.
fileprivate var cellHeights: [CGFloat?]
public init(items: [TableItemProperties<MessageType>], customComponentRenderer: CustomComponentRendererType, layoutEngine: LayoutEngine) {
self.customComponentRenderer = customComponentRenderer
self.items = items
self.layoutEngine = layoutEngine
self.cellHeights = Array(repeating: .none, count: items.count)
super.init(frame: .zero, style: .plain)
self.dataSource = self
self.delegate = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
let cellRender = itemRender(at: indexPath)
let cell = dequeueReusableCell(with: cellRender.typeIdentifier)
cell.component = cellRender.component
let componentHeight = cell.component?.layout.height
if componentHeight?.value == .none && componentHeight?.maximum == .none {
// TODO replace this with a logger
print("WARNING: Table item component with identifier '\(cellRender.typeIdentifier)' does not specify layout height! You need to either set layout.height.value or layout.height.maximum")
}
// For some reason the first page loads its cells with smaller bounds.
// This forces the cell to have the width of its parent view.
if let width = self.superview?.bounds.width {
let baseHeight = itemBaseHeight(at: indexPath)
cell.bounds.size.width = width
cell.bounds.size.height = baseHeight
cell.contentView.bounds.size.width = width
cell.contentView.bounds.size.height = baseHeight
}
cell.selectionStyle = item.onTap.map { _ in item.selectionStyle.asUITableViewCellSelectionStyle } ?? .none
cell.isDebugModeEnabled = isDebugModeEnabled
cell.render()
// After rendering the cell, the parent view returned by rendering the
// item component has the actual height calculated after applying layout.
// This height needs to be cached in order to be returned in the
// UITableViewCellDelegate's method tableView(_,heightForRowAt:)
let actualCellHeight = cell.contentView.subviews[0].bounds.height
cellHeights[indexPath.row] = actualCellHeight
cell.bounds.size.height = actualCellHeight
cell.contentView.bounds.size.height = actualCellHeight
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return itemBaseHeight(at: indexPath)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = items[indexPath.row]
item.onTap |> { mailbox.dispatch(message: $0) }
}
}
fileprivate extension PortalTableView {
fileprivate func dequeueReusableCell(with identifier: String) -> PortalTableViewCell<MessageType, CustomComponentRendererType> {
if let cell = dequeueReusableCell(withIdentifier: identifier) as? PortalTableViewCell<MessageType, CustomComponentRendererType> {
return cell
} else {
let cell = PortalTableViewCell<MessageType, CustomComponentRendererType>(
reuseIdentifier: identifier,
customComponentRenderer: customComponentRenderer,
layoutEngine: layoutEngine
)
cell.mailbox.forward(to: mailbox)
return cell
}
}
fileprivate func itemRender(at indexPath: IndexPath) -> TableItemRender<MessageType> {
// TODO cache the result of calling renderer. Once the diff algorithm is implemented find a way to only
// replace items that have changed.
// IGListKit uses some library or algorithm to diff array. Maybe that can be used to make the array diff
// more efficient.
//
// https://github.com/Instagram/IGListKit
//
// Check the video of the talk that presents IGListKit to find the array diff algorithm.
// Also there is Dwifft which seems to be based in the same algorithm:
//
// https://github.com/jflinter/Dwifft
//
let item = items[indexPath.row]
return item.renderer(item.height)
}
fileprivate func itemMaxHeight(at indexPath: IndexPath) -> CGFloat {
return CGFloat(items[indexPath.row].height)
}
/// Returns the cached actual height for the item at the given `indexPath`.
/// Actual heights are cached using the `cellHeights` instance variable and
/// are calculated after rending the item component inside the table view cell.
/// This is usefull when cells have dynamic height.
///
/// - Parameter indexPath: The item's index path.
/// - Returns: The cached actual item height.
fileprivate func itemActualHeight(at indexPath: IndexPath) -> CGFloat? {
return cellHeights[indexPath.row]
}
/// Returns the item's cached actual height if available. Otherwise it
/// returns the item's max height.
///
/// - Parameter indexPath: The item's index path.
/// - Returns: the item's cached actual height or its max height.
fileprivate func itemBaseHeight(at indexPath: IndexPath) -> CGFloat {
return itemActualHeight(at: indexPath) ?? itemMaxHeight(at: indexPath)
}
}
| mit | 6b26a300df80a313b2bcd410a9a96868 | 41.909091 | 197 | 0.675999 | 5.299118 | false | false | false | false |
XLsn0w/XLsn0wKit_swift | XLsn0wKit/XLsn0wLog/XLsn0wLog.swift | 1 | 11291 | /*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************
*********************************************************************************************
*********************************************************************************************/
import UIKit/*****如果不想使用外部参数名printObject可以使用下划线_进行忽略****************************/
public func XLsn0wLog<T>(_ printObject: T,
printFile: String = #file,
printLine: Int = #line,
printFunction: String = #function,
printFalse: Bool = false) {
if printFalse {/***打印失败***不管Debug*还是Release*都执行打印**************************************/
print("\n©XLsn0wLog© \n file: \((printFile as NSString).lastPathComponent) \n line: \(printLine) \n func: \(printFunction) \n---print---\n\(printObject) \n---print---\n©XLsn0wLog©\n")
} else {
#if DEBUG/*****只有Debug***才执行打印*********************************************************/
print("\n©XLsn0wLog© \n file: \((printFile as NSString).lastPathComponent) \n line: \(printLine) \n func: \(printFunction) \n---print---\n\(printObject) \n---print---\n©XLsn0wLog©\n")
#endif
}
}
/*********************************************************************************************
*********************************************************************************************
*********************************************************************************************
*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
public func XLsn0wPrint<T>(_ printObject: T,
printFile: String = #file,
printLine: Int = #line,
printFunction: String = #function) -> Void {
#if DEBUG
let filePath = printFile as NSString
let filePath_copy = filePath.lastPathComponent as NSString
let fileName = filePath_copy.deletingPathExtension
print("\n©XLsn0wLog©\(fileName).\(printFunction)[\(printLine)]: \(printObject)\n")
#endif
}
/*********************************************************************************************
*********************************************************************************************
*********************************************************************************************
*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
public func printNSLog<T>(_ printObject : T,
file: String = #file,
function: String = #function,
line: Int = #line) {
#if DEBUG
let filePath = file as NSString
let filePath_copy = filePath.lastPathComponent as NSString
let fileName = filePath_copy.deletingPathExtension
NSLog("\n©XLsn0wLog©\(fileName).\(function)[\(line)]: \(printObject)\n")
#endif
}
public class Log: NSObject,NSCoding {
enum Level: String {
case verbose
case debug
case info
case warning
case error
}
/// Print verbose log (white)
///
/// - parameter log: log content string
public class func v(_ log: Any?, fileName: String = #file, function: String = #function, lineNumber: Int = #line) {
let info = formatInfo(fileName: fileName, function: function, lineNumber: lineNumber)
self.addLog(log, info: info, level: Log.Level.verbose)
}
/// Print debug log (blue)
///
/// - parameter log: log content string
public class func d(_ log: Any?, fileName: String = #file, function: String = #function, lineNumber: Int = #line) {
let info = formatInfo(fileName: fileName, function: function, lineNumber: lineNumber)
self.addLog(log, info: info, level: Log.Level.debug)
}
/// Print info log (green)
///
/// - parameter log: log content string
public class func i(_ log: Any?, fileName: String = #file, function: String = #function, lineNumber: Int = #line) {
let info = formatInfo(fileName: fileName, function: function, lineNumber: lineNumber)
self.addLog(log, info: info, level: Log.Level.info)
}
/// Print warning log (yellow)
///
/// - parameter log: log content string
public class func w(_ log: Any?, fileName: String = #file, function: String = #function, lineNumber: Int = #line) {
let info = formatInfo(fileName: fileName, function: function, lineNumber: lineNumber)
self.addLog(log, info: info, level: Log.Level.warning)
}
/// Print error log (red)
///
/// - parameter log: log content string
public class func e(_ log: Any?, fileName: String = #file, function: String = #function, lineNumber: Int = #line) {
let info = formatInfo(fileName: fileName, function: function, lineNumber: lineNumber)
self.addLog(log, info: info, level: Log.Level.error)
}
/// Emoji mark of verbose logs, default is ✉️
public var verboseMark: String = "✉️"
/// Emoji mark of debug logs, default is 🌐
public var debugMark: String = "🌐"
/// Emoji mark of info logs, default is 📟
public var infoMark: String = "📟"
/// Emoji mark of warning logs, default is ⚠️
public var warningMark: String = "⚠️"
/// Emoji mark of error logs, default is ❌
public var errorMark: String = "❌"
private class func addLog(_ log: Any?, info: String, level: Log.Level) {
let log = Log(info: info, log: log, level: level)
print("\(log.mark(for: log.level))\(log.info)", log.log, separator: "", terminator: "\n")
}
fileprivate func mark(for level: Log.Level) -> String {
switch level {
case .verbose: return verboseMark
case .debug: return debugMark
case .info: return infoMark
case .warning: return warningMark
case .error: return errorMark
}
}
private class func formatInfo(fileName: String, function: String, lineNumber: Int) -> String {
let className = (fileName as NSString).pathComponents.last!.replacingOccurrences(of: "swift", with: "")
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
let date = fmt.string(from: Date())
let text = date + " " + className + function + " [line " + String(lineNumber) + "]:\n"
return text
}
var info: String
var log: String
var level: Log.Level
init(info: String, log: Any?, level: Log.Level) {
self.info = info
self.level = level
guard let log = log else {
self.log = ""
return
}
self.log = String.init(describing: log)
}
public required init?(coder aDecoder: NSCoder) {
self.info = aDecoder.decodeObject(forKey: "info") as! String
self.log = aDecoder.decodeObject(forKey: "log") as! String
let levelString = aDecoder.decodeObject(forKey: "level") as! String
self.level = Level.init(rawValue: levelString)!
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.info, forKey: "info")
aCoder.encode(self.log, forKey: "log")
aCoder.encode(self.level.rawValue, forKey: "level")
}
}
/*********************************************************************************************
*********************************************************************************************
*********************************************************************************************
*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
| mit | 546ebff742bd4c6fb519b4a6f15f1e65 | 53.990148 | 191 | 0.328227 | 4.222012 | false | false | false | false |
bluezald/DesignPatterns | DesignPatterns/DesignPatterns/DesignPatternsTableViewController.swift | 1 | 3160 | //
// DesignPatternsTableViewController.swift
// DesignPatterns
//
// Created by Vincent Bacalso on 05/10/2016.
// Copyright © 2016 bluezald. All rights reserved.
//
import UIKit
class DesignPatternsTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | bc8f110eaf2a062da8798fd334e80a26 | 32.252632 | 136 | 0.673947 | 5.32715 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Business/WalletTransactions/WalletTransactions.swift | 2 | 4813 | //
// WalletTransactions.swift
// Neocom
//
// Created by Artem Shimanski on 2/12/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import EVEAPI
import CoreData
import Expressible
struct WalletTransactions: View {
@Environment(\.managedObjectContext) private var managedObjectContext
@EnvironmentObject private var sharedState: SharedState
@ObservedObject var transactions: Lazy<WalletTransactionsData, Account> = Lazy()
var body: some View {
let result = sharedState.account.map { account in
self.transactions.get(account, initial: WalletTransactionsData(esi: sharedState.esi, characterID: account.characterID, managedObjectContext: managedObjectContext))
}
let list = List {
if result?.result?.value != nil {
WalletTransactionsContent(transactions: result!.result!.value!.transactions,
contacts: result!.result!.value!.contacts,
locations: result!.result!.value!.locations)
}
}.listStyle(GroupedListStyle())
.overlay(result == nil ? Text(RuntimeError.noAccount).padding() : nil)
.overlay((result?.result?.error).map{Text($0)})
.overlay(result?.result?.value?.transactions.isEmpty == true ? Text(RuntimeError.noResult).padding() : nil)
return Group {
if result != nil {
list.onRefresh(isRefreshing: Binding(result!, keyPath: \.isLoading)) {
result?.update(cachePolicy: .reloadIgnoringLocalCacheData)
}
}
else {
list
}
}
.navigationBarTitle(Text("Wallet Transactions"))
}
}
struct WalletTransactionsContent: View {
var transactions: ESI.WalletTransactions
var contacts: [Int64: Contact]
var locations: [Int64: EVELocation]
private struct WalletTransactionsSection {
var date: Date
var transactions: ESI.WalletTransactions
}
var body: some View {
let calendar = Calendar(identifier: .gregorian)
let items = transactions.sorted{$0.date > $1.date}
let sections = Dictionary(grouping: items, by: { (i) -> Date in
let components = calendar.dateComponents([.year, .month, .day], from: i.date)
return calendar.date(from: components) ?? i.date
}).sorted {$0.key > $1.key}.map { (date, transactions) in
WalletTransactionsSection(date: date, transactions: transactions)
}
return ForEach(sections, id: \.date) { section in
Section(header: Text(DateFormatter.localizedString(from: section.date, dateStyle: .medium, timeStyle: .none).uppercased())) {
ForEach(section.transactions, id: \.transactionID) { item in
WalletTransactionCell(item: item, contacts: self.contacts, locations: self.locations)
}
}
}
}
}
#if DEBUG
struct WalletTransactions_Previews: PreviewProvider {
static var previews: some View {
let contact = Contact(entity: NSEntityDescription.entity(forEntityName: "Contact", in: Storage.testStorage.persistentContainer.viewContext)!, insertInto: nil)
contact.name = "Artem Valiant"
contact.contactID = 1554561480
let solarSystem = try! Storage.testStorage.persistentContainer.viewContext.from(SDEMapSolarSystem.self).first()!
let location = EVELocation(solarSystem: solarSystem, id: Int64(solarSystem.solarSystemID))
let transactions = (0..<100).map { i in
ESI.WalletTransactions.Element(clientID: Int(contact.contactID),
date: Date(timeIntervalSinceNow: -3600 * TimeInterval(i) * 3),
isBuy: true,
isPersonal: true,
journalRefID: 1,
locationID: location.id,
quantity: 2,
transactionID: i,
typeID: 645,
unitPrice: 1000000)
}
return NavigationView {
// WalletTransactions()
List {
WalletTransactionsContent(transactions: transactions, contacts: [1554561480: contact], locations: [location.id: location])
}.listStyle(GroupedListStyle())
.navigationBarTitle(Text("Wallet Transactions"))
}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| lgpl-2.1 | cd20f1d4b9e1b1bbb0b085fad9869548 | 39.436975 | 175 | 0.577099 | 5.311258 | false | false | false | false |
Bajocode/ExploringModerniOSArchitectures | Architectures/VIPER/View/MovieCollectionViewCell.swift | 1 | 1263 | //
// MovieCollectionViewCell.swift
// Architectures
//
// Created by Fabijan Bajo on 31/05/2017.
//
//
import UIKit
class MovieCollectionViewCell: UICollectionViewCell, CellConfigurable {
// MARK: - Properties
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var ratingLabel: UILabel!
@IBOutlet fileprivate var thumbImageView: UIImageView!
@IBOutlet fileprivate var activityIndicator: UIActivityIndicatorView!
// MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
activityIndicator.startAnimating()
}
override func prepareForReuse() {
super.prepareForReuse()
activityIndicator.startAnimating()
}
// MARK: - Methods
func configure(with object: Transportable) {
let instance = object as! MovieResultsInteractor.PresentableInstance
titleLabel.text = instance.title
ratingLabel.text = instance.ratingText
thumbImageView.downloadImage(from: instance.thumbnailURL) {
if self.thumbImageView.image == nil {
self.activityIndicator.startAnimating()
} else {
self.activityIndicator.stopAnimating()
}
}
}
}
| mit | 54745e5389b40f54e36f58af2c6ca7c7 | 26.456522 | 76 | 0.657165 | 5.539474 | false | false | false | false |
patrick-ogrady/godseye-ios | sample/SampleBroadcaster-Swift/SampleBroadcaster-Swift/feedsMapViewController.swift | 1 | 5223 | //
// feedsMapViewController.swift
// SampleBroadcaster-Swift
//
// Created by Patrick O'Grady on 9/10/15.
// Copyright © 2015 videocore. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class feedsMapViewController: UIViewController, MKMapViewDelegate {
var eventObject:PFObject!
var selectedFeed: PFObject!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
self.feedsMapView.delegate = self
var feedsTabBar = self.tabBarController as! feedsTabViewController
self.eventObject = feedsTabBar.eventObject
var query = PFQuery(className: "feeds")
// let then = NSDate(timeIntervalSinceNow: -3)
// query.whereKey("createdAt", greaterThanOrEqualTo:then)
query.whereKey("event", equalTo: eventObject.objectId!)
query.orderByDescending("views")
// query.limit = 4
var feeds = query.findObjects()
for feedObj in feeds! {
var object = feedObj as! PFObject
var name = object["name"] as! String
var coords = object["location"] as! PFGeoPoint
var views = object["views"] as! Int
self.feedsMapView.addAnnotation(Event(title: name, coordinate: CLLocationCoordinate2D(latitude: coords.latitude, longitude: coords.longitude), locationName: "Views: \(views)", pfEventObject: object))
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var feedsMapView: MKMapView!
@IBAction func dismissView(sender: UIBarButtonItem) {
self.tabBarController?.dismissViewControllerAnimated(true, completion: nil)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView! {
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier("eventLocations")
let eventMarker = UIImage(named: "EventAnnotation")
let arrow = UIButton(type: UIButtonType.System)
if let arrowImage = UIImage(named: "Arrow") {
arrow.setImage(arrowImage, forState: .Normal)
arrow.frame = CGRectMake(arrowImage.size.width, arrowImage.size.height, arrowImage.size.width, arrowImage.size.height)
}
//NEED TO ADD TARGET TO THE BUTTON SO THAT USER IS BROUGHT TO FEEDS PAGE WHEN CLICKED
let pfAnnotation = annotation as! Event
var obj = pfAnnotation.eventObject
var views = obj["views"] as! Int
//Scaling the image code
let cgImage = UIImage(named: "EventAnnotation")!.CGImage
let width = CGImageGetWidth(cgImage) / 5 //Multiplied times the number of views
let height = CGImageGetHeight(cgImage) / 5
let bitsPerComponent = CGImageGetBitsPerComponent(cgImage)
let bytesPerRow = CGImageGetBytesPerRow(cgImage)
let colorSpace = CGImageGetColorSpace(cgImage)
let bitmapInfo = CGImageGetBitmapInfo(cgImage)
let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo.rawValue)
CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)
CGContextDrawImage(context, CGRect(origin: CGPointZero, size: CGSize(width: CGFloat(width), height: CGFloat(height))), cgImage)
let scaledImage = CGBitmapContextCreateImage(context)
if( pinView == nil ) {
pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: "eventLocations")
pinView!.image = UIImage(CGImage: scaledImage!)
pinView!.canShowCallout = true
//Adding a custom button to the right accessory view
pinView!.rightCalloutAccessoryView = arrow
}
return pinView
}
//View more arrow touched
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let object = view.annotation! as! Event
self.selectedFeed = object.eventObject
self.performSegueWithIdentifier("viewFeed", sender: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if(segue.identifier == "viewFeed") {
var destination = segue.destinationViewController as! feedViewController
destination.feedObject = self.selectedFeed
destination.eventObject = self.eventObject
} else {
var destination = segue.destinationViewController as! ViewController
destination.event = self.eventObject
}
}
}
| mit | 1c824a445338c7954cbb359e02d96be5 | 39.169231 | 211 | 0.665837 | 5.372428 | false | false | false | false |
AlexIzh/Griddle | Griddle/Classes/Source/ArraySource.swift | 1 | 3680 | //
// ArraySource.swift
// CollectionPresenter
//
// Created by Alex on 20/02/16.
// Copyright © 2016 Moqod. All rights reserved.
//
import Foundation
public enum ArrayAction<Model> {
case insert(index: Int, model: Model)
case delete(index: Int)
case replace(index: Int, newModel: Model)
case move(oldIndex: Int, newIndex: Int)
}
public struct ArraySection<Element>: DataSection {
public var header: Any? { return nil }
public var footer: Any? { return nil }
public var items: [Element] = []
public init(items: [Element] = []) {
self.items = items
}
}
open class ArraySource<Element>: DataSource, ExpressibleByArrayLiteral {
public var delegate = DataSourceDelegate()
private var section = ArraySection<Element>()
public var sectionsCount: Int { return 1 }
public var count: Int {
return section.items.count
}
public var items: [Element] {
get { return section.items }
set {
section.items = newValue
delegate.didRefreshAll()
}
}
public subscript(index: Int) -> Element {
get { return section.items[index] }
set {
delegate.willBeginEditing()
section.items[index] = newValue
delegate.didUpdate(.row(.update(.item(section: 0, item: index))))
delegate.didEndEditing()
}
}
// MARK: - Life cycle
public required convenience init(arrayLiteral elements: Element...) {
self.init(array: elements)
}
public init(array: [Element]) {
section.items = array
}
// MARK: - Public methods
public func append(_ item: Element) {
delegate.willBeginEditing()
insert(item, at: items.count)
delegate.didEndEditing()
}
public func sections() -> [ArraySection<Element>] {
return [section]
}
public func itemsCount(for section: Int) -> Int {
return self.section.items.count
}
public func item(at section: Int, index: Int) -> Element? {
guard section == 0 && index >= 0 && index < self.section.items.count
else { return nil }
return self.section.items[index]
}
public func header(at section: Int) -> Any? {
return nil
}
public func footer(at section: Int) -> Any? {
return nil
}
public func perform(actions: [ArrayAction<Element>]) {
delegate.willBeginEditing()
for action in actions {
switch action {
case .insert(let index, let model): insert(model, at: index)
case .delete(let index): deleteItem(at: index)
case .move(let oldIndex, let newIndex): moveItem(from: oldIndex, to: newIndex)
case .replace(let index, let newModel): replaceItem(at: index, with: newModel)
}
}
delegate.didEndEditing()
}
// MARK: - Private methods
func replaceItem(at index: Int, with model: Element) {
section.items[index] = model
delegate.didUpdate(.row(.update(.item(section: 0, item: index))))
}
func moveItem(from index: Int, to newIndex: Int) {
let item = section.items[index]
section.items.remove(at: index)
section.items.insert(item, at: newIndex)
delegate.didUpdate(.row(.move(from: .item(section: 0, item: index), to: .item(section: 0, item: newIndex))))
}
func deleteItem(at index: Int) {
section.items.remove(at: index)
delegate.didUpdate(.row(.delete(.item(section: 0, item: index))))
}
func insert(_ item: Element, at index: Int) {
let insertIndex = index > section.items.count ? section.items.count : index
section.items.insert(item, at: insertIndex)
delegate.didUpdate(.row(.insert(.item(section: 0, item: index))))
}
}
| mit | 18f24e91155425fc325d5104346502b3 | 25.65942 | 114 | 0.631693 | 3.96444 | false | false | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/SwiftExtensions/AALocalized.swift | 4 | 1417 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
// Shorter helper for localized strings
public func AALocalized(_ text: String) -> String {
let appRes = NSLocalizedString(text, comment: "")
if (appRes != text) {
return appRes
}
for t in tables {
let res = NSLocalizedString(text, tableName: t.table, bundle: t.bundle, value: text, comment: "")
if (res != text) {
return res
}
}
return NSLocalizedString(text, tableName: nil, bundle: Bundle.framework, value: text, comment: "")
}
// Registration localization table
public func AARegisterLocalizedBundle(_ table: String, bundle: Bundle) {
tables.append(LocTable(table: table, bundle: bundle))
}
private var tables = [LocTable]()
private class LocTable {
let table: String
let bundle: Bundle
init(table: String, bundle: Bundle) {
self.table = table
self.bundle = bundle
}
}
// Extensions on various UIView
public extension UILabel {
public var textLocalized: String? {
get {
return self.text
}
set (value) {
if value != nil {
self.text = AALocalized(value!).replace("{appname}", dest: ActorSDK.sharedActor().appName)
} else {
self.text = nil
}
}
}
}
| agpl-3.0 | 2b72c6cfcd7b4d66096548e740d6d289 | 21.140625 | 106 | 0.573747 | 4.280967 | false | false | false | false |
radex/swift-compiler-crashes | crashes-fuzzing/21859-swift-printingdiagnosticconsumer-handlediagnostic.swift | 11 | 2594 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var b: T
case c
struct A : a {
}
let t: BooleanType, A : B
enum B<T where h: C {
class b<c {
func i() 0
protocol A : a: BooleanType, A : B<T {
{
enum S<T where d<T where h: A
typeal
case c
func b
struct S<T where B : e : a {
{
typealias e == {
protocol c
typealias e : BooleanType, A : d {
struct X<T : a {
enum a
Void{
for ( )
struct B<T where d: b: e
class A : p
class d<T : CollectionType
{
let t: BooleanType, A : b: a {
let c : BooleanType, A {
typealias e == c,
enum a: a<h where d<T : CollectionType
for ( )
struct B : C {
func j<S : Int -> {
}
struct B
}
{
protocol A : A
extension String {
let : T
}
extension String {
typealias e : AnyObject
struct Q<T {
func < {
enum B<h {
protocol A {
enum a
class b
class b: d where h: e
class A : T
struct S<T {
let : C {
class A : a {
class a {
struct S<T where h: b<T : BooleanType, A {
enum a<h {
let a {
func b
typealias e : a {
struct S<h where T {
protocol A {
{
let t: e
class A : AnyObject
class A {
protocol A {
case c<T where B { func b: a: A {
func b: e
struct Q<c {
struct B { func c
}
if true {
struct S<h {
}
struct A {
}
if true {
typeal
func b
enum B
}
protocol A : P {
case c
protocol A : AnyObject
struct S<T where g: e : P {
{
func < {
var b = compose(
}
protocol A : a {
{
enum S<T : a {
enum S<T where H : BooleanType, A : BooleanType, A : A
Void{
func c<T {
}
struct A {
struct d<T : b: T
let : Int = [Void{
if true {
extension String {
protocol A : a {
}
struct Q<T where B :
{
typealias e : b: BooleanType, A : e : b<T {
class A {
class A : a {
protocol A : e
func j<T where H : B<d where H : P {
if true {
let t: CollectionType
func b<T {
case c,
case c
class a<T {
protocol A {
class A {
protocol A {
case c,
func i() 0
var b<T where B : A
case c( )"\(
func b
protocol P {
case c
}
func < {
class A {
class A : B<T {
protocol A {
let a {
struct Q<T {
let : Int = F>([1)"\() -> {
func b: BooleanType, A : A
struct B<h where h: p
var b
var b<T {
var b = compose(
{
func j<T where g: A : P {
func i([Void
}
var b = [1)
}
var b<h {
protocol c {
class A : BooleanType, A {
func b<T where h: AnyObject
}
}
class b<T where d<T where B :
class A : Int = [1)
enum S<T where h: BooleanType, A {
func b
protocol A {
{
class d<d {
let a {
struct B :
}
{
class A : p
}
func j<h where B :
enum B
{
class A : AnyObject
case c
struct A : C {
struct X<T {
protocol A {
let t: a {
}
let : p
}
case c
}
struct Q<T where d: a {
}
enum b
var b
enum a: p
{
protocol c( ) 0
| mit | 983ea5e3c3e4255ec91f3221fccb71c6 | 12.581152 | 87 | 0.616808 | 2.528265 | false | false | false | false |
ohwutup/ReactiveCocoa | ReactiveCocoaTests/InterceptingSpec.swift | 1 | 28014 | import Foundation
@testable import ReactiveCocoa
import ReactiveSwift
import enum Result.NoError
import Quick
import Nimble
import CoreGraphics
class InterceptingSpec: QuickSpec {
override func spec() {
describe("trigger(for:)") {
var object: InterceptedObject!
weak var _object: InterceptedObject?
beforeEach {
object = InterceptedObject()
_object = object
}
afterEach {
object = nil
expect(_object).to(beNil())
}
it("should send a value when the selector is invoked") {
let signal = object.reactive.trigger(for: #selector(object.increment))
var counter = 0
signal.observeValues { counter += 1 }
expect(counter) == 0
expect(object.counter) == 0
object.increment()
expect(counter) == 1
expect(object.counter) == 1
object.increment()
expect(counter) == 2
expect(object.counter) == 2
}
it("should complete when the object deinitializes") {
let signal = object.reactive.trigger(for: #selector(object.increment))
var isCompleted = false
signal.observeCompleted { isCompleted = true }
expect(isCompleted) == false
object = nil
expect(_object).to(beNil())
expect(isCompleted) == true
}
it("should multicast") {
let signal1 = object.reactive.trigger(for: #selector(object.increment))
let signal2 = object.reactive.trigger(for: #selector(object.increment))
var counter1 = 0
var counter2 = 0
signal1.observeValues { counter1 += 1 }
signal2.observeValues { counter2 += 1 }
expect(counter1) == 0
expect(counter2) == 0
object.increment()
expect(counter1) == 1
expect(counter2) == 1
object.increment()
expect(counter1) == 2
expect(counter2) == 2
}
it("should not deadlock") {
for _ in 1 ... 10 {
var isDeadlocked = true
func createQueue() -> DispatchQueue {
if #available(*, macOS 10.10) {
return .global(qos: .userInitiated)
} else {
return .global(priority: .high)
}
}
createQueue().async {
_ = object.reactive.trigger(for: #selector(object.increment))
createQueue().async {
_ = object.reactive.trigger(for: #selector(object.increment))
isDeadlocked = false
}
}
expect(isDeadlocked).toEventually(beFalsy())
}
}
it("should send completed on deallocation") {
var completed = false
var deallocated = false
autoreleasepool {
let object = InterceptedObject()
object.reactive.lifetime.ended.observeCompleted {
deallocated = true
}
object.reactive.trigger(for: #selector(object.lifeIsGood)).observeCompleted {
completed = true
}
expect(deallocated) == false
expect(completed) == false
}
expect(deallocated) == true
expect(completed) == true
}
it("should send arguments for invocation and invoke the original method on previously KVO'd receiver") {
var latestValue: Bool?
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.startWithValues { objectValue in
latestValue = objectValue as! Bool?
}
expect(latestValue).to(beNil())
var firstValue: Bool?
var secondValue: String?
object.reactive
.signal(for: #selector(object.set(first:second:)))
.observeValues { x in
firstValue = x[0] as! Bool?
secondValue = x[1] as! String?
}
object.set(first: true, second: "Winner")
expect(object.hasInvokedSetObjectValueAndSecondObjectValue) == true
expect(object.objectValue as! Bool?) == true
expect(object.secondObjectValue as! String?) == "Winner"
expect(latestValue) == true
expect(firstValue) == true
expect(secondValue) == "Winner"
}
it("should send arguments for invocation and invoke the a KVO-swizzled then RAC-swizzled setter") {
var latestValue: Bool?
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.startWithValues { objectValue in
latestValue = objectValue as! Bool?
}
expect(latestValue).to(beNil())
var value: Bool?
object.reactive.signal(for: #selector(setter: object.objectValue)).observeValues { x in
value = x[0] as! Bool?
}
object.objectValue = true
expect(object.objectValue as! Bool?) == true
expect(latestValue) == true
expect(value) == true
}
it("should send arguments for invocation and invoke the a RAC-swizzled then KVO-swizzled setter") {
let object = InterceptedObject()
var value: Bool?
object.reactive.signal(for: #selector(setter: object.objectValue)).observeValues { x in
value = x[0] as! Bool?
}
var latestValue: Bool?
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.startWithValues { objectValue in
latestValue = objectValue as! Bool?
}
expect(latestValue).to(beNil())
object.objectValue = true
expect(object.objectValue as! Bool?) == true
expect(latestValue) == true
expect(value) == true
}
it("should send arguments for invocation and invoke the original method when receiver is subsequently KVO'd") {
let object = InterceptedObject()
var firstValue: Bool?
var secondValue: String?
object.reactive.signal(for: #selector(object.set(first:second:))).observeValues { x in
firstValue = x[0] as! Bool?
secondValue = x[1] as! String?
}
var latestValue: Bool?
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.startWithValues { objectValue in
latestValue = objectValue as! Bool?
}
expect(latestValue).to(beNil())
object.set(first: true, second: "Winner")
expect(object.hasInvokedSetObjectValueAndSecondObjectValue) == true
expect(object.objectValue as! Bool?) == true
expect(object.secondObjectValue as! String?) == "Winner"
expect(latestValue) == true
expect(firstValue) == true
expect(secondValue) == "Winner"
}
it("should send a value event for every invocation of a method on a receiver that is subsequently KVO'd twice") {
var counter = 0
object.reactive.trigger(for: #selector(setter: InterceptedObject.objectValue))
.observeValues { counter += 1 }
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
.dispose()
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
expect(counter) == 0
object.objectValue = 1
expect(counter) == 1
object.objectValue = 1
expect(counter) == 2
}
it("should send a value event for every invocation of a method on a receiver that is KVO'd twice while being swizzled by RAC in between") {
var counter = 0
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
.dispose()
object.reactive.trigger(for: #selector(setter: InterceptedObject.objectValue))
.observeValues { counter += 1 }
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
expect(counter) == 0
object.objectValue = 1
expect(counter) == 1
object.objectValue = 1
expect(counter) == 2
}
it("should call the right signal for two instances of the same class, adding signals for the same selector") {
let object1 = InterceptedObject()
let object2 = InterceptedObject()
let selector = NSSelectorFromString("lifeIsGood:")
var value1: Int?
object1.reactive.signal(for: selector).observeValues { x in
value1 = x[0] as! Int?
}
var value2: Int?
object2.reactive.signal(for: selector).observeValues { x in
value2 = x[0] as! Int?
}
object1.lifeIsGood(42)
expect(value1) == 42
expect(value2).to(beNil())
object2.lifeIsGood(420)
expect(value1) == 42
expect(value2) == 420
}
it("should send on signal after the original method is invoked") {
let object = InterceptedObject()
var invokedMethodBefore = false
object.reactive.trigger(for: #selector(object.set(first:second:))).observeValues {
invokedMethodBefore = object.hasInvokedSetObjectValueAndSecondObjectValue
}
object.set(first: true, second: "Winner")
expect(invokedMethodBefore) == true
}
}
describe("interoperability") {
var invoked: Bool!
var object: InterceptedObject!
var originalClass: AnyClass!
beforeEach {
invoked = false
object = InterceptedObject()
originalClass = InterceptedObject.self
}
it("should invoke the swizzled `forwardInvocation:` on an instance isa-swizzled by both RAC and KVO.") {
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
_ = object.reactive.trigger(for: #selector(object.lifeIsGood))
let swizzledSelector = #selector(object.lifeIsGood)
// Redirect `swizzledSelector` to the forwarding machinery.
let method = class_getInstanceMethod(originalClass, swizzledSelector)!
let typeEncoding = method_getTypeEncoding(method)
let original = class_replaceMethod(originalClass,
swizzledSelector,
_rac_objc_msgForward,
typeEncoding)
defer {
_ = class_replaceMethod(originalClass,
swizzledSelector,
original,
typeEncoding)
}
// Swizzle `forwardInvocation:` to intercept `swizzledSelector`.
let forwardInvocationBlock: @convention(block) (AnyObject, AnyObject) -> Void = { _, invocation in
if (invocation.selector == swizzledSelector) {
expect(invoked) == false
invoked = true
}
}
let method2 = class_getInstanceMethod(originalClass, ObjCSelector.forwardInvocation)!
let typeEncoding2 = method_getTypeEncoding(method2)
let original2 = class_replaceMethod(originalClass,
ObjCSelector.forwardInvocation,
imp_implementationWithBlock(forwardInvocationBlock as Any),
typeEncoding2)
defer {
_ = class_replaceMethod(originalClass,
ObjCSelector.forwardInvocation,
original2,
typeEncoding2)
}
object.lifeIsGood(nil)
expect(invoked) == true
}
it("should invoke the swizzled `forwardInvocation:` on an instance isa-swizzled by RAC.") {
_ = object.reactive.trigger(for: #selector(object.lifeIsGood))
let swizzledSelector = #selector(object.lifeIsGood)
// Redirect `swizzledSelector` to the forwarding machinery.
let method = class_getInstanceMethod(originalClass, swizzledSelector)!
let typeEncoding = method_getTypeEncoding(method)
let original = class_replaceMethod(originalClass,
swizzledSelector,
_rac_objc_msgForward,
typeEncoding)
defer {
_ = class_replaceMethod(originalClass,
swizzledSelector,
original,
typeEncoding)
}
// Swizzle `forwardInvocation:` to intercept `swizzledSelector`.
let forwardInvocationBlock: @convention(block) (AnyObject, AnyObject) -> Void = { _, invocation in
if (invocation.selector == swizzledSelector) {
expect(invoked) == false
invoked = true
}
}
let method2 = class_getInstanceMethod(originalClass, ObjCSelector.forwardInvocation)!
let typeEncoding2 = method_getTypeEncoding(method2)
let original2 = class_replaceMethod(originalClass,
ObjCSelector.forwardInvocation,
imp_implementationWithBlock(forwardInvocationBlock as Any),
typeEncoding2)
defer {
_ = class_replaceMethod(originalClass,
ObjCSelector.forwardInvocation,
original2,
typeEncoding2)
}
object.lifeIsGood(nil)
expect(invoked) == true
}
it("should invoke the swizzled selector on an instance isa-swizzled by RAC.") {
_ = object.reactive.trigger(for: #selector(object.lifeIsGood))
let swizzledSelector = #selector(object.lifeIsGood)
let lifeIsGoodBlock: @convention(block) (AnyObject, AnyObject) -> Void = { _ in
expect(invoked) == false
invoked = true
}
let method = class_getInstanceMethod(originalClass, swizzledSelector)!
let typeEncoding = method_getTypeEncoding(method)
let original = class_replaceMethod(originalClass,
swizzledSelector,
imp_implementationWithBlock(lifeIsGoodBlock as Any),
typeEncoding)
defer {
_ = class_replaceMethod(originalClass,
swizzledSelector,
original,
typeEncoding)
}
object.lifeIsGood(nil)
expect(invoked) == true
}
}
it("should swizzle an NSObject method") {
let object = NSObject()
var value: [Any?]?
object.reactive
.signal(for: #selector(getter: object.description))
.observeValues { x in
value = x
}
expect(value).to(beNil())
expect(object.description).notTo(beNil())
expect(value).toNot(beNil())
}
describe("a class that already overrides -forwardInvocation:") {
it("should invoke the superclass' implementation") {
let object = ForwardInvocationTestObject()
var value: Int?
object.reactive
.signal(for: #selector(object.lifeIsGood))
.observeValues { x in
value = x[0] as! Int?
}
object.lifeIsGood(42)
expect(value) == 42
expect(object.forwardedCount) == 0
object.perform(ForwardInvocationTestObject.forwardedSelector)
expect(object.forwardedCount) == 1
expect(object.forwardedSelector) == ForwardInvocationTestObject.forwardedSelector
}
it("should not infinite recurse when KVO'd after RAC swizzled") {
let object = ForwardInvocationTestObject()
var value: Int?
object.reactive
.signal(for: #selector(object.lifeIsGood))
.observeValues { x in
value = x[0] as! Int?
}
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
object.lifeIsGood(42)
expect(value) == 42
expect(object.forwardedCount) == 0
object.perform(ForwardInvocationTestObject.forwardedSelector)
expect(object.forwardedCount) == 1
expect(object.forwardedSelector) == ForwardInvocationTestObject.forwardedSelector
}
}
describe("two classes in the same hierarchy") {
var superclassObj: InterceptedObject!
var superclassTuple: [Any?]?
var subclassObj: InterceptedObjectSubclass!
var subclassTuple: [Any?]?
beforeEach {
superclassObj = InterceptedObject()
expect(superclassObj).notTo(beNil())
subclassObj = InterceptedObjectSubclass()
expect(subclassObj).notTo(beNil())
}
it("should not collide") {
superclassObj.reactive
.signal(for: #selector(InterceptedObject.foo))
.observeValues { args in
superclassTuple = args
}
subclassObj
.reactive
.signal(for: #selector(InterceptedObject.foo))
.observeValues { args in
subclassTuple = args
}
expect(superclassObj.foo(40, "foo")) == "Not Subclass 40 foo"
let expectedValues = [40, "foo"] as NSArray
expect(superclassTuple as NSArray?) == expectedValues
expect(subclassObj.foo(40, "foo")) == "Subclass 40 foo"
expect(subclassTuple as NSArray?) == expectedValues
}
it("should not collide when the superclass is invoked asynchronously") {
superclassObj.reactive
.signal(for: #selector(InterceptedObject.set(first:second:)))
.observeValues { args in
superclassTuple = args
}
subclassObj
.reactive
.signal(for: #selector(InterceptedObject.set(first:second:)))
.observeValues { args in
subclassTuple = args
}
superclassObj.set(first: "foo", second:"42")
expect(superclassObj.hasInvokedSetObjectValueAndSecondObjectValue) == true
let expectedValues = ["foo", "42"] as NSArray
expect(superclassTuple as NSArray?) == expectedValues
subclassObj.set(first: "foo", second:"42")
expect(subclassObj.hasInvokedSetObjectValueAndSecondObjectValue) == false
expect(subclassObj.hasInvokedSetObjectValueAndSecondObjectValue).toEventually(beTruthy())
expect(subclassTuple as NSArray?) == expectedValues
}
}
describe("class reporting") {
var object: InterceptedObject!
var originalClass: AnyClass!
beforeEach {
object = InterceptedObject()
originalClass = InterceptedObject.self
}
it("should report the original class") {
_ = object.reactive.trigger(for: #selector(object.lifeIsGood))
expect((object as AnyObject).objcClass).to(beIdenticalTo(originalClass))
}
it("should report the original class when it's KVO'd after dynamically subclassing") {
_ = object.reactive.trigger(for: #selector(object.lifeIsGood))
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
expect((object as AnyObject).objcClass).to(beIdenticalTo(originalClass))
}
it("should report the original class when it's KVO'd before dynamically subclassing") {
object.reactive
.values(forKeyPath: #keyPath(InterceptedObject.objectValue))
.start()
_ = object.reactive.trigger(for: #selector(object.lifeIsGood))
expect((object as AnyObject).objcClass).to(beIdenticalTo(originalClass))
}
}
describe("signal(for:)") {
var object: InterceptedObject!
weak var _object: InterceptedObject?
beforeEach {
object = InterceptedObject()
_object = object
}
afterEach {
object = nil
expect(_object).to(beNil())
}
it("should send a value with bridged numeric arguments") {
let signal = object.reactive.signal(for: #selector(object.testNumericValues(c:s:i:l:ll:uc:us:ui:ul:ull:f:d:b:)))
var arguments = [[Any?]]()
signal.observeValues { arguments.append($0) }
expect(arguments.count) == 0
func call(offset: UInt) {
object.testNumericValues(c: CChar.max - CChar(offset),
s: CShort.max - CShort(offset),
i: CInt.max - CInt(offset),
l: CLong.max - CLong(offset),
ll: CLongLong.max - CLongLong(offset),
uc: CUnsignedChar.max - CUnsignedChar(offset),
us: CUnsignedShort.max - CUnsignedShort(offset),
ui: CUnsignedInt.max - CUnsignedInt(offset),
ul: CUnsignedLong.max - CUnsignedLong(offset),
ull: CUnsignedLongLong.max - CUnsignedLongLong(offset),
f: CFloat.greatestFiniteMagnitude - CFloat(offset),
d: CDouble.greatestFiniteMagnitude - CDouble(offset),
b: offset % 2 == 0 ? true : false)
}
func validate(arguments: [Any?], offset: UInt) {
expect(arguments[0] as? CChar) == CChar.max - CChar(offset)
expect(arguments[1] as? CShort) == CShort.max - CShort(offset)
expect(arguments[2] as? CInt) == CInt.max - CInt(offset)
expect(arguments[3] as? CLong) == CLong.max - CLong(offset)
expect(arguments[4] as? CLongLong) == CLongLong.max - CLongLong(offset)
expect(arguments[5] as? CUnsignedChar) == CUnsignedChar.max - CUnsignedChar(offset)
expect(arguments[6] as? CUnsignedShort) == CUnsignedShort.max - CUnsignedShort(offset)
expect(arguments[7] as? CUnsignedInt) == CUnsignedInt.max - CUnsignedInt(offset)
expect(arguments[8] as? CUnsignedLong) == CUnsignedLong.max - CUnsignedLong(offset)
expect(arguments[9] as? CUnsignedLongLong) == CUnsignedLongLong.max - CUnsignedLongLong(offset)
expect(arguments[10] as? CFloat) == CFloat.greatestFiniteMagnitude - CFloat(offset)
expect(arguments[11] as? CDouble) == CDouble.greatestFiniteMagnitude - CDouble(offset)
expect(arguments[12] as? CBool) == (offset % 2 == 0 ? true : false)
}
call(offset: 0)
expect(arguments.count) == 1
validate(arguments: arguments[0], offset: 0)
call(offset: 1)
expect(arguments.count) == 2
validate(arguments: arguments[1], offset: 1)
call(offset: 2)
expect(arguments.count) == 3
validate(arguments: arguments[2], offset: 2)
}
it("should send a value with bridged reference arguments") {
let signal = object.reactive.signal(for: #selector(object.testReferences(nonnull:nullable:iuo:class:nullableClass:iuoClass:)))
var arguments = [[Any?]]()
signal.observeValues { arguments.append($0) }
expect(arguments.count) == 0
let token = NSObject()
object.testReferences(nonnull: token,
nullable: token,
iuo: token,
class: InterceptingSpec.self,
nullableClass: InterceptingSpec.self,
iuoClass: InterceptingSpec.self)
expect(arguments.count) == 1
expect((arguments[0][0] as! NSObject)) == token
expect(arguments[0][1] as! NSObject?) == token
expect(arguments[0][2] as! NSObject?) == token
expect(arguments[0][3] as! AnyClass is InterceptingSpec.Type) == true
expect(arguments[0][4] as! AnyClass? is InterceptingSpec.Type) == true
expect(arguments[0][5] as! AnyClass? is InterceptingSpec.Type) == true
object.testReferences(nonnull: token,
nullable: nil,
iuo: nil,
class: InterceptingSpec.self,
nullableClass: nil,
iuoClass: nil)
expect(arguments.count) == 2
expect((arguments[1][0] as! NSObject)) == token
expect(arguments[1][1] as! NSObject?).to(beNil())
expect(arguments[1][2] as! NSObject?).to(beNil())
expect(arguments[1][3] as! AnyClass is InterceptingSpec.Type) == true
expect(arguments[1][4] as! AnyClass?).to(beNil())
expect(arguments[1][5] as! AnyClass?).to(beNil())
}
it("should send a value with bridged struct arguments") {
let signal = object.reactive.signal(for: #selector(object.testBridgedStructs(p:s:r:a:)))
var arguments = [[Any?]]()
signal.observeValues { arguments.append($0) }
expect(arguments.count) == 0
func call(offset: CGFloat) {
object.testBridgedStructs(p: CGPoint(x: offset, y: offset),
s: CGSize(width: offset, height: offset),
r: CGRect(x: offset, y: offset, width: offset, height: offset),
a: CGAffineTransform(translationX: offset, y: offset))
}
func validate(arguments: [Any?], offset: CGFloat) {
expect((arguments[0] as! CGPoint)) == CGPoint(x: offset, y: offset)
expect((arguments[1] as! CGSize)) == CGSize(width: offset, height: offset)
expect((arguments[2] as! CGRect)) == CGRect(x: offset, y: offset, width: offset, height: offset)
expect((arguments[3] as! CGAffineTransform)) == CGAffineTransform(translationX: offset, y: offset)
}
call(offset: 0)
expect(arguments.count) == 1
validate(arguments: arguments[0], offset: 0)
call(offset: 1)
expect(arguments.count) == 2
validate(arguments: arguments[1], offset: 1)
call(offset: 2)
expect(arguments.count) == 3
validate(arguments: arguments[2], offset: 2)
}
it("should complete when the object deinitializes") {
let signal = object.reactive.signal(for: #selector(object.increment))
var isCompleted = false
signal.observeCompleted { isCompleted = true }
expect(isCompleted) == false
object = nil
expect(_object).to(beNil())
expect(isCompleted) == true
}
it("should multicast") {
let signal1 = object.reactive.signal(for: #selector(object.increment))
let signal2 = object.reactive.signal(for: #selector(object.increment))
var counter1 = 0
var counter2 = 0
signal1.observeValues { _ in counter1 += 1 }
signal2.observeValues { _ in counter2 += 1 }
expect(counter1) == 0
expect(counter2) == 0
object.increment()
expect(counter1) == 1
expect(counter2) == 1
object.increment()
expect(counter1) == 2
expect(counter2) == 2
}
it("should not deadlock") {
for _ in 1 ... 10 {
var isDeadlocked = true
DispatchQueue.global(priority: .high).async {
_ = object.reactive.signal(for: #selector(object.increment))
DispatchQueue.global(priority: .high).async {
_ = object.reactive.signal(for: #selector(object.increment))
isDeadlocked = false
}
}
expect(isDeadlocked).toEventually(beFalsy())
}
}
}
}
}
private class ForwardInvocationTestObject: InterceptedObject {
static let forwardedSelector = Selector((("forwarded")))
var forwardedCount = 0
var forwardedSelector: Selector?
override open class func initialize() {
struct Static {
static var token: Int = {
let impl: @convention(c) (Any, Selector, AnyObject) -> Void = { object, _, invocation in
let object = object as! ForwardInvocationTestObject
object.forwardedCount += 1
object.forwardedSelector = invocation.selector
}
let success = class_addMethod(ForwardInvocationTestObject.self,
ObjCSelector.forwardInvocation,
unsafeBitCast(impl, to: IMP.self),
ObjCMethodEncoding.forwardInvocation)
assert(success)
assert(ForwardInvocationTestObject.instancesRespond(to: ObjCSelector.forwardInvocation))
let success2 = class_addMethod(ForwardInvocationTestObject.self,
ForwardInvocationTestObject.forwardedSelector,
_rac_objc_msgForward,
ObjCMethodEncoding.forwardInvocation)
assert(success2)
assert(ForwardInvocationTestObject.instancesRespond(to: ForwardInvocationTestObject.forwardedSelector))
return 0
}()
}
_ = Static.token
}
}
@objc private protocol NSInvocationProtocol {
var target: NSObject { get }
var selector: Selector { get }
func invoke()
}
private class InterceptedObjectSubclass: InterceptedObject {
dynamic override func foo(_ number: Int, _ string: String) -> String {
return "Subclass \(number) \(string)"
}
dynamic override func set(first: Any?, second: Any?) {
DispatchQueue.main.async {
super.set(first: first, second: second)
}
}
}
private class InterceptedObject: NSObject {
var counter = 0
dynamic var hasInvokedSetObjectValueAndSecondObjectValue = false
dynamic var objectValue: Any?
dynamic var secondObjectValue: Any?
dynamic func increment() {
counter += 1
}
dynamic func foo(_ number: Int, _ string: String) -> String {
return "Not Subclass \(number) \(string)"
}
dynamic func lifeIsGood(_ value: Any?) {}
dynamic func set(first: Any?, second: Any?) {
objectValue = first
secondObjectValue = second
hasInvokedSetObjectValueAndSecondObjectValue = true
}
dynamic func testNumericValues(c: CChar, s: CShort, i: CInt, l: CLong, ll: CLongLong, uc: CUnsignedChar, us: CUnsignedShort, ui: CUnsignedInt, ul: CUnsignedLong, ull: CUnsignedLongLong, f: CFloat, d: CDouble, b: CBool) {}
dynamic func testReferences(nonnull: NSObject, nullable: NSObject?, iuo: NSObject!, class: AnyClass, nullableClass: AnyClass?, iuoClass: AnyClass!) {}
dynamic func testBridgedStructs(p: CGPoint, s: CGSize, r: CGRect, a: CGAffineTransform) {}
}
| mit | 2d47e332f94f31b61aa1addc75b2c7d8 | 29.784615 | 222 | 0.643321 | 4.041258 | false | false | false | false |
ericmarkmartin/Nightscouter2 | Nightscouter Watch App Extension/SitesTableInterfaceController.swift | 1 | 4419 | //
// SitesTableInterfaceController.swift
// Nightscouter
//
// Created by Peter Ina on 10/4/15.
// Copyright © 2015 Peter Ina. All rights reserved.
//
import WatchKit
import NightscouterWatchKit
class SitesTableInterfaceController: WKInterfaceController {
struct ControllerName {
static let SiteDetail: String = "SiteDetail"
}
struct RowIdentifier {
static let rowSiteTypeIdentifier = "SiteRowController"
static let rowEmptyTypeIdentifier = "SiteEmptyRowController"
static let rowUpdateTypeIdentifier = "SiteUpdateRowController"
}
@IBOutlet var sitesTable: WKInterfaceTable!
@IBOutlet var sitesLoading: WKInterfaceLabel!
var sites: [Site] = [] {
didSet {
self.updateTableData()
}
}
var lastUpdatedTime: NSDate? {
didSet {
if let date = lastUpdatedTime {
timeStamp = AppConfiguration.lastUpdatedFromPhoneDateFormatter.stringFromDate(date)
}
sitesLoading.setHidden(!self.sites.isEmpty)
}
}
var timeStamp: String = ""
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
print(">>> Entering \(__FUNCTION__) <<<")
self.updateTableData()
// TODO: If there is only one site in the array, push to the detail controller right away. If a new or second one is added dismiss and return to table view.
// TODO: Faking a data transfter date.
// TODO: Need to update the table when data changes... also need to call updateTable if empty to show an empty row.
NSNotificationCenter.defaultCenter().addObserverForName(DataUpdatedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (_) -> Void in
self.sites = SitesDataSource.sharedInstance.sites
self.lastUpdatedTime = NSDate()
// self.updateTableData()
}
// WatchSessionManager.sharedManager.startSearching()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
// create object.
// push controller...
print(">>> Entering \(__FUNCTION__) <<<")
SitesDataSource.sharedInstance.lastViewedSiteIndex = rowIndex
// let site = sites[rowIndex]
// let mvm = site.generateSummaryModelViewModel()
// print(mvm)
// push relevant context over to the detail page.
pushControllerWithName(ControllerName.SiteDetail, context: [DefaultKey.lastViewedSiteIndex.rawValue: rowIndex])
}
private func updateTableData() {
print(">>> Entering \(__FUNCTION__) <<<")
if self.sites.isEmpty {
self.sitesLoading.setHidden(true)
self.sitesTable.setNumberOfRows(1, withRowType: RowIdentifier.rowEmptyTypeIdentifier)
let row = self.sitesTable.rowControllerAtIndex(0) as? SiteEmptyRowController
if let row = row {
row.messageLabel.setText(LocalizedString.emptyTableViewCellTitle.localized)
}
} else {
self.sitesLoading.setHidden(true)
var rowSiteType = self.sites.map{ _ in RowIdentifier.rowSiteTypeIdentifier }
rowSiteType.append(RowIdentifier.rowUpdateTypeIdentifier)
self.sitesTable.setRowTypes(rowSiteType)
for (index, site) in self.sites.enumerate() {
if let row = self.sitesTable.rowControllerAtIndex(index) as? SiteRowController {
let mvm = site.generateSummaryModelViewModel()
row.configure(withDataSource: mvm, delegate: mvm)
}
}
let updateRow = self.sitesTable.rowControllerAtIndex(self.sites.count) as? SiteUpdateRowController
if let updateRow = updateRow {
updateRow.siteLastReadingLabel.setText(self.timeStamp)
updateRow.siteLastReadingLabelHeader.setText(LocalizedString.updateDateFromPhoneString.localized)
}
}
}
@IBAction func updateButton() {
WatchSessionManager.sharedManager.requestCompanionAppUpdate()
}
}
| mit | 65a851bb6e0b3a46a556460321483f42 | 35.213115 | 164 | 0.625622 | 5.414216 | false | true | false | false |
brianjmoore/material-components-ios | components/TextFields/examples/supplemental/TextFieldKitchenSinkExampleSupplemental.swift | 1 | 19616 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// swiftlint:disable file_length
// swiftlint:disable line_length
// swiftlint:disable type_body_length
// swiftlint:disable function_body_length
import UIKit
extension TextFieldKitchenSinkSwiftExample {
func setupExampleViews() {
view.backgroundColor = UIColor(white:0.97, alpha: 1.0)
title = "Material Text Fields"
let textFieldControllersFullWidth = setupFullWidthTextFields()
allTextFieldControllers = [setupFilledTextFields(), setupDefaultTextFields(),
textFieldControllersFullWidth,
setupFloatingTextFields(),
setupSpecialTextFields()].flatMap { $0 as! [MDCTextInputController] }
let multilineTextFieldControllersFullWidth = setupFullWidthMultilineTextFields()
allMultilineTextFieldControllers = [setupAreaTextFields(), setupDefaultMultilineTextFields(),
multilineTextFieldControllersFullWidth,
setupFloatingMultilineTextFields(),
setupSpecialMultilineTextFields()].flatMap { $0 as! [MDCTextInputController] }
controllersFullWidth = textFieldControllersFullWidth + multilineTextFieldControllersFullWidth
allInputControllers = allTextFieldControllers + allMultilineTextFieldControllers
setupScrollView()
NotificationCenter.default.addObserver(self,
selector: #selector(TextFieldKitchenSinkSwiftExample.contentSizeCategoryDidChange(notif:)),
name:.UIContentSizeCategoryDidChange,
object: nil)
}
func setupButton() -> MDCButton {
let button = MDCButton()
button.setTitleColor(.white, for: .normal)
button.mdc_adjustsFontForContentSizeCategory = true
button.translatesAutoresizingMaskIntoConstraints = false
return button
}
func setupControls() -> [UIView] {
let container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(container)
container.addSubview(errorLabel)
let errorSwitch = UISwitch()
errorSwitch.translatesAutoresizingMaskIntoConstraints = false
errorSwitch.addTarget(self,
action: #selector(TextFieldKitchenSinkSwiftExample.errorSwitchDidChange(errorSwitch:)),
for: .touchUpInside)
container.addSubview(errorSwitch)
errorSwitch.accessibilityLabel = "Show errors"
container.addSubview(helperLabel)
let helperSwitch = UISwitch()
helperSwitch.translatesAutoresizingMaskIntoConstraints = false
helperSwitch.addTarget(self,
action: #selector(TextFieldKitchenSinkSwiftExample.helperSwitchDidChange(helperSwitch:)),
for: .touchUpInside)
container.addSubview(helperSwitch)
helperSwitch.accessibilityLabel = "Helper text"
let views = ["errorLabel": errorLabel, "errorSwitch": errorSwitch,
"helperLabel": helperLabel, "helperSwitch": helperSwitch]
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat:
"H:|-[errorLabel]-[errorSwitch]|", options: [.alignAllCenterY], metrics: nil, views: views))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat:
"H:|-[helperLabel]-[helperSwitch]|", options: [.alignAllCenterY], metrics: nil, views: views))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat:
"V:|-[errorSwitch]-[helperSwitch]|", options: [], metrics: nil, views: views))
textInsetsModeButton.addTarget(self,
action: #selector(textInsetsModeButtonDidTouch(button:)),
for: .touchUpInside)
textInsetsModeButton.setTitle("Text Insets Mode: If Content", for: .normal)
scrollView.addSubview(textInsetsModeButton)
characterModeButton.addTarget(self,
action: #selector(textFieldModeButtonDidTouch(button:)),
for: .touchUpInside)
characterModeButton.setTitle("Character Count Mode: Always", for: .normal)
scrollView.addSubview(characterModeButton)
clearModeButton.addTarget(self,
action: #selector(textFieldModeButtonDidTouch(button:)),
for: .touchUpInside)
clearModeButton.setTitle("Clear Button Mode: While Editing", for: .normal)
scrollView.addSubview(clearModeButton)
underlineButton.addTarget(self,
action: #selector(textFieldModeButtonDidTouch(button:)),
for: .touchUpInside)
underlineButton.setTitle("Underline Mode: While Editing", for: .normal)
scrollView.addSubview(underlineButton)
return [container, textInsetsModeButton, characterModeButton, underlineButton, clearModeButton]
}
func setupSectionLabels() {
scrollView.addSubview(controlLabel)
scrollView.addSubview(singleLabel)
scrollView.addSubview(multiLabel)
NSLayoutConstraint(item: singleLabel,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leadingMargin,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: singleLabel,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailingMargin,
multiplier: 1,
constant: 0).isActive = true
}
func setupScrollView() {
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(
withVisualFormat: "V:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView": scrollView]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView": scrollView]))
let marginOffset: CGFloat = 16
let margins = UIEdgeInsets(top: 0, left: marginOffset, bottom: 0, right: marginOffset)
scrollView.layoutMargins = margins
setupSectionLabels()
let prefix = "view"
let concatenatingClosure = {
(accumulator, object: AnyObject) in
accumulator + "-[" + self.unique(from: object, with: prefix) +
"]"
}
let allControls = setupControls()
let controlsString = allControls.reduce("", concatenatingClosure)
var controls = [String: UIView]()
allControls.forEach { control in
controls[unique(from: control, with: prefix)] =
control
}
let allTextFields = allTextFieldControllers.flatMap { $0.textInput }
let textFieldsString = allTextFields.reduce("", concatenatingClosure)
var textFields = [String: UIView]()
allTextFields.forEach { textInput in
textFields[unique(from: textInput, with: prefix)] = textInput
}
let allTextViews = allMultilineTextFieldControllers.flatMap { $0.textInput }
let textViewsString = allTextViews.reduce("", concatenatingClosure)
var textViews = [String: UIView]()
allTextViews.forEach { input in
textViews[unique(from: input, with: prefix)] = input
}
let visualString = "V:[singleLabel]" +
textFieldsString + "[unstyledTextField]-20-[multiLabel]" + textViewsString +
"[unstyledTextView]-10-[controlLabel]" + controlsString
let labels: [String: UIView] = ["controlLabel": controlLabel,
"singleLabel": singleLabel,
"multiLabel": multiLabel,
"unstyledTextField": unstyledTextField,
"unstyledTextView": unstyledMultilineTextField]
var views = [String: UIView]()
let dictionaries = [labels, textFields, controls, textViews]
dictionaries.forEach { dictionary in
dictionary.forEach { (key, value) in
views[key] = value
// We have a scrollview and we're adding some elements that are subclassed from scrollviews.
// So constraints need to be in relation to something that doesn't have a content size.
// We'll use the view controller's view.
let leading = NSLayoutConstraint(item: value,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leadingMargin,
multiplier: 1.0,
constant: 0.0)
leading.priority = 750.0
leading.isActive = true
let trailing = NSLayoutConstraint(item: value,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0)
trailing.priority = 750.0
trailing.isActive = true
}
}
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: visualString,
options: [.alignAllCenterX],
metrics: nil,
views: views))
controllersFullWidth.flatMap { $0.textInput }.forEach { textInput in
NSLayoutConstraint(item: textInput,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: textInput,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
// This constraint is necessary for the scrollview to have a content width.
NSLayoutConstraint(item: textInput,
attribute: .trailing,
relatedBy: .equal,
toItem: scrollView,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
}
// These used to be done in the visual format string but iOS 11 changed that.
#if swift(>=3.2)
if #available(iOS 11.0, *) {
NSLayoutConstraint(item: singleLabel,
attribute: .topMargin,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .top,
multiplier: 1.0,
constant: 20).isActive = true
NSLayoutConstraint(item: allControls.last as Any,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .bottomMargin,
multiplier: 1.0,
constant: -20).isActive = true
} else {
NSLayoutConstraint(item: singleLabel,
attribute: .topMargin,
relatedBy: .equal,
toItem: scrollView,
attribute: .top,
multiplier: 1.0,
constant: 20).isActive = true
NSLayoutConstraint(item: allControls.last as Any,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView,
attribute: .bottomMargin,
multiplier: 1.0,
constant: -20).isActive = true
}
#else
NSLayoutConstraint(item: singleLabel,
attribute: .topMargin,
relatedBy: .equal,
toItem: scrollView,
attribute: .top,
multiplier: 1.0,
constant: 20).isActive = true
NSLayoutConstraint(item: allControls.last as Any,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView,
attribute: .bottomMargin,
multiplier: 1.0,
constant: -20).isActive = true
#endif
registerKeyboardNotifications()
addGestureRecognizer()
}
func addGestureRecognizer() {
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapDidTouch(sender: )))
self.scrollView.addGestureRecognizer(tapRecognizer)
}
func registerKeyboardNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(TextFieldKitchenSinkSwiftExample.keyboardWillShow(notif:)),
name: .UIKeyboardWillShow,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(TextFieldKitchenSinkSwiftExample.keyboardWillShow(notif:)),
name: .UIKeyboardWillChangeFrame,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(TextFieldKitchenSinkSwiftExample.keyboardWillHide(notif:)),
name: .UIKeyboardWillHide,
object: nil)
}
@objc func keyboardWillShow(notif: Notification) {
guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
return
}
scrollView.contentInset = UIEdgeInsets(top: 0.0,
left: 0.0,
bottom: frame.height,
right: 0.0)
}
@objc func keyboardWillHide(notif: Notification) {
scrollView.contentInset = UIEdgeInsets()
}
func unique(from input: AnyObject, with prefix: String) -> String {
return prefix + String(describing: Unmanaged.passUnretained(input).toOpaque())
}
}
extension TextFieldKitchenSinkSwiftExample {
// 3 of the 'mode' buttons all are similar. The following code is shared by them
@objc func textFieldModeButtonDidTouch(button: MDCButton) {
var controllersToChange = allInputControllers
var partialTitle = ""
if button == characterModeButton {
partialTitle = "Character Count Mode"
controllersToChange = controllersWithCharacterCount
} else if button == clearModeButton {
partialTitle = "Clear Button Mode"
controllersToChange = allTextFieldControllers
} else {
partialTitle = "Underline View Mode"
}
let closure: (UITextFieldViewMode, String) -> Void = { mode, title in
controllersToChange.forEach { controller in
if button == self.characterModeButton {
controller.characterCountViewMode = mode
} else if button == self.clearModeButton {
if let input = controller.textInput as? MDCTextField {
input.clearButtonMode = mode
}
} else {
controller.underlineViewMode = mode
}
button.setTitle(title + ": " + self.modeName(mode: mode), for: .normal)
}
}
let alert = UIAlertController(title: partialTitle,
message: nil,
preferredStyle: .alert)
presentAlert(alert: alert, partialTitle: partialTitle, closure: closure)
}
func presentAlert (alert: UIAlertController,
partialTitle: String,
closure: @escaping (_ mode: UITextFieldViewMode, _ title: String) -> Void) -> Void {
for rawMode in 0...3 {
let mode = UITextFieldViewMode(rawValue: rawMode)!
alert.addAction(UIAlertAction(title: modeName(mode: mode),
style: .default,
handler: { _ in
closure(mode, partialTitle)
}))
}
present(alert, animated: true, completion: nil)
}
func modeName(mode: UITextFieldViewMode) -> String {
switch mode {
case .always:
return "Always"
case .whileEditing:
return "While Editing"
case .unlessEditing:
return "Unless Editing"
case .never:
return "Never"
}
}
}
extension TextFieldKitchenSinkSwiftExample {
// The 'text insets' button does not have the same options as the other mode buttons
@objc func textInsetsModeButtonDidTouch(button: MDCButton) {
let closure: (MDCTextInputTextInsetsMode, String) -> Void = { mode, title in
self.allInputControllers.forEach { controller in
guard let input = controller.textInput as? MDCTextInput else {
return
}
input.textInsetsMode = mode
button.setTitle(title + ": " + self.textInsetsModeName(mode: mode), for: .normal)
}
}
let title = "Text Insets Mode"
let alert = UIAlertController(title: title,
message: nil,
preferredStyle: .alert)
for rawMode: UInt in 0...2 {
let mode = MDCTextInputTextInsetsMode(rawValue: rawMode)!
alert.addAction(UIAlertAction(title: textInsetsModeName(mode: mode),
style: .default,
handler: { _ in
closure(mode, title)
}))
}
present(alert, animated: true, completion: nil)
}
func textInsetsModeName(mode: MDCTextInputTextInsetsMode) -> String {
switch mode {
case .always:
return "Always"
case .ifContent:
return "If Content"
case .never:
return "Never"
}
}
}
extension TextFieldKitchenSinkSwiftExample {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension TextFieldKitchenSinkSwiftExample {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Text Field", "Kitchen Sink"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
}
| apache-2.0 | 675a66dc3ce240932612aacb4a6eda8d | 38.232 | 134 | 0.579578 | 5.788138 | false | false | false | false |
pietro82/TransitApp | TransitApp/PlaceDataManager.swift | 1 | 3221 | //
// DataManager.swift
// TransitApp
//
// Created by Pietro Santececca on 23/01/17.
// Copyright © 2017 Tecnojam. All rights reserved.
//
import Alamofire
import MapKit
class PlaceDataManager {
static func retreivePlacesFromGoogle(lat: Double, lon: Double, input: String, completion: @escaping ([Place]) -> Void) {
let parameters: [String: String] = [
"input": input,
"key": Constants.googleKey,
"location": "\(lat),\(lon)",
"radius": Constants.googleSearchRadius
]
Alamofire.request(Constants.googleSearchBaseUrl, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.responseJSON { response in
guard response.result.isSuccess else {
print("Error while fetching google search results: \(response.result.error)")
return
}
if let resultResponse = response.result.value as? [String:Any], resultResponse["status"] as? String == "OK" {
var placeArray = [Place]()
if let predictions = resultResponse["predictions"] as? [AnyObject] {
for (i, prediction) in predictions.enumerated() where i < 3 {
if let description = prediction["description"] as? String,
let placeId = prediction["place_id"] as? String {
let place = Place(id: placeId, description: description)
placeArray.append(place)
}
}
}
completion(placeArray)
}
}
}
static func retreivePlaceDetailsFromGoogle(placeId: String, placeDescription: String, completion: @escaping (Place) -> Void) {
var place = Place(id: placeId, description: placeDescription)
let parameters: [String: String] = [
"placeid": place.id,
"key": Constants.googleKey,
]
Alamofire.request(Constants.googleDetailsBaseUrl, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.responseJSON { response in
guard response.result.isSuccess else {
print("Error while fetching google detail result: \(response.result.error)")
return
}
if let resultResponse = response.result.value as? [String:Any],
resultResponse["status"] as? String == "OK",
let result = resultResponse["result"] as? [String:Any],
let geometry = result["geometry"] as? [String:Any],
let location = geometry["location"] as? [String:Any],
let latitude = location["lat"] as? CLLocationDegrees,
let longitude = location["lng"] as? CLLocationDegrees
{
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
place.coordinate = coordinate
completion(place)
}
}
}
}
| mit | a0be217a3c32940279cd375b272e4761 | 38.268293 | 140 | 0.544099 | 5.160256 | false | false | false | false |
interstateone/Fresh | Fresh/Components/Sound List/SoundListCellView.swift | 1 | 942 | //
// SoundListCellView.swift
// Fresh
//
// Created by Brandon Evans on 2016-01-08.
// Copyright © 2016 Brandon Evans. All rights reserved.
//
import Cocoa
class SoundListCellView: NSTableCellView {
@IBOutlet var trackNameField: NSTextField!
@IBOutlet var authorNameField: NSTextField!
@IBOutlet var playingImageView: NSImageView!
var playing: Bool = false {
didSet {
playingImageView.hidden = !playing
}
}
override var backgroundStyle: NSBackgroundStyle {
didSet {
guard let row = superview as? NSTableRowView else { return }
if row.selected {
trackNameField.textColor = .whiteColor()
authorNameField.textColor = .whiteColor()
}
else {
trackNameField.textColor = .blackColor()
authorNameField.textColor = .darkGrayColor()
}
}
}
}
| mit | 051788e8a17f5cb8388339bfaa5db259 | 25.138889 | 72 | 0.597237 | 5.005319 | false | false | false | false |
Virpik/T | src/UI/TableView/TableViewModel/TableViewModel.swift | 1 | 7384 | //
// TImage.swift
// TDemo
//
// Created by Virpik on 26/10/2017.
// Copyright © 2017 Virpik. All rights reserved.
//
import Foundation
import UIKit
open class TableViewModel: NSObject, UITableViewDelegate, UITableViewDataSource {
public let tableView: UITableView
public var sections: [[AnyRowModel]] = []
// public var moveHandlers: MoveHandlers? {
// set(handlers) {
// self._managerMoveCells.handlers = handlers
// }
//
// get {
// return self._managerMoveCells.handlers
// }
// }
//
public var handlers: Handlers = Handlers()
public var cellMoviesPressDuration: TimeInterval {
get {
return self.managerMoveCells.cellMoviesPressDuration
}
set(value) {
self.managerMoveCells.cellMoviesPressDuration = value
}
}
public lazy var managerMoveCells: ManagerMoveCells = {
let ds = TableViewModel.ManagerMoveCells.DataSourse { (indexPath) -> AnyRowModel? in
return self.sections[indexPath.section][indexPath.row]
}
return ManagerMoveCells(tableView: self.tableView, dataSourse: ds)
}()
private var _cashHeightRows: [IndexPath: CGSize] = [:]
public init (tableView: UITableView, handlers: Handlers? = nil) {
self.tableView = tableView
if let handlers = handlers {
self.handlers = handlers
}
super.init()
self.tableView.delegate = self
self.tableView.dataSource = self
var mHandlers = MoveHandlers()
mHandlers.handlerBeginMove = { context in
//
self.handlers.moveHandlers?.handlerBeginMove?(context)
}
mHandlers.handlerMove = { atContext, toContext in
//
self.handlers.moveHandlers?.handlerMove?(atContext, toContext)
}
mHandlers.handlerDidMove = { atContex, toContext in
let atIndexPath = atContex.indexPath
let toIndexPath = toContext.indexPath
let item = self.sections[atIndexPath.section][atIndexPath.row]
self.sections[atIndexPath.section].remove(at: atIndexPath.row)
self.sections[toIndexPath.section].insert(item, at: toIndexPath.row)
self.handlers.moveHandlers?.handlerDidMove?(atContex, toContext)
}
mHandlers.handlerEndMove = { atContext, toContext in
//
self.handlers.moveHandlers?.handlerEndMove?(atContext, toContext)
}
self.managerMoveCells.handlers = mHandlers
}
public func set(sections: [[AnyRowModel]]){
self.sections = sections
sections.forEach {
$0.forEach({ (rowModel) in
if rowModel.rowType.self == UITableViewCell.self {
return
}
self.tableView.register(type: rowModel.rowType.self, isNib: rowModel.isNib)
})
}
self.tableView.reloadData()
}
public func reload(rows: [Row]) {
rows.forEach { (row) in
self.sections[row.indexPath.section][row.indexPath.row] = row.rowModel
if let cell = self.tableView.cellForRow(at: row.indexPath) {
row.rowModel.build(cell: cell, indexPath: row.indexPath)
}
}
}
public func remove(sections: [[AnyRowModel]], indexPaths: [IndexPath], animation: UITableView.RowAnimation = .bottom) {
self.tableView.beginUpdates()
self.sections = sections
self.tableView.deleteRows(at: indexPaths, with: animation)
self.tableView.endUpdates()
}
public func update(sections: [[AnyRowModel]], indexPaths: [IndexPath], animation: UITableView.RowAnimation = .automatic) {
self.tableView.beginUpdates()
self.sections = sections
self.tableView.reloadRows(at: indexPaths, with: animation)
self.tableView.endUpdates()
}
public func insert(sections: [[AnyRowModel]], indexPaths: [IndexPath], animation: UITableView.RowAnimation = .bottom) {
self.tableView.beginUpdates()
self.sections = sections
self.tableView.insertRows(at: indexPaths, with: animation)
self.tableView.endUpdates()
}
public func insert(rows: [Row]) {
self.tableView.beginUpdates()
rows.forEach { row in
self.sections[row.indexPath.section].insert(row.rowModel, at: row.indexPath.row)
self.tableView.insertRows(at: [row.indexPath], with: row.animation)
}
self.tableView.endUpdates()
}
public func replace(rows: [Row]) {
self.tableView.beginUpdates()
rows.forEach { row in
self.sections[row.indexPath.section][row.indexPath.row] = row.rowModel
self.tableView.reloadRows(at: [row.indexPath], with: row.animation)
}
self.tableView.endUpdates()
}
public func remove(rows: [(IndexPath, UITableView.RowAnimation)]) {
self.tableView.beginUpdates()
rows.forEach { row in
self.sections[row.0.section].remove(at: row.0.row)
self.tableView.deleteRows(at: [row.0], with: row.1)
}
self.tableView.endUpdates()
}
// MARK: - scroll view
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
// tLog(scrollView.contentOffset)
self.handlers.handlerDidScroll?(scrollView)
}
open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
// tLog(scrollView.contentOffset)
}
// MARK: - Table view delegate && data sourse
open func numberOfSections(in tableView: UITableView) -> Int {
return self.sections.count
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.sections[indexPath.section][indexPath.row].rowHeight ?? tableView.rowHeight
}
open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return self._cashHeightRows[indexPath]?.height ?? tableView.estimatedRowHeight
}
open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
self._cashHeightRows[indexPath] = cell.bounds.size
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sections[section].count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = self.sections[indexPath.section][indexPath.row]
guard let cell = self.tableView.cell(type: model.rowType) else {
return UITableViewCell()
}
model.build(cell: cell, indexPath: indexPath)
return cell
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model = self.sections[indexPath.section][indexPath.row]
guard let cell = self.tableView.cellForRow(at: indexPath) else {
return
}
model.didSelect(cell: cell, indexPath: indexPath)
}
}
| mit | 5fabe4965c6814f1a020da954ce5dfbf | 30.021008 | 126 | 0.616687 | 4.77555 | false | false | false | false |
donald-pinckney/awesome-playgrounds | Physics/Schrödinger.playground/Sources/Plotting/Vector/Vector-functions.swift | 1 | 1743 | import Foundation
// Math functions
func applyFunc(var v: Vector, _ f: Double -> Double) -> Vector {
for i in 0..<v.count {
v[i] = f(v[i])
}
return v
}
public func sin(v: Vector) -> Vector {
return applyFunc(v, sin)
}
public func cos(v: Vector) -> Vector {
return applyFunc(v, cos)
}
public func tan(v: Vector) -> Vector {
return applyFunc(v, tan)
}
public func ln(v: Vector) -> Vector {
return applyFunc(v, log)
}
public func exp(v: Vector) -> Vector {
return applyFunc(v, exp)
}
public func scale(v: Vector, _ a: Double) -> Vector {
return applyFunc(v) { a * $0 }
}
public func dot(a: Vector, _ b: Vector) -> Double {
assert(a.count == b.count)
var ret = 0.0
for i in 0..<a.count {
ret += a[i] * b[i]
}
return ret
}
public func add(var a: Vector, _ b: Vector) -> Vector {
assert(a.count == b.count)
for i in 0..<a.count {
a[i] += b[i]
}
return a
}
public func add(var a: Vector, _ b: Double) -> Vector {
for i in 0..<a.count {
a[i] += b
}
return a
}
public func subtract(var a: Vector, _ b: Vector) -> Vector {
assert(a.count == b.count)
for i in 0..<a.count {
a[i] -= b[i]
}
return a
}
public func multiply(var a: Vector, _ b: Vector) -> Vector {
assert(a.count == b.count)
for i in 0..<a.count {
a[i] *= b[i]
}
return a
}
public func max(a: Vector) -> Double {
var x = a.values[0]
for d in a.values {
if d > x {
x = d
}
}
return x
}
public func min(a: Vector) -> Double {
var x = a.values[0]
for d in a.values {
if d < x {
x = d
}
}
return x
}
| mit | 0ead4d9d0618dd2ac0c5cf09d16f0c60 | 16.088235 | 64 | 0.511761 | 2.954237 | false | false | false | false |
iAugux/iBBS-Swift | iBBS/IBBSRegisterViewController.swift | 1 | 7884 | //
// IBBSRegisterViewController.swift
// iBBS
//
// Created by Augus on 9/23/15.
// Copyright © 2015 iAugus. All rights reserved.
//
import UIKit
import SnapKit
import SwiftyJSON
class IBBSRegisterViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var avatarImageView: IBBSAvatarImageView! {
didSet{
avatarImageView.antiOffScreenRendering = false
avatarImageView.backgroundColor = CUSTOM_THEME_COLOR.darkerColor(0.75)
avatarImageView.image = AVATAR_PLACEHOLDER_IMAGE
}
}
@IBOutlet var passwordTextField: UITextField! {
didSet {
passwordTextField.secureTextEntry = true
}
}
@IBOutlet var passwordAgainTextField: UITextField! {
didSet{
passwordAgainTextField.secureTextEntry = true
}
}
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var emailTextField: UITextField!
override func loadView() {
super.loadView()
usernameTextField.delegate = self
emailTextField.delegate = self
passwordTextField.delegate = self
passwordAgainTextField.delegate = self
view.backgroundColor = UIColor(patternImage: BACKGROUNDER_IMAGE!)
// blur view
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
blurView.alpha = BLUR_VIEW_ALPHA_OF_BG_IMAGE + 0.2
view.insertSubview(blurView, atIndex: 0)
blurView.snp_makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsZero)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
usernameTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButton(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
@IBAction func signupButton(sender: AnyObject) {
let username = usernameTextField.text as NSString?
let email = emailTextField.text as NSString?
let passwd = passwordTextField.text as NSString?
let passwdAgain = passwordAgainTextField.text as NSString?
if username?.length == 0 || email?.length == 0 || passwd?.length == 0 || passwdAgain?.length == 0 {
// not all the form are filled in
let alertCtl = UIAlertController(title: FILL_IN_ALL_THE_FORM, message: CHECK_IT_AGAIN, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: I_WILL_CHECK, style: .Cancel, handler: nil)
alertCtl.addAction(cancelAction)
presentViewController(alertCtl, animated: true, completion: nil)
return
}
if username?.length > 15 || username?.length < 4 {
let alertCtl = UIAlertController(title: "", message: CHECK_DIGITS_OF_USERNAME, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: TRY_AGAIN, style: .Cancel, handler: nil)
alertCtl.addAction(cancelAction)
presentViewController(alertCtl, animated: true, completion: nil)
return
}
if !email!.isValidEmail(){
// invalid email address
let alertCtl = UIAlertController(title: "", message: INVALID_EMAIL, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: TRY_AGAIN, style: .Cancel, handler: nil)
alertCtl.addAction(cancelAction)
presentViewController(alertCtl, animated: true, completion: nil)
return
}
if passwd?.length < 6 {
let alertCtl = UIAlertController(title: "", message: CHECK_DIGITS_OF_PASSWORD, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: I_KNOW, style: .Cancel, handler: nil)
alertCtl.addAction(cancelAction)
presentViewController(alertCtl, animated: true, completion: nil)
return
}
if !passwd!.isValidPassword() {
let alertCtl = UIAlertController(title: "", message: INVALID_PASSWORD, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: TRY_AGAIN, style: .Cancel, handler: nil)
alertCtl.addAction(cancelAction)
presentViewController(alertCtl, animated: true, completion: nil)
return
}
if passwd != passwdAgain {
let alertCtl = UIAlertController(title: PASSWD_MUST_BE_THE_SAME, message: TRY_AGAIN, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: TRY_AGAIN, style: .Cancel, handler: nil)
alertCtl.addAction(cancelAction)
presentViewController(alertCtl, animated: true, completion: nil)
return
}
// everything is fine, ready to go
let encryptedPasswd = (passwd as! String).MD5()
APIClient.defaultClient.userRegister(email!, username: username!, passwd: encryptedPasswd, success: { (json) -> Void in
let model = IBBSModel(json: json)
if model.success {
// register successfully!
APIClient.defaultClient.userLogin(username!, passwd: encryptedPasswd, success: { (json) -> Void in
IBBSLoginKey.saveTokenJson(json.object)
IBBSToast.make(REGISTER_SUCESSFULLY, interval: TIME_OF_TOAST_OF_REGISTER_SUCCESS)
executeAfterDelay(1, completion: {
self.navigationController?.popViewControllerAnimated(true)
})
}, failure: { (error) -> Void in
DEBUGLog(error)
IBBSToast.make(SERVER_ERROR, interval: TIME_OF_TOAST_OF_SERVER_ERROR)
})
} else {
// failed
let alertCtl = UIAlertController(title: REGISTER_FAILED, message: model.message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: TRY_AGAIN, style: .Cancel, handler: nil)
alertCtl.addAction(cancelAction)
self.presentViewController(alertCtl, animated: true, completion: nil)
}
}, failure: { (error) -> Void in
DEBUGLog(error)
IBBSToast.make(SERVER_ERROR, interval: TIME_OF_TOAST_OF_SERVER_ERROR)
})
}
// MARK: - text field delegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == usernameTextField {
textField.resignFirstResponder()
emailTextField.becomeFirstResponder()
} else if textField == emailTextField {
textField.resignFirstResponder()
passwordTextField.becomeFirstResponder()
} else if textField == passwordTextField {
textField.resignFirstResponder()
passwordAgainTextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
// performSelector("signupButton:")
}
return true
}
// MARK: -
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// dismiss keyboard
_ = view.subviews.map() {
if $0 is UITextField {
$0.resignFirstResponder()
}
}
}
}
| mit | 2b41ca137b2d623ff6d000cc8871805a | 35.49537 | 127 | 0.587213 | 5.322755 | false | false | false | false |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationOrbit.swift | 6 | 7029 | //
// Created by Tom Baranes on 23/08/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationOrbit: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 1.9
fileprivate let satelliteCoreRatio: CGFloat = 0.25
fileprivate let distanceRatio: CGFloat = 1.5
fileprivate var coreSize: CGFloat = 0
fileprivate var satelliteSize: CGFloat = 0
fileprivate var size: CGSize = .zero
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
self.size = size
coreSize = size.width / (1 + satelliteCoreRatio + distanceRatio)
satelliteSize = coreSize * satelliteCoreRatio
animateRing1(in: layer, color: color)
animateRing2(in: layer, color: color)
animateCore(in: layer, color: color)
animateSatellite(in: layer, color: color)
}
}
// MARK: - Satellite
private extension ActivityIndicatorAnimationOrbit {
func animateSatellite(in layer: CALayer, color: UIColor) {
let rotateAnimation = makeSatelliteRotateAnimation(layer: layer)
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: satelliteSize, height: satelliteSize), color: color)
let frame = CGRect(x: 0, y: 0, width: satelliteSize, height: satelliteSize)
circle.frame = frame
circle.add(rotateAnimation, forKey: "animation")
layer.addSublayer(circle)
}
func makeSatelliteRotateAnimation(layer: CALayer) -> CAKeyframeAnimation {
let rotateAnimation = CAKeyframeAnimation(keyPath: "position")
rotateAnimation.path = UIBezierPath(arcCenter: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY),
radius: (size.width - satelliteSize) / 2,
startAngle: CGFloat.pi * 1.5,
endAngle: CGFloat.pi * 1.5 + 4 * CGFloat.pi,
clockwise: true).cgPath
rotateAnimation.duration = duration * 2
rotateAnimation.repeatCount = .infinity
rotateAnimation.isRemovedOnCompletion = false
return rotateAnimation
}
}
// MARK: - Core
private extension ActivityIndicatorAnimationOrbit {
func animateCore(in layer: CALayer, color: UIColor) {
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: coreSize, height: coreSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2,
y: (layer.bounds.size.height - coreSize) / 2,
width: coreSize,
height: coreSize)
circle.frame = frame
circle.add(coreScaleAnimation, forKey: "animation")
layer.addSublayer(circle)
}
var coreScaleAnimation: CAKeyframeAnimation {
let inTimingFunction = CAMediaTimingFunction(controlPoints: 0.7, 0, 1, 0.5)
let outTimingFunction = CAMediaTimingFunction(controlPoints: 0, 0.7, 0.5, 1)
let standByTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.45, 0.55, 1]
scaleAnimation.timingFunctions = [inTimingFunction, standByTimingFunction, outTimingFunction]
scaleAnimation.values = [1, 1.3, 1.3, 1]
scaleAnimation.duration = duration
scaleAnimation.repeatCount = .infinity
scaleAnimation.isRemovedOnCompletion = false
return scaleAnimation
}
}
// MARK: - Ring 1
private extension ActivityIndicatorAnimationOrbit {
func animateRing1(in layer: CALayer, color: UIColor) {
let animation = ring1Animation
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: coreSize, height: coreSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2,
y: (layer.bounds.size.height - coreSize) / 2,
width: coreSize,
height: coreSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
var ring1Animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [ring1ScaleAnimation, ring1OpacityAnimation]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
var ring1ScaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.45, 0.45, 1]
scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
scaleAnimation.values = [0, 0, 1.3, 2]
scaleAnimation.duration = duration
return scaleAnimation
}
var ring1OpacityAnimation: CAKeyframeAnimation {
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
let timingFunction = CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1)
opacityAnimation.keyTimes = [0, 0.45, 1]
ring1ScaleAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), timingFunction]
opacityAnimation.values = [0.8, 0.8, 0]
opacityAnimation.duration = duration
return opacityAnimation
}
}
// MARK: - Ring 2
private extension ActivityIndicatorAnimationOrbit {
func animateRing2(in layer: CALayer, color: UIColor) {
let animation = ring2Animation
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: coreSize, height: coreSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2,
y: (layer.bounds.size.height - coreSize) / 2,
width: coreSize,
height: coreSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
var ring2Animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [ring2ScaleAnimation, ring2OpacityAnimation]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
var ring2ScaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.55, 0.55, 1]
scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
scaleAnimation.values = [0, 0, 1.3, 2.1]
scaleAnimation.duration = duration
return scaleAnimation
}
var ring2OpacityAnimation: CAKeyframeAnimation {
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
let timingFunction = CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1)
opacityAnimation.keyTimes = [0, 0.55, 0.65, 1]
ring2ScaleAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), timingFunction]
opacityAnimation.values = [0.7, 0.7, 0, 0]
opacityAnimation.duration = duration
return opacityAnimation
}
}
| gpl-3.0 | 2783f05f64b0f71857635327eca94c51 | 37.404372 | 129 | 0.705179 | 4.590464 | false | false | false | false |
meteochu/Alamofire | Source/Response.swift | 1 | 3811 | //
// Response.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// Used to store all response data returned from a completed `Request`.
public struct Response<Value, Error: ErrorProtocol> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The result of response serialization.
public let result: Result<Value, Error>
/// The timeline of the complete lifecycle of the `Request`.
public let timeline: Timeline
/**
Initializes the `Response` instance with the specified URL request, URL response, server data and response
serialization result.
- parameter request: The URL request sent to the server.
- parameter response: The server's response to the URL request.
- parameter data: The data returned by the server.
- parameter result: The result of response serialization.
- parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
- returns: the new `Response` instance.
*/
public init(
request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
result: Result<Value, Error>,
timeline: Timeline = Timeline())
{
self.request = request
self.response = response
self.data = data
self.result = result
self.timeline = timeline
}
}
// MARK: - CustomStringConvertible
extension Response: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
return result.debugDescription
}
}
// MARK: - CustomDebugStringConvertible
extension Response: CustomDebugStringConvertible {
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the server data and the response serialization result.
public var debugDescription: String {
var output: [String] = []
output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.count ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joined(separator: "\n")
}
}
| mit | 02d8b1773eae7f051c84b0b1a62d3e0d | 38.28866 | 119 | 0.689583 | 4.769712 | false | false | false | false |
rsaenzi/MyMoviesListApp | MyMoviesListApp/MyMoviesListApp/AuthModule.swift | 1 | 565 | //
// AuthModule.swift
// MyMoviesListApp
//
// Created by Rigoberto Sáenz Imbacuán on 5/29/17.
// Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved.
//
import Foundation
class AuthModule {
var wireframe: AuthWireframe
var interactor: AuthInteractor
var presenter: AuthPresenter
init() {
wireframe = AuthWireframe()
interactor = AuthInteractor()
presenter = AuthPresenter()
presenter.wireframe = wireframe
presenter.interactor = interactor
}
}
| mit | 3684486e9f2da815f41fc1183d51b651 | 19.740741 | 67 | 0.635714 | 4.955752 | false | false | false | false |
larryhou/swift | LocationTraker/LocationTraker/AppDelegate.swift | 1 | 8549 | //
// AppDelegate.swift
// LocationTraker
//
// Created by larryhou on 25/7/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var trackController: TrackTimeTableViewController!
var formatter: NSDateFormatter!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if launchOptions != nil {
for (key, value) in launchOptions! {
print("\(key): \(value)")
}
}
formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd E HH:mm:ss.SSS"
trackController = (window!.rootViewController as! UINavigationController).topViewController as! TrackTimeTableViewController
trackController.managedObjectContext = managedObjectContext
let binaryOptions: NSData? = launchOptions == nil ? nil : NSKeyedArchiver.archivedDataWithRootObject(launchOptions!)
insertAPPStatus(APPStatusType.Launch, data: binaryOptions)
return true
}
func insertAPPStatus(type: APPStatusType, data: NSData? = nil) {
let date = NSDate()
let status = NSEntityDescription.insertNewObjectForEntityForName("APPStatus", inManagedObjectContext: managedObjectContext) as! APPStatus
status.timestamp = formatter.stringFromDate(date)
status.status = type.rawValue
status.date = date
status.data = data
do {
try managedObjectContext.save()
} catch {}
}
func cleanUpStatus() {
let request = NSFetchRequest(entityName: "APPStatus")
request.predicate = NSPredicate(format: "date != nil")
request.resultType = NSFetchRequestResultType.ManagedObjectIDResultType
do {
let ids = try managedObjectContext.executeFetchRequest(request) as! [NSManagedObjectID]
if ids.count > 0 {
let deleteRequest = NSBatchDeleteRequest(objectIDs: ids)
try managedObjectContext.executeRequest(deleteRequest)
}
} catch {
print(error)
}
}
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.
print(__FUNCTION__)
insertAPPStatus(APPStatusType.ResignActive)
}
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.
print(__FUNCTION__)
trackController.enterBackgroundMode()
insertAPPStatus(APPStatusType.EnterBackground)
}
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.
print(__FUNCTION__)
trackController.enterForegroundMode()
insertAPPStatus(APPStatusType.EnterForeground)
}
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.
print(__FUNCTION__)
insertAPPStatus(APPStatusType.BecomeActive)
}
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.
print(__FUNCTION__)
self.saveContext()
insertAPPStatus(APPStatusType.Terminate)
}
// 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.larryhou.samples.LocationTraker" 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("LocationTraker", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("data.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
var params: [String: AnyObject] = [:]
params.updateValue(true, forKey: NSMigratePersistentStoresAutomaticallyOption)
params.updateValue(true, forKey: NSInferMappingModelAutomaticallyOption)
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: params)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 3de3f7377c57de0dc6887688654ddff1 | 49.880952 | 291 | 0.704024 | 5.803123 | false | false | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Catch.swift | 8 | 10060 | //
// Catch.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
public func `catch`(_ handler: @escaping (Swift.Error) throws -> Observable<Element>)
-> Observable<Element> {
Catch(source: self.asObservable(), handler: handler)
}
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
@available(*, deprecated, renamed: "catch(_:)")
public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable<Element>)
-> Observable<Element> {
`catch`(handler)
}
/**
Continues an observable sequence that is terminated by an error with a single element.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter element: Last element in an observable sequence in case error occurs.
- returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred.
*/
public func catchAndReturn(_ element: Element)
-> Observable<Element> {
Catch(source: self.asObservable(), handler: { _ in Observable.just(element) })
}
/**
Continues an observable sequence that is terminated by an error with a single element.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter element: Last element in an observable sequence in case error occurs.
- returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred.
*/
@available(*, deprecated, renamed: "catchAndReturn(_:)")
public func catchErrorJustReturn(_ element: Element)
-> Observable<Element> {
catchAndReturn(element)
}
}
extension ObservableType {
/**
Continues an observable sequence that is terminated by an error with the next observable sequence.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
@available(*, deprecated, renamed: "catch(onSuccess:onFailure:onDisposed:)")
public static func catchError<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Observable<Element>
where Sequence.Element == Observable<Element> {
`catch`(sequence: sequence)
}
/**
Continues an observable sequence that is terminated by an error with the next observable sequence.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
public static func `catch`<Sequence: Swift.Sequence>(sequence: Sequence) -> Observable<Element>
where Sequence.Element == Observable<Element> {
CatchSequence(sources: sequence)
}
}
extension ObservableType {
/**
Repeats the source observable sequence until it successfully terminates.
**This could potentially create an infinite sequence.**
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- returns: Observable sequence to repeat until it successfully terminates.
*/
public func retry() -> Observable<Element> {
CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()))
}
/**
Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates.
If you encounter an error and want it to retry once, then you must use `retry(2)`
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to repeat the sequence.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
public func retry(_ maxAttemptCount: Int)
-> Observable<Element> {
CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount))
}
}
// catch with callback
final private class CatchSinkProxy<Observer: ObserverType>: ObserverType {
typealias Element = Observer.Element
typealias Parent = CatchSink<Observer>
private let parent: Parent
init(parent: Parent) {
self.parent = parent
}
func on(_ event: Event<Element>) {
self.parent.forwardOn(event)
switch event {
case .next:
break
case .error, .completed:
self.parent.dispose()
}
}
}
final private class CatchSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = Catch<Element>
private let parent: Parent
private let subscription = SerialDisposable()
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let d1 = SingleAssignmentDisposable()
self.subscription.disposable = d1
d1.setDisposable(self.parent.source.subscribe(self))
return self.subscription
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self.forwardOn(event)
case .completed:
self.forwardOn(event)
self.dispose()
case .error(let error):
do {
let catchSequence = try self.parent.handler(error)
let observer = CatchSinkProxy(parent: self)
self.subscription.disposable = catchSequence.subscribe(observer)
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
}
}
}
final private class Catch<Element>: Producer<Element> {
typealias Handler = (Swift.Error) throws -> Observable<Element>
fileprivate let source: Observable<Element>
fileprivate let handler: Handler
init(source: Observable<Element>, handler: @escaping Handler) {
self.source = source
self.handler = handler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = CatchSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
// catch enumerable
final private class CatchSequenceSink<Sequence: Swift.Sequence, Observer: ObserverType>
: TailRecursiveSink<Sequence, Observer>
, ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = CatchSequence<Sequence>
private var lastError: Swift.Error?
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self.forwardOn(event)
case .error(let error):
self.lastError = error
self.schedule(.moveNext)
case .completed:
self.forwardOn(event)
self.dispose()
}
}
override func subscribeToNext(_ source: Observable<Element>) -> Disposable {
source.subscribe(self)
}
override func done() {
if let lastError = self.lastError {
self.forwardOn(.error(lastError))
}
else {
self.forwardOn(.completed)
}
self.dispose()
}
override func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
if let onError = observable as? CatchSequence<Sequence> {
return (onError.sources.makeIterator(), nil)
}
else {
return nil
}
}
}
final private class CatchSequence<Sequence: Swift.Sequence>: Producer<Sequence.Element.Element> where Sequence.Element: ObservableConvertibleType {
typealias Element = Sequence.Element.Element
let sources: Sequence
init(sources: Sequence) {
self.sources = sources
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = CatchSequenceSink<Sequence, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run((self.sources.makeIterator(), nil))
return (sink: sink, subscription: subscription)
}
}
| mit | 68bb47719307575b301778a809cae705 | 35.578182 | 189 | 0.673029 | 4.945428 | false | false | false | false |
blg-andreasbraun/ProcedureKit | Tests/CapabilityTests.swift | 2 | 4757 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import XCTest
import TestingProcedureKit
@testable import ProcedureKit
class GetAuthorizationStatusTests: TestableCapabilityTestCase {
func test__sets_result() {
wait(for: getAuthorizationStatus)
XCTAssertGetAuthorizationStatus(getAuthorizationStatus.output.success, expected: (true, .unknown))
XCTAssertTestCapabilityStatusChecked()
}
func test__async_sets_result() {
capability.isAsynchronous = true
wait(for: getAuthorizationStatus)
XCTAssertGetAuthorizationStatus(getAuthorizationStatus.output.success, expected: (true, .unknown))
XCTAssertTestCapabilityStatusChecked()
}
func test__runs_completion_block() {
var completedWithResult: GetAuthorizationStatusProcedure<TestableCapability.Status>.Output = (false, .unknown)
getAuthorizationStatus = GetAuthorizationStatusProcedure(capability) { completedWithResult = $0 }
wait(for: getAuthorizationStatus)
XCTAssertGetAuthorizationStatus(completedWithResult, expected: (true, .unknown))
XCTAssertTestCapabilityStatusChecked()
}
func test__async_runs_completion_block() {
capability.isAsynchronous = true
var completedWithResult: GetAuthorizationStatusProcedure<TestableCapability.Status>.Output = (false, .unknown)
getAuthorizationStatus = GetAuthorizationStatusProcedure(capability) { result in
completedWithResult = result
}
wait(for: getAuthorizationStatus)
XCTAssertGetAuthorizationStatus(completedWithResult, expected: (true, .unknown))
XCTAssertTestCapabilityStatusChecked()
}
func test__void_status_equal() {
XCTAssertEqual(Capability.VoidStatus(), Capability.VoidStatus())
}
func test__void_status_meets_requirements() {
XCTAssertTrue(Capability.VoidStatus().meets(requirement: ()))
}
}
class AuthorizeTests: TestableCapabilityTestCase {
func test__authorize() {
wait(for: authorize)
XCTAssertTrue(capability.didRequestAuthorization)
}
}
class AuthorizedForTests: TestableCapabilityTestCase {
func test__is_mututally_exclusive() {
XCTAssertTrue(authorizedFor.isMutuallyExclusive)
}
func test__default_mututally_exclusive_category() {
XCTAssertEqual(authorizedFor.category, "TestableCapability")
}
func test__custom_mututally_exclusive_category() {
authorizedFor = AuthorizedFor(capability, category: "testing")
XCTAssertEqual(authorizedFor.category, "testing")
}
func test__has_authorize_dependency() {
guard let dependency = authorizedFor.dependencies.first else {
XCTFail("Condition did not return a dependency")
return
}
guard let _ = dependency as? AuthorizeCapabilityProcedure<TestableCapability.Status> else {
XCTFail("Dependency is not the correct type")
return
}
}
func test__fails_if_capability_is_not_available() {
capability.serviceIsAvailable = false
wait(for: procedure)
XCTAssertConditionResult(authorizedFor.output.value ?? .success(true), failedWithError: ProcedureKitError.capabilityUnavailable())
}
func test__async_fails_if_capability_is_not_available() {
capability.isAsynchronous = true
capability.serviceIsAvailable = false
wait(for: procedure)
XCTAssertConditionResult(authorizedFor.output.value ?? .success(true), failedWithError: ProcedureKitError.capabilityUnavailable())
}
func test__fails_if_requirement_is_not_met() {
capability.requirement = .maximum
capability.responseAuthorizationStatus = .minimumAuthorized
wait(for: procedure)
XCTAssertConditionResult(authorizedFor.output.value ?? .success(true), failedWithError: ProcedureKitError.capabilityUnauthorized())
}
func test__async_fails_if_requirement_is_not_met() {
capability.isAsynchronous = true
capability.requirement = .maximum
capability.responseAuthorizationStatus = .minimumAuthorized
wait(for: procedure)
XCTAssertConditionResult(authorizedFor.output.value ?? .success(true), failedWithError: ProcedureKitError.capabilityUnauthorized())
}
func test__suceeds_if_requirement_is_met() {
wait(for: procedure)
XCTAssertConditionResultSatisfied(authorizedFor.output.value ?? .success(false))
}
func test__async_suceeds_if_requirement_is_met() {
capability.isAsynchronous = true
wait(for: procedure)
XCTAssertConditionResultSatisfied(authorizedFor.output.value ?? .success(false))
}
}
| mit | f6c30ae467eb83535efabf781ccf9e43 | 33.215827 | 139 | 0.708999 | 4.990556 | false | true | false | false |
callmeed/math-dog-tvos | TvDemo/ViewController.swift | 1 | 2113 | //
// ViewController.swift
// TvDemo
//
// Created by Erik Dungan on 9/19/15.
// Copyright © 2015 Under100. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var choiceA: UIButton!
@IBOutlet weak var choiceB: UIButton!
@IBOutlet weak var choiceC: UIButton!
var currentAnswer = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
generateQuestion()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func submitAnswer(sender: UIButton) {
let submittedAnswer = Int((sender.titleLabel?.text)!)
if submittedAnswer == self.currentAnswer {
self.questionLabel.text = "Great Job!"
} else {
self.questionLabel.text = "Ahhh, not quite"
}
let _ = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "generateQuestion", userInfo: nil, repeats: false)
}
func generateQuestion() {
let a1 = Int(arc4random_uniform(12))
let a2 = Int(arc4random_uniform(12))
let answer = a1 + a2
self.currentAnswer = Int(answer)
let wrongAnswerA = answer + Int(arc4random_uniform(4)) + 1
var wrongAnswerB = answer - 2 + Int(arc4random_uniform(4))
while wrongAnswerB == answer || wrongAnswerB == wrongAnswerA || wrongAnswerB < 0 {
wrongAnswerB = answer - 2 + Int(arc4random_uniform(4))
}
var answerSet = [answer, wrongAnswerA, wrongAnswerB]
answerSet.shuffleInPlace()
self.choiceA.setTitle(String(answerSet[0]), forState: UIControlState.Normal)
self.choiceB.setTitle(String(answerSet[1]), forState: UIControlState.Normal)
self.choiceC.setTitle(String(answerSet[2]), forState: UIControlState.Normal)
self.questionLabel.text = String(a1) + " + " + String(a2) + " ="
}
}
| mit | 111ca80b0bb5e2a3664fda619c19024f | 33.064516 | 134 | 0.642992 | 4.182178 | false | false | false | false |
PJayRushton/CircleProgressView | CircularProgressView/ViewController.swift | 1 | 1363 | //
// ViewController.swift
// CircularProgressView
//
// Created by Parker Rushton on 2/24/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var circleProgressView: CircleProgressView!
@IBOutlet weak var progressSlider: UISlider!
@IBOutlet weak var widthSlider: UISlider!
let total = 10.0
var current = 3.0
override func viewDidLoad() {
super.viewDidLoad()
progressSlider.maximumValue = Float(total)
progressSlider.setValue(Float(current), animated: false)
widthSlider.maximumValue = Float(circleProgressView.frame.size.width / 2)
widthSlider.setValue(Float(circleProgressView.lineWidth), animated: false)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
circleProgressView.update(total, current: current)
}
@IBAction func progressSliderValueChanged(sender: UISlider) {
let intSliderValue = Int(sender.value)
sender.setValue(Float(intSliderValue), animated: true)
current = Double(intSliderValue)
circleProgressView.update(total, current: current)
}
@IBAction func widthSliderValueChanged(sender: UISlider) {
circleProgressView.lineWidth = CGFloat(sender.value)
}
}
| mit | 8ec42201e13e46b72cc152b279251bc9 | 29.266667 | 82 | 0.69163 | 4.696552 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Toolbox/MusicInfo/Detail/View/SongDetailPositionCharaItemView.swift | 1 | 1604 | //
// SongDetailPositionCharaItemView.swift
// DereGuide
//
// Created by zzk on 04/10/2017.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class SongDetailPositionCharaItemView: UIView {
let charaIcon = CGSSCharaIconView()
let charaPlaceholder = UIView()
private(set) var charaID: Int!
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(charaIcon)
charaIcon.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
addSubview(charaPlaceholder)
charaPlaceholder.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
charaPlaceholder.layer.masksToBounds = true
charaPlaceholder.layer.cornerRadius = 4
charaPlaceholder.layer.borderWidth = 1 / Screen.scale
charaPlaceholder.layer.borderColor = UIColor.border.cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupWith(charaID: Int) {
self.charaID = charaID
if charaID != 0 {
showsPlaceholder = false
charaIcon.charaID = charaID
} else {
showsPlaceholder = true
charaIcon.charaID = nil
}
}
var showsPlaceholder: Bool = true {
didSet {
charaPlaceholder.isHidden = !showsPlaceholder
charaIcon.isHidden = showsPlaceholder
bringSubview(toFront: showsPlaceholder ? charaPlaceholder : charaIcon)
}
}
}
| mit | 649c05564813660c174a95dcbc1c3a36 | 26.169492 | 82 | 0.613849 | 4.502809 | false | false | false | false |
swiftix/swift | test/SILGen/objc_bridging_any.swift | 1 | 42730 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import objc_generics
protocol P {}
protocol CP: class {}
struct KnownUnbridged {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any11passingToId{{.*}}F
func passingToId<T: CP, U>(receiver: NSIdLover,
string: String,
nsString: NSString,
object: AnyObject,
classGeneric: T,
classExistential: CP,
generic: U,
existential: P,
error: Error,
any: Any,
knownUnbridged: KnownUnbridged,
optionalA: String?,
optionalB: NSString?,
optionalC: Any?) {
// CHECK: bb0([[SELF:%.*]] : $NSIdLover,
// CHECK: debug_value [[STRING:%.*]] : $String
// CHECK: debug_value [[NSSTRING:%.*]] : $NSString
// CHECK: debug_value [[OBJECT:%.*]] : $AnyObject
// CHECK: debug_value [[CLASS_GENERIC:%.*]] : $T
// CHECK: debug_value [[CLASS_EXISTENTIAL:%.*]] : $CP
// CHECK: debug_value_addr [[GENERIC:%.*]] : $*U
// CHECK: debug_value_addr [[EXISTENTIAL:%.*]] : $*P
// CHECK: debug_value [[ERROR:%.*]] : $Error
// CHECK: debug_value_addr [[ANY:%.*]] : $*Any
// CHECK: debug_value [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged
// CHECK: debug_value [[OPT_STRING:%.*]] : $Optional<String>
// CHECK: debug_value [[OPT_NSSTRING:%.*]] : $Optional<NSString>
// CHECK: debug_value_addr [[OPT_ANY:%.*]] : $*Optional<Any>
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]]
// CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]]
// CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]]
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: end_borrow [[BORROWED_STRING]] from [[STRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(string)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]]
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject
// CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(nsString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]]
// CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject
// CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(classGeneric)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]]
// CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]]
// CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]]
// CHECK: apply [[METHOD]]([[OBJECT_COPY]], [[BORROWED_SELF]])
// CHECK: destroy_value [[OBJECT_COPY]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(object)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]]
// CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]]
// CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]]
// CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(classExistential)
// These cases perform a universal bridging conversion.
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[COPY:%.*]] = alloc_stack $U
// CHECK: copy_addr [[GENERIC]] to [initialization] [[COPY]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]])
// CHECK: dealloc_stack [[COPY]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(generic)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[COPY:%.*]] = alloc_stack $P
// CHECK: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]]
// CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(existential)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
// CHECK: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error
// CHECK: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
// CHECK: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
// CHECK: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
// CHECK: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: destroy_value [[ERROR_COPY]] : $Error
// CHECK: end_borrow [[BORROWED_ERROR]] from [[ERROR]]
// CHECK: apply [[METHOD]]([[BRIDGED_ERROR]], [[BORROWED_SELF]])
// CHECK: destroy_value [[BRIDGED_ERROR]] : $AnyObject
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(error)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[COPY:%.*]] = alloc_stack $Any
// CHECK: copy_addr [[ANY]] to [initialization] [[COPY]]
// CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(any)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged
// CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]])
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(knownUnbridged)
// These cases bridge using Optional's _ObjectiveCBridgeable conformance.
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]]
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<String>
// CHECK: store [[OPT_STRING_COPY]] to [init] [[TMP]]
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]])
// CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(optionalA)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OPT_NSSTRING:%.*]] = begin_borrow [[OPT_NSSTRING]]
// CHECK: [[OPT_NSSTRING_COPY:%.*]] = copy_value [[BORROWED_OPT_NSSTRING]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString>
// CHECK: store [[OPT_NSSTRING_COPY]] to [init] [[TMP]]
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]])
// CHECK: end_borrow [[BORROWED_OPT_NSSTRING]] from [[OPT_NSSTRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(optionalB)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any>
// CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]])
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(optionalC)
// TODO: Property and subscript setters
}
// Once upon a time, as a workaround for rdar://problem/28318984, we had
// to skip the peephole for types with nontrivial SIL lowerings because we
// didn't correctly form the substitutions for a generic
// _bridgeAnythingToObjectiveC call. That's not true anymore.
func zim() {}
struct Zang {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any27typesWithNontrivialLoweringySo9NSIdLoverC8receiver_tF
func typesWithNontrivialLowering(receiver: NSIdLover) {
// CHECK: apply {{.*}}<() -> ()>
receiver.takesId(zim)
// CHECK: apply {{.*}}<Zang.Type>
receiver.takesId(Zang.self)
// CHECK: apply {{.*}}<(() -> (), Zang.Type)>
receiver.takesId((zim, Zang.self))
// CHECK: apply {{%.*}}<(Int, String)>
receiver.takesId((0, "one"))
}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any19passingToNullableId{{.*}}F
func passingToNullableId<T: CP, U>(receiver: NSIdLover,
string: String,
nsString: NSString,
object: AnyObject,
classGeneric: T,
classExistential: CP,
generic: U,
existential: P,
error: Error,
any: Any,
knownUnbridged: KnownUnbridged,
optString: String?,
optNSString: NSString?,
optObject: AnyObject?,
optClassGeneric: T?,
optClassExistential: CP?,
optGeneric: U?,
optExistential: P?,
optAny: Any?,
optKnownUnbridged: KnownUnbridged?,
optOptA: String??,
optOptB: NSString??,
optOptC: Any??)
{
// CHECK: bb0([[SELF:%.*]] : $NSIdLover,
// CHECK: [[STRING:%.*]] : $String,
// CHECK: [[NSSTRING:%.*]] : $NSString
// CHECK: [[OBJECT:%.*]] : $AnyObject
// CHECK: [[CLASS_GENERIC:%.*]] : $T
// CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP
// CHECK: [[GENERIC:%.*]] : $*U
// CHECK: [[EXISTENTIAL:%.*]] : $*P
// CHECK: [[ERROR:%.*]] : $Error
// CHECK: [[ANY:%.*]] : $*Any,
// CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged,
// CHECK: [[OPT_STRING:%.*]] : $Optional<String>,
// CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString>
// CHECK: [[OPT_OBJECT:%.*]] : $Optional<AnyObject>
// CHECK: [[OPT_CLASS_GENERIC:%.*]] : $Optional<T>
// CHECK: [[OPT_CLASS_EXISTENTIAL:%.*]] : $Optional<CP>
// CHECK: [[OPT_GENERIC:%.*]] : $*Optional<U>
// CHECK: [[OPT_EXISTENTIAL:%.*]] : $*Optional<P>
// CHECK: [[OPT_ANY:%.*]] : $*Optional<Any>
// CHECK: [[OPT_KNOWN_UNBRIDGED:%.*]] : $Optional<KnownUnbridged>
// CHECK: [[OPT_OPT_A:%.*]] : $Optional<Optional<String>>
// CHECK: [[OPT_OPT_B:%.*]] : $Optional<Optional<NSString>>
// CHECK: [[OPT_OPT_C:%.*]] : $*Optional<Optional<Any>>
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]]
// CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]]
// CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]]
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[OPT_ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(string)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]]
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(nsString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]]
// CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]]
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[OBJECT_COPY]]
// CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(object)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]]
// CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(classGeneric)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]]
// CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]]
// CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]]
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(classExistential)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U
// CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(generic)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P
// CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]]
// CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[COPY]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(existential)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
// CHECK-NEXT: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error
// CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
// CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
// CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
// CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
// CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject
// CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK-NEXT: destroy_value [[ERROR_COPY]] : $Error
// CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]]
// CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR_OPT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[BRIDGED_ERROR_OPT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(error)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]]
// CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[COPY]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(any)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged
// CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]])
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(knownUnbridged)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]]
// CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]]
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]]
// CHECK: switch_enum [[OPT_STRING_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[STRING_DATA:%.*]] : $String):
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_DATA:%.*]] = begin_borrow [[STRING_DATA]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_DATA]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_STRING_DATA]] from [[STRING_DATA]]
// CHECK: destroy_value [[STRING_DATA]]
// CHECK: br [[JOIN:bb.*]]([[OPT_ANYOBJECT]]
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_NONE:%.*]] = enum $Optional<AnyObject>, #Optional.none!enumelt
// CHECK: br [[JOIN]]([[OPT_NONE]]
//
// CHECK: [[JOIN]]([[PHI:%.*]] : $Optional<AnyObject>):
// CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]]
// CHECK: apply [[METHOD]]([[PHI]], [[BORROWED_SELF]])
// CHECK: destroy_value [[PHI]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(optString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]]
receiver.takesNullableId(optNSString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_SELF]]
// CHECK: [[BORROWED_OPT_OBJECT:%.*]] = begin_borrow [[OPT_OBJECT]]
// CHECK: [[OPT_OBJECT_COPY:%.*]] = copy_value [[BORROWED_OPT_OBJECT]]
// CHECK: apply [[METHOD]]([[OPT_OBJECT_COPY]], [[BORROWED_SELF]])
receiver.takesNullableId(optObject)
receiver.takesNullableId(optClassGeneric)
receiver.takesNullableId(optClassExistential)
receiver.takesNullableId(optGeneric)
receiver.takesNullableId(optExistential)
receiver.takesNullableId(optAny)
receiver.takesNullableId(optKnownUnbridged)
receiver.takesNullableId(optOptA)
receiver.takesNullableId(optOptB)
receiver.takesNullableId(optOptC)
}
protocol Anyable {
init(any: Any)
init(anyMaybe: Any?)
var anyProperty: Any { get }
var maybeAnyProperty: Any? { get }
}
// Make sure we generate correct bridging thunks
class SwiftIdLover : NSObject, Anyable {
func methodReturningAny() -> Any {}
// SEMANTIC ARC TODO: This is another case of pattern matching the body of one
// function in a different function... Just pattern match the unreachable case
// to preserve behavior. We should check if it is correct.
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF : $@convention(method) (@guaranteed SwiftIdLover) -> @out Any
// CHECK: unreachable
// CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF'
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased AnyObject {
// CHECK: bb0([[SELF:%[0-9]+]] : $SwiftIdLover):
// CHECK: [[NATIVE_RESULT:%.*]] = alloc_stack $Any
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $SwiftIdLover
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE_IMP:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF
// CHECK: apply [[NATIVE_IMP]]([[NATIVE_RESULT]], [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[OPEN_RESULT:%.*]] = open_existential_addr immutable_access [[NATIVE_RESULT]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[OPEN_RESULT]] to [initialization] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[OBJC_RESULT:%.*]] = apply [[BRIDGE_ANYTHING]]<{{.*}}>([[TMP]])
// CHECK: return [[OBJC_RESULT]]
// CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo'
func methodReturningOptionalAny() -> Any? {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyF
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyFTo
// CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
@objc func methodTakingAny(a: Any) {}
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> ()
// CHECK: bb0([[ARG:%.*]] : $AnyObject, [[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[OPENED_SELF:%.*]] = open_existential_ref [[ARG_COPY]]
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[INIT:%.*]] = init_existential_addr [[RESULT]] : $*Any
// CHECK-NEXT: store [[OPENED_SELF]] to [init] [[INIT]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tF
// CHECK-NEXT: apply [[METHOD]]([[RESULT]], [[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return
func methodTakingOptionalAny(a: Any?) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tF
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tFTo
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF : $@convention(method) (@owned @noescape @callee_owned (@in Any) -> (), @guaranteed SwiftIdLover) -> ()
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcFTo : $@convention(objc_method) (@convention(block) @noescape (AnyObject) -> (), SwiftIdLover) -> ()
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) @noescape (AnyObject) -> (), [[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0yXlIyBy_ypIxi_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]])
// CHECK-NEXT: [[THUNK_CVT:%.*]] = convert_function [[THUNK]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0yXlIyBy_ypIxi_TR
// CHECK: bb0([[ANY:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) @noescape (AnyObject) -> ()):
// CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_addr immutable_access [[ANY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[OPENED_ANY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: apply [[BLOCK]]([[BRIDGED]])
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK-NEXT: destroy_value [[BLOCK]]
// CHECK-NEXT: destroy_value [[BRIDGED]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[ANY]]
// CHECK-NEXT: return [[VOID]]
@objc func methodTakingBlockTakingAny(_: (Any) -> ()) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned (@in Any) -> ()
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) (AnyObject) -> ()
// CHECK: bb0([[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD:%.*]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned (@in Any) -> ()
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: store [[RESULT:%.*]] to [init] [[BLOCK_STORAGE_ADDR]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0ypIexi_yXlIeyBy_TR
// CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned (@in Any) -> (), invoke [[THUNK_FN]]
// CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]]
// CHECK-NEXT: destroy_addr [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]]
// CHECK-NEXT: return [[BLOCK]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIexi_yXlIeyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> (), AnyObject) -> ()
// CHECK: bb0([[BLOCK_STORAGE:%.*]] : $*@block_storage @callee_owned (@in Any) -> (), [[ANY:%.*]] : $AnyObject):
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]]
// CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY_COPY]]
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[INIT:%.*]] = init_existential_addr [[RESULT]] : $*Any
// CHECK-NEXT: store [[OPENED_ANY]] to [init] [[INIT]]
// CHECK-NEXT: apply [[FUNCTION]]([[RESULT]])
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: return [[VOID]] : $()
@objc func methodTakingBlockTakingOptionalAny(_: (Any?) -> ()) {}
@objc func methodReturningBlockTakingAny() -> ((Any) -> ()) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF : $@convention(method) (@owned @noescape @callee_owned () -> @out Any, @guaranteed SwiftIdLover) -> () {
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycFTo : $@convention(objc_method) (@convention(block) @noescape () -> @autoreleased AnyObject, SwiftIdLover) -> ()
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) @noescape () -> @autoreleased AnyObject, [[ANY:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0yXlIyBa_ypIxr_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]])
// CHECK-NEXT: [[THUNK_CVT:%.*]] = convert_function [[THUNK]]
// CHECK-NEXT: [[BORROWED_ANY_COPY:%.*]] = begin_borrow [[ANY_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_ANY_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_ANY_COPY]] from [[ANY_COPY]]
// CHECK-NEXT: destroy_value [[ANY_COPY]]
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0yXlIyBa_ypIxr_TR : $@convention(thin) (@owned @convention(block) @noescape () -> @autoreleased AnyObject) -> @out Any
// CHECK: bb0([[ANY_ADDR:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) @noescape () -> @autoreleased AnyObject):
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BLOCK]]()
// CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[BRIDGED]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] :
// CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[ANY_ADDR]], [[OPTIONAL]])
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: destroy_value [[BLOCK]]
// CHECK-NEXT: return [[EMPTY]]
@objc func methodReturningBlockTakingOptionalAny() -> ((Any?) -> ()) {}
@objc func methodTakingBlockReturningAny(_: () -> Any) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned () -> @out Any
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) () -> @autoreleased AnyObject
// CHECK: bb0([[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF
// CHECK-NEXT: [[FUNCTION:%.*]] = apply [[METHOD]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned () -> @out Any
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: store [[FUNCTION]] to [init] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0ypIexr_yXlIeyBa_TR
// CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned () -> @out Any, invoke [[THUNK_FN]]
// CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]]
// CHECK-NEXT: destroy_addr [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]]
// CHECK-NEXT: return [[BLOCK]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIexr_yXlIeyBa_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> @out Any) -> @autoreleased AnyObject
// CHECK: bb0(%0 : $*@block_storage @callee_owned () -> @out Any):
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0
// CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: apply [[FUNCTION]]([[RESULT]])
// CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr immutable_access [[RESULT]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[RESULT]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: return [[BRIDGED]]
@objc func methodTakingBlockReturningOptionalAny(_: () -> Any?) {}
@objc func methodReturningBlockReturningAny() -> (() -> Any) {}
@objc func methodReturningBlockReturningOptionalAny() -> (() -> Any?) {}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypSgIexr_yXlSgIeyBa_TR
// CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
override init() { super.init() }
@objc dynamic required convenience init(any: Any) { self.init() }
@objc dynamic required convenience init(anyMaybe: Any?) { self.init() }
@objc dynamic var anyProperty: Any
@objc dynamic var maybeAnyProperty: Any?
subscript(_: IndexForAnySubscript) -> Any { get {} set {} }
@objc func methodReturningAnyOrError() throws -> Any {}
}
class IndexForAnySubscript {}
func dynamicLookup(x: AnyObject) {
_ = x.anyProperty
_ = x[IndexForAnySubscript()]
}
extension GenericClass {
// CHECK-LABEL: sil hidden @_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF :
func pseudogenericAnyErasure(x: T) -> Any {
// CHECK: bb0([[ANY_OUT:%.*]] : $*Any, [[ARG:%.*]] : $T, [[SELF:%.*]] : $GenericClass<T>
// CHECK: [[ANY_BUF:%.*]] = init_existential_addr [[ANY_OUT]] : $*Any, $AnyObject
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[ARG_COPY]] : $T : $T, $AnyObject
// CHECK: store [[ANYOBJECT]] to [init] [[ANY_BUF]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
return x
}
// CHECK: } // end sil function '_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF'
}
// Make sure AnyHashable erasure marks Hashable conformance as used
class AnyHashableClass : NSObject {
// CHECK-LABEL: sil hidden @_T017objc_bridging_any16AnyHashableClassC07returnsdE0s0dE0VyF
// CHECK: [[FN:%.*]] = function_ref @_swift_convertToAnyHashable
// CHECK: apply [[FN]]<GenericOption>({{.*}})
func returnsAnyHashable() -> AnyHashable {
return GenericOption.multithreaded
}
}
// CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
// CHECK-NEXT: base_protocol Equatable: GenericOption: Equatable module objc_generics
// CHECK-NEXT: method #Hashable.hashValue!getter.1: {{.*}} : @_T0SC13GenericOptionVs8Hashable13objc_genericssACP9hashValueSivgTW
// CHECK-NEXT: }
| apache-2.0 | 982a15def9591acef5d848b88d44ece1 | 56.587601 | 223 | 0.610906 | 3.596801 | false | false | false | false |
pablogsIO/MadridShops | MadridShops/View/ShopCell.swift | 1 | 2092 | //
// ShopCell.swift
// MadridShops
//
// Created by Pablo García on 08/09/2017.
// Copyright © 2017 KC. All rights reserved.
//
import UIKit
class ShopCell: UICollectionViewCell {
var cityDataInformation: CityDataInformation?
var shop: CityDataInformationModel?
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var backgroundImage: UIImageView!
func refresh(cityDataInformation: CityDataInformation) {
self.cityDataInformation = cityDataInformation
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
self.imageView.clipsToBounds = true
self.label.text = cityDataInformation.name
self.cityDataInformation?.logo.loadImage(into: imageView)
self.cityDataInformation?.image.loadImage(into: backgroundImage)
imageView.clipsToBounds = true
UIView.animate(withDuration: 1.0) {
self.imageView.layer.cornerRadius = 30
}
}
func refresh(shop: Shop) {
self.shop = shop
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
self.imageView.clipsToBounds = true
self.label.text = shop.name
self.imageView.kf.setImage(with: URL(string: (self.shop?.logo)!))
//self.shopCD?.logo?.loadImage(into: imageView)
//self.shopCD?.image?.loadImage(into: backgroundImage)
imageView.clipsToBounds = true
UIView.animate(withDuration: 1.0) {
self.imageView.layer.cornerRadius = 30
}
}
func refresh(cityDataModel: CityDataInformationModel) {
self.shop = cityDataModel
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
self.imageView.clipsToBounds = true
self.label.text = cityDataModel.name
self.imageView.kf.setImage(with: URL(string: (self.shop?.logo)!))
//self.shopCD?.logo?.loadImage(into: imageView)
self.backgroundImage.kf.setImage(with: URL(string: (self.shop?.image)!))
//self.shopCD?.image?.loadImage(into: backgroundImage)
imageView.clipsToBounds = true
UIView.animate(withDuration: 1.0) {
self.imageView.layer.cornerRadius = 30
}
}
}
| mit | 8376365ce1779240b46454b0ae1f6dc1 | 30.666667 | 74 | 0.725359 | 3.718861 | false | false | false | false |
psoamusic/PourOver | PourOver/POPresetsTableViewController.swift | 1 | 886 | //
// POPresetsTableViewController.swift
// PourOver
//
// Created by kevin on 6/19/16.
// Copyright © 2016 labuser. All rights reserved.
//
import UIKit
class POPresetsTableViewController: POPieceTableViewController {
//===================================================================================
//MARK: Refresh
//===================================================================================
override func refreshPieces() {
cellDictionaries.removeAll(keepCapacity: false)
if let availablePatches = POPdFileLoader.sharedPdFileLoader.availablePresets() {
cellDictionaries = availablePatches
}
//add spacer cells to the top and bottom for correct scrolling behavior
cellDictionaries.insert(Dictionary(), atIndex: 0)
cellDictionaries.append(Dictionary())
}
}
| gpl-3.0 | c05467fd96f202d14b62e3b507ad74a7 | 29.517241 | 89 | 0.540113 | 5.673077 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeConstants/AwesomeConstants/Classes/Extensions/UIViewControllerExtensions.swift | 1 | 2710 | //
// UIViewController+Quests.swift
// Quests
//
// Created by Evandro Harrison Hoffmann on 3/23/17.
// Copyright © 2017 Mindvalley. All rights reserved.
//
import UIKit
extension UIApplication {
public var topViewController: UIViewController? {
if var topController = self.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return nil
}
public static var topViewController: UIViewController? {
return UIApplication.shared.topViewController
}
public func vibrate(_ feedbackType: UINotificationFeedbackType) {
if #available(iOS 10.0, *) {
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(feedbackType)
} else {
// Fallback on earlier versions
}
}
}
import SafariServices
extension UIViewController: SFSafariViewControllerDelegate {
public func presentWebPageInSafari(withURLString URLString: String) {
if let url = URL(string: URLString) {
if UIApplication.shared.canOpenURL(url) {
let vc = SFSafariViewController(url: url, entersReaderIfAvailable: true)
vc.delegate = self
self.present(vc, animated: true)
}
}
}
public func presentWebPageInSafari(withURL url: URL) {
if UIApplication.shared.canOpenURL(url) {
let vc = SFSafariViewController(url: url, entersReaderIfAvailable: true)
vc.delegate = self
self.present(vc, animated: true)
}
}
public func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
import AVKit
import AVFoundation
extension UIViewController {
public func openMedia(urlString: String?) {
guard let urlString = urlString, let url = URL(string: urlString) else {
return
}
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
let playerViewController = AVPlayerViewController()
playerViewController.showsPlaybackControls = true
playerViewController.player = AVPlayer(url: url)
playerViewController.player?.play()
present(playerViewController, animated: true, completion: {
})
}
public func setLayoutsForPhoneX(constraints: [NSLayoutConstraint]) {
for constraint in constraints {
constraint.constant += 20
}
}
}
| mit | b1702fe2786041ffb4b0c540f2679a3f | 28.445652 | 98 | 0.651163 | 5.620332 | false | false | false | false |
Thuva4/Algorithms_Example | BubbleSort/Swift/Bubble_Sort.swift | 1 | 1098 | // An Example of a bubble sort algorithm in Swift
//
// Essentialy this algorithm will loop through the values up to
// the index where we last did a sort (everything above is already in order/sorted)
// comparing a one value to the value before it. If the value before it is higher,
// swap them, and note the highest swap index. On the next iteration of the loop we
// only need to go as high as the previous swap.
import Foundation
var array = [5,3,4,6,8,2,9,1,7,10,11]
var sortedArray = NSMutableArray(array: array)
var sortedAboveIndex = array.count // Assume all values are not in order
do {
var lastSwapIndex = 0
for ( var i = 1; i < sortedAboveIndex; i++ ) {
if (sortedArray[i - 1].integerValue > sortedArray[i].integerValue) {
sortedArray.exchangeObjectAtIndex(i, withObjectAtIndex: i-1)
lastSwapIndex = i
}
}
sortedAboveIndex = lastSwapIndex
} while (sortedAboveIndex != 0)
// [5, 3, 4, 6, 8, 2, 9, 1, 7, 10, 11]
println(array)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
println(sortedArray as Array) | apache-2.0 | 34fae15d56022c656e98b1a3697db702 | 33.483871 | 83 | 0.656648 | 3.409938 | false | false | false | false |
ravenshore/iOS-Floaters | floaters/Floater.swift | 1 | 8128 | //
// floater.swift
// floaters
//
// Created by Razvigor Andreev on 2/8/16.
// Copyright © 2016 Razvigor Andreev. All rights reserved.
//
import UIKit
@IBDesignable public class Floater: UIView {
var image1: UIImage?
var image2: UIImage?
var image3: UIImage?
var image4: UIImage?
var isAnimating: Bool = false
var views: [UIView]!
var duration: TimeInterval = 1.0
var duration1: TimeInterval = 2.0
var duration2: TimeInterval = 2.0
var floatieSize = CGSize(width: 50, height: 50)
var floatieDelay: Double = 10
var delay: Double = 10.0
var startingAlpha: CGFloat = 1.0
var endingAlpha: CGFloat = 0.0
var upwards: Bool = true
var remove: Bool = true
@IBInspectable var removeAtEnd: Bool = true {
didSet {
remove = removeAtEnd
}
}
@IBInspectable var FloatingUp: Bool = true {
didSet {
upwards = FloatingUp
}
}
@IBInspectable var alphaAtStart: CGFloat = 1.0 {
didSet {
startingAlpha = alphaAtStart
}
}
@IBInspectable var alphaAtEnd: CGFloat = 0.0 {
didSet {
endingAlpha = alphaAtEnd
}
}
@IBInspectable var rotationSpeed: Double = 10 {
didSet {
duration2 = 20 / rotationSpeed
}
}
@IBInspectable var density: Double = 10 {
didSet {
floatieDelay = 1 / density
}
}
@IBInspectable var delayedStart: Double = 10 {
didSet {
delay = delayedStart
}
}
@IBInspectable var speedY: CGFloat = 10 {
didSet {
duration = Double(10/speedY)
}
}
@IBInspectable var speedX: CGFloat = 5 {
didSet {
duration1 = Double(10/speedX)
}
}
@IBInspectable var floatieWidth: CGFloat = 50 {
didSet {
floatieSize.width = floatieWidth
}
}
@IBInspectable var floatieHeight: CGFloat = 50 {
didSet {
floatieSize.height = floatieHeight
}
}
@IBInspectable var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var floaterImage1: UIImage? {
didSet {
image1 = floaterImage1
}
}
@IBInspectable var floaterImage2: UIImage? {
didSet {
image2 = floaterImage2
}
}
@IBInspectable var floaterImage3: UIImage? {
didSet {
image3 = floaterImage3
}
}
@IBInspectable var floaterImage4: UIImage? {
didSet {
image4 = floaterImage4
}
}
override public func awakeFromNib() {
super.awakeFromNib()
}
func startAnimation() {
if !isAnimating {
print("Start Animating")
isAnimating = true
views = []
var imagesArray = [UIImage?]()
var actualImages = [UIImage]()
let frameW = self.frame.width
let frameH = self.frame.height
var startingPoint: CGFloat!
var endingPoint: CGFloat!
if upwards {
startingPoint = frameH
endingPoint = floatieHeight*2
} else {
startingPoint = 0
endingPoint = frameH - floatieHeight*2
}
imagesArray += [image1, image2, image3, image4]
if !imagesArray.isEmpty {
for i in imagesArray {
if i != nil {
actualImages.append(i!)
}
}
}
DispatchQueue.global(qos: .background).async {
var next = true
while self.isAnimating {
if next {
next = false
DispatchQueue.main.asyncAfter(deadline: .now() + self.floatieDelay) {
let randomNumber = self.randomIntBetweenNumbers(firstNum: 1, secondNum: 2)
var randomRotation: CGFloat!
if randomNumber == 1 {
randomRotation = -1
} else {
randomRotation = 1
}
let randomX = self.randomFloatBetweenNumbers(firstNum: 0 + self.floatieSize.width/2, secondNum: self.frame.width - self.floatieSize.width/2)
let floatieView = UIView(frame: CGRect(x: randomX, y: startingPoint, width: 50, height: 50))
self.addSubview(floatieView)
let floatie = UIImageView(frame: CGRect(x: 0, y: 0, width: self.floatieSize.width, height: self.floatieSize.height))
if !actualImages.isEmpty {
let randomImageIndex = (self.randomIntBetweenNumbers(firstNum: 1, secondNum: actualImages.count) - 1 )
floatie.image = actualImages[randomImageIndex]
floatie.center = CGPoint(x: 0, y: 0)
floatie.backgroundColor = UIColor.clear
floatie.layer.zPosition = 10
floatie.alpha = self.startingAlpha
floatieView.addSubview(floatie)
var xChange: CGFloat!
if randomX < self.frame.width/2 {
xChange = randomX + self.randomFloatBetweenNumbers(firstNum: randomX, secondNum: frameW-randomX)
} else {
xChange = self.randomFloatBetweenNumbers(firstNum: self.floatieSize.width*2, secondNum: randomX)
}
self.views.append(floatieView)
UIView.animate(withDuration: self.duration, delay: 0,
options: [], animations: {
floatieView.center.y = endingPoint
floatie.alpha = self.endingAlpha
next = true
}, completion: {(value: Bool) in
if self.remove {
floatieView.removeFromSuperview()
}
})
UIView.animate(withDuration: self.duration1, delay: 0,
options: [.repeat, .autoreverse], animations: {
floatieView.center.x = xChange
}, completion: nil)
UIView.animate(withDuration: self.duration2, delay: 0, options: [.repeat, .autoreverse], animations: {floatieView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)*randomRotation)
}, completion: nil)
}
}
}
}
}
} else {
print("Already Animating")
}
}
func stopAnimation() {
print("Stop Animating")
views = []
isAnimating = false
if !views.isEmpty {
for i in views {
i.removeFromSuperview()
}
}
}
func randomFloatBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}
func randomIntBetweenNumbers(firstNum: Int, secondNum: Int) -> Int{
return firstNum + Int(arc4random_uniform(UInt32(secondNum - firstNum + 1)))
}
}
| mit | 0ef068f0b51d63257000cb4af3a3f923 | 32.582645 | 225 | 0.495017 | 5.079375 | false | false | false | false |
OpenKitten/BSON | Sources/BSON/Codable/Decoding/UnkeyedBSONDecodingContainer.swift | 1 | 5511 | import Foundation
internal struct UnkeyedBSONDecodingContainer: UnkeyedDecodingContainer {
var codingPath: [CodingKey]
var count: Int? {
return self.iterator.count
}
var isAtEnd: Bool {
return self.iterator.isDrained
}
var currentIndex: Int {
return self.iterator.currentIndex
}
let decoder: _BSONDecoder
var iterator: DocumentPairIterator
mutating func nextElement() throws -> DecoderValue {
guard let pair = iterator.next() else {
throw EndOfBSONDocument()
}
return .primitive(pair.value)
}
init(decoder: _BSONDecoder, codingPath: [CodingKey]) throws {
guard let document = decoder.document else {
throw DecodingError.valueNotFound(Document.self, .init(codingPath: codingPath, debugDescription: "An unkeyed container could not be made because the value is not a document"))
}
self.decoder = decoder
self.codingPath = codingPath
self.iterator = document.pairs
}
func decodeNil() -> Bool {
if case .nothing = self.decoder.wrapped {
return true
}
return false
}
func decode(_ type: Bool.Type) throws -> Bool {
return try self.decoder.wrapped.unwrap(asType: Bool.self, path: self.codingPath.path)
}
func decode(_ type: String.Type) throws -> String {
return try self.decoder.settings.stringDecodingStrategy.decode(from: decoder, path: self.codingPath.path)
}
func decode(_ type: Double.Type) throws -> Double {
return try self.decoder.settings.doubleDecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: Float.Type) throws -> Float {
return try self.decoder.settings.floatDecodingStrategy.decode(from: self.decoder.wrapped, path: self.codingPath.path)
}
func decode(_ type: Int.Type) throws -> Int {
return try self.decoder.settings.intDecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: Int8.Type) throws -> Int8 {
return try self.decoder.settings.int8DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: Int16.Type) throws -> Int16 {
return try self.decoder.settings.int16DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: Int32.Type) throws -> Int32 {
return try self.decoder.settings.int32DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: Int64.Type) throws -> Int64 {
return try self.decoder.settings.int64DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: UInt.Type) throws -> UInt {
return try self.decoder.settings.uintDecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return try self.decoder.settings.uint8DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return try self.decoder.settings.uint16DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return try self.decoder.settings.uint32DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return try self.decoder.settings.uint64DecodingStrategy.decode(from: self.decoder, path: self.codingPath.path)
}
mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if type is Primitive.Type {
let element = try self.nextElement().primitive
if let value = element as? T {
return value
} else {
throw BSONTypeConversionError(from: element, to: type)
}
} else if let type = T.self as? BSONDataType.Type {
return try type.init(primitive: self.nextElement().primitive) as! T
} else {
let decoder = try _BSONDecoder(wrapped: self.nextElement(), settings: self.decoder.settings, codingPath: self.codingPath, userInfo: self.decoder.userInfo)
return try type.init(from: decoder)
}
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
let document = try self.decode(Document.self)
let decoder = _BSONDecoder(wrapped: .document(document), settings: self.decoder.settings, codingPath: self.codingPath, userInfo: self.decoder.userInfo)
return KeyedDecodingContainer(KeyedBSONDecodingContainer(for: decoder, codingPath: self.codingPath))
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
let document = try self.decode(Document.self)
let decoder = _BSONDecoder(wrapped: .document(document), settings: self.decoder.settings, codingPath: self.codingPath, userInfo: self.decoder.userInfo)
return try UnkeyedBSONDecodingContainer(decoder: decoder, codingPath: self.codingPath)
}
mutating func superDecoder() throws -> Decoder {
return self.decoder
}
}
| mit | e97689a5698274478590d94b624f8497 | 39.522059 | 187 | 0.662493 | 4.487785 | false | false | false | false |
luzefeng/iOS8-day-by-day | 24-presentation-controllers/BouncyPresent/BouncyPresent/OverlayViewController.swift | 22 | 1190 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class OverlayViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// These settings are of questionable (OK, they look shit) style, but I never said I was a designer
view.layer.cornerRadius = 20.0
view.layer.shadowColor = UIColor.blackColor().CGColor
view.layer.shadowOffset = CGSizeMake(0, 0)
view.layer.shadowRadius = 10
view.layer.shadowOpacity = 0.5
}
@IBAction func handleDismissedPressed(sender: AnyObject) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 | d7b0c54070ed2e975b3c5190efee3108 | 31.162162 | 103 | 0.733613 | 4.358974 | false | false | false | false |
dannofx/AudioPal | AudioPal/AudioPal/SetNameViewController.swift | 1 | 3928 | //
// SetNameViewController.swift
// AudioPal
//
// Created by Danno on 5/18/17.
// Copyright © 2017 Daniel Heredia. All rights reserved.
//
import UIKit
class SetNameViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var logoContainer: UIView!
@IBOutlet weak var logoConstraint: NSLayoutConstraint!
var initialLogoValue: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
startButton.isEnabled = false
nameTextField.delegate = self
initialLogoValue = logoConstraint.constant
if logoContainer.frame.origin.y < 0.0 {
initialLogoValue += logoContainer.frame.origin.y
}
addStyle()
prepareForAnimation()
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.animatePhase1()
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isPortrait || UIDevice.current.orientation.isFlat {
self.logoContainer.isHidden = false
} else {
self.logoContainer.isHidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didChangeText(sender: UITextField) {
startButton.isEnabled = sender.text != ""
}
@IBAction func startApp(sender: UIButton) {
UserDefaults.standard.setValue(nameTextField?.text, forKey: StoredValues.username)
let username: String = nameTextField!.text!
let userInfo: [AnyHashable : Any] = [StoredValues.username: username]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationNames.userReady),
object: self,
userInfo: userInfo)
self.dismiss(animated: true)
}
@IBAction func hideKeyboard(sender: UIView) {
self.view.endEditing(true)
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
// MARK: - Add style
private extension SetNameViewController {
func addStyle() {
// Textfield
let border = CALayer()
let width: CGFloat = 2.0
border.borderColor = UIColor.untLightYellow.cgColor
let y = nameTextField.frame.height - width
let frameWidth = nameTextField.frame.width
border.frame = CGRect(x: 0.0, y: y, width: frameWidth, height: width)
border.borderWidth = width
nameTextField.layer.addSublayer(border)
nameTextField.layer.masksToBounds = false
}
func prepareForAnimation() {
self.logoConstraint.constant = -20
self.startButton.isHidden = true
self.nameTextField.isHidden = true
self.nameLabel.isHidden = true
}
func animatePhase1() {
self.logoConstraint.constant = self.initialLogoValue
self.view.setNeedsUpdateConstraints()
UIView.animate(withDuration: 1.0, animations: {
self.view.layoutIfNeeded()
}) { _ in
self.animatePhase2()
}
}
func animatePhase2() {
UIView.transition(with: self.view,
duration: 1.0,
options: .transitionCrossDissolve,
animations: {
self.startButton.isHidden = false
self.nameTextField.isHidden = false
self.nameLabel.isHidden = false
})
}
}
| mit | 0b238af783185c3a01b72ce16ef89085 | 30.669355 | 112 | 0.610135 | 5.113281 | false | false | false | false |
silence0201/Swift-Study | AdvancedSwift/错误处理/Higher-Order Functions and Errors.playgroundpage/Contents.swift | 1 | 4842 | /*:
## Higher-Order Functions and Errors
One domain where Swift's error handling unfortunately does *not* work very well
is asynchronous APIs that need to pass errors to the caller in callback
functions. Let's look at a function that asynchronously computes a large number
and calls back our code when the computation has finished:
*/
//#-hidden-code
import Foundation
//#-end-hidden-code
func compute(callback: (Int) -> ())
//#-hidden-code
{
// Dummy implementation: generate a random number
let random = Int(arc4random())
callback(random)
}
//#-end-hidden-code
/*:
We can call it by providing a callback function. The callback receives the
result as the only parameter:
*/
//#-editable-code
compute { result in
print(result)
}
//#-end-editable-code
/*:
If the computation can fail, we could specify that the callback receives an
optional integer, which would be `nil` in case of a failure:
*/
//#-editable-code
func computeOptional(callback: (Int?) -> ())
//#-end-editable-code
//#-hidden-code
{
// Dummy implementation: generate a random number, sometimes return nil
let random = Int(arc4random())
if random % 3 == 0 { callback(nil) }
else { callback(random) }
}
//#-end-hidden-code
/*:
Now, in our callback, we must check whether the optional is non-`nil`, e.g. by
using the `??` operator:
*/
//#-editable-code
computeOptional { result in
print(result ?? -1)
}
//#-end-editable-code
/*:
But what if we want to report specific errors to the callback, rather than just
an optional? This function signature seems like a natural solution:
``` swift-example
func computeThrows(callback: Int throws -> ())
```
Perhaps surprisingly, this type has a totally different meaning. Instead of
saying that the computation might fail, it expresses that the callback itself
could throw an error. This highlights the key difference that we mentioned
earlier: optionals and `Result` work on types, whereas `throws` works only on
function types. Annotating a function with `throws` means that the *function*
might fail.
It becomes a bit clearer when we try to rewrite the wrong attempt from above
using `Result`:
``` swift-example
func computeResult(callback: Int -> Result<()>)
```
This isn't correct either. We need to wrap the `Int` argument in a `Result`, not
the callback's return type. Finally, this is the correct solution:
*/
//#-hidden-code
enum Result<A> {
case failure(Error)
case success(A)
}
//#-end-hidden-code
//#-hidden-code
struct ComputeError: Error {}
//#-end-hidden-code
//#-editable-code
func computeResult(callback: (Result<Int>) -> ())
//#-end-editable-code
//#-hidden-code
{
// Dummy implementation: generate a random number, sometimes return nil
let random = Int(arc4random())
if random % 3 == 0 { callback(.failure(ComputeError())) }
else { callback(.success(random)) }
}
//#-end-hidden-code
/*:
Unfortunately, there's currently no clear way to write the variant above with
`throws`. The best we can do is wrap the `Int` inside another throwing function.
This makes the type more complicated:
``` swift-example
func compute(callback: (() throws -> Int) -> ())
```
And using this variant becomes more complicated for the caller too. In order to
get the integer out, the callback now has to call the throwing function. This is
where the caller must perform the error checking:
``` swift-example
compute { (resultFunc: () throws -> Int) in
do {
let result = try resultFunc()
print(result)
} catch {
print("An error occurred: \(error)")
}
}
```
This works, but it's definitely not idiomatic Swift; `Result` is the way to go
for asynchronous error handling. It's unfortunate that this creates an impedance
mismatch with synchronous functions that use `throws`. The Swift team has
expressed interest in extending the `throws` model to other scenarios, but this
will likely be part of the much greater task of adding native concurrency
features to the language, and that won't happen until after Swift 4.
Until then, we're stuck with using our own custom `Result` types. Apple did
consider adding a `Result` type to the standard library, but ultimately [decided
against
it](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001433.html)
on the grounds that it wasn't independently valuable enough outside the error
handling domain and that the team didn't want to endorse it as an alternative to
`throws`-style error handling. Luckily, using `Result` for asynchronous APIs is
a pretty well established practice among the Swift developer community, so you
shouldn't hesitate to use it in your APIs when the native error handling isn't
appropriate. It certainly beats the Objective-C style of having completion
handlers with two nullable arguments (a result object and an error object).
*/
| mit | 39df9ca2ad5a9c9869779efaf664d7c1 | 28.888889 | 87 | 0.731929 | 4.028286 | false | false | false | false |
buyiyang/iosstar | iOSStar/General/Extension/UIBarButtonItem+Category.swift | 4 | 1660 | //
// UIBarButtonItem+Category.swift
// iOSStar
//
// Created by MONSTER on 2017/6/21.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
import UIKit
extension UIBarButtonItem {
class func creatBarButtonItem(title : String , target : Any? ,action : Selector) -> UIBarButtonItem {
let btn = UIButton()
var countStringTitle = title
// 是否以 "+" 结尾
if countStringTitle.hasSuffix("+") {
countStringTitle.remove(at: countStringTitle.index(before: countStringTitle.endIndex))
}
let titleNum = Int(countStringTitle)
if titleNum! <= 9 {
btn.width = 20
btn.height = 20
} else {
btn.width = 20 + 10
btn.height = 20
}
btn.layer.cornerRadius = 10;
btn.layer.masksToBounds = true;
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
btn.setTitle(title, for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.backgroundColor = UIColor.red
btn.addTarget(target, action: action, for: .touchUpInside)
return UIBarButtonItem(customView: btn)
}
class func creatRightBarButtonItem(title:String, target : Any? ,action : Selector) -> UIBarButtonItem {
let btn = UIButton()
btn.setTitle(title, for: .normal)
let color = UIColor(hexString: AppConst.Color.main)
btn.setTitleColor(color, for: .normal)
btn.addTarget(target, action: action, for: .touchUpInside)
btn.sizeToFit()
return UIBarButtonItem(customView: btn)
}
}
| gpl-3.0 | 3140b0804106d72ae9eb84dc5332f093 | 28.945455 | 107 | 0.607772 | 4.403743 | false | false | false | false |
pepincho/Scrabble-Engine | Sources/Board.swift | 1 | 6325 | import Foundation
enum Direction {
case Horizontal
case Vertical
}
class Board {
let nrows: Int
let ncolumns: Int
let middle: Coordinate
var cells: [[Cell]]
typealias Coordinate = (row: Int, col: Int)
init(dims: (Int, Int)) {
nrows = dims.0
ncolumns = dims.1
middle = (row: nrows / 2, col: ncolumns / 2)
cells = []
for _ in 0..<nrows {
var row : [Cell] = []
for _ in 0..<ncolumns {
row.append(Cell())
}
cells.append(row)
}
}
convenience init?(dim: Int) {
self.init(dims: (dim, dim))
}
private func indexIsValid(_ row: Int, _ col: Int) -> Bool {
return row >= 0 && row < nrows && col >= 0 && col < ncolumns
}
///
/// проверява дали координатите на думата са валидни
///
private func wordCoordinatesAreValid(_ coordinates: Coordinate, _ direction: Direction, _ letters_count: Int) -> Bool {
let start_index_is_valid = indexIsValid(coordinates.row, coordinates.col)
var end_index_is_valid: Bool
switch direction {
case .Horizontal:
end_index_is_valid = indexIsValid(coordinates.row, coordinates.col + letters_count - 1)
case .Vertical:
end_index_is_valid = indexIsValid(coordinates.row + letters_count - 1, coordinates.col)
}
return start_index_is_valid && end_index_is_valid
}
// subscript(coordinate: Coordinate) -> Cell {
subscript(row: Int, col: Int) -> Cell {
get {
// assert(indexIsValid(row: coordinate.row, column: coordinate.col), "Index out of range")
assert(indexIsValid(row, col), "Index out of range")
return cells[row][col]
}
set {
// assert(indexIsValid(row: coordinate.row, column: coordinate.col), "Index out of range")
assert(indexIsValid(row, col), "Index out of range")
cells[row][col] = newValue
}
}
///
/// checks is it possible to write a word on the board
/// като проверява дали има плочки върху които ще се изписва думата
///
private func tryWord(_ tiles: [Tile], _ letters_count: Int, _ start_row_col: Coordinate, _ direction: Direction) -> Bool {
if direction == .Horizontal {
for i in 0..<letters_count {
if self[start_row_col.row, start_row_col.col + i].hasTile() == true {
// && self[start_row_col.row, start_row_col.col + i].tile!.letter != tiles[i].letter {
return false
}
}
} else {
for i in 0..<letters_count {
if self[start_row_col.row + i, start_row_col.col].hasTile() == true {
// && self[start_row_col.row, start_row_col.col + i].tile!.letter != tiles[i].letter {
return false
}
}
}
return true
}
///
/// check the center cell of the board
///
func isEmpty() -> Bool {
return cells[middle.row][middle.col].hasTile() == false
}
///
/// това е помощна функция
/// добавя плочките за думата върху дъската
/// и пресметя точките от написаната дума
///
private func addWordCalcHelper(_ tiles: [Tile], _ start: Coordinate, _ direction: Direction) -> Int {
var score = 0
var ws_multipliers: [Int] = []
for (indx, tile) in tiles.enumerated() {
var curr_indx = start
switch direction {
case .Horizontal:
curr_indx.col = curr_indx.col + indx
case .Vertical:
curr_indx.row = curr_indx.row + indx
}
var ls_multiplier = 1
let curr_cell = self[curr_indx.row, curr_indx.col]
if curr_cell.bonusType != nil {
if curr_cell.bonusType! == "WS" {
ws_multipliers.append(curr_cell.bonusMultiplier!)
} else {
ls_multiplier = curr_cell.bonusMultiplier!
}
}
if self[curr_indx.row, curr_indx.col].hasTile() == false {
self[curr_indx.row, curr_indx.col].setTile(tile: tile)
score = score + tile.score * ls_multiplier
}
else if self[curr_indx.row, curr_indx.col].hasTile() == true
&& self[curr_indx.row, curr_indx.col].tile!.letter == tile.letter {
score = score + tile.score * ls_multiplier
}
}
for i in ws_multipliers {
score = score * i
}
return score
}
///
/// returns the score of the word and add tiles to the board
///
func addWord(tiles_word: [Tile], start_row_col: Coordinate, direction: Direction) -> Int {
if self.isEmpty() && start_row_col != middle {
print("The first word should start from the middle of the board!")
return 0
}
if tryWord(tiles_word, tiles_word.count, start_row_col, direction) == false
|| wordCoordinatesAreValid(start_row_col, direction, tiles_word.count) == false {
print("Can't write the word on the board!")
return 0
} else {
// put the tiles on the board
// calculate the score of the word
return addWordCalcHelper(tiles_word, start_row_col, direction)
}
}
///
/// запазваме моментното съдържание на дъската във файл
/// като бонусите и плочките върху клетките от дъската
///
func saveBoardToFile() {
let new_saved_game_file = FileManager.default.currentDirectoryPath + "/Sources/new_saved_game.txt"
Parser.writeToFile(content: "--BOARD--", filePath: new_saved_game_file)
Parser.writeToFile(content: "\(nrows) \(ncolumns)", filePath: new_saved_game_file)
for i in 0..<nrows {
for j in 0..<ncolumns {
var line = ""
if self[i, j].hasBonus() == true && self[i, j].hasTile() == true {
line += "\(i) \(j) \(self[i, j].bonusType!) \(self[i, j].bonusMultiplier!)"
line += "\n"
line += "\(i) \(j) \(self[i, j].tile!.letter) \(self[i, j].tile!.score)"
}
else if self[i, j].hasBonus() == true && self[i, j].hasTile() == false {
line += "\(i) \(j) \(self[i, j].bonusType!) \(self[i, j].bonusMultiplier!)"
}
else if self[i, j].hasBonus() == false && self[i, j].hasTile() == true {
line += "\(i) \(j) \(self[i, j].tile!.letter) \(self[i, j].tile!.score)"
}
if line != "" {
Parser.writeToFile(content: line, filePath: new_saved_game_file)
}
}
}
}
}
extension Board: CustomStringConvertible {
var description: String {
return cells.map { row in row.map { $0.description }.joined(separator: " | ") }
.joined(separator: "\n\n") + "\n\n"
}
}
| mit | bf8954bf2f048f039cbccc64be5031f3 | 29.437186 | 123 | 0.616477 | 3.052923 | false | false | false | false |
NqiOS/DYTV-swift | DYTV/DYTV/Classes/Main/View/NQCollectionBaseCell.swift | 1 | 1226 | //
// NQCollectionBaseCell.swift
// DYTV
//
// Created by djk on 17/3/13.
// Copyright © 2017年 NQ. All rights reserved.
//
import UIKit
import Kingfisher
class NQCollectionBaseCell: UICollectionViewCell {
// MARK:- 控件属性
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nickNameLabel: UILabel!
// MARK:- 定义模型
var anchor : NQAnchorModel? {
didSet {
// 0.校验模型是否有值
guard let anchor = anchor else { return }
// 1.取出在线人数显示的文字
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线"
} else {
onlineStr = "\(anchor.online)在线"
}
onlineBtn.setTitle(onlineStr, for: UIControlState())
// 2.昵称的显示
nickNameLabel.text = anchor.nickname
// 3.设置封面图片
guard let iconURL = URL(string: anchor.vertical_src) else { return }
iconImageView.kf.setImage(with: iconURL)
}
}
}
| mit | f1001345fbf44937cfb2749e6982bb02 | 25.44186 | 80 | 0.547054 | 4.511905 | false | false | false | false |
pomozoff/XCGLogger | XCGLogger/Library/XCGLogger/XCGLogger.swift | 1 | 36354 | //
// XCGLogger.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2014-06-06.
// Copyright (c) 2014 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
#if os(OSX)
import AppKit
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
// MARK: - XCGLogDetails
// - Data structure to hold all info about a log message, passed to log destination classes
public struct XCGLogDetails {
public var logLevel: XCGLogger.LogLevel
public var date: NSDate
public var logMessage: String
public var functionName: String
public var fileName: String
public var lineNumber: Int
public init(logLevel: XCGLogger.LogLevel, date: NSDate, logMessage: String, functionName: String, fileName: String, lineNumber: Int) {
self.logLevel = logLevel
self.date = date
self.logMessage = logMessage
self.functionName = functionName
self.fileName = fileName
self.lineNumber = lineNumber
}
}
// MARK: - XCGLogDestinationProtocol
// - Protocol for output classes to conform to
public protocol XCGLogDestinationProtocol: CustomDebugStringConvertible {
var owner: XCGLogger {get set}
var identifier: String {get set}
var outputLogLevel: XCGLogger.LogLevel {get set}
func processLogDetails(logDetails: XCGLogDetails)
func processInternalLogDetails(logDetails: XCGLogDetails) // Same as processLogDetails but should omit function/file/line info
func isEnabledForLogLevel(logLevel: XCGLogger.LogLevel) -> Bool
}
// MARK: - XCGBaseLogDestination
// - A base class log destination that doesn't actually output the log anywhere and is intented to be subclassed
public class XCGBaseLogDestination: XCGLogDestinationProtocol, CustomDebugStringConvertible {
// MARK: - Properties
public var owner: XCGLogger
public var identifier: String
public var outputLogLevel: XCGLogger.LogLevel = .Debug
public var showLogIdentifier: Bool = false
public var showFunctionName: Bool = true
public var showThreadName: Bool = false
public var showFileName: Bool = true
public var showLineNumber: Bool = true
public var showLogLevel: Bool = true
public var showDate: Bool = true
// MARK: - CustomDebugStringConvertible
public var debugDescription: String {
get {
return "\(extractClassName(self)): \(identifier) - LogLevel: \(outputLogLevel) showLogIdentifier: \(showLogIdentifier) showFunctionName: \(showFunctionName) showThreadName: \(showThreadName) showLogLevel: \(showLogLevel) showFileName: \(showFileName) showLineNumber: \(showLineNumber) showDate: \(showDate)"
}
}
// MARK: - Life Cycle
public init(owner: XCGLogger, identifier: String = "") {
self.owner = owner
self.identifier = identifier
}
// MARK: - Methods to Process Log Details
public func processLogDetails(logDetails: XCGLogDetails) {
var extendedDetails: String = ""
if showDate {
var formattedDate: String = logDetails.date.description
if let dateFormatter = owner.dateFormatter {
formattedDate = dateFormatter.stringFromDate(logDetails.date)
}
extendedDetails.appendContentsOf(formattedDate + " ")
}
if showLogLevel {
extendedDetails += "[\(logDetails.logLevel)] "
}
if showLogIdentifier {
extendedDetails += "[\(owner.identifier)] "
}
if showThreadName {
if NSThread.isMainThread() {
extendedDetails += "[main] "
}
else {
if let threadName = NSThread.currentThread().name where !threadName.isEmpty {
extendedDetails += "[" + threadName + "] "
}
else if let queueName = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)) where !queueName.isEmpty {
extendedDetails += "[" + queueName + "] "
}
else {
extendedDetails += "[" + String(format:"%p", NSThread.currentThread()) + "] "
}
}
}
if showFileName {
extendedDetails += "[" + (logDetails.fileName as NSString).lastPathComponent + (showLineNumber ? ":" + String(logDetails.lineNumber) : "") + "] "
}
else if showLineNumber {
extendedDetails += "[" + String(logDetails.lineNumber) + "] "
}
if showFunctionName {
extendedDetails.appendContentsOf(logDetails.functionName + " ")
}
extendedDetails.appendContentsOf("> " + logDetails.logMessage)
output(logDetails, text: extendedDetails)
}
public func processInternalLogDetails(logDetails: XCGLogDetails) {
var extendedDetails: String = ""
if showDate {
var formattedDate: String = logDetails.date.description
if let dateFormatter = owner.dateFormatter {
formattedDate = dateFormatter.stringFromDate(logDetails.date)
}
extendedDetails += "\(formattedDate) "
}
if showLogLevel {
extendedDetails += "[\(logDetails.logLevel)] "
}
if showLogIdentifier {
extendedDetails += "[\(owner.identifier)] "
}
extendedDetails.appendContentsOf("> " + logDetails.logMessage)
output(logDetails, text: extendedDetails)
}
// MARK: - Misc methods
public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool {
return logLevel >= self.outputLogLevel
}
// MARK: - Methods that must be overriden in subclasses
public func output(logDetails: XCGLogDetails, text: String) {
// Do something with the text in an overridden version of this method
precondition(false, "Must override this")
}
}
// MARK: - XCGConsoleLogDestination
// - A standard log destination that outputs log details to the console
public class XCGConsoleLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var logQueue: dispatch_queue_t? = nil
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let outputClosure = {
let adjustedText: String
if let xcodeColor = (self.xcodeColors ?? self.owner.xcodeColors)[logDetails.logLevel] where self.owner.xcodeColorsEnabled {
adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)"
}
else {
adjustedText = text
}
print("\(adjustedText)")
}
if let logQueue = logQueue {
dispatch_async(logQueue, outputClosure)
}
else {
outputClosure()
}
}
}
// MARK: - XCGNSLogDestination
// - A standard log destination that outputs log details to the console using NSLog instead of println
public class XCGNSLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var logQueue: dispatch_queue_t? = nil
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil
public override var showDate: Bool {
get {
return false
}
set {
// ignored, NSLog adds the date, so we always want showDate to be false in this subclass
}
}
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let outputClosure = {
let adjustedText: String
if let xcodeColor = (self.xcodeColors ?? self.owner.xcodeColors)[logDetails.logLevel] where self.owner.xcodeColorsEnabled {
adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)"
}
else {
adjustedText = text
}
NSLog("%@", adjustedText)
}
if let logQueue = logQueue {
dispatch_async(logQueue, outputClosure)
}
else {
outputClosure()
}
}
}
// MARK: - XCGFileLogDestination
// - A standard log destination that outputs log details to a file
public class XCGFileLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var logQueue: dispatch_queue_t? = nil
private var writeToFileURL: NSURL? = nil {
didSet {
openFile()
}
}
private var logFileHandle: NSFileHandle? = nil
// MARK: - Life Cycle
public init(owner: XCGLogger, writeToFile: AnyObject, identifier: String = "") {
super.init(owner: owner, identifier: identifier)
if writeToFile is NSString {
writeToFileURL = NSURL.fileURLWithPath(writeToFile as! String)
}
else if writeToFile is NSURL {
writeToFileURL = writeToFile as? NSURL
}
else {
writeToFileURL = nil
}
openFile()
}
deinit {
// close file stream if open
closeFile()
}
// MARK: - File Handling Methods
private func openFile() {
if logFileHandle != nil {
closeFile()
}
if let writeToFileURL = writeToFileURL,
let path = writeToFileURL.path {
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
do {
logFileHandle = try NSFileHandle(forWritingToURL: writeToFileURL)
}
catch let error as NSError {
owner._logln("Attempt to open log file for writing failed: \(error.localizedDescription)", logLevel: .Error)
logFileHandle = nil
return
}
owner.logAppDetails(self)
let logDetails = XCGLogDetails(logLevel: .Info, date: NSDate(), logMessage: "XCGLogger writing to log to: \(writeToFileURL)", functionName: "", fileName: "", lineNumber: 0)
owner._logln(logDetails.logMessage, logLevel: logDetails.logLevel)
processInternalLogDetails(logDetails)
}
}
private func closeFile() {
logFileHandle?.closeFile()
logFileHandle = nil
}
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let outputClosure = {
if let encodedData = "\(text)\n".dataUsingEncoding(NSUTF8StringEncoding) {
self.logFileHandle?.writeData(encodedData)
}
}
if let logQueue = logQueue {
dispatch_async(logQueue, outputClosure)
}
else {
outputClosure()
}
}
}
// MARK: - XCGLogger
// - The main logging class
public class XCGLogger: CustomDebugStringConvertible {
// MARK: - Constants
public struct Constants {
public static let defaultInstanceIdentifier = "com.cerebralgardens.xcglogger.defaultInstance"
public static let baseConsoleLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console"
public static let nslogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console.nslog"
public static let baseFileLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.file"
public static let logQueueIdentifier = "com.cerebralgardens.xcglogger.queue"
public static let nsdataFormatterCacheIdentifier = "com.cerebralgardens.xcglogger.nsdataFormatterCache"
public static let versionString = "3.3"
}
public typealias constants = Constants // Preserve backwards compatibility: Constants should be capitalized since it's a type
// MARK: - Enums
public enum LogLevel: Int, Comparable, CustomStringConvertible {
case Verbose
case Debug
case Info
case Warning
case Error
case Severe
case None
public var description: String {
switch self {
case .Verbose:
return "Verbose"
case .Debug:
return "Debug"
case .Info:
return "Info"
case .Warning:
return "Warning"
case .Error:
return "Error"
case .Severe:
return "Severe"
case .None:
return "None"
}
}
}
public struct XcodeColor {
public static let escape = "\u{001b}["
public static let resetFg = "\u{001b}[fg;"
public static let resetBg = "\u{001b}[bg;"
public static let reset = "\u{001b}[;"
public var fg: (Int, Int, Int)? = nil
public var bg: (Int, Int, Int)? = nil
public func format() -> String {
guard fg != nil || bg != nil else {
// neither set, return reset value
return XcodeColor.reset
}
var format: String = ""
if let fg = fg {
format += "\(XcodeColor.escape)fg\(fg.0),\(fg.1),\(fg.2);"
}
else {
format += XcodeColor.resetFg
}
if let bg = bg {
format += "\(XcodeColor.escape)bg\(bg.0),\(bg.1),\(bg.2);"
}
else {
format += XcodeColor.resetBg
}
return format
}
public init(fg: (Int, Int, Int)? = nil, bg: (Int, Int, Int)? = nil) {
self.fg = fg
self.bg = bg
}
#if os(OSX)
public init(fg: NSColor, bg: NSColor? = nil) {
if let fgColorSpaceCorrected = fg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.fg = (Int(fgColorSpaceCorrected.redComponent * 255), Int(fgColorSpaceCorrected.greenComponent * 255), Int(fgColorSpaceCorrected.blueComponent * 255))
}
else {
self.fg = nil
}
if let bg = bg,
let bgColorSpaceCorrected = bg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.bg = (Int(bgColorSpaceCorrected.redComponent * 255), Int(bgColorSpaceCorrected.greenComponent * 255), Int(bgColorSpaceCorrected.blueComponent * 255))
}
else {
self.bg = nil
}
}
#elseif os(iOS) || os(tvOS) || os(watchOS)
public init(fg: UIColor, bg: UIColor? = nil) {
var redComponent: CGFloat = 0
var greenComponent: CGFloat = 0
var blueComponent: CGFloat = 0
var alphaComponent: CGFloat = 0
fg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.fg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
if let bg = bg {
bg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.bg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
}
else {
self.bg = nil
}
}
#endif
public static let red: XcodeColor = {
return XcodeColor(fg: (255, 0, 0))
}()
public static let green: XcodeColor = {
return XcodeColor(fg: (0, 255, 0))
}()
public static let blue: XcodeColor = {
return XcodeColor(fg: (0, 0, 255))
}()
public static let black: XcodeColor = {
return XcodeColor(fg: (0, 0, 0))
}()
public static let white: XcodeColor = {
return XcodeColor(fg: (255, 255, 255))
}()
public static let lightGrey: XcodeColor = {
return XcodeColor(fg: (211, 211, 211))
}()
public static let darkGrey: XcodeColor = {
return XcodeColor(fg: (169, 169, 169))
}()
public static let orange: XcodeColor = {
return XcodeColor(fg: (255, 165, 0))
}()
public static let whiteOnRed: XcodeColor = {
return XcodeColor(fg: (255, 255, 255), bg: (255, 0, 0))
}()
public static let darkGreen: XcodeColor = {
return XcodeColor(fg: (0, 128, 0))
}()
}
// MARK: - Properties (Options)
public var identifier: String = ""
public var outputLogLevel: LogLevel = .Debug {
didSet {
for index in 0 ..< logDestinations.count {
logDestinations[index].outputLogLevel = outputLogLevel
}
}
}
public var xcodeColorsEnabled: Bool = false
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor] = [
.Verbose: .lightGrey,
.Debug: .darkGrey,
.Info: .blue,
.Warning: .orange,
.Error: .red,
.Severe: .whiteOnRed
]
// MARK: - Properties
public class var logQueue: dispatch_queue_t {
struct Statics {
static var logQueue = dispatch_queue_create(XCGLogger.Constants.logQueueIdentifier, nil)
}
return Statics.logQueue
}
private var _dateFormatter: NSDateFormatter? = nil
public var dateFormatter: NSDateFormatter? {
get {
if _dateFormatter != nil {
return _dateFormatter
}
let defaultDateFormatter = NSDateFormatter()
defaultDateFormatter.locale = NSLocale.currentLocale()
defaultDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
_dateFormatter = defaultDateFormatter
return _dateFormatter
}
set {
_dateFormatter = newValue
}
}
public var logDestinations: Array<XCGLogDestinationProtocol> = []
// MARK: - Life Cycle
public init(identifier: String = "", includeDefaultDestinations: Bool = true) {
self.identifier = identifier
// Check if XcodeColors is installed and enabled
if let xcodeColors = NSProcessInfo.processInfo().environment["XcodeColors"] {
xcodeColorsEnabled = xcodeColors == "YES"
}
if includeDefaultDestinations {
// Setup a standard console log destination
addLogDestination(XCGConsoleLogDestination(owner: self, identifier: XCGLogger.Constants.baseConsoleLogDestinationIdentifier))
}
}
// MARK: - Default instance
public class func defaultInstance() -> XCGLogger {
struct Statics {
static let instance: XCGLogger = XCGLogger(identifier: XCGLogger.Constants.defaultInstanceIdentifier)
}
return Statics.instance
}
// MARK: - Setup methods
public class func setup(logLevel: LogLevel = .Debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) {
defaultInstance().setup(logLevel, showLogIdentifier: showLogIdentifier, showFunctionName: showFunctionName, showThreadName: showThreadName, showLogLevel: showLogLevel, showFileNames: showFileNames, showLineNumbers: showLineNumbers, showDate: showDate, writeToFile: writeToFile)
}
public func setup(logLevel: LogLevel = .Debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) {
outputLogLevel = logLevel;
if let standardConsoleLogDestination = logDestination(XCGLogger.Constants.baseConsoleLogDestinationIdentifier) as? XCGConsoleLogDestination {
standardConsoleLogDestination.showLogIdentifier = showLogIdentifier
standardConsoleLogDestination.showFunctionName = showFunctionName
standardConsoleLogDestination.showThreadName = showThreadName
standardConsoleLogDestination.showLogLevel = showLogLevel
standardConsoleLogDestination.showFileName = showFileNames
standardConsoleLogDestination.showLineNumber = showLineNumbers
standardConsoleLogDestination.showDate = showDate
standardConsoleLogDestination.outputLogLevel = logLevel
}
logAppDetails()
if let writeToFile: AnyObject = writeToFile {
// We've been passed a file to use for logging, set up a file logger
let standardFileLogDestination: XCGFileLogDestination = XCGFileLogDestination(owner: self, writeToFile: writeToFile, identifier: XCGLogger.Constants.baseFileLogDestinationIdentifier)
standardFileLogDestination.showLogIdentifier = showLogIdentifier
standardFileLogDestination.showFunctionName = showFunctionName
standardFileLogDestination.showThreadName = showThreadName
standardFileLogDestination.showLogLevel = showLogLevel
standardFileLogDestination.showFileName = showFileNames
standardFileLogDestination.showLineNumber = showLineNumbers
standardFileLogDestination.showDate = showDate
standardFileLogDestination.outputLogLevel = fileLogLevel ?? logLevel
addLogDestination(standardFileLogDestination)
}
}
// MARK: - Logging methods
public class func logln(@autoclosure(escaping) closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func logln(logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.defaultInstance().logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func logln(@autoclosure(escaping) closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func logln(logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
var logDetails: XCGLogDetails!
for logDestination in self.logDestinations {
guard logDestination.isEnabledForLogLevel(logLevel) else {
continue
}
if logDetails == nil {
guard let logMessage = closure() else {
break
}
logDetails = XCGLogDetails(logLevel: logLevel, date: NSDate(), logMessage: logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
logDestination.processLogDetails(logDetails)
}
}
public class func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) {
self.defaultInstance().exec(logLevel, closure: closure)
}
public func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) {
guard isEnabledForLogLevel(logLevel) else {
return
}
closure()
}
public func logAppDetails(selectedLogDestination: XCGLogDestinationProtocol? = nil) {
let date = NSDate()
var buildString = ""
if let infoDictionary = NSBundle.mainBundle().infoDictionary {
if let CFBundleShortVersionString = infoDictionary["CFBundleShortVersionString"] as? String {
buildString.appendContentsOf("Version: " + CFBundleShortVersionString)
}
if let CFBundleVersion = infoDictionary["CFBundleVersion"] as? String {
buildString.appendContentsOf("Build: " + CFBundleVersion)
}
}
let processInfo: NSProcessInfo = NSProcessInfo.processInfo()
let XCGLoggerVersionNumber = XCGLogger.Constants.versionString
let logMessage0 = processInfo.processName + " " + buildString + "PID: " + String(processInfo.processIdentifier)
let logMessage1 = "XCGLogger Version: " + XCGLoggerVersionNumber + " - LogLevel: \(outputLogLevel)"
let logDetails: Array<XCGLogDetails> = [
XCGLogDetails(logLevel: .Info, date: date, logMessage: logMessage0, functionName: "", fileName: "", lineNumber: 0),
XCGLogDetails(logLevel: .Info, date: date, logMessage: logMessage1, functionName: "", fileName: "", lineNumber: 0),
]
for logDestination in (selectedLogDestination != nil ? [selectedLogDestination!] : logDestinations) {
for logDetail in logDetails {
guard logDestination.isEnabledForLogLevel(.Info) else {
continue
}
logDestination.processInternalLogDetails(logDetail)
}
}
}
// MARK: - Convenience logging methods
// MARK: * Verbose
public class func verbose(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func verbose(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.defaultInstance().logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func verbose(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func verbose(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Debug
public class func debug(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func debug(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.defaultInstance().logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func debug(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func debug(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Info
public class func info(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func info(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.defaultInstance().logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func info(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func info(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Warning
public class func warning(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func warning(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.defaultInstance().logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func warning(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func warning(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Error
public class func error(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func error(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.defaultInstance().logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func error(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func error(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Severe
public class func severe(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func severe(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.defaultInstance().logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func severe(@autoclosure(escaping) closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func severe(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, closure: () -> String?) {
self.logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: - Exec Methods
// MARK: * Verbose
public class func verboseExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Verbose, closure: closure)
}
public func verboseExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Verbose, closure: closure)
}
// MARK: * Debug
public class func debugExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Debug, closure: closure)
}
public func debugExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Debug, closure: closure)
}
// MARK: * Info
public class func infoExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Info, closure: closure)
}
public func infoExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Info, closure: closure)
}
// MARK: * Warning
public class func warningExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Warning, closure: closure)
}
public func warningExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Warning, closure: closure)
}
// MARK: * Error
public class func errorExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Error, closure: closure)
}
public func errorExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Error, closure: closure)
}
// MARK: * Severe
public class func severeExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Severe, closure: closure)
}
public func severeExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Severe, closure: closure)
}
// MARK: - Misc methods
public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool {
return logLevel >= self.outputLogLevel
}
public func logDestination(identifier: String) -> XCGLogDestinationProtocol? {
for logDestination in logDestinations {
if logDestination.identifier == identifier {
return logDestination
}
}
return nil
}
public func addLogDestination(logDestination: XCGLogDestinationProtocol) -> Bool {
let existingLogDestination: XCGLogDestinationProtocol? = self.logDestination(logDestination.identifier)
if existingLogDestination != nil {
return false
}
logDestinations.append(logDestination)
return true
}
public func removeLogDestination(logDestination: XCGLogDestinationProtocol) {
removeLogDestination(logDestination.identifier)
}
public func removeLogDestination(identifier: String) {
logDestinations = logDestinations.filter({$0.identifier != identifier})
}
// MARK: - Private methods
private func _logln(logMessage: String, logLevel: LogLevel = .Debug) {
var logDetails: XCGLogDetails? = nil
for logDestination in self.logDestinations {
if (logDestination.isEnabledForLogLevel(logLevel)) {
if logDetails == nil {
logDetails = XCGLogDetails(logLevel: logLevel, date: NSDate(), logMessage: logMessage, functionName: "", fileName: "", lineNumber: 0)
}
logDestination.processInternalLogDetails(logDetails!)
}
}
}
// MARK: - DebugPrintable
public var debugDescription: String {
get {
var description: String = "\(extractClassName(self)): \(identifier) - logDestinations: \r"
for logDestination in logDestinations {
description += "\t \(logDestination.debugDescription)\r"
}
return description
}
}
}
// Implement Comparable for XCGLogger.LogLevel
public func < (lhs:XCGLogger.LogLevel, rhs:XCGLogger.LogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
func extractClassName(someObject: Any) -> String {
return (someObject is Any.Type) ? "\(someObject)" : "\(someObject.dynamicType)"
}
| mit | 08c9bd241bd7af50b6ae90f20f530445 | 39.348502 | 322 | 0.636656 | 4.983413 | false | false | false | false |
fmpinheiro/taiga-ios | taiga-ios/ResponseCollectionSerializable.swift | 1 | 1605 | //
// ResponseCollectionSerializable.swift
// taiga-ios
//
// Created by Rhonan Carneiro on 21/10/15.
// Copyright © 2015 Taiga. All rights reserved.
//
import Foundation
import Alamofire
public protocol ResponseCollectionSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}
extension Alamofire.Request {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let response = response {
return .Success(T.collection(response: response, representation: value))
} else {
let failureReason = "Response collection could not be serialized due to nil response"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
} | apache-2.0 | 91e1b515735bf8308577c12ff733e85d | 39.125 | 130 | 0.640274 | 5.512027 | false | false | false | false |
SwifterSwift/SwifterSwift | Sources/SwifterSwift/UIKit/UIImageExtensions.swift | 1 | 16432 | // UIImageExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(UIKit)
import UIKit
// MARK: - Properties
public extension UIImage {
/// SwifterSwift: Size in bytes of UIImage.
var bytesSize: Int {
return jpegData(compressionQuality: 1)?.count ?? 0
}
/// SwifterSwift: Size in kilo bytes of UIImage.
var kilobytesSize: Int {
return (jpegData(compressionQuality: 1)?.count ?? 0) / 1024
}
/// SwifterSwift: UIImage with .alwaysOriginal rendering mode.
var original: UIImage {
return withRenderingMode(.alwaysOriginal)
}
/// SwifterSwift: UIImage with .alwaysTemplate rendering mode.
var template: UIImage {
return withRenderingMode(.alwaysTemplate)
}
#if canImport(CoreImage)
/// SwifterSwift: Average color for this image.
func averageColor() -> UIColor? {
// https://stackoverflow.com/questions/26330924
guard let ciImage = ciImage ?? CIImage(image: self) else { return nil }
// CIAreaAverage returns a single-pixel image that contains the average color for a given region of an image.
let parameters = [kCIInputImageKey: ciImage, kCIInputExtentKey: CIVector(cgRect: ciImage.extent)]
guard let outputImage = CIFilter(name: "CIAreaAverage", parameters: parameters)?.outputImage else {
return nil
}
// After getting the single-pixel image from the filter extract pixel's RGBA8 data
var bitmap = [UInt8](repeating: 0, count: 4)
let workingColorSpace: Any = cgImage?.colorSpace ?? NSNull()
let context = CIContext(options: [.workingColorSpace: workingColorSpace])
context.render(outputImage,
toBitmap: &bitmap,
rowBytes: 4,
bounds: CGRect(x: 0, y: 0, width: 1, height: 1),
format: .RGBA8,
colorSpace: nil)
// Convert pixel data to UIColor
return UIColor(red: CGFloat(bitmap[0]) / 255.0,
green: CGFloat(bitmap[1]) / 255.0,
blue: CGFloat(bitmap[2]) / 255.0,
alpha: CGFloat(bitmap[3]) / 255.0)
}
#endif
}
// MARK: - Methods
public extension UIImage {
/// SwifterSwift: Compressed UIImage from original UIImage.
///
/// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5).
/// - Returns: optional UIImage (if applicable).
func compressed(quality: CGFloat = 0.5) -> UIImage? {
guard let data = jpegData(compressionQuality: quality) else { return nil }
return UIImage(data: data)
}
/// SwifterSwift: Compressed UIImage data from original UIImage.
///
/// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5).
/// - Returns: optional Data (if applicable).
func compressedData(quality: CGFloat = 0.5) -> Data? {
return jpegData(compressionQuality: quality)
}
/// SwifterSwift: UIImage Cropped to CGRect.
///
/// - Parameter rect: CGRect to crop UIImage to.
/// - Returns: cropped UIImage
func cropped(to rect: CGRect) -> UIImage {
guard rect.size.width <= size.width, rect.size.height <= size.height else { return self }
let scaledRect = rect.applying(CGAffineTransform(scaleX: scale, y: scale))
guard let image = cgImage?.cropping(to: scaledRect) else { return self }
return UIImage(cgImage: image, scale: scale, orientation: imageOrientation)
}
/// SwifterSwift: UIImage scaled to height with respect to aspect ratio.
///
/// - Parameters:
/// - toHeight: new height.
/// - opaque: flag indicating whether the bitmap is opaque.
/// - Returns: optional scaled UIImage (if applicable).
func scaled(toHeight: CGFloat, opaque: Bool = false) -> UIImage? {
let scale = toHeight / size.height
let newWidth = size.width * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: toHeight), opaque, self.scale)
draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: UIImage scaled to width with respect to aspect ratio.
///
/// - Parameters:
/// - toWidth: new width.
/// - opaque: flag indicating whether the bitmap is opaque.
/// - Returns: optional scaled UIImage (if applicable).
func scaled(toWidth: CGFloat, opaque: Bool = false) -> UIImage? {
let scale = toWidth / size.width
let newHeight = size.height * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: toWidth, height: newHeight), opaque, self.scale)
draw(in: CGRect(x: 0, y: 0, width: toWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: Creates a copy of the receiver rotated by the given angle.
///
/// // Rotate the image by 180°
/// image.rotated(by: Measurement(value: 180, unit: .degrees))
///
/// - Parameter angle: The angle measurement by which to rotate the image.
/// - Returns: A new image rotated by the given angle.
@available(tvOS 10.0, watchOS 3.0, *)
func rotated(by angle: Measurement<UnitAngle>) -> UIImage? {
let radians = CGFloat(angle.converted(to: .radians).value)
let destRect = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: radians))
let roundedDestRect = CGRect(x: destRect.origin.x.rounded(),
y: destRect.origin.y.rounded(),
width: destRect.width.rounded(),
height: destRect.height.rounded())
UIGraphicsBeginImageContextWithOptions(roundedDestRect.size, false, scale)
guard let contextRef = UIGraphicsGetCurrentContext() else { return nil }
contextRef.translateBy(x: roundedDestRect.width / 2, y: roundedDestRect.height / 2)
contextRef.rotate(by: radians)
draw(in: CGRect(origin: CGPoint(x: -size.width / 2,
y: -size.height / 2),
size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: Creates a copy of the receiver rotated by the given angle (in radians).
///
/// // Rotate the image by 180°
/// image.rotated(by: .pi)
///
/// - Parameter radians: The angle, in radians, by which to rotate the image.
/// - Returns: A new image rotated by the given angle.
func rotated(by radians: CGFloat) -> UIImage? {
let destRect = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: radians))
let roundedDestRect = CGRect(x: destRect.origin.x.rounded(),
y: destRect.origin.y.rounded(),
width: destRect.width.rounded(),
height: destRect.height.rounded())
UIGraphicsBeginImageContextWithOptions(roundedDestRect.size, false, scale)
guard let contextRef = UIGraphicsGetCurrentContext() else { return nil }
contextRef.translateBy(x: roundedDestRect.width / 2, y: roundedDestRect.height / 2)
contextRef.rotate(by: radians)
draw(in: CGRect(origin: CGPoint(x: -size.width / 2,
y: -size.height / 2),
size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: UIImage filled with color
///
/// - Parameter color: color to fill image with.
/// - Returns: UIImage filled with given color.
func filled(withColor color: UIColor) -> UIImage {
#if !os(watchOS)
if #available(tvOS 10.0, *) {
let format = UIGraphicsImageRendererFormat()
format.scale = scale
let renderer = UIGraphicsImageRenderer(size: size, format: format)
return renderer.image { context in
color.setFill()
context.fill(CGRect(origin: .zero, size: size))
}
}
#endif
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.setFill()
guard let context = UIGraphicsGetCurrentContext() else { return self }
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
guard let mask = cgImage else { return self }
context.clip(to: rect, mask: mask)
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: UIImage tinted with color.
///
/// - Parameters:
/// - color: color to tint image with.
/// - blendMode: how to blend the tint.
/// - alpha: alpha value used to draw.
/// - Returns: UIImage tinted with given color.
func tint(_ color: UIColor, blendMode: CGBlendMode, alpha: CGFloat = 1.0) -> UIImage {
let drawRect = CGRect(origin: .zero, size: size)
#if !os(watchOS)
if #available(tvOS 10.0, *) {
let format = UIGraphicsImageRendererFormat()
format.scale = scale
return UIGraphicsImageRenderer(size: size, format: format).image { context in
color.setFill()
context.fill(drawRect)
draw(in: drawRect, blendMode: blendMode, alpha: alpha)
}
}
#endif
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
color.setFill()
context?.fill(drawRect)
draw(in: drawRect, blendMode: blendMode, alpha: alpha)
return UIGraphicsGetImageFromCurrentImageContext()!
}
/// SwifterSwift: UImage with background color.
///
/// - Parameters:
/// - backgroundColor: Color to use as background color.
/// - Returns: UIImage with a background color that is visible where alpha < 1.
func withBackgroundColor(_ backgroundColor: UIColor) -> UIImage {
#if !os(watchOS)
if #available(tvOS 10.0, *) {
let format = UIGraphicsImageRendererFormat()
format.scale = scale
return UIGraphicsImageRenderer(size: size, format: format).image { context in
backgroundColor.setFill()
context.fill(context.format.bounds)
draw(at: .zero)
}
}
#endif
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
backgroundColor.setFill()
UIRectFill(CGRect(origin: .zero, size: size))
draw(at: .zero)
return UIGraphicsGetImageFromCurrentImageContext()!
}
/// SwifterSwift: UIImage with rounded corners.
///
/// - Parameters:
/// - radius: corner radius (optional), resulting image will be round if unspecified.
/// - Returns: UIImage with all corners rounded.
func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? {
let maxRadius = min(size.width, size.height) / 2
let cornerRadius: CGFloat
if let radius = radius, radius > 0, radius <= maxRadius {
cornerRadius = radius
} else {
cornerRadius = maxRadius
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let rect = CGRect(origin: .zero, size: size)
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/// SwifterSwift: Base 64 encoded PNG data of the image.
///
/// - Returns: Base 64 encoded PNG data of the image as a String.
func pngBase64String() -> String? {
return pngData()?.base64EncodedString()
}
/// SwifterSwift: Base 64 encoded JPEG data of the image.
///
/// - Parameter: compressionQuality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).
/// - Returns: Base 64 encoded JPEG data of the image as a String.
func jpegBase64String(compressionQuality: CGFloat) -> String? {
return jpegData(compressionQuality: compressionQuality)?.base64EncodedString()
}
/// SwifterSwift: UIImage with color uses .alwaysOriginal rendering mode.
///
/// - Parameters:
/// - color: Color of image.
/// - Returns: UIImage with color.
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
func withAlwaysOriginalTintColor(_ color: UIColor) -> UIImage {
return withTintColor(color, renderingMode: .alwaysOriginal)
}
}
// MARK: - Initializers
public extension UIImage {
/// SwifterSwift: Create UIImage from color and size.
///
/// - Parameters:
/// - color: image fill color.
/// - size: image size.
convenience init(color: UIColor, size: CGSize) {
UIGraphicsBeginImageContextWithOptions(size, false, 1)
defer {
UIGraphicsEndImageContext()
}
color.setFill()
UIRectFill(CGRect(origin: .zero, size: size))
guard let aCgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
self.init()
return
}
self.init(cgImage: aCgImage)
}
/// SwifterSwift: Create a new image from a base 64 string.
///
/// - Parameters:
/// - base64String: a base-64 `String`, representing the image
/// - scale: The scale factor to assume when interpreting the image data created from the base-64 string. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property.
convenience init?(base64String: String, scale: CGFloat = 1.0) {
guard let data = Data(base64Encoded: base64String) else { return nil }
self.init(data: data, scale: scale)
}
/// SwifterSwift: Create a new image from a URL
///
/// - Important:
/// Use this method to convert data:// URLs to UIImage objects.
/// Don't use this synchronous initializer to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
/// Instead, for non-file URLs, consider using this in an asynchronous way, using `dataTask(with:completionHandler:)` method of the URLSession class or a library such as `AlamofireImage`, `Kingfisher`, `SDWebImage`, or others to perform asynchronous network image loading.
/// - Parameters:
/// - url: a `URL`, representing the image location
/// - scale: The scale factor to assume when interpreting the image data created from the URL. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property.
convenience init?(url: URL, scale: CGFloat = 1.0) throws {
let data = try Data(contentsOf: url)
self.init(data: data, scale: scale)
}
}
#endif
| mit | 104950022f6fb2764b9a6914cd1ec5b8 | 41.675325 | 322 | 0.63238 | 4.778941 | false | false | false | false |
sketchytech/Aldwych_JSON_Swift | Sources/JSONSearch.swift | 2 | 7939 | //
// JSONSearch.swift
// SaveFile
//
// Created by Anthony Levings on 06/04/2015.
//
import Foundation
public func replaceStringUsingRegularExpressionInJSONArray(expression exp:String, inout arr:JSONArray, withString string: String,options opt:NSMatchingOptions = nil) {
// make sure we can make type changes everywhere
arr.restrictTypeChanges = false
arr.inheritRestrictions = true
for a in enumerate(arr) {
if let array = a.element.jsonArr {
replaceStringUsingRegularExpressionInJSONArray(expression: exp, &arr[a.index]!, withString:string)
}
else if let str = a.element.str {
var s = str
s.replaceStringsUsingRegularExpression(expression: exp, withString:string, error: nil)
arr[a.index] = s
}
else if let dic = a.element.jsonDict {
replaceStringUsingRegularExpressionInJSONDictionary(exp, &arr[a.index]!, withString: string,options:opt)
}
}
}
public func replaceStringUsingRegularExpressionInJSONDictionary(exp:String, inout dict:JSONDictionary, withString string:String, options opt:NSMatchingOptions = nil) {
// make sure we can make type changes everywhere
dict.restrictTypeChanges = false
dict.inheritRestrictions = true
for (k,v) in dict {
if let st = v?.str {
var s = st
s.replaceStringsUsingRegularExpression(expression: exp, withString: string, options:opt, error: nil)
dict[k] = s
}
else if let dic = v?.jsonDict {
replaceStringUsingRegularExpressionInJSONDictionary(exp, &dict[k]!, withString: string)
}
else if let arr = v?.jsonArr {
replaceStringUsingRegularExpressionInJSONArray(expression: exp, &dict[k]!, withString:string, options:opt)
}
}
}
public func replaceStringWithStringInJSONArray(string:String, inout arr:JSONArray, withString: String, options opt:NSMatchingOptions = nil) {
// make sure we can make type changes everywhere
arr.restrictTypeChanges = false
arr.inheritRestrictions = true
for a in enumerate(arr) {
if let array = a.element.jsonArr {
replaceStringUsingRegularExpressionInJSONArray(expression: string, &arr[a.index]!, withString:withString)
}
else if let str = a.element.str {
var s = str
s.stringByReplacingOccurrencesOfString(str, withString: withString, options: nil, range: nil)
arr[a.index] = s
}
else if let dic = a.element.jsonDict {
replaceStringUsingRegularExpressionInJSONDictionary(string, &arr[a.index]!, withString: withString,options:opt)
}
}
}
public func replaceStringWithStringInJSONDictionary(string:String, inout dict:JSONDictionary, withString:String, options opt:NSMatchingOptions = nil) {
// make sure we can make type changes everywhere
dict.restrictTypeChanges = false
dict.inheritRestrictions = true
for (k,v) in dict {
if let st = v?.str {
var s = st
s.replaceStringsUsingRegularExpression(expression: string, withString: withString, options:opt, error: nil)
dict[k] = s
}
else if let dic = v?.jsonDict {
replaceStringUsingRegularExpressionInJSONDictionary(string, &dict[k]!, withString: withString)
}
else if let arr = v?.jsonArr {
replaceStringUsingRegularExpressionInJSONArray(expression: string, &dict[k]!, withString:withString, options:opt)
}
}
}
public func replaceValue(key:String, inout dict:JSONDictionary, array arra:JSONArray) {
// make sure we can make type changes everywhere
dict.restrictTypeChanges = false
dict.inheritRestrictions = true
if contains(dict.keys,key) {
dict[key] = arra
}
else if let dK = dict.keysWithArrayValues {
for k in dK {
if let arr = dict[k]?.jsonArr {
for a in enumerate(arr) {
if let dictionary = a.element.jsonDict {
replaceValue(key, &dict[k]![a.index]!,array: arra)
}
}
}
}
}
/*
// needs testing and repeating across
else if let dK = dict.keysWithDictionaryValues {
println("dictionary keys")
for k in dK {
replaceValue(key, &dict[k]!,array: arra)
}
}*/
}
func replaceValue(key:String, inout dict:JSONDictionary, dictionary dic:JSONDictionary) {
// make sure we can make type changes everywhere
dict.restrictTypeChanges = false
dict.inheritRestrictions = true
if contains(dict.keys,key) {
dict[key] = dic
}
else if let dK = dict.keysWithArrayValues {
for k in dK {
if let arr = dict[k]?.jsonArr {
for a in enumerate(arr) {
if let dictionary = a.element.jsonDict {
replaceValue(key, &dict[k]![a.index]!,dictionary: dic)
}
}
}
}
}
}
func replaceValue(key:String, inout dict:JSONDictionary, string str:String) {
// make sure we can make type changes everywhere
dict.restrictTypeChanges = false
dict.inheritRestrictions = true
if contains(dict.keys,key) {
dict[key] = str
}
/*
// needs testing and repeating across
else if let dK = dict.keysWithDictionaryValues {
println("dictionary keys")
for k in dK {
replaceValue(key, &dict[k]!,string:str)
}
}*/
else if let dK = dict.keysWithArrayValues {
for k in dK {
if let arr = dict[k]?.jsonArr {
for a in enumerate(arr) {
if let dictionary = a.element.jsonDict {
replaceValue(key, &dict[k]![a.index]!,string: str)
}
}
}
}
}
}
func replaceValue(key:String, inout dict:JSONDictionary, number num:NSNumber) {
// make sure we can make type changes everywhere
dict.restrictTypeChanges = false
dict.inheritRestrictions = true
if contains(dict.keys,key) {
dict[key] = num
}
else if let dK = dict.keysWithArrayValues {
for k in dK {
if let arr = dict[k]?.jsonArr {
for a in enumerate(arr) {
if let dictionary = a.element.jsonDict {
replaceValue(key, &dict[k]![a.index]!,number: num)
}
}
}
}
}
}
func replaceValueWithNull(key:String, inout dict:JSONDictionary) {
// make sure we can make type changes everywhere
dict.restrictTypeChanges = false
dict.inheritRestrictions = true
if contains(dict.keys,key) {
dict[key] = NSNull()
}
else if let dK = dict.keysWithArrayValues {
for k in dK {
if let arr = dict[k]?.jsonArr {
for a in enumerate(arr) {
if let dictionary = a.element.jsonDict {
replaceValueWithNull(key, &dict[k]![a.index]!)
}
}
}
}
}
}
func searchKeys(key:String, dict:JSONDictionary) -> Value? {
if contains(dict.keys,key) {
return dict[key]!
}
else if let dK = dict.keysWithArrayValues {
for k in dK {
if let arr = dict[k]?.jsonArr {
for a in arr {
if let dictionary = a.jsonDict {
searchKeys(key, dictionary)
}
}
}
}
}
return nil
}
| mit | 423a12454527464cf9d7175e3f236b44 | 28.1875 | 167 | 0.570601 | 4.462619 | false | false | false | false |
dn-m/Collections | Collections/Subsets.swift | 1 | 1250 | //
// Subsets.swift
// Collections
//
// Created by James Bean on 12/23/16.
//
//
extension Collection where Index == Int, IndexDistance == Int {
// MARK: - Subsets
/// - returns: All combinations of with a given cardinality
/// (how many elements chosen per combination).
public func subsets(cardinality k: Int) -> [[Iterator.Element]] {
func subsets(
cardinality k: Int,
combinedWith prefix: [Iterator.Element],
startingAt index: Int
) -> [[Iterator.Element]]
{
guard k > 0 else {
return [prefix]
}
if index < count {
let first = self[index]
return (
subsets(
cardinality: k - 1,
combinedWith: prefix + [first],
startingAt: index + 1
) +
subsets(
cardinality: k,
combinedWith: prefix,
startingAt: index + 1
)
)
}
return []
}
return subsets(cardinality: k, combinedWith: [], startingAt: 0)
}
}
| mit | e8ecfc82a2a91a8ec6170b10bdf59898 | 24.510204 | 71 | 0.4408 | 5.165289 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/check-array-formation-through-concatenation.swift | 2 | 458 | /**
* https://leetcode.com/problems/check-array-formation-through-concatenation/
*
*
*/
// Date: Sat Jan 2 20:30:00 PST 2021
class Solution {
func canFormArray(_ arr: [Int], _ pieces: [[Int]]) -> Bool {
var dict: [Int : [Int]] = [:]
for x in pieces {
dict[x[0]] = x
}
var result = [Int]()
for x in arr {
result += dict[x, default: []]
}
return result == arr
}
} | mit | 34edef4e3bef0318559dbe07fcd9a8c7 | 21.95 | 77 | 0.482533 | 3.469697 | false | false | false | false |
zhou9734/Warm | Warm/Classes/Home/View/HomeTableViewCell.swift | 1 | 3905 | //
// HomeTableViewCell.swift
// Warm
//
// Created by zhoucj on 16/9/13.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
import SDWebImage
class HomeTableViewCell: UITableViewCell {
var salon: WSalon?{
didSet{
guard let _salon = salon else{
return
}
bgImageView.sd_setImageWithURL(NSURL(string: _salon.avatar!), placeholderImage: placeholderImage)
titleLbl.text = _salon.title
iconImageView.sd_setImageWithURL(NSURL(string: _salon.user!.avatar!))
nicknameLbl.text = _salon.user!.nickname
likeCountLbl.text = "\(_salon.follow_count)"
commentCountLbl.text = "\(_salon.comment_count)"
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
contentView.addSubview(bgImageView)
contentView.addSubview(titleLbl)
contentView.addSubview(iconImageView)
contentView.addSubview(nicknameLbl)
contentView.addSubview(likeCountLbl)
contentView.addSubview(likeImageView)
contentView.addSubview(commentCountLbl)
contentView.addSubview(commentImageView)
contentView.addSubview(splieLine)
}
//背景图片
private lazy var bgImageView: UIImageView = {
let iv = UIImageView()
iv.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 170)
return iv
}()
//标题
private lazy var titleLbl: UILabel = {
let width = ScreenWidth - 40
let lbl = UILabel(frame: CGRect(x: 20, y: 55, width: width, height: 50))
lbl.numberOfLines = 0
lbl.textColor = UIColor.whiteColor()
lbl.textAlignment = .Center
return lbl
}()
//头像
private lazy var iconImageView: UIImageView = {
let iv = UIImageView()
iv.frame = CGRect(x: 15, y: 175, width: 45 , height: 45)
iv.layer.cornerRadius = 45/2
iv.layer.masksToBounds = true
return iv
}()
private lazy var nicknameLbl: UILabel = {
let lbl = UILabel(frame: CGRect(x: 75, y: 182, width: 130, height: 35))
lbl.textColor = UIColor.blackColor()
lbl.font = UIFont.systemFontOfSize(14)
lbl.textAlignment = .Left
return lbl
}()
//喜欢的数量
private lazy var likeCountLbl: UILabel = {
let lbl = UILabel(frame: CGRect(x: ScreenWidth - 130, y: 182, width: 30, height: 30))
lbl.textColor = UIColor.grayColor()
lbl.textAlignment = .Right
lbl.font = UIFont.systemFontOfSize(15)
return lbl
}()
//心
private lazy var likeImageView: UIImageView = {
let iv = UIImageView()
iv.frame = CGRect(x: ScreenWidth - 90, y: 185, width: 22 , height: 22)
iv.image = UIImage(named: "myshalonLoved_13x11_")
return iv
}()
//评论数量
private lazy var commentCountLbl: UILabel = {
let lbl = UILabel(frame: CGRect(x: ScreenWidth - 75, y: 182, width: 30, height: 30))
lbl.textColor = UIColor.grayColor()
lbl.textAlignment = .Right
lbl.font = UIFont.systemFontOfSize(15)
return lbl
}()
//评论图片
private lazy var commentImageView: UIImageView = {
let iv = UIImageView()
iv.frame = CGRect(x: ScreenWidth - 40, y: 185, width: 22 , height: 22)
iv.image = UIImage(named: "myshalonComment_13x12_")
return iv
}()
//分割线
private lazy var splieLine: UIView = {
let _view = UIView(frame: CGRect(x: 15, y: 225, width: ScreenWidth - 30, height: 1))
_view.backgroundColor = SpliteColor
return _view
}()
}
| mit | d6eaa51b127dc5080e58f4b05ff37a57 | 32.789474 | 109 | 0.610852 | 4.303911 | false | false | false | false |
carlospaelinck/pokebattle | PokéBattle/DataLoaderController.swift | 1 | 3490 | //
// DataLoaderController.swift
// PokéBattle
//
// Created by Carlos Paelinck on 4/11/16.
// Copyright © 2016 Carlos Paelinck. All rights reserved.
//
import Foundation
class DataLoaderController {
var pokémon: [Pokémon] = []
var attacks: [Attack] = []
static let SharedInstance = DataLoaderController()
init() {
loadPokémonData()
loadAttackData()
}
func loadAttackData() {
guard let attackDataPath = NSBundle.mainBundle().pathForResource("pokémonAttacks", ofType: ".json") else { return }
guard let attackData = NSData(contentsOfFile: attackDataPath) else { return }
guard let attackDataObjects = try? NSJSONSerialization.JSONObjectWithData(attackData, options: NSJSONReadingOptions(rawValue: 0)) as? [[String: AnyObject]] else { return }
var allAttacks: [Attack] = []
attackDataObjects?.forEach {
guard let name = $0["name"] as? String else { return }
guard let learnset = $0["learnset"] as? [Int] else { return }
guard let typeId = $0["type"] as? String else { return }
guard let categoryId = $0["category"] as? Int else { return }
guard let basePower = $0["basePower"] as? Int else { return }
guard let type = PokémonType(rawValue: typeId) else { return }
guard let category = AttackCategory(rawValue: categoryId) else { return }
let attack = Attack(
name: name,
basePower: basePower,
type: type,
category: category,
learnset: learnset
)
allAttacks.append(attack)
}
attacks = allAttacks.sort { $0.0.name < $0.1.name }
}
func loadPokémonData() {
guard let pokémonDataPath = NSBundle.mainBundle().pathForResource("pokémonData", ofType: ".json") else { return }
guard let pokémonData = NSData(contentsOfFile: pokémonDataPath) else { return }
guard let pokémonObjects = try? NSJSONSerialization.JSONObjectWithData(pokémonData, options: NSJSONReadingOptions(rawValue: 0)) as? [[String: AnyObject]] else { return }
var allPokémon: [Pokémon] = []
pokémonObjects?.forEach {
guard let id = $0["id"] as? Int else { return }
guard let name = $0["name"] as? String else { return }
guard let typeIds = $0["types"] as? [String] else { return }
guard let statsRaw = $0["stats"] as? [Int] else { return }
var types: [PokémonType] = []
guard let primaryType = PokémonType(rawValue: typeIds.first!) else { return }
types.append(primaryType)
if let secondaryType = PokémonType(rawValue: typeIds.last!) where typeIds.count == 2 {
types.append(secondaryType)
}
let stats = Stats(
hitPoints: statsRaw[0],
attack: statsRaw[1],
defense: statsRaw[2],
specialAttack: statsRaw[3],
specialDefense: statsRaw[4],
speed: statsRaw[5]
)
let pokémon = Pokémon(id: id, name: name, types: types, stats: stats)
allPokémon.append(pokémon)
}
pokémon = allPokémon.sort { $0.0.id < $0.1.id }
}
} | mit | 8716f5188ed1011b7d45c49537f29770 | 37.932584 | 179 | 0.56149 | 4.22439 | false | false | false | false |
nicholas-richardson/swift3-treehouse | swift3-Basics/FunFacts/FunFacts/ViewController.swift | 1 | 927 | //
// ViewController.swift
// FunFacts
//
// Created by Nick Richardson on 7/19/17.
// Copyright © 2017 Nick Richardson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var funFactLabel: UILabel!
@IBOutlet weak var funFactButton: UIButton!
let factProvider = FactProvider()
let colorProvider = backgroundColorProvider()
override func viewDidLoad() {
super.viewDidLoad()
funFactLabel.text = factProvider.randomFact()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showFact() {
funFactLabel.text = factProvider.randomFact()
let randomColor = colorProvider.randomColor()
view.backgroundColor = randomColor
funFactButton.tintColor = randomColor
}
}
| mit | 37ccc24ad418b53359f016d9e2910715 | 22.74359 | 58 | 0.670626 | 4.748718 | false | false | false | false |
carabina/Nuke | Example/Tests/Source/MockURLSessionManager.swift | 2 | 931 | //
// MockImageDataLoader.swift
// Nuke
//
// Created by Alexander Grebenyuk on 3/14/15.
// Copyright (c) 2015 Alexander Grebenyuk. All rights reserved.
//
import Foundation
import Nuke
class MockImageDataLoader: ImageDataLoader {
var enabled = true
var createdTaskCount = 0
override func imageDataTaskWithURL(url: NSURL, progressHandler: ImageDataLoadingProgressHandler?, completionHandler: ImageDataLoadingCompletionHandler) -> NSURLSessionDataTask {
if self.enabled {
let bundle = NSBundle(forClass: MockImageDataLoader.self)
let URL = bundle.URLForResource("Image", withExtension: "jpg")
let data = NSData(contentsOfURL: URL!)
dispatch_async(dispatch_get_main_queue()) {
completionHandler(data: data, response: nil, error: nil)
}
}
self.createdTaskCount++
return MockURLSessionDataTask()
}
}
| mit | 9706a127ba11b5955bc7523e7b29a566 | 32.25 | 181 | 0.674544 | 4.874346 | false | false | false | false |
nguyenantinhbk77/practice-swift | CoreData/SuperDB/SuperDB/SuperDBDateCell.swift | 2 | 1488 | //
// SuperDBDateCell.swift
// SuperDB
//
// Created by Domenico on 01/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
let __dateFormatter = NSDateFormatter()
class SuperDBDateCell: SuperDBEditCell {
private var datePicker: UIDatePicker!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
__dateFormatter.dateStyle = .MediumStyle
self.textField.clearButtonMode = .Never
self.datePicker = UIDatePicker(frame: CGRectZero)
self.datePicker.datePickerMode = .Date
self.datePicker.addTarget(self, action: "datePickerChanged:", forControlEvents: .ValueChanged)
self.textField.inputView = self.datePicker
}
//MARK: - SuperDBEditCell Overrides
override var value:AnyObject! {
get{
if self.textField.text == nil || count(self.textField.text) == 0 {
return nil
} else {
return self.datePicker.date as NSDate!
}
}
set{
if let _value = newValue as? NSDate {
self.datePicker.date = _value
self.textField.text = __dateFormatter.stringFromDate(_value)
} else {
self.textField.text = nil
}
}
}
}
| mit | 70643cdc78cb2a7536f20091678d363e | 27.075472 | 102 | 0.594758 | 4.769231 | false | false | false | false |
hironytic/FormulaCalc | FormulaCalc/Model/SheetItemStore.swift | 1 | 6892 | //
// SheetItemStore.swift
// FormulaCalc
//
// Copyright (c) 2017 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import RxSwift
import RealmSwift
public enum SheetItemStoreError: Error {
case itemNotFound
}
public protocol ISheetItemStore: class {
var update: Observable<SheetItem?> { get }
var onUpdateName: AnyObserver</* name: */ String> { get }
var onUpdateType: AnyObserver</* type: */ SheetItemType> { get }
var onUpdateNumberValue: AnyObserver</* numberValue: */ Double> { get }
var onUpdateStringValue: AnyObserver</* stringValue: */ String> { get }
var onUpdateFormula: AnyObserver</* formula: */ String> { get }
var onUpdateThousandSeparator: AnyObserver</* thousandSeparator: */ Bool> { get }
var onUpdateFractionDigits: AnyObserver</* fractionDigits: */ Int> { get }
var onUpdateVisible: AnyObserver</* visible: */ Bool> { get }
}
public protocol ISheetItemStoreLocator {
func resolveSheetItemStore(id: String) -> ISheetItemStore
}
extension DefaultLocator: ISheetItemStoreLocator {
public func resolveSheetItemStore(id: String) -> ISheetItemStore {
return SheetItemStore(locator: self, id: id)
}
}
public class SheetItemStore: ISheetItemStore {
public typealias Locator = IErrorStoreLocator & ISheetDatabaseLocator
public let update: Observable<SheetItem?>
public let onUpdateName: AnyObserver</* name: */ String>
public let onUpdateType: AnyObserver</* type: */ SheetItemType>
public let onUpdateNumberValue: AnyObserver</* numberValue: */ Double>
public let onUpdateStringValue: AnyObserver</* stringValue: */ String>
public let onUpdateFormula: AnyObserver</* formula: */ String>
public let onUpdateThousandSeparator: AnyObserver</* thousandSeparator: */ Bool>
public let onUpdateFractionDigits: AnyObserver</* fractionDigits: */ Int>
public let onUpdateVisible: AnyObserver</* visible: */ Bool>
private let _locator: Locator
private let _sheetDatabase: ISheetDatabase
private let _notificationToken: NotificationToken?
private var _lastNewItemNumber = 0
private let _updateSubject: BehaviorSubject<SheetItem?>
private let _onUpdateName = ActionObserver</* newName: */ String>()
private let _onUpdateType = ActionObserver</* type: */ SheetItemType>()
private let _onUpdateNumberValue = ActionObserver</* numberValue: */ Double>()
private let _onUpdateStringValue = ActionObserver</* stringValue: */ String>()
private let _onUpdateFormula = ActionObserver</* formula: */ String>()
private let _onUpdateThousandSeparator = ActionObserver</* thousandSeparator: */ Bool>()
private let _onUpdateFractionDigits = ActionObserver</* fractionDigits: */ Int>()
private let _onUpdateVisible = ActionObserver</* visible: */ Bool>()
public init(locator: Locator, id: String) {
_locator = locator
_sheetDatabase = _locator.resolveSheetDatabase()
do {
let realm = try _sheetDatabase.createRealm()
let results = realm.objects(SheetItem.self).filter("id = %@", id)
let sheetItem = results.first
let updateSubject = BehaviorSubject(value: sheetItem)
_updateSubject = updateSubject
_notificationToken = results.addNotificationBlock { changes in
switch changes {
case .update(let results, _, _, _):
updateSubject.onNext(results.first)
default:
break
}
}
} catch let error {
_updateSubject = BehaviorSubject(value: nil)
_notificationToken = nil
_locator.resolveErrorStore().onPostError.onNext(error)
}
update = _updateSubject.asObservable()
onUpdateName = _onUpdateName.asObserver()
onUpdateType = _onUpdateType.asObserver()
onUpdateNumberValue = _onUpdateNumberValue.asObserver()
onUpdateStringValue = _onUpdateStringValue.asObserver()
onUpdateFormula = _onUpdateFormula.asObserver()
onUpdateThousandSeparator = _onUpdateThousandSeparator.asObserver()
onUpdateFractionDigits = _onUpdateFractionDigits.asObserver()
onUpdateVisible = _onUpdateVisible.asObserver()
_onUpdateName.handler = { [weak self] name in self?.updateValue({ $0.name = name }) }
_onUpdateType.handler = { [weak self] type in self?.updateValue({ $0.type = type }) }
_onUpdateNumberValue.handler = { [weak self] numberValue in self?.updateValue({ $0.numberValue = numberValue }) }
_onUpdateStringValue.handler = { [weak self] stringValue in self?.updateValue({ $0.stringValue = stringValue }) }
_onUpdateFormula.handler = { [weak self] formula in self?.updateValue({ $0.formula = formula }) }
_onUpdateThousandSeparator.handler = { [weak self] thousandSeparator in self?.updateValue({ $0.thousandSeparator = thousandSeparator }) }
_onUpdateFractionDigits.handler = { [weak self] fractionDigits in self?.updateValue({ $0.fractionDigits = fractionDigits }) }
_onUpdateVisible.handler = { [weak self] visible in self?.updateValue({ $0.visible = visible }) }
}
deinit {
self._notificationToken?.stop()
}
private func updateValue(_ updater: @escaping (SheetItem) -> Void) {
do {
guard let sheetItem = try _updateSubject.value() else { throw SheetItemStoreError.itemNotFound }
let realm = try _sheetDatabase.createRealm()
try realm.write {
updater(sheetItem)
}
} catch let error {
_locator.resolveErrorStore().onPostError.onNext(error)
}
}
}
| mit | 325cfb648f14fc203b16ff7c45a541ae | 44.642384 | 145 | 0.679193 | 4.809491 | false | false | false | false |
HackerEcology/BeginnerCourse | tdjackey/GuidedTour.playground/section-23.swift | 5 | 391 | let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
| mit | 2f8c081f68aa7cb359779f2eb4075a99 | 34.545455 | 69 | 0.70844 | 3.688679 | false | false | false | false |
lvogelzang/Blocky | Blocky/Levels/Level54.swift | 1 | 877 | //
// Level54.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level54: Level {
let levelNumber = 54
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| mit | ee169df6ca8c3882ca4e4970a70e8d5f | 24.794118 | 89 | 0.573546 | 2.649547 | false | false | false | false |
MrLSPBoy/LSPDouYu | LSPDouYuTV/LSPDouYuTV/Classes/Home/Controller/LSFunnyViewController.swift | 1 | 1065 | //
// LSFunnyViewController.swift
// LSPDouYuTV
//
// Created by lishaopeng on 17/3/6.
// Copyright © 2017年 lishaopeng. All rights reserved.
//
import UIKit
fileprivate let kTopMargin : CGFloat = 8
class LSFunnyViewController: LSBaseAnchorViewController {
//MARK:懒加载ViewModel
fileprivate lazy var funnyVM : LSFunnyViewModel = LSFunnyViewModel()
}
extension LSFunnyViewController {
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0)
}
}
extension LSFunnyViewController{
override func loadData() {
//1.给父类中ViewModel赋值
baseVM = funnyVM
//2.请求数据
funnyVM.loadFunnyData {
self.collectionView.reloadData()
//3.数据请求完成
self.loadDataFinished()
}
}
}
| mit | da35040ccfceb52c67d5252961a12b6d | 23.380952 | 97 | 0.649414 | 4.591928 | false | false | false | false |
yopeso/Taylor | TaylorFramework/Modules/EasterEggs/PacmanRunner.swift | 4 | 1439 | //
// PacmanRunner.swift
// Taylor
//
// Created by Dmitrii Celpan on 11/11/15.
// Copyright © 2015 YOPESO. All rights reserved.
//
import Cocoa
class PacmanRunner {
let printer = Printer(verbosityLevel: .error)
let currentPath = FileManager.default.currentDirectoryPath
func runEasterEggPrompt() {
printer.printError("Taylor is mad! Would you like to play with her(it)? (Y/N)")
runEasterEggIfNeeded(input())
}
func runEasterEggIfNeeded(_ userInput: String) {
if userInput.uppercased() == "Y" {
let paths = filePaths(for: currentPath)
runEasterEgg(paths)
} else {
printer.printError("O Kay! Next time :)")
}
}
func formatInputString(_ string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
func input() -> String {
let keyboard = FileHandle.standardInput
let inputData = keyboard.availableData
return String(String(data: inputData, encoding: String.Encoding.utf8)?.characters.first ?? Character(""))
}
func runEasterEgg(_ paths: [Path]) {
let pacman = Pacman(paths: paths)
pacman.start()
}
func filePaths(for path: Path) -> [Path] {
let parameters = ["path": [currentPath], "type": ["swift"]]
return Finder().findFilePaths(parameters: parameters)
}
}
| mit | 4bbd7fb2c148dfd6476a1cb6ef3f4415 | 27.76 | 113 | 0.618915 | 4.217009 | false | false | false | false |
quadro5/swift3_L | swift_question.playground/Pages/Let11 Container With Most Water.xcplaygroundpage/Contents.swift | 1 | 1003 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
class Solution {
func maxArea(_ height: [Int]) -> Int {
// index: x
// value: y
if height.count < 2 {
return min(height[0], height[1])
}
let len = height.count
var maxWater: Int = 0
var start: Int = 0
var end: Int = len - 1
while start < end {
let minHeight = min(height[start], height[end])
maxWater = max(maxWater, (end-start) * min(height[start], height[end]))
// if start is the min, need to update
while start < end && height[start] <= minHeight {
start += 1
}
// if end is the min, need to update
while start < end && height[end] <= minHeight {
end -= 1
}
}
return maxWater
}
}
//let res = Solution().maxArea([1, 2, 3, 4])
//print("res = \(res)")
| unlicense | 2feebec618679b85744420a3fada1675 | 22.880952 | 83 | 0.475573 | 3.964427 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/ReaderBlockedSiteCell.swift | 1 | 1195 | import Foundation
import WordPressShared.WPStyleGuide
public class ReaderBlockedSiteCell: UITableViewCell
{
@IBOutlet private weak var label: UILabel!
public override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
private func applyStyles() {
label.font = WPStyleGuide.subtitleFont()
label.textColor = WPStyleGuide.whisperGrey()
}
public func setSiteName(name:String) {
let format = NSLocalizedString("The site %@ will no longer appear in your reader. Tap to undo.",
comment:"Message expliaining that the specified site will no longer appear in the user's reader. The '%@' characters are a placeholder for the title of the site.")
let str = NSString(format: format, name)
let range = str.rangeOfString(name)
let attributes = WPStyleGuide.subtitleAttributes()
let boldAttributes = WPStyleGuide.subtitleAttributesBold()
let attrStr = NSMutableAttributedString(string: str as String, attributes: attributes as? [String:AnyObject])
attrStr.setAttributes(boldAttributes as? [String:AnyObject], range: range)
label.attributedText = attrStr
}
}
| gpl-2.0 | f02ad01b0b008664858e8c5d33478469 | 35.212121 | 176 | 0.701255 | 5.063559 | false | false | false | false |
lanit-tercom-school/grouplock | GroupLockiOS/GroupLockTests/PasswordInteractorTests.swift | 1 | 977 | //
// PasswordInteractorTests.swift
// GroupLock
//
// Created by Sergej Jaskiewicz on 11.07.16.
// Copyright (c) 2016 Lanit-Tercom School. All rights reserved.
//
import XCTest
@testable import GroupLock
class PasswordInteractorTests: XCTestCase {
// MARK: Subject under test
var sut: PasswordInteractor!
// MARK: - Test lifecycle
override func setUp() {
super.setUp()
sut = PasswordInteractor()
}
override func tearDown() {
sut = nil
super.tearDown()
}
// MARK: - Test doubles
// MARK: - Tests
func test_ThatPasswordIsCorrectMethod_VerifiesThePassword() {
// Given:
let passwordToVerify = "password"
let expectedCorrectness = true
// When:
let actualCorrectness = sut.passwordIsCorrect(passwordToVerify)
// Then:
XCTAssertEqual(actualCorrectness, expectedCorrectness, "passwordIsCorrect(_:) should verify the password")
}
}
| apache-2.0 | d290418197d8a101e814819620f16b4a | 19.354167 | 114 | 0.643808 | 4.544186 | false | true | false | false |
caicai0/ios_demo | load/thirdpart/Alamofire/ParameterEncoding.swift | 4 | 17741 | //
// ParameterEncoding.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// HTTP method definitions.
///
/// See https://tools.ietf.org/html/rfc7231#section-4.3
public enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
// MARK: -
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
/// A type used to define how a set of parameters are applied to a `URLRequest`.
public protocol ParameterEncoding {
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
///
/// - returns: The encoded request.
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
// MARK: -
/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
/// the HTTP body depends on the destination of the encoding.
///
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
/// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode
/// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending
/// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
public struct URLEncoding: ParameterEncoding {
// MARK: Helper Types
/// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
/// resulting URL request.
///
/// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
/// requests and sets as the HTTP body for requests with any other HTTP method.
/// - queryString: Sets or appends encoded query string result to existing query string.
/// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
public enum Destination {
case methodDependent, queryString, httpBody
}
// MARK: Properties
/// Returns a default `URLEncoding` instance.
public static var `default`: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.methodDependent` destination.
public static var methodDependent: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.queryString` destination.
public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
/// Returns a `URLEncoding` instance with an `.httpBody` destination.
public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
/// The destination defining where the encoded query string is to be applied to the URL request.
public let destination: Destination
// MARK: Initialization
/// Creates a `URLEncoding` instance using the specified destination.
///
/// - parameter destination: The destination defining where the encoded query string is to be applied.
///
/// - returns: The new `URLEncoding` instance.
public init(destination: Destination = .methodDependent) {
self.destination = destination
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
}
return urlRequest
}
/// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
///
/// - parameter key: The key of the query component.
/// - parameter value: The value of the query component.
///
/// - returns: The percent-escaped, URL encoded query string components.
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: "\(key)[]", value: value)
}
} else if let value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape((value.boolValue ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
} else if let bool = value as? Bool {
components.append((escape(key), escape((bool ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string.substring(with: range)
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring
index = endIndex
}
}
return escaped
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
switch destination {
case .queryString:
return true
case .httpBody:
return false
default:
break
}
switch method {
case .get, .head, .delete:
return true
default:
return false
}
}
}
// MARK: -
/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
public struct JSONEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncoding { return JSONEncoding() }
/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions
// MARK: Initialization
/// Creates a `JSONEncoding` instance using the specified options.
///
/// - parameter options: The options for writing the parameters as JSON data.
///
/// - returns: The new `JSONEncoding` instance.
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
/// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
///
/// - parameter urlRequest: The request to apply the JSON object to.
/// - parameter jsonObject: The JSON object to apply to the request.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let jsonObject = jsonObject else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
/// field of an encoded request is set to `application/x-plist`.
public struct PropertyListEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a default `PropertyListEncoding` instance.
public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
/// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
/// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
/// The property list serialization format.
public let format: PropertyListSerialization.PropertyListFormat
/// The options for writing the parameters as plist data.
public let options: PropertyListSerialization.WriteOptions
// MARK: Initialization
/// Creates a `PropertyListEncoding` instance using the specified format and options.
///
/// - parameter format: The property list serialization format.
/// - parameter options: The options for writing the parameters as plist data.
///
/// - returns: The new `PropertyListEncoding` instance.
public init(
format: PropertyListSerialization.PropertyListFormat = .xml,
options: PropertyListSerialization.WriteOptions = 0)
{
self.format = format
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try PropertyListSerialization.data(
fromPropertyList: parameters,
format: format,
options: options
)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
extension NSNumber {
fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
| mit | ed707d39a7d32d779370681fa808039d | 40.06713 | 123 | 0.64613 | 5.099454 | false | false | false | false |
themonki/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/MessagesUtils/EKButtonView.swift | 1 | 2272 | //
// EKButtonView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 12/8/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
class EKButtonView: UIView {
// MARK: - Properties
private let button = UIButton()
private let titleLabel = UILabel()
private let content: EKProperty.ButtonContent
// MARK: - Setup
init(content: EKProperty.ButtonContent) {
self.content = content
super.init(frame: .zero)
setupTitleLabel()
setupButton()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupButton() {
addSubview(button)
button.fillSuperview()
button.addTarget(self, action: #selector(buttonTouchUp), for: [.touchUpInside, .touchUpOutside, .touchCancel])
button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
button.addTarget(self, action: #selector(buttonTouchUpInside), for: .touchUpInside)
}
private func setupTitleLabel() {
titleLabel.numberOfLines = content.label.style.numberOfLines
titleLabel.font = content.label.style.font
titleLabel.textColor = content.label.style.color
titleLabel.text = content.label.text
titleLabel.textAlignment = .center
titleLabel.lineBreakMode = .byWordWrapping
backgroundColor = content.backgroundColor
addSubview(titleLabel)
titleLabel.layoutToSuperview(axis: .horizontally, offset: content.contentEdgeInset)
titleLabel.layoutToSuperview(axis: .vertically, offset: content.contentEdgeInset)
}
private func setBackground(by content: EKProperty.ButtonContent, isHighlighted: Bool) {
if isHighlighted {
backgroundColor = content.highlightedBackgroundColor
} else {
backgroundColor = content.backgroundColor
}
}
// MARK: - Selectors
@objc func buttonTouchUpInside() {
content.action?()
}
@objc func buttonTouchDown() {
setBackground(by: content, isHighlighted: true)
}
@objc func buttonTouchUp() {
setBackground(by: content, isHighlighted: false)
}
}
| apache-2.0 | fe06d85626ad1a4017f1aecc6ed8b12a | 29.28 | 118 | 0.654337 | 5.013245 | false | false | false | false |
IGRSoft/IGRPhotoTweaks | IGRPhotoTweaks/PhotoTweakView/IGRPhotoTweakView+Mask.swift | 1 | 1398 | //
// IGRPhotoTweakView+Mask.swift
// Pods
//
// Created by Vitalii Parovishnyk on 4/26/17.
//
//
import Foundation
extension IGRPhotoTweakView {
internal func setupMasks()
{
self.topMask = IGRCropMaskView()
self.addSubview(self.topMask)
self.leftMask = IGRCropMaskView()
self.addSubview(self.leftMask)
self.rightMask = IGRCropMaskView()
self.addSubview(self.rightMask)
self.bottomMask = IGRCropMaskView()
self.addSubview(self.bottomMask)
self.setupMaskLayoutConstraints()
}
internal func updateMasks() {
self.layoutIfNeeded()
}
internal func highlightMask(_ highlight:Bool, animate: Bool) {
if (self.isHighlightMask()) {
let newAlphaValue: CGFloat = highlight ? self.highlightMaskAlphaValue() : 1.0
let animationBlock: (() -> Void)? = {
self.topMask.alpha = newAlphaValue
self.leftMask.alpha = newAlphaValue
self.bottomMask.alpha = newAlphaValue
self.rightMask.alpha = newAlphaValue
}
if animate {
UIView.animate(withDuration: kAnimationDuration, animations: animationBlock!)
}
else {
animationBlock!()
}
}
}
}
| mit | e39ca9f298f6421f65fc9225309f425d | 25.377358 | 93 | 0.560086 | 4.787671 | false | false | false | false |
jrmgx/swift | jrmgx/Classes/Transition/JrmgxPanTransition.swift | 1 | 952 |
import UIKit
open class JrmgxPanTransition: UIPercentDrivenInteractiveTransition {
open let parentViewController: UIViewController
open var interactive = false
public init(withViewController: UIViewController) {
parentViewController = withViewController
}
open func pan() {
let pan = UIPanGestureRecognizer(target: self, action: #selector(JrmgxPanTransition.userDidPan(_:)))
parentViewController.view.addGestureRecognizer(pan)
}
// TODO WIP
open func userDidPan(_ recognizer: UIPanGestureRecognizer) {
//let location = recognizer.locationInView(parentViewController.view)
let velocity = recognizer.velocity(in: parentViewController.view)
let rightToLeftSwipe = velocity.x < 0
switch recognizer.state {
case .began:
interactive = true
if rightToLeftSwipe {
}
default:
break
}
}
}
| mit | ce1ec20c064b8773c54c67a5f28f1724 | 26.2 | 108 | 0.667017 | 5.534884 | false | false | false | false |
ahoppen/swift | test/Distributed/actor_protocols.swift | 3 | 3046 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s
// REQUIRES: concurrency
// REQUIRES: distributed
import Distributed
import FakeDistributedActorSystems
typealias DefaultDistributedActorSystem = FakeActorSystem
// ==== -----------------------------------------------------------------------
actor A: Actor {} // ok
class C: Actor, UnsafeSendable {
// expected-error@-1{{non-actor type 'C' cannot conform to the 'Actor' protocol}} {{1-6=actor}}
// expected-warning@-2{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
struct S: Actor {
// expected-error@-1{{non-class type 'S' cannot conform to class protocol 'AnyActor'}}
// expected-error@-2{{non-class type 'S' cannot conform to class protocol 'Actor'}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
struct E: Actor {
// expected-error@-1{{non-class type 'E' cannot conform to class protocol 'AnyActor'}}
// expected-error@-2{{non-class type 'E' cannot conform to class protocol 'Actor'}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
// ==== -----------------------------------------------------------------------
distributed actor DA: DistributedActor {
typealias ActorSystem = FakeActorSystem
}
// FIXME(distributed): error reporting is a bit whacky here; needs cleanup
// expected-error@+2{{actor type 'A2' cannot conform to the 'DistributedActor' protocol. Isolation rules of these actor types are not interchangeable.}}
// expected-error@+1{{actor type 'A2' cannot conform to the 'DistributedActor' protocol. Isolation rules of these actor types are not interchangeable.}}
actor A2: DistributedActor {
nonisolated var id: ID {
fatalError()
}
nonisolated var actorSystem: ActorSystem {
fatalError()
}
init(system: FakeActorSystem) {
fatalError()
}
static func resolve(id: ID, using system: FakeActorSystem) throws -> Self {
fatalError()
}
}
// expected-error@+1{{non-distributed actor type 'C2' cannot conform to the 'DistributedActor' protocol}}
final class C2: DistributedActor {
nonisolated var id: ID {
fatalError()
}
nonisolated var actorSystem: ActorSystem {
fatalError()
}
required init(system: FakeActorSystem) {
fatalError()
}
static func resolve(id: ID, using system: FakeActorSystem) throws -> Self {
fatalError()
}
}
struct S2: DistributedActor {
// expected-error@-1{{non-class type 'S2' cannot conform to class protocol 'DistributedActor'}}
// expected-error@-2{{non-class type 'S2' cannot conform to class protocol 'AnyActor'}}
// expected-error@-3{{type 'S2' does not conform to protocol 'Identifiable'}}
}
| apache-2.0 | 1d1b5ae154ccee222281f9e8ee3fcd1e | 33.613636 | 219 | 0.69304 | 4.27209 | false | false | false | false |
practicalswift/swift | test/SILGen/cf_members.swift | 12 | 14042 | // RUN: %target-swift-emit-silgen -I %S/../IDE/Inputs/custom-modules %s -enable-objc-interop -I %S/Inputs/usr/include | %FileCheck %s
import ImportAsMember
func makeMetatype() -> Struct1.Type { return Struct1.self }
// CHECK-LABEL: sil [ossa] @$s10cf_members17importAsUnaryInityyF
public func importAsUnaryInit() {
// CHECK: function_ref @CCPowerSupplyCreateDangerous : $@convention(c) () -> @owned CCPowerSupply
var a = CCPowerSupply(dangerous: ())
let f: (()) -> CCPowerSupply = CCPowerSupply.init(dangerous:)
a = f(())
}
// CHECK-LABEL: sil [ossa] @$s10cf_members3foo{{[_0-9a-zA-Z]*}}F
public func foo(_ x: Double) {
// CHECK: bb0([[X:%.*]] : $Double):
// CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBALVAR]] : $*Double
// CHECK: [[ZZ:%.*]] = load [trivial] [[READ]]
let zz = Struct1.globalVar
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBALVAR]] : $*Double
// CHECK: assign [[ZZ]] to [[WRITE]]
Struct1.globalVar = zz
// CHECK: [[Z:%.*]] = project_box
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: apply [[FN]]([[X]])
var z = Struct1(value: x)
// The metatype expression should still be evaluated even if it isn't
// used.
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: apply [[FN]]([[X]])
z = makeMetatype().init(value: x)
// CHECK: [[SELF_META:%.*]] = metatype $@thin Struct1.Type
// CHECK: [[THUNK:%.*]] = function_ref @$sSo10IAMStruct1V5valueABSd_tcfCTcTO
// CHECK: [[A:%.*]] = apply [[THUNK]]([[SELF_META]])
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]]
// CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]]
// CHECK: [[BORROWED_A2:%.*]] = begin_borrow [[A_COPY]]
let a: (Double) -> Struct1 = Struct1.init(value:)
// CHECK: apply [[BORROWED_A2]]([[X]])
// CHECK: destroy_value [[A_COPY]]
// CHECK: end_borrow [[BORROWED_A]]
z = a(x)
// TODO: Support @convention(c) references that only capture thin metatype
// let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:)
// z = b(x)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace
// CHECK: apply [[FN]]([[WRITE]])
z.invert()
// CHECK: [[WRITE:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[WRITE]]
// CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] :
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1
// CHECK: apply [[FN]]([[ZTMP]], [[X]])
z = z.translate(radians: x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME:@\$sSo10IAMStruct1V9translate7radiansABSd_tFTcTO]]
// CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]])
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]]
// CHECK: [[BORROWED_C2:%.*]] = begin_borrow [[C_COPY]]
let c: (Double) -> Struct1 = z.translate(radians:)
// CHECK: apply [[BORROWED_C2]]([[X]])
// CHECK: destroy_value [[C_COPY]]
// CHECK: end_borrow [[BORROWED_C]]
z = c(x)
// CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME]]
// CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]]
// CHECK: [[BORROW:%.*]] = begin_borrow [[THICK]]
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[BORROW_COPY:%.*]] = begin_borrow [[COPY]]
// CHECK: apply [[BORROW_COPY]]([[ZVAL]])
// CHECK: destroy_value [[COPY]]
z = d(z)(x)
// TODO: If we implement SE-0042, this should thunk the value Struct1 param
// to a const* param to the underlying C symbol.
//
// let e: @convention(c) (Struct1, Double) -> Struct1
// = Struct1.translate(radians:)
// z = e(z, x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale
// CHECK: apply [[FN]]([[ZVAL]], [[X]])
z = z.scale(x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[THUNK:%.*]] = function_ref @$sSo10IAMStruct1V5scaleyABSdFTcTO
// CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]])
// CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]]
// CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]]
// CHECK: [[BORROWED_F2:%.*]] = begin_borrow [[F_COPY]]
let f = z.scale
// CHECK: apply [[BORROWED_F2]]([[X]])
// CHECK: destroy_value [[F_COPY]]
// CHECK: end_borrow [[BORROWED_F]]
z = f(x)
// CHECK: [[THUNK:%.*]] = function_ref @$sSo10IAMStruct1V5scaleyABSdFTcTO
// CHECK: thin_to_thick_function [[THUNK]]
let g = Struct1.scale
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
z = g(z)(x)
// TODO: If we implement SE-0042, this should directly reference the
// underlying C function.
// let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale
// z = h(z, x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] :
// CHECK: [[ZVAL_2:%.*]] = load [trivial] [[ZTMP]]
// CHECK: store [[ZVAL_2]] to [trivial] [[ZTMP_2:%.*]] :
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double
// CHECK: apply [[GET]]([[ZTMP_2]])
_ = z.radius
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> ()
// CHECK: apply [[SET]]([[ZVAL]], [[X]])
z.radius = x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.altitude
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> ()
// CHECK: apply [[SET]]([[WRITE]], [[X]])
z.altitude = x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.magnitude
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: apply [[FN]]()
var y = Struct1.staticMethod()
// CHECK: [[SELF:%.*]] = metatype
// CHECK: [[THUNK:%.*]] = function_ref @$sSo10IAMStruct1V12staticMethods5Int32VyFZTcTO
// CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]])
// CHECK: [[BORROWED_I:%.*]] = begin_borrow [[I]]
// CHECK: [[I_COPY:%.*]] = copy_value [[BORROWED_I]]
// CHECK: [[BORROWED_I2:%.*]] = begin_borrow [[I_COPY]]
let i = Struct1.staticMethod
// CHECK: apply [[BORROWED_I2]]()
// CHECK: destroy_value [[I_COPY]]
// CHECK: end_borrow [[BORROWED_I]]
y = i()
// TODO: Support @convention(c) references that only capture thin metatype
// let j: @convention(c) () -> Int32 = Struct1.staticMethod
// y = j()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = Struct1.property
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
Struct1.property = y
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = Struct1.getOnlyProperty
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().property
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
makeMetatype().property = y
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().getOnlyProperty
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> ()
// CHECK: apply [[FN]]([[X]], [[ZVAL]])
z.selfComesLast(x: x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
let k: (Double) -> () = z.selfComesLast(x:)
k(x)
let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
l(z)(x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:)
// m(z, x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> ()
// CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]])
z.selfComesThird(a: y, b: 0, x: x)
let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:)
n(y, 0, x)
let o: (Struct1) -> (Int32, Float, Double) -> ()
= Struct1.selfComesThird(a:b:x:)
o(z)(y, 0, x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let p: @convention(c) (Struct1, Int, Float, Double) -> ()
// = Struct1.selfComesThird(a:b:x:)
// p(z, y, 0, x)
}
// CHECK: } // end sil function '$s10cf_members3foo{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$sSo10IAMStruct1V5valueABSd_tcfCTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $@thin Struct1.Type):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$sSo10IAMStruct1V9translate7radiansABSd_tFTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: store [[SELF]] to [trivial] [[TMP:%.*]] :
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$sSo10IAMStruct1V5scaleyABSdFTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$sSo10IAMStruct1V12staticMethods5Int32VyFZTO
// CHECK: bb0([[SELF:%.*]] : $@thin Struct1.Type):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: [[RET:%.*]] = apply [[CFUNC]]()
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$sSo10IAMStruct1V13selfComesLast1xySd_tFTO
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast
// CHECK: apply [[CFUNC]]([[X]], [[SELF]])
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$sSo10IAMStruct1V14selfComesThird1a1b1xys5Int32V_SfSdtFTO
// CHECK: bb0([[X:%.*]] : $Int32, [[Y:%.*]] : $Float, [[Z:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird
// CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]])
// CHECK-LABEL: sil [ossa] @$s10cf_members3bar{{[_0-9a-zA-Z]*}}F
public func bar(_ x: Double) {
// CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply
let ps = CCPowerSupply(watts: x)
// CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator
let fridge = CCRefrigerator(powerSupply: ps)
// CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> ()
fridge.open()
// CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply
let ps2 = fridge.powerSupply
// CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> ()
fridge.powerSupply = ps2
let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:)
let _ = a(x)
let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open
b(fridge)()
let c = fridge.open
c()
}
// CHECK-LABEL: sil [ossa] @$s10cf_members28importGlobalVarsAsProperties{{[_0-9a-zA-Z]*}}F
public func importGlobalVarsAsProperties()
-> (Double, CCPowerSupply, CCPowerSupply?) {
// CHECK: global_addr @kCCPowerSupplyDC
// CHECK: global_addr @kCCPowerSupplyAC
// CHECK: global_addr @kCCPowerSupplyDefaultPower
return (CCPowerSupply.defaultPower, CCPowerSupply.AC, CCPowerSupply.DC)
}
| apache-2.0 | b006b60c98214ef0491b5c70ff8d7317 | 45.496689 | 133 | 0.584461 | 3.339358 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/CollectionKit-master/Examples/DynamicView.swift | 2 | 3288 | //
// DynamicView.swift
// CollectionKitExample
//
// Created by YiLun Zhao on 2016-02-21.
// Copyright © 2016 lkzhao. All rights reserved.
//
import UIKit
let kTiltAnimationVelocityListenerIdentifier = "kTiltAnimationVelocityListenerIdentifier"
open class DynamicView: UIView {
open var tapAnimation = true
open var tiltAnimation = false {
didSet {
if tiltAnimation {
yaal.center.velocity.changes.addListenerWith(identifier:kTiltAnimationVelocityListenerIdentifier) { [weak self] _, v in
self?.velocityUpdated(v)
}
} else {
yaal.center.velocity.changes.removeListenerWith(identifier: kTiltAnimationVelocityListenerIdentifier)
yaal.rotationX.animateTo(0, stiffness: 150, damping: 7)
yaal.rotationY.animateTo(0, stiffness: 150, damping: 7)
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
layer.yaal.perspective.setTo(-1/500)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.yaal.perspective.setTo(-1/500)
}
func velocityUpdated(_ velocity: CGPoint) {
let maxRotate = CGFloat.pi/6
let rotateX = -(velocity.y / 3000).clamp(-maxRotate, maxRotate)
let rotateY = (velocity.x / 3000).clamp(-maxRotate, maxRotate)
yaal.rotationX.animateTo(rotateX, stiffness: 400, damping: 20)
yaal.rotationY.animateTo(rotateY, stiffness: 400, damping: 20)
}
func touchAnim(touches:Set<UITouch>) {
if let touch = touches.first, tapAnimation {
var loc = touch.location(in: self)
loc = CGPoint(x: loc.x.clamp(0, bounds.width), y: loc.y.clamp(0, bounds.height))
loc = loc - bounds.center
let rotation = CGPoint(x: -loc.y / bounds.height, y: loc.x / bounds.width)
if #available(iOS 9.0, *) {
let force = touch.maximumPossibleForce == 0 ? 1 : touch.force
let rotation = rotation * (0.21 + force * 0.04)
yaal.scale.animateTo(0.95 - force*0.01)
yaal.rotationX.animateTo(rotation.x)
yaal.rotationY.animateTo(rotation.y)
} else {
let rotation = rotation * 0.25
yaal.scale.animateTo(0.94)
yaal.rotationX.animateTo(rotation.x)
yaal.rotationY.animateTo(rotation.y)
}
}
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
touchAnim(touches: touches)
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
touchAnim(touches: touches)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if tapAnimation {
yaal.scale.animateTo(1.0, stiffness: 150, damping: 7)
yaal.rotationX.animateTo(0, stiffness: 150, damping: 7)
yaal.rotationY.animateTo(0, stiffness: 150, damping: 7)
}
}
open override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
super.touchesCancelled(touches!, with: event)
if tapAnimation {
yaal.scale.animateTo(1.0, stiffness: 150, damping: 7)
yaal.rotationX.animateTo(0, stiffness: 150, damping: 7)
yaal.rotationY.animateTo(0, stiffness: 150, damping: 7)
}
}
}
| mit | 7dbba9839417e8e391301b843cbc8662 | 34.728261 | 127 | 0.675692 | 3.636062 | false | false | false | false |
grpc/grpc-swift | Sources/GRPC/Interceptor/ClientInterceptorPipeline.swift | 1 | 19632 | /*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Logging
import NIOCore
import NIOHPACK
import NIOHTTP2
/// A pipeline for intercepting client request and response streams.
///
/// The interceptor pipeline lies between the call object (`UnaryCall`, `ClientStreamingCall`, etc.)
/// and the transport used to send and receive messages from the server (a `NIO.Channel`). It holds
/// a collection of interceptors which may be used to observe or alter messages as the travel
/// through the pipeline.
///
/// ```
/// ┌───────────────────────────────────────────────────────────────────┐
/// │ Call │
/// └────────────────────────────────────────────────────────┬──────────┘
/// │ send(_:promise) /
/// │ cancel(promise:)
/// ┌────────────────────────────────────────────────────────▼──────────┐
/// │ InterceptorPipeline ╎ │
/// │ ╎ │
/// │ ┌──────────────────────────────────────────────────────▼────────┐ │
/// │ │ Tail Interceptor (hands response parts to a callback) │ │
/// │ └────────▲─────────────────────────────────────────────┬────────┘ │
/// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
/// │ │ Interceptor 1 │ │
/// │ └────────▲─────────────────────────────────────────────┬────────┘ │
/// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
/// │ │ Interceptor 2 │ │
/// │ └────────▲─────────────────────────────────────────────┬────────┘ │
/// │ ╎ ╎ │
/// │ ╎ (More interceptors) ╎ │
/// │ ╎ ╎ │
/// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
/// │ │ Head Interceptor (interacts with transport) │ │
/// │ └────────▲─────────────────────────────────────────────┬────────┘ │
/// │ ╎ receive(_:) │ │
/// └──────────▲─────────────────────────────────────────────┼──────────┘
/// │ receive(_:) │ send(_:promise:) /
/// │ │ cancel(promise:)
/// ┌──────────┴─────────────────────────────────────────────▼──────────┐
/// │ ClientTransport │
/// │ (a NIO.ChannelHandler) │
/// ```
@usableFromInline
internal final class ClientInterceptorPipeline<Request, Response> {
/// A logger.
@usableFromInline
internal var logger: GRPCLogger
/// The `EventLoop` this RPC is being executed on.
@usableFromInline
internal let eventLoop: EventLoop
/// The details of the call.
@usableFromInline
internal let details: CallDetails
/// A task for closing the RPC in case of a timeout.
@usableFromInline
internal var _scheduledClose: Scheduled<Void>?
@usableFromInline
internal let _errorDelegate: ClientErrorDelegate?
@usableFromInline
internal private(set) var _onError: ((Error) -> Void)?
@usableFromInline
internal private(set) var _onCancel: ((EventLoopPromise<Void>?) -> Void)?
@usableFromInline
internal private(set) var _onRequestPart:
((GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void)?
@usableFromInline
internal private(set) var _onResponsePart: ((GRPCClientResponsePart<Response>) -> Void)?
/// The index after the last user interceptor context index. (i.e. `_userContexts.endIndex`).
@usableFromInline
internal let _headIndex: Int
/// The index before the first user interceptor context index (always -1).
@usableFromInline
internal let _tailIndex: Int
@usableFromInline
internal var _userContexts: [ClientInterceptorContext<Request, Response>]
/// Whether the interceptor pipeline is still open. It becomes closed after an 'end' response
/// part has traversed the pipeline.
@usableFromInline
internal var _isOpen = true
/// The index of the next context on the inbound side of the context at the given index.
@inlinable
internal func _nextInboundIndex(after index: Int) -> Int {
// Unchecked arithmetic is okay here: our smallest inbound index is '_tailIndex' but we will
// never ask for the inbound index after the tail.
assert(self._indexIsValid(index))
return index &- 1
}
/// The index of the next context on the outbound side of the context at the given index.
@inlinable
internal func _nextOutboundIndex(after index: Int) -> Int {
// Unchecked arithmetic is okay here: our greatest outbound index is '_headIndex' but we will
// never ask for the outbound index after the head.
assert(self._indexIsValid(index))
return index &+ 1
}
/// Returns true of the index is in the range `_tailIndex ... _headIndex`.
@inlinable
internal func _indexIsValid(_ index: Int) -> Bool {
return index >= self._tailIndex && index <= self._headIndex
}
@inlinable
internal init(
eventLoop: EventLoop,
details: CallDetails,
logger: GRPCLogger,
interceptors: [ClientInterceptor<Request, Response>],
errorDelegate: ClientErrorDelegate?,
onError: @escaping (Error) -> Void,
onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
onRequestPart: @escaping (GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void,
onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
) {
self.eventLoop = eventLoop
self.details = details
self.logger = logger
self._errorDelegate = errorDelegate
self._onError = onError
self._onCancel = onCancel
self._onRequestPart = onRequestPart
self._onResponsePart = onResponsePart
// The tail is before the interceptors.
self._tailIndex = -1
// The head is after the interceptors.
self._headIndex = interceptors.endIndex
// Make some contexts.
self._userContexts = []
self._userContexts.reserveCapacity(interceptors.count)
for index in 0 ..< interceptors.count {
let context = ClientInterceptorContext(for: interceptors[index], atIndex: index, in: self)
self._userContexts.append(context)
}
self._setupDeadline()
}
/// Emit a response part message into the interceptor pipeline.
///
/// This should be called by the transport layer when receiving a response part from the server.
///
/// - Parameter part: The part to emit into the pipeline.
/// - Important: This *must* to be called from the `eventLoop`.
@inlinable
internal func receive(_ part: GRPCClientResponsePart<Response>) {
self.invokeReceive(part, fromContextAtIndex: self._headIndex)
}
/// Invoke receive on the appropriate context when called from the context at the given index.
@inlinable
internal func invokeReceive(
_ part: GRPCClientResponsePart<Response>,
fromContextAtIndex index: Int
) {
self._invokeReceive(part, onContextAtIndex: self._nextInboundIndex(after: index))
}
/// Invoke receive on the context at the given index, if doing so is safe.
@inlinable
internal func _invokeReceive(
_ part: GRPCClientResponsePart<Response>,
onContextAtIndex index: Int
) {
self.eventLoop.assertInEventLoop()
assert(self._indexIsValid(index))
guard self._isOpen else {
return
}
self._invokeReceive(part, onContextAtUncheckedIndex: index)
}
/// Invoke receive on the context at the given index, assuming that the index is valid and the
/// pipeline is still open.
@inlinable
internal func _invokeReceive(
_ part: GRPCClientResponsePart<Response>,
onContextAtUncheckedIndex index: Int
) {
switch index {
case self._headIndex:
self._invokeReceive(part, onContextAtUncheckedIndex: self._nextInboundIndex(after: index))
case self._tailIndex:
if part.isEnd {
// Update our state before handling the response part.
self._isOpen = false
self._onResponsePart?(part)
self.close()
} else {
self._onResponsePart?(part)
}
default:
self._userContexts[index].invokeReceive(part)
}
}
/// Emit an error into the interceptor pipeline.
///
/// This should be called by the transport layer when receiving an error.
///
/// - Parameter error: The error to emit.
/// - Important: This *must* to be called from the `eventLoop`.
@inlinable
internal func errorCaught(_ error: Error) {
self.invokeErrorCaught(error, fromContextAtIndex: self._headIndex)
}
/// Invoke `errorCaught` on the appropriate context when called from the context at the given
/// index.
@inlinable
internal func invokeErrorCaught(_ error: Error, fromContextAtIndex index: Int) {
self._invokeErrorCaught(error, onContextAtIndex: self._nextInboundIndex(after: index))
}
/// Invoke `errorCaught` on the context at the given index if that index exists and the pipeline
/// is still open.
@inlinable
internal func _invokeErrorCaught(_ error: Error, onContextAtIndex index: Int) {
self.eventLoop.assertInEventLoop()
assert(self._indexIsValid(index))
guard self._isOpen else {
return
}
self._invokeErrorCaught(error, onContextAtUncheckedIndex: index)
}
/// Invoke `errorCaught` on the context at the given index assuming the index exists and the
/// pipeline is still open.
@inlinable
internal func _invokeErrorCaught(_ error: Error, onContextAtUncheckedIndex index: Int) {
switch index {
case self._headIndex:
self._invokeErrorCaught(error, onContextAtIndex: self._nextInboundIndex(after: index))
case self._tailIndex:
self._errorCaught(error)
default:
self._userContexts[index].invokeErrorCaught(error)
}
}
/// Handles a caught error which has traversed the interceptor pipeline.
@usableFromInline
internal func _errorCaught(_ error: Error) {
// We're about to call out to an error handler: update our state first.
self._isOpen = false
var unwrappedError: Error
// Unwrap the error, if possible.
if let errorContext = error as? GRPCError.WithContext {
unwrappedError = errorContext.error
self._errorDelegate?.didCatchError(
errorContext.error,
logger: self.logger.unwrapped,
file: errorContext.file,
line: errorContext.line
)
} else {
unwrappedError = error
self._errorDelegate?.didCatchErrorWithoutContext(error, logger: self.logger.unwrapped)
}
// Emit the unwrapped error.
self._onError?(unwrappedError)
// Close the pipeline.
self.close()
}
/// Writes a request message into the interceptor pipeline.
///
/// This should be called by the call object to send requests parts to the transport.
///
/// - Parameters:
/// - part: The request part to write.
/// - promise: A promise to complete when the request part has been successfully written.
/// - Important: This *must* to be called from the `eventLoop`.
@inlinable
internal func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
self.invokeSend(part, promise: promise, fromContextAtIndex: self._tailIndex)
}
/// Invoke send on the appropriate context when called from the context at the given index.
@inlinable
internal func invokeSend(
_ part: GRPCClientRequestPart<Request>,
promise: EventLoopPromise<Void>?,
fromContextAtIndex index: Int
) {
self._invokeSend(
part,
promise: promise,
onContextAtIndex: self._nextOutboundIndex(after: index)
)
}
/// Invoke send on the context at the given index, if it exists and the pipeline is still open.
@inlinable
internal func _invokeSend(
_ part: GRPCClientRequestPart<Request>,
promise: EventLoopPromise<Void>?,
onContextAtIndex index: Int
) {
self.eventLoop.assertInEventLoop()
assert(self._indexIsValid(index))
guard self._isOpen else {
promise?.fail(GRPCError.AlreadyComplete())
return
}
self._invokeSend(part, promise: promise, onContextAtUncheckedIndex: index)
}
/// Invoke send on the context at the given index assuming the index exists and the pipeline is
/// still open.
@inlinable
internal func _invokeSend(
_ part: GRPCClientRequestPart<Request>,
promise: EventLoopPromise<Void>?,
onContextAtUncheckedIndex index: Int
) {
switch index {
case self._headIndex:
self._onRequestPart?(part, promise)
case self._tailIndex:
self._invokeSend(
part,
promise: promise,
onContextAtUncheckedIndex: self._nextOutboundIndex(after: index)
)
default:
self._userContexts[index].invokeSend(part, promise: promise)
}
}
/// Send a request to cancel the RPC through the interceptor pipeline.
///
/// This should be called by the call object when attempting to cancel the RPC.
///
/// - Parameter promise: A promise to complete when the cancellation request has been handled.
/// - Important: This *must* to be called from the `eventLoop`.
@inlinable
internal func cancel(promise: EventLoopPromise<Void>?) {
self.invokeCancel(promise: promise, fromContextAtIndex: self._tailIndex)
}
/// Invoke `cancel` on the appropriate context when called from the context at the given index.
@inlinable
internal func invokeCancel(promise: EventLoopPromise<Void>?, fromContextAtIndex index: Int) {
self._invokeCancel(promise: promise, onContextAtIndex: self._nextOutboundIndex(after: index))
}
/// Invoke `cancel` on the context at the given index if the index is valid and the pipeline is
/// still open.
@inlinable
internal func _invokeCancel(
promise: EventLoopPromise<Void>?,
onContextAtIndex index: Int
) {
self.eventLoop.assertInEventLoop()
assert(self._indexIsValid(index))
guard self._isOpen else {
promise?.fail(GRPCError.AlreadyComplete())
return
}
self._invokeCancel(promise: promise, onContextAtUncheckedIndex: index)
}
/// Invoke `cancel` on the context at the given index assuming the index is valid and the
/// pipeline is still open.
@inlinable
internal func _invokeCancel(
promise: EventLoopPromise<Void>?,
onContextAtUncheckedIndex index: Int
) {
switch index {
case self._headIndex:
self._onCancel?(promise)
case self._tailIndex:
self._invokeCancel(
promise: promise,
onContextAtUncheckedIndex: self._nextOutboundIndex(after: index)
)
default:
self._userContexts[index].invokeCancel(promise: promise)
}
}
}
// MARK: - Lifecycle
extension ClientInterceptorPipeline {
/// Closes the pipeline. This should be called once, by the tail interceptor, to indicate that
/// the RPC has completed. If this is not called, we will leak.
/// - Important: This *must* to be called from the `eventLoop`.
@inlinable
internal func close() {
self.eventLoop.assertInEventLoop()
self._isOpen = false
// Cancel the timeout.
self._scheduledClose?.cancel()
self._scheduledClose = nil
// Drop the contexts since they reference us.
self._userContexts.removeAll()
// Cancel the transport.
self._onCancel?(nil)
// `ClientTransport` holds a reference to us and references to itself via these callbacks. Break
// these references now by replacing the callbacks.
self._onError = nil
self._onCancel = nil
self._onRequestPart = nil
self._onResponsePart = nil
}
/// Sets up a deadline for the pipeline.
@inlinable
internal func _setupDeadline() {
func setup() {
self.eventLoop.assertInEventLoop()
let timeLimit = self.details.options.timeLimit
let deadline = timeLimit.makeDeadline()
// There's no point scheduling this.
if deadline == .distantFuture {
return
}
self._scheduledClose = self.eventLoop.scheduleTask(deadline: deadline) {
// When the error hits the tail we'll call 'close()', this will cancel the transport if
// necessary.
self.errorCaught(GRPCError.RPCTimedOut(timeLimit))
}
}
if self.eventLoop.inEventLoop {
setup()
} else {
self.eventLoop.execute {
setup()
}
}
}
}
extension ClientInterceptorContext {
@inlinable
internal func invokeReceive(_ part: GRPCClientResponsePart<Response>) {
self.interceptor.receive(part, context: self)
}
@inlinable
internal func invokeSend(
_ part: GRPCClientRequestPart<Request>,
promise: EventLoopPromise<Void>?
) {
self.interceptor.send(part, promise: promise, context: self)
}
@inlinable
internal func invokeCancel(promise: EventLoopPromise<Void>?) {
self.interceptor.cancel(promise: promise, context: self)
}
@inlinable
internal func invokeErrorCaught(_ error: Error) {
self.interceptor.errorCaught(error, context: self)
}
}
| apache-2.0 | 4769f065383f214471025f2acadec960 | 33.571984 | 100 | 0.625267 | 4.55641 | false | false | false | false |
austinzheng/swift | test/SILOptimizer/specialize_checked_cast_branch.swift | 8 | 13761 | // RUN: %target-swift-frontend -module-name specialize_checked_cast_branch -emit-sil -O -sil-inline-threshold 0 -Xllvm -sil-disable-pass=function-signature-opts %s -o - | %FileCheck %s
class C {}
class D : C {}
class E {}
struct NotUInt8 { var value: UInt8 }
struct NotUInt64 { var value: UInt64 }
var b = NotUInt8(value: 0)
var c = C()
var d = D()
var e = E()
var f = NotUInt64(value: 0)
var o : AnyObject = c
////////////////////////
// Arch to Arch Casts //
////////////////////////
public func ArchetypeToArchetypeCast<T1, T2>(t1 : T1, t2 : T2) -> T2 {
if let x = t1 as? T2 {
return x
}
preconditionFailure("??? Profit?")
}
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA1DCTg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D
// CHECK: bb0([[ARG:%.*]] : $C, [[ARG2:%.*]] : $D):
// CHECK: checked_cast_br [[ARG]] : $C to $D, bb1, bb2
//
// CHECK: bb1([[T0:%.*]] : $D):
// CHECK: strong_retain [[ARG]]
// CHECK: return [[T0]]
//
// CHECK: bb2
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK: } // end sil function '$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA1DCTg5'
_ = ArchetypeToArchetypeCast(t1: c, t2: d)
// x -> x where x is a class.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AFTg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: strong_retain %0 : $C
// CHECK: return %0 : $C
// CHECK: } // end sil function '$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AFTg5'
_ = ArchetypeToArchetypeCast(t1: c, t2: c)
// TODO: x -> x where x is not a class.
_ = ArchetypeToArchetypeCast(t1: b, t2: b)
// TODO: x -> y where x is not a class and y is not a class.
_ = ArchetypeToArchetypeCast(t1: b, t2: f)
// x -> y where x is not a class but y is.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA8NotUInt8V_AA1CCTg5 : $@convention(thin) (NotUInt8, @guaranteed C) -> @owned C {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK: } // end sil function '$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA8NotUInt8V_AA1CCTg5'
_ = ArchetypeToArchetypeCast(t1: b, t2: c)
// y -> x where x is a class but y is not.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA8NotUInt8VTg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8 {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK: } // end sil function '$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA8NotUInt8VTg5'
_ = ArchetypeToArchetypeCast(t1: c, t2: b)
// y -> x where x is a super class of y.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1DC_AA1CCTg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C {
// CHECK: [[T1:%.*]] = upcast %0 : $D to $C
// CHECK: strong_retain %0 : $D
// CHECK: return [[T1]] : $C
// CHECK: } // end sil function '$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1DC_AA1CCTg5'
_ = ArchetypeToArchetypeCast(t1: d, t2: c)
// x -> y where x and y are unrelated.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA1ECTg5 : $@convention(thin) (@guaranteed C, @guaranteed E) -> @owned E {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK: } // end sil function '$s30specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA1ECTg5'
_ = ArchetypeToArchetypeCast(t1: c, t2: e)
///////////////////////////
// Archetype To Concrete //
///////////////////////////
func ArchetypeToConcreteCastUInt8<T>(t : T) -> NotUInt8 {
if let x = t as? NotUInt8 {
return x
}
preconditionFailure("??? Profit?")
}
func ArchetypeToConcreteCastC<T>(t : T) -> C {
if let x = t as? C {
return x
}
preconditionFailure("??? Profit?")
}
func ArchetypeToConcreteCastD<T>(t : T) -> D {
if let x = t as? D {
return x
}
preconditionFailure("??? Profit?")
}
func ArchetypeToConcreteCastE<T>(t : T) -> E {
if let x = t as? E {
return x
}
preconditionFailure("??? Profit?")
}
// uint8 -> uint8
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch28ArchetypeToConcreteCastUInt81tAA03NotI0Vx_tlFAE_Tg5 : $@convention(thin) (NotUInt8) -> NotUInt8 {
// CHECK: bb0([[ARG:%.*]] :
// CHECK: return [[ARG]] : $NotUInt8
// CHECK: } // end sil function '$s30specialize_checked_cast_branch28ArchetypeToConcreteCastUInt81tAA03NotI0Vx_tlFAE_Tg5'
_ = ArchetypeToConcreteCastUInt8(t: b)
// TODO: This needs FileCheck love.
_ = ArchetypeToConcreteCastUInt8(t: c)
// UInt64 -> Uint8
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch28ArchetypeToConcreteCastUInt81tAA03NotI0Vx_tlFAA0J6UInt64V_Tg5 : $@convention(thin) (NotUInt64) -> NotUInt8 {
// CHECK: bb0
// CHECK-NOT: checked_cast_br
// CHECK: builtin "int_trap"
// CHECK: unreachable
_ = ArchetypeToConcreteCastUInt8(t: f)
// NotUInt8 -> C
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA8NotUInt8V_Tg5 : $@convention(thin) (NotUInt8) -> @owned C {
// CHECK: bb0
// CHECK-NOT: checked_cast_br
// CHECK: unreachable
// CHECK: } // end sil function '$s30specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA8NotUInt8V_Tg5'
_ = ArchetypeToConcreteCastC(t: b)
// C -> C
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAE_Tg5 : $@convention(thin) (@guaranteed C) -> @owned C {
// CHECK: bb0([[ARG:%.*]] : $C)
// CHECK: strong_retain [[ARG]]
// CHECK: return [[ARG]] : $C
// CHECK: } // end sil function '$s30specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAE_Tg5'
_ = ArchetypeToConcreteCastC(t: c)
// D -> C
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA1DC_Tg5 : $@convention(thin) (@guaranteed D) -> @owned C {
// CHECK: bb0([[ARG:%.*]] : $D):
// CHECK: [[CAST:%.*]] = upcast [[ARG]] : $D to $C
// CHECK: strong_retain [[ARG]]
// CHECK: return [[CAST]]
// CHECK: } // end sil function '$s30specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA1DC_Tg5'
_ = ArchetypeToConcreteCastC(t: d)
// E -> C
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA1EC_Tg5 : $@convention(thin) (@guaranteed E) -> @owned C {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
_ = ArchetypeToConcreteCastC(t: e)
// C -> D
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ArchetypeToConcreteCastD1tAA1DCx_tlFAA1CC_Tg5 : $@convention(thin) (@guaranteed C) -> @owned D {
// CHECK: bb0([[ARG:%.*]] : $C):
// CHECK: checked_cast_br [[ARG]] : $C to $D, [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]([[T0:%.*]] : $D):
// CHECK: strong_retain [[ARG]]
// CHECK: return [[T0]] : $D
//
// CHECK: [[FAIL_BB]]:
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK: } // end sil function '$s30specialize_checked_cast_branch24ArchetypeToConcreteCastD1tAA1DCx_tlFAA1CC_Tg5'
_ = ArchetypeToConcreteCastD(t: c)
// C -> E
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ArchetypeToConcreteCastE1tAA1ECx_tlFAA1CC_Tg5 : $@convention(thin) (@guaranteed C) -> @owned E {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
_ = ArchetypeToConcreteCastE(t: c)
///////////////////////////
// Concrete To Archetype //
///////////////////////////
func ConcreteToArchetypeCastUInt8<T>(t: NotUInt8, t2: T) -> T {
if let x = t as? T {
return x
}
preconditionFailure("??? Profit?")
}
func ConcreteToArchetypeCastC<T>(t: C, t2: T) -> T {
if let x = t as? T {
return x
}
preconditionFailure("??? Profit?")
}
func ConcreteToArchetypeCastD<T>(t: D, t2: T) -> T {
if let x = t as? T {
return x
}
preconditionFailure("??? Profit?")
}
// x -> x where x is not a class.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAF_Tg5 : $@convention(thin) (NotUInt8, NotUInt8) -> NotUInt8 {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: return %0 : $NotUInt8
// CHECK: } // end sil function '$s30specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAF_Tg5'
_ = ConcreteToArchetypeCastUInt8(t: b, t2: b)
// x -> y where x,y are not classes and x is a different type from y.
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAA0K6UInt64V_Tg5 : $@convention(thin) (NotUInt8, NotUInt64) -> NotUInt64 {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: unreachable
// CHECK: } // end sil function '$s30specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAA0K6UInt64V_Tg5
_ = ConcreteToArchetypeCastUInt8(t: b, t2: f)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAA1CC_Tg5 : $@convention(thin) (NotUInt8, @guaranteed C) -> @owned C
// CHECK: bb0
// CHECK: unreachable
_ = ConcreteToArchetypeCastUInt8(t: b, t2: c)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAF_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C
// CHECK: bb0
// CHECK: return %0
_ = ConcreteToArchetypeCastC(t: c, t2: c)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAA8NotUInt8V_Tg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8
// CHECK: bb0
// CHECK: unreachable
_ = ConcreteToArchetypeCastC(t: c, t2: b)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAA1DC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D
// CHECK: bb0
// CHECK: checked_cast_br %0 : $C to $D
// CHECK: bb1
_ = ConcreteToArchetypeCastC(t: c, t2: d)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAA1EC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed E) -> @owned E
// CHECK: bb0
// CHECK: unreachable
_ = ConcreteToArchetypeCastC(t: c, t2: e)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch24ConcreteToArchetypeCastD1t2t2xAA1DC_xtlFAA1CC_Tg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C
// CHECK: bb0
// CHECK: [[T0:%.*]] = upcast %0 : $D to $C
// CHECK: return [[T0]]
_ = ConcreteToArchetypeCastD(t: d, t2: c)
////////////////////////
// Super To Archetype //
////////////////////////
func SuperToArchetypeCastC<T>(c : C, t : T) -> T {
if let x = c as? T {
return x
}
preconditionFailure("??? Profit?")
}
func SuperToArchetypeCastD<T>(d : D, t : T) -> T {
if let x = d as? T {
return x
}
preconditionFailure("??? Profit?")
}
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch21SuperToArchetypeCastC1c1txAA1CC_xtlFAF_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C
// CHECK: bb0
// CHECK: return %0 : $C
_ = SuperToArchetypeCastC(c: c, t: c)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch21SuperToArchetypeCastC1c1txAA1CC_xtlFAA1DC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D
// CHECK: bb0
// CHECK: checked_cast_br %0 : $C to $D
// CHECK: bb1
_ = SuperToArchetypeCastC(c: c, t: d)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch21SuperToArchetypeCastC1c1txAA1CC_xtlFAA8NotUInt8V_Tg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8
// CHECK: bb0
// CHECK: unreachable
_ = SuperToArchetypeCastC(c: c, t: b)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch21SuperToArchetypeCastD1d1txAA1DC_xtlFAA1CC_Tg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C
// CHECK: bb0
// CHECK: [[T0:%.*]] = upcast %0 : $D to $C
// CHECK: return [[T0]]
_ = SuperToArchetypeCastD(d: d, t: c)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch21SuperToArchetypeCastD1d1txAA1DC_xtlFAF_Tg5 : $@convention(thin) (@guaranteed D, @guaranteed D) -> @owned D
// CHECK: bb0
// CHECK: return %0 : $D
_ = SuperToArchetypeCastD(d: d, t: d)
//////////////////////////////
// Existential To Archetype //
//////////////////////////////
func ExistentialToArchetypeCast<T>(o : AnyObject, t : T) -> T {
if let x = o as? T {
return x
}
preconditionFailure("??? Profit?")
}
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch26ExistentialToArchetypeCast1o1txyXl_xtlFAA1CC_Tg5 : $@convention(thin) (@guaranteed AnyObject, @guaranteed C) -> @owned C
// CHECK: bb0
// CHECK: checked_cast_br %0 : $AnyObject to $C
// CHECK: bb1
_ = ExistentialToArchetypeCast(o: o, t: c)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch26ExistentialToArchetypeCast1o1txyXl_xtlFAA8NotUInt8V_Tg5 : $@convention(thin) (@guaranteed AnyObject, NotUInt8) -> NotUInt8
// CHECK: bb0
// CHECK: checked_cast_addr_br take_always AnyObject in {{%.*}} : $*AnyObject to NotUInt8 in {{%.*}} : $*NotUInt8,
// CHECK: bb1
_ = ExistentialToArchetypeCast(o: o, t: b)
// CHECK-LABEL: sil shared @$s30specialize_checked_cast_branch26ExistentialToArchetypeCast1o1txyXl_xtlFyXl_Tg5 : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject) -> @owned AnyObject
// CHECK: bb0
// CHECK-NOT: checked_cast_br %
// CHECK: return %0 : $AnyObject
// CHECK-NOT: checked_cast_br %
_ = ExistentialToArchetypeCast(o: o, t: o)
| apache-2.0 | fad3531cfb50e221284b483c1727212b | 39.354839 | 198 | 0.686142 | 3.052573 | false | false | false | false |
emmlytics/pod | Emmlytics/Classes/EmmlyticsCore.swift | 1 | 13554 | import Foundation
import UIKit
import CoreTelephony
import SystemConfiguration.CaptiveNetwork
private let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in
let originalMethod = class_getInstanceMethod(forClass, originalSelector)
let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
func getWiFiSsid() -> String? {
var ssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
break
}
}
}
return ssid
}
func deviceRemainingFreeSpaceInBytes() -> Int64? {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
guard
let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: documentDirectory),
let freeSize = systemAttributes[.systemFreeSize] as? NSNumber
else {
// something failed
return nil
}
return freeSize.int64Value
}
let systemVersion = UIDevice.current.systemVersion
let model = UIDevice.current.model
let battery = UIDevice.current.batteryLevel
let batterystate = UIDevice.current.batteryState.rawValue
let orientation = UIDevice.current.orientation.rawValue
let localizedmodel = UIDevice.current.localizedModel
let devicename = UIDevice.current.name
let systemname = UIDevice.current.systemName
let networkInfo = CTTelephonyNetworkInfo()
let carrier = networkInfo.subscriberCellularProvider
let carrierName = carrier?.carrierName;
let countrycodeiso = carrier?.isoCountryCode;
let countrycode = carrier?.mobileCountryCode;
let networkcode = carrier?.mobileNetworkCode;
let uniqueid = UIDevice.current.identifierForVendor!.uuidString
let networkString = networkInfo.currentRadioAccessTechnology
public class Emmlytics
{
//Setup Fallback Variables
public init() {} // not sure why i have to add this POS. Stack Overflow is your friend
var AppID = UserDefaults.standard.value(forKey: "emmlyticsAppId") as! String
var UserID = UserDefaults.standard.value(forKey: "emmlyticsUserID") as! String
var url = UserDefaults.standard.value(forKey: "emmlyticsURL") as! String
//Just data and stuff.
var DataCarrierName = "No Carrier"
var Datacountrycodeiso = "Unknown"
var Datacountrycode = "Unknown"
var Datanetworkcode = "Unknown"
var connectivity = "Unknown"
var currentssid = "Not Connected"
var memory = "unavailable"
public func sendAnalytics(event:String)
{
if carrier != nil {DataCarrierName = (carrierName! as String)}
if carrier != nil {Datacountrycodeiso = (countrycodeiso! as String)}
if carrier != nil {Datacountrycode = (countrycode! as String)}
if carrier != nil {Datanetworkcode = (networkcode! as String)}
if networkString == CTRadioAccessTechnologyLTE{
connectivity = "4G"
}else if networkString == CTRadioAccessTechnologyWCDMA{
connectivity = "3G"
}else if networkString == CTRadioAccessTechnologyEdge{
connectivity = "EDGE"
}
let ssid = getWiFiSsid()
if ssid != nil {currentssid = ssid!}
let locale = Locale.current
if let bytes = deviceRemainingFreeSpaceInBytes() {
memory = "\(bytes)"
}
UIDevice.current.isBatteryMonitoringEnabled = true
let battery = UIDevice.current.batteryLevel
let URLString = url + "analytic"
let bodyParameters = [
"AppID": AppID,
"UserID": UserID,
"Event": event,
"OSVersion": systemVersion,
"Model:": model,
"Battery": battery,
"BatteryState": batterystate,
"Ssid": currentssid,
"DeviceID": uniqueid,
"Orientation": orientation,
"Locale": locale,
"LocalizedModel":localizedmodel,
"DeviceName": devicename,
"SystemName": systemname,
"DataCarrier": DataCarrierName,
"Connectivity":connectivity,
"Datacountrycode": Datacountrycode,
"Datanetworkcode": Datanetworkcode,
"AvailableMemory": memory,
] as [String : Any]
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
guard let URL = URL(string:URLString) else {return}
var request = URLRequest(url: URL)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
let bodyString = bodyParameters.queryParameters
request.httpBody = bodyString.data(using: .utf8, allowLossyConversion: true)
/* Start a new Task */
let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error == nil) {
// Success
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
// Failure
print("URL Session Task Failed: %@", error!.localizedDescription);
}
})
task.resume()
session.finishTasksAndInvalidate()
}
public class func show(viewController: UIViewController){
Emmlytics().sendAnalytics(event: "appfeedback")
let frameworkBundle = Bundle(identifier:"org.cocoapods.Emmlytics")
let bundleURL = frameworkBundle?.resourceURL?.appendingPathComponent("Emmlytics.bundle")
let bundle = Bundle(url: bundleURL!)
let storyboard = UIStoryboard(name: "emmlytics", bundle: bundle)
let controller = storyboard.instantiateInitialViewController() as! emmViewController
viewController.present(controller, animated: true) {
}
}
public func sendFeedback(feedback: String, rating: Int)
{
let URLString = url + "feedback"
let bodyParameters = [
"AppID": AppID,
"UserID": UserID,
"Rating": rating,
"feedback": feedback,
"DeviceID": uniqueid
] as [String : Any]
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
guard let URL = URL(string: URLString) else {return}
var request = URLRequest(url: URL)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
let bodyString = bodyParameters.queryParameters
request.httpBody = bodyString.data(using: .utf8, allowLossyConversion: true)
let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error == nil) {
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
print("URL Session Task Failed: %@", error!.localizedDescription);
}
})
task.resume()
session.finishTasksAndInvalidate()
}
}
protocol URLQueryParameterStringConvertible {
var queryParameters: String {get}
}
extension Dictionary : URLQueryParameterStringConvertible {
var queryParameters: String {
var parts: [String] = []
for (key, value) in self {
let part = String(format: "%@=%@",
String(describing: key).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,
String(describing: value).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
parts.append(part as String)
}
return parts.joined(separator: "&")
}
}
extension URL {
func appendingQueryParameters(_ parametersDictionary : Dictionary<String, String>) -> URL {
let URLString : String = String(format: "%@?%@", self.absoluteString, parametersDictionary.queryParameters)
return URL(string: URLString)!
}
}
func SendNetmon(call: String,method: String,result:String,latency:String,bytesmoved: String )
{
let AppID = UserDefaults.standard.value(forKey: "emmlyticsAppId") as! String
let UserID = UserDefaults.standard.value(forKey: "emmlyticsUserID") as! String
let url = UserDefaults.standard.value(forKey: "emmlyticsURL") as! String
let URLString = url+"netmon"
let bodyParameters = [
"AppID": AppID,
"UserID": UserID,
"DeviceID": uniqueid,
"URL":call,
"Method":method,
"Result":result,
"Latency":latency,
"DataMoved":bytesmoved
]
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
guard let URL = URL(string: URLString) else {return}
var request = URLRequest(url: URL)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
let bodyString = bodyParameters.queryParameters
request.httpBody = bodyString.data(using: .utf8, allowLossyConversion: true)
/* Start a new Task */
let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error == nil) {
// Success
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
// Failure
print("URL Session Task Failed: %@", error!.localizedDescription);
}
})
task.resume()
session.finishTasksAndInvalidate()
}
extension URLSession {
open override class func initialize() {
// make sure this isn't a subclass
guard self === URLSession.self else { return }
let originalSelector = #selector((self.dataTask(with:completionHandler:)) as (URLSession) -> (URLRequest, @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask)
let swizzledSelector = #selector((self.my_dataTaskWithRequest(with:completionHandler:)) as (URLSession) -> (URLRequest, @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask)
swizzling(self, originalSelector, swizzledSelector)
//This is to disable the monitoring capability
}
// Swizzled Method
func my_dataTaskWithRequest(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask {
let startTime = NSDate.timeIntervalSinceReferenceDate
var currentTime: TimeInterval = 0
return my_dataTaskWithRequest(with: request, completionHandler: { (data, response, error) in
do {
if let data = data {
let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
currentTime = NSDate.timeIntervalSinceReferenceDate
let elapsedTime = currentTime - startTime
let URLfield = response?.url?.absoluteString
// print ("URL:",URLfield!)
// print ( "Request :",request.httpMethod!)
// print("Bytes Sent :",data)
let elapsedString = String(format: "%.1f",Double(elapsedTime * 1000))
//print ("Round Trip Response time (ms) ",elapsedString, " ms")
let statusCode = (response as! HTTPURLResponse).statusCode
print ("Status : ", statusCode)
let teststring: String = "\(data)"
let endIndex = teststring.index(teststring.endIndex, offsetBy: -6)
let datastring = teststring.substring(to: endIndex)
let url = UserDefaults.standard.value(forKey: "emmlyticsURL") as! String
if (URLfield! != url + "netmon" && URLfield! != url + "analytic" && URLfield! != url + "feedback")
{
print("writing")
SendNetmon(call:URLfield!, method: request.httpMethod!, result: String(statusCode), latency: elapsedString, bytesmoved: datastring)
}
}
else {
print ( "Request",request.httpMethod?.description)
print ( "Error :----",error.debugDescription)
}
} catch {
print("Swizzelled Error -> \(error)")
}
})
}
}
| mit | 0c4a676ac2715e7aef1e52d85e4da26b | 39.100592 | 199 | 0.618415 | 5.14774 | false | false | false | false |
sjtu-meow/iOS | Meow/Logger.swift | 3 | 1927 | import Foundation
class Logger {
let destination: URL
lazy fileprivate var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
lazy fileprivate var fileHandle: FileHandle? = {
let path = self.destination.path
FileManager.default.createFile(atPath: path, contents: nil, attributes: nil)
do {
let fileHandle = try FileHandle(forWritingTo: self.destination)
print("Successfully logging to: \(path)")
return fileHandle
} catch let error as NSError {
print("Serious error in logging: could not open path to log file. \(error).")
}
return nil
}()
init(destination: URL) {
self.destination = destination
}
deinit {
fileHandle?.closeFile()
}
func log(_ message: String, function: String = #function, file: String = #file, line: Int = #line) {
let logMessage = stringRepresentation(message, function: function, file: file, line: line)
printToConsole(logMessage)
printToDestination(logMessage)
}
}
private extension Logger {
func stringRepresentation(_ message: String, function: String, file: String, line: Int) -> String {
let dateString = dateFormatter.string(from: Date())
let file = URL(fileURLWithPath: file).lastPathComponent
return "\(dateString) [\(file):\(line)] \(function): \(message)\n"
}
func printToConsole(_ logMessage: String) {
print(logMessage)
}
func printToDestination(_ logMessage: String) {
if let data = logMessage.data(using: String.Encoding.utf8) {
fileHandle?.write(data)
} else {
print("Serious error in logging: could not encode logged string into data.")
}
}
}
| apache-2.0 | d8613156eb8e93b7427a0369347ce841 | 30.080645 | 104 | 0.624805 | 4.769802 | false | false | false | false |
alexreidy/Digital-Ear | Digital Ear/WaveformView.swift | 1 | 1392 | //
// WaveformView.swift
// Digital Ear
//
// Created by Alex Reidy on 4/20/15.
// Copyright (c) 2015 Alex Reidy. All rights reserved.
//
import Foundation
import UIKit
class WaveformView: UIView {
fileprivate let N_BARS = 5000
var samples: [Float] = []
convenience init(frame: CGRect, samples: [Float]) {
self.init(frame: frame)
self.samples = Ear.adjustForNoiseAndTrimEnds(samples)
}
override func draw(_ rect: CGRect) {
if samples.count < N_BARS {
return
}
let ctx = UIGraphicsGetCurrentContext()
let dx: Float = Float(self.frame.width) / Float(N_BARS)
var SAMPLES_PER_BAR: Int = samples.count / N_BARS
ctx?.setFillColor(red: 48.0/255.0, green: 48.0/255.0, blue: 48.0/255.0, alpha: 1.0)
ctx?.fill(CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
ctx?.setFillColor(red: 31.0/255.0, green: 239.0/255.0, blue: 156.0/255.0, alpha: 1.0)
for k in 0 ..< N_BARS {
let avgAmplitude: Float = average(Array(samples[k * SAMPLES_PER_BAR..<(k+1) * SAMPLES_PER_BAR]))
let r = CGRect(x: CGFloat(Float(k) * dx), y: CGFloat(self.frame.height/2), width: CGFloat(dx),
height: CGFloat(avgAmplitude * 5 * Float(self.frame.height)))
ctx?.fill(r)
}
}
}
| mit | 98820d3f3d5bf282bc71f4696532a356 | 31.372093 | 108 | 0.58046 | 3.306413 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | watchOS2/time Notification/timeNotification WatchKit Extension/timeZoneInterfaceController.swift | 1 | 3881 | //
// timeZoneInterfaceController.swift
// timeNotification
//
// Created by Luis Castillo on 1/21/16.
// Copyright © 2016 LC. All rights reserved.
//
import WatchKit
import Foundation
//for sessions
import WatchConnectivity
class timeZoneInterfaceController: WKInterfaceController, WCSessionDelegate
{
//ui properties
@IBOutlet var timeZoneAbbrevLabel: WKInterfaceLabel!
@IBOutlet var timeZoneLocationLabel: WKInterfaceLabel!
@IBOutlet var timeLabel: WKInterfaceLabel!
@IBOutlet var scheduleNotficationButton: WKInterfaceButton!
//properties
var timezoneAbbreviation:String = String()
var timezoneLocation:String = String()
let session:WCSession = WCSession.defaultSession()
//models
let timezone:timezoneModel = timezoneModel()
//MARK: View Loading
override func awakeWithContext(context: AnyObject?)
{
super.awakeWithContext(context)
//sessions
session.delegate = self
session.activateSession()
//
self.initalTimezoneSetup(context)
}//eom
override func willActivate()
{
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}//eom
override func didDeactivate()
{
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}//eom
//MARK: Initial Setup
func initalTimezoneSetup(context:AnyObject?)
{
if let currTimeZone:NSDictionary = context as? NSDictionary
{
//location
if let location:String = currTimeZone .objectForKey("location") as? String
{
self.timezoneLocation = location
self.timeZoneLocationLabel.setText(location)
}
//abbrev
if let timezoneAbbrev:String = currTimeZone .objectForKey("abbreviation") as? String
{
self.timezoneAbbreviation = timezoneAbbrev
self.timeZoneAbbrevLabel.setText(timezoneAbbrev)
}
//timezone
if let timezone:String = currTimeZone .objectForKey("timezone") as? String
{
//self.setTitle(timezone)
}
}//eo-valid data
self.updateTime()
self.setupTimer()
}//eom
//MARK: Update Data
func updateTime()
{
let time = timezone.getTimeZoneByAbbrev(timezoneAbbreviation)
self.timeLabel.setText(time)
}//eom
//MARK: - setting up timer
func setupTimer()
{
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
timer.fire()
}//eom
//MARK: Notification
@IBAction func scheduleNotification()
{
self.initateTimezoneNotificationFromPhone(self.timezoneAbbreviation)
self.scheduleNotficationButton.setTitle("Scheduled")
self.scheduleNotficationButton.setBackgroundColor(UIColor.grayColor())
}//eo-a
/*sends a message to the phone , to schedule a notification */
func initateTimezoneNotificationFromPhone(timezoneAbbrev:String)
{
let message = ["request" : "fireLocalNotification" , "timezone" : timezoneAbbrev]
WCSession.defaultSession().sendMessage(message,
replyHandler: nil,
errorHandler: {
error in
print(error.localizedDescription)
})
}//eom
}//eoc
| mit | dfe789f552ab2f4dfdaf9b7f977cd1e5 | 28.172932 | 141 | 0.583763 | 5.647744 | false | false | false | false |
milseman/swift | test/DebugInfo/ProtocolContainer.swift | 13 | 801 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
protocol AProtocol {
func print()
}
class AClass : AProtocol {
var x: UInt32
init() { x = 0xDEADBEEF }
func print() { markUsed("x = \(x)")}
}
// CHECK: define hidden {{.*}}void @_T017ProtocolContainer3foo{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: entry:
// CHECK: %[[X:.*]] = alloca %T17ProtocolContainer9AProtocolP, align {{(4|8)}}
// CHECK: call void @llvm.dbg.declare(metadata %T17ProtocolContainer9AProtocolP* %[[X]], metadata ![[XMD:.*]], metadata !{{[0-9]+}})
// CHECK-NOT: !DILocalVariable({{.*}} name: "x"
// CHECK-NOT: !DILocalVariable({{.*}} name: "x"
func foo (_ x : AProtocol) {
var x = x
x.print() // Set breakpoint here
}
var aProtocol : AProtocol = AClass()
foo(aProtocol)
| apache-2.0 | ce48d12554022957b58284206a044bc9 | 31.04 | 137 | 0.612984 | 3.080769 | false | false | false | false |
modocache/swift | test/SILGen/struct_resilience.swift | 3 | 10867 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | %FileCheck %s
import resilient_struct
// Resilient structs are always address-only
// CHECK-LABEL: sil hidden @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_ : $@convention(thin) (@in Size, @owned @callee_owned (@in Size) -> @out Size) -> @out Size
// CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@callee_owned (@in Size) -> @out Size):
func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
// Stored properties of resilient structs from outside our resilience
// domain are accessed through accessors
// CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size
var s2 = s
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1wSi : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizes1wSi : $@convention(method) (Int, @inout Size) -> ()
// CHECK: apply [[FN]]([[RESULT]], [[OTHER_SIZE_BOX]])
s2.w = s.w
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1hSi : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
// Use materializeForSet for inout access of properties in resilient structs
// from a different resilience domain
func inoutFunc(_ x: inout Int) {}
// CHECK-LABEL: sil hidden @_TF17struct_resilience18resilientInOutTestFRV16resilient_struct4SizeT_ : $@convention(thin) (@inout Size) -> ()
func resilientInOutTest(_ s: inout Size) {
// CHECK: function_ref @_TF17struct_resilience9inoutFuncFRSiT_
// CHECK: function_ref @_TFV16resilient_struct4Sizem1wSi
inoutFunc(&s.w)
// CHECK: return
}
// Fixed-layout structs may be trivial or loadable
// CHECK-LABEL: sil hidden @_TF17struct_resilience28functionWithFixedLayoutTypesFTV16resilient_struct5Point1fFS1_S1__S1_ : $@convention(thin) (Point, @owned @callee_owned (Point) -> Point) -> Point
// CHECK: bb0(%0 : $Point, %1 : $@callee_owned (Point) -> Point):
func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point {
// Stored properties of fixed layout structs are accessed directly
var p2 = p
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x
// CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x
// CHECK: assign [[RESULT]] to [[DEST]] : $*Int
p2.x = p.x
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y
_ = p.y
// CHECK: [[NEW_POINT:%.*]] = apply %1(%0)
// CHECK: return [[NEW_POINT]]
return f(p)
}
// Fixed-layout struct with resilient stored properties is still address-only
// CHECK-LABEL: sil hidden @_TF17struct_resilience39functionWithFixedLayoutOfResilientTypesFTV16resilient_struct9Rectangle1fFS1_S1__S1_ : $@convention(thin) (@in Rectangle, @owned @callee_owned (@in Rectangle) -> @out Rectangle) -> @out Rectangle
// CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@callee_owned (@in Rectangle) -> @out Rectangle):
func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle {
return f(r)
}
// Make sure we generate getters and setters for stored properties of
// resilient structs
public struct MySize {
// Static computed property
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg10expirationSi : $@convention(method) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes10expirationSi : $@convention(method) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem10expirationSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public static var expiration: Int {
get { return copyright + 70 }
set { copyright = newValue - 70 }
}
// Instance computed property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1dSi : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1dSi : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1dSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public var d: Int {
get { return 0 }
set { }
}
// Instance stored property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1wSi : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1wSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public var w: Int
// Read-only instance stored property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1hSi : $@convention(method) (@in_guaranteed MySize) -> Int
public let h: Int
// Static stored property
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg9copyrightSi : $@convention(method) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes9copyrightSi : $@convention(method) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem9copyrightSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public static var copyright: Int = 0
}
// CHECK-LABEL: sil @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_ : $@convention(thin) (@in MySize, @owned @callee_owned (@in MySize) -> @out MySize) -> @out MySize
public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
// Stored properties of resilient structs from inside our resilience
// domain are accessed directly
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize
var s2 = s
// CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w
// CHECK: [[SRC:%.*]] = load [[SRC_ADDR]] : $*Int
// CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[SIZE_BOX]] : $*MySize, #MySize.w
// CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int
s2.w = s.w
// CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h
// CHECK: [[RESULT:%.*]] = load [[RESULT_ADDR]] : $*Int
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
// CHECK-LABEL: sil [transparent] [fragile] @_TF17struct_resilience25publicTransparentFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int
@_transparent public func publicTransparentFunction(_ s: MySize) -> Int {
// Since the body of a public transparent function might be inlined into
// other resilience domains, we have to use accessors
// CHECK: [[SELF:%.*]] = alloc_stack $MySize
// CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @_TFV17struct_resilience6MySizeg1wSi
// CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]])
// CHECK-NEXT: destroy_addr [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// CHECK-LABEL: sil [transparent] [fragile] @_TF17struct_resilience30publicTransparentLocalFunctionFVS_6MySizeFT_Si : $@convention(thin) (@in MySize) -> @owned @callee_owned () -> Int
@_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int {
// CHECK-LABEL: sil shared [fragile] @_TFF17struct_resilience30publicTransparentLocalFunctionFVS_6MySizeFT_SiU_FT_Si : $@convention(thin) (@owned @box MySize) -> Int
// CHECK: function_ref @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK: return {{.*}} : $Int
return { s.w }
}
// CHECK-LABEL: sil hidden [transparent] @_TF17struct_resilience27internalTransparentFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int
@_transparent func internalTransparentFunction(_ s: MySize) -> Int {
// The body of an internal transparent function will not be inlined into
// other resilience domains, so we can access storage directly
// CHECK: [[W_ADDR:%.*]] = struct_element_addr %0 : $*MySize, #MySize.w
// CHECK-NEXT: [[RESULT:%.*]] = load [[W_ADDR]] : $*Int
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// CHECK-LABEL: sil [fragile] [always_inline] @_TF17struct_resilience26publicInlineAlwaysFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int
@inline(__always) public func publicInlineAlwaysFunction(_ s: MySize) -> Int {
// Since the body of a public transparent function might be inlined into
// other resilience domains, we have to use accessors
// CHECK: [[SELF:%.*]] = alloc_stack $MySize
// CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @_TFV17struct_resilience6MySizeg1wSi
// CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]])
// CHECK-NEXT: destroy_addr [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// Make sure that @_versioned entities can be resilient
@_versioned struct VersionedResilientStruct {
@_versioned let x: Int
@_versioned let y: Int
@_versioned init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
// CHECK-LABEL: sil [transparent] [fragile] @_TF17struct_resilience27useVersionedResilientStructFVS_24VersionedResilientStructS0_ : $@convention(thin) (@in VersionedResilientStruct) -> @out VersionedResilientStruct
@_versioned
@_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct)
-> VersionedResilientStruct {
// CHECK: function_ref @_TFV17struct_resilience24VersionedResilientStructCfT1xSi1ySi_S0_
// CHECK: function_ref @_TFV17struct_resilience24VersionedResilientStructg1ySi
// CHECK: function_ref @_TFV17struct_resilience24VersionedResilientStructg1xSi
return VersionedResilientStruct(x: s.y, y: s.x)
}
| apache-2.0 | 416ea24b85cf6afeb7488840838fd001 | 45.440171 | 246 | 0.674611 | 3.557119 | false | false | false | false |
fhchina/EasyIOS-Swift | Pod/Classes/Easy/Core/EZNavigationController.swift | 1 | 2097 | //
// EZNavigationController.swift
// medical
//
// Created by zhuchao on 15/4/24.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import UIKit
public class EZNavigationController: UINavigationController,UINavigationControllerDelegate,UIGestureRecognizerDelegate{
public var popGestureRecognizerEnabled = true
override public func viewDidLoad() {
super.viewDidLoad()
self.configGestureRecognizer()
// Do any additional setup after loading the view.
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func configGestureRecognizer() {
if let target = self.interactivePopGestureRecognizer.delegate {
var pan = UIPanGestureRecognizer(target: target, action: Selector("handleNavigationTransition:"))
pan.delegate = self
self.view.addGestureRecognizer(pan)
}
//禁掉系统的侧滑手势
weak var weekSelf = self
self.interactivePopGestureRecognizer.enabled = false;
self.interactivePopGestureRecognizer.delegate = weekSelf;
}
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer != self.interactivePopGestureRecognizer && self.viewControllers.count > 1 && self.popGestureRecognizerEnabled{
return true
}else{
return false
}
}
override public func pushViewController(viewController: UIViewController, animated: Bool) {
self.interactivePopGestureRecognizer?.enabled = false
super.pushViewController(viewController, animated: animated)
}
//UINavigationControllerDelegate
public func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
if self.popGestureRecognizerEnabled {
self.interactivePopGestureRecognizer?.enabled = true
}
}
}
| mit | 90642745d94836fecefc1ceaecee4fa2 | 33.616667 | 156 | 0.699085 | 6.00289 | false | false | false | false |
Yamievw/programmeerproject | YamievanWijnbergen-Programmeerproject/DiversMapViewController.swift | 1 | 3168 | //
// DiversMapViewController.swift
// YamievanWijnbergen-Programmeerproject
//
// Created by Yamie van Wijnbergen on 13/06/2017.
// Copyright © 2017 Yamie van Wijnbergen. All rights reserved.
//
import UIKit
import FirebaseDatabase
import CoreLocation
import MapKit
class DiversMapViewController: UIViewController, MKMapViewDelegate {
var diverss = [Annotation]()
var divers = [User]()
var diver: User?
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Get Map.
mapView.showsUserLocation = true
mapView.delegate = self
mapView.isZoomEnabled = true
getUserLocations()
navigationController?.navigationBar.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Zoom in to exact location of current user.
@IBAction func zoomIn(_ sender: Any) {
let userLocation = mapView.userLocation
let region = MKCoordinateRegionMakeWithDistance((userLocation.location?.coordinate)!, 2000, 2000)
mapView.setRegion(region, animated: true)
}
// Get only location for each user.
func getUserLocations() {
Database.database().reference().child("Userinfo").observe(.childAdded, with: { (snapshot) in
let dictionary = snapshot.value as! [String: Any]
let user = User(dictionary: dictionary)
let diversss = Annotation(user: user)
user.id = snapshot.key
self.diverss.append(diversss)
// Add annotation to map for each user.
self.mapView.addAnnotation(diversss)
})
}
// Create button to get more info on user.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "") {
annotationView.annotation = annotation
return annotationView
} else {
let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:"")
annotationView.isEnabled = true
annotationView.canShowCallout = true
let btn = UIButton(type: .detailDisclosure)
annotationView.rightCalloutAccessoryView = btn
return annotationView
}
}
// Segue to UserProfile.
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
self.diver = (view.annotation! as? Annotation)?.user
performSegue(withIdentifier: "diversInfo", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? UserProfileViewController {
viewController.diver = self.diver!
}
}
}
| mit | 047c5db92c81e3383aec73ffb4776f3b | 33.053763 | 129 | 0.64288 | 5.304858 | false | false | false | false |
iosyaowei/Weibo | WeiBo/Classes/View(视图和控制器)/Main/MainBaseController/YWNavgationViewController.swift | 1 | 1568 | //
// YWNavgationViewController.swift
// WeiBo
//
// Created by yao wei on 16/9/9.
// Copyright © 2016年 yao wei. All rights reserved.
//
import UIKit
class YWNavgationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
//隐藏默认 的NavgationBar
navigationBar.isHidden = true
}
//重写 push 方法 所有的push 都做都会调用此方法
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
//如果不是根控制器 栈底控制器 才需要隐藏 根控制器不需要隐藏
//注意super 之前和之后的问题的区别 childViewControllers.count > 1
if childViewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
//一层显示首页标题 其他显示返回
if let vc = (viewController as? YWBaseViewController){
var title = "返回"
if childViewControllers.count == 1 {
title = childViewControllers.first?.title ?? "返回"
}
vc.navItem.leftBarButtonItem = UIBarButtonItem(title: title, target: self, action: #selector(popToParent),isBack:true)
}
}
super.pushViewController(viewController, animated:true)
}
@objc private func popToParent(){
popViewController(animated: true)
}
}
| mit | 244ab18bca256d78fd5ea357b34f7848 | 26.057692 | 134 | 0.57285 | 5.043011 | false | false | false | false |
abertelrud/swift-package-manager | Sources/Build/LLBuildManifestBuilder.swift | 2 | 44883 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2015-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 Basics
import PackageGraph
import PackageModel
import LLBuildManifest
import SPMBuildCore
@_implementationOnly import DriverSupport
@_implementationOnly import SwiftDriver
import TSCBasic
public class LLBuildManifestBuilder {
public enum TargetKind {
case main
case test
public var targetName: String {
switch self {
case .main: return "main"
case .test: return "test"
}
}
}
/// The build plan to work on.
public let plan: BuildPlan
/// Whether to sandbox commands from build tool plugins.
public let disableSandboxForPluginCommands: Bool
/// File system reference.
private let fileSystem: FileSystem
/// ObservabilityScope with which to emit diagnostics
public let observabilityScope: ObservabilityScope
public private(set) var manifest: BuildManifest = BuildManifest()
var buildConfig: String { buildParameters.configuration.dirname }
var buildParameters: BuildParameters { plan.buildParameters }
var buildEnvironment: BuildEnvironment { buildParameters.buildEnvironment }
/// Create a new builder with a build plan.
public init(_ plan: BuildPlan, disableSandboxForPluginCommands: Bool = false, fileSystem: FileSystem, observabilityScope: ObservabilityScope) {
self.plan = plan
self.disableSandboxForPluginCommands = disableSandboxForPluginCommands
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope
}
// MARK:- Generate Manifest
/// Generate manifest at the given path.
@discardableResult
public func generateManifest(at path: AbsolutePath) throws -> BuildManifest {
manifest.createTarget(TargetKind.main.targetName)
manifest.createTarget(TargetKind.test.targetName)
manifest.defaultTarget = TargetKind.main.targetName
addPackageStructureCommand()
addBinaryDependencyCommands()
if buildParameters.useExplicitModuleBuild {
// Explicit module builds use the integrated driver directly and
// require that every target's build jobs specify its dependencies explicitly to plan
// its build.
// Currently behind:
// --experimental-explicit-module-build
try addTargetsToExplicitBuildManifest()
} else {
// Create commands for all target descriptions in the plan.
for (_, description) in plan.targetMap {
switch description {
case .swift(let desc):
try self.createSwiftCompileCommand(desc)
case .clang(let desc):
try self.createClangCompileCommand(desc)
}
}
}
try self.addTestDiscoveryGenerationCommand()
try self.addTestEntryPointGenerationCommand()
// Create command for all products in the plan.
for (_, description) in plan.productMap {
try self.createProductCommand(description)
}
try ManifestWriter(fileSystem: self.fileSystem).write(manifest, at: path)
return manifest
}
func addNode(_ node: Node, toTarget targetKind: TargetKind) {
manifest.addNode(node, toTarget: targetKind.targetName)
}
}
// MARK: - Package Structure
extension LLBuildManifestBuilder {
fileprivate func addPackageStructureCommand() {
let inputs = plan.graph.rootPackages.flatMap { package -> [Node] in
var inputs = package.targets
.map { $0.sources.root }
.sorted()
.map { Node.directoryStructure($0) }
// Add the output paths of any prebuilds that were run, so that we redo the plan if they change.
var derivedSourceDirPaths: [AbsolutePath] = []
for result in plan.prebuildCommandResults.values.flatMap({ $0 }) {
derivedSourceDirPaths.append(contentsOf: result.outputDirectories)
}
inputs.append(contentsOf: derivedSourceDirPaths.sorted().map{ Node.directoryStructure($0) })
// FIXME: Need to handle version-specific manifests.
inputs.append(file: package.manifest.path)
// FIXME: This won't be the location of Package.resolved for multiroot packages.
inputs.append(file: package.path.appending(component: "Package.resolved"))
// FIXME: Add config file as an input
return inputs
}
let name = "PackageStructure"
let output: Node = .virtual(name)
manifest.addPkgStructureCmd(
name: name,
inputs: inputs,
outputs: [output]
)
manifest.addNode(output, toTarget: name)
}
}
// MARK:- Binary Dependencies
extension LLBuildManifestBuilder {
// Creates commands for copying all binary artifacts depended on in the plan.
fileprivate func addBinaryDependencyCommands() {
let binaryPaths = Set(plan.targetMap.values.flatMap({ $0.libraryBinaryPaths }))
for binaryPath in binaryPaths {
let destination = destinationPath(forBinaryAt: binaryPath)
addCopyCommand(from: binaryPath, to: destination)
}
}
}
// MARK: - Resources Bundle
extension LLBuildManifestBuilder {
/// Adds command for creating the resources bundle of the given target.
///
/// Returns the virtual node that will build the entire bundle.
fileprivate func createResourcesBundle(
for target: TargetBuildDescription
) -> Node? {
guard let bundlePath = target.bundlePath else { return nil }
var outputs: [Node] = []
let infoPlistDestination = RelativePath("Info.plist")
// Create a copy command for each resource file.
for resource in target.resources {
let destination = bundlePath.appending(resource.destination)
let (_, output) = addCopyCommand(from: resource.path, to: destination)
outputs.append(output)
}
// Create a copy command for the Info.plist if a resource with the same name doesn't exist yet.
if let infoPlistPath = target.resourceBundleInfoPlistPath {
let destination = bundlePath.appending(infoPlistDestination)
let (_, output) = addCopyCommand(from: infoPlistPath, to: destination)
outputs.append(output)
}
let cmdName = target.target.getLLBuildResourcesCmdName(config: buildConfig)
manifest.addPhonyCmd(name: cmdName, inputs: outputs, outputs: [.virtual(cmdName)])
return .virtual(cmdName)
}
}
// MARK:- Compile Swift
extension LLBuildManifestBuilder {
/// Create a llbuild target for a Swift target description.
private func createSwiftCompileCommand(
_ target: SwiftTargetBuildDescription
) throws {
// Inputs.
let inputs = try self.computeSwiftCompileCmdInputs(target)
// Outputs.
let objectNodes = try target.objects.map(Node.file)
let moduleNode = Node.file(target.moduleOutputPath)
let cmdOutputs = objectNodes + [moduleNode]
if buildParameters.useIntegratedSwiftDriver {
try self.addSwiftCmdsViaIntegratedDriver(target, inputs: inputs, objectNodes: objectNodes, moduleNode: moduleNode)
} else if buildParameters.emitSwiftModuleSeparately {
try self.addSwiftCmdsEmitSwiftModuleSeparately(target, inputs: inputs, objectNodes: objectNodes, moduleNode: moduleNode)
} else {
try self.addCmdWithBuiltinSwiftTool(target, inputs: inputs, cmdOutputs: cmdOutputs)
}
self.addTargetCmd(target, cmdOutputs: cmdOutputs)
try self.addModuleWrapCmd(target)
}
private func addSwiftCmdsViaIntegratedDriver(
_ target: SwiftTargetBuildDescription,
inputs: [Node],
objectNodes: [Node],
moduleNode: Node
) throws {
// Use the integrated Swift driver to compute the set of frontend
// jobs needed to build this Swift target.
var commandLine = try target.emitCommandLine();
commandLine.append("-driver-use-frontend-path")
commandLine.append(buildParameters.toolchain.swiftCompilerPath.pathString)
// FIXME: At some point SwiftPM should provide its own executor for
// running jobs/launching processes during planning
let resolver = try ArgsResolver(fileSystem: target.fileSystem)
let executor = SPMSwiftDriverExecutor(resolver: resolver,
fileSystem: target.fileSystem,
env: ProcessEnv.vars)
var driver = try Driver(args: commandLine,
diagnosticsEngine: self.observabilityScope.makeDiagnosticsEngine(),
fileSystem: self.fileSystem,
executor: executor)
let jobs = try driver.planBuild()
try addSwiftDriverJobs(for: target, jobs: jobs, inputs: inputs, resolver: resolver,
isMainModule: { driver.isExplicitMainModuleJob(job: $0)})
}
private func addSwiftDriverJobs(for targetDescription: SwiftTargetBuildDescription,
jobs: [Job], inputs: [Node],
resolver: ArgsResolver,
isMainModule: (Job) -> Bool,
uniqueExplicitDependencyTracker: UniqueExplicitDependencyJobTracker? = nil) throws {
// Add build jobs to the manifest
for job in jobs {
let tool = try resolver.resolve(.path(job.tool))
let commandLine = try job.commandLine.map{ try resolver.resolve($0) }
let arguments = [tool] + commandLine
// Check if an explicit pre-build dependency job has already been
// added as a part of this build.
if let uniqueDependencyTracker = uniqueExplicitDependencyTracker,
job.isExplicitDependencyPreBuildJob {
if try !uniqueDependencyTracker.registerExplicitDependencyBuildJob(job) {
// This is a duplicate of a previously-seen identical job.
// Skip adding it to the manifest
continue
}
}
let jobInputs = try job.inputs.map { try $0.resolveToNode(fileSystem: self.fileSystem) }
let jobOutputs = try job.outputs.map { try $0.resolveToNode(fileSystem: self.fileSystem) }
// Add target dependencies as inputs to the main module build command.
//
// Jobs for a target's intermediate build artifacts, such as PCMs or
// modules built from a .swiftinterface, do not have a
// dependency on cross-target build products. If multiple targets share
// common intermediate dependency modules, such dependencies can lead
// to cycles in the resulting manifest.
var manifestNodeInputs : [Node] = []
if buildParameters.useExplicitModuleBuild && !isMainModule(job) {
manifestNodeInputs = jobInputs
} else {
manifestNodeInputs = (inputs + jobInputs).uniqued()
}
guard let firstJobOutput = jobOutputs.first else {
throw InternalError("unknown first JobOutput")
}
let moduleName = targetDescription.target.c99name
let description = job.description
if job.kind.isSwiftFrontend {
manifest.addSwiftFrontendCmd(
name: firstJobOutput.name,
moduleName: moduleName,
description: description,
inputs: manifestNodeInputs,
outputs: jobOutputs,
arguments: arguments
)
} else {
manifest.addShellCmd(
name: firstJobOutput.name,
description: description,
inputs: manifestNodeInputs,
outputs: jobOutputs,
arguments: arguments
)
}
}
}
// Building a Swift module in Explicit Module Build mode requires passing all of its module
// dependencies as explicit arguments to the build command. Thus, building a SwiftPM package
// with multiple inter-dependent targets thus requires that each target’s build job must
// have its target dependencies’ modules passed into it as explicit module dependencies.
// Because none of the targets have been built yet, a given target's dependency scanning
// action will not be able to discover its target dependencies' modules. Instead, it is
// SwiftPM's responsibility to communicate to the driver, when planning a given target's
// build, that this target has dependencies that are other targets, along with a list of
// future artifacts of such dependencies (.swiftmodule and .pcm files).
// The driver will then use those artifacts as explicit inputs to its module’s build jobs.
//
// Consider an example SwiftPM package with two targets: target B, and target A, where A
// depends on B:
// SwiftPM will process targets in a topological order and “bubble-up” each target’s
// inter-module dependency graph to its dependencies. First, SwiftPM will process B, and be
// able to plan its full build because it does not have any target dependencies. Then the
// driver is tasked with planning a build for A. SwiftPM will pass as input to the driver
// the module dependency graph of its target’s dependencies, in this case, just the
// dependency graph of B. The driver is then responsible for the necessary post-processing
// to merge the dependency graphs and plan the build for A, using artifacts of B as explicit
// inputs.
public func addTargetsToExplicitBuildManifest() throws {
// Sort the product targets in topological order in order to collect and "bubble up"
// their respective dependency graphs to the depending targets.
let nodes: [ResolvedTarget.Dependency] = plan.targetMap.keys.map {
ResolvedTarget.Dependency.target($0, conditions: [])
}
let allPackageDependencies = try topologicalSort(nodes, successors: { $0.dependencies })
// Instantiate the inter-module dependency oracle which will cache commonly-scanned
// modules across targets' Driver instances.
let dependencyOracle = InterModuleDependencyOracle()
// Explicit dependency pre-build jobs may be common to multiple targets.
// We de-duplicate them here to avoid adding identical entries to the
// downstream LLBuild manifest
let explicitDependencyJobTracker = UniqueExplicitDependencyJobTracker()
// Create commands for all target descriptions in the plan.
for dependency in allPackageDependencies.reversed() {
guard case .target(let target, _) = dependency else {
// Product dependency build jobs are added after the fact.
// Targets that depend on product dependencies will expand the corresponding
// product into its constituent targets.
continue
}
guard target.underlyingTarget.type != .systemModule,
target.underlyingTarget.type != .binary else {
// Much like non-Swift targets, system modules will consist of a modulemap
// somewhere in the filesystem, with the path to that module being either
// manually-specified or computed based on the system module type (apt, brew).
// Similarly, binary targets will bring in an .xcframework, the contents of
// which will be exposed via search paths.
//
// In both cases, the dependency scanning action in the driver will be automatically
// be able to detect such targets' modules.
continue
}
guard let description = plan.targetMap[target] else {
throw InternalError("Expected description for target \(target)")
}
switch description {
case .swift(let desc):
try self.createExplicitSwiftTargetCompileCommand(description: desc,
dependencyOracle: dependencyOracle,
explicitDependencyJobTracker: explicitDependencyJobTracker)
case .clang(let desc):
try self.createClangCompileCommand(desc)
}
}
}
private func createExplicitSwiftTargetCompileCommand(
description: SwiftTargetBuildDescription,
dependencyOracle: InterModuleDependencyOracle,
explicitDependencyJobTracker: UniqueExplicitDependencyJobTracker?
) throws {
// Inputs.
let inputs = try self.computeSwiftCompileCmdInputs(description)
// Outputs.
let objectNodes = try description.objects.map(Node.file)
let moduleNode = Node.file(description.moduleOutputPath)
let cmdOutputs = objectNodes + [moduleNode]
// Commands.
try addExplicitBuildSwiftCmds(description, inputs: inputs,
dependencyOracle: dependencyOracle,
explicitDependencyJobTracker: explicitDependencyJobTracker)
self.addTargetCmd(description, cmdOutputs: cmdOutputs)
try self.addModuleWrapCmd(description)
}
private func addExplicitBuildSwiftCmds(
_ targetDescription: SwiftTargetBuildDescription,
inputs: [Node],
dependencyOracle: InterModuleDependencyOracle,
explicitDependencyJobTracker: UniqueExplicitDependencyJobTracker? = nil
) throws {
// Pass the driver its external dependencies (target dependencies)
var dependencyModuleDetailsMap: SwiftDriver.ExternalTargetModuleDetailsMap = [:]
// Collect paths for target dependencies of this target (direct and transitive)
try self.collectTargetDependencyModuleDetails(for: targetDescription.target, dependencyModuleDetailsMap: &dependencyModuleDetailsMap)
// Compute the set of frontend
// jobs needed to build this Swift target.
var commandLine = try targetDescription.emitCommandLine();
commandLine.append("-driver-use-frontend-path")
commandLine.append(buildParameters.toolchain.swiftCompilerPath.pathString)
commandLine.append("-experimental-explicit-module-build")
let resolver = try ArgsResolver(fileSystem: self.fileSystem)
let executor = SPMSwiftDriverExecutor(resolver: resolver,
fileSystem: self.fileSystem,
env: ProcessEnv.vars)
var driver = try Driver(args: commandLine,
fileSystem: self.fileSystem,
executor: executor,
externalTargetModuleDetailsMap: dependencyModuleDetailsMap,
interModuleDependencyOracle: dependencyOracle
)
let jobs = try driver.planBuild()
try addSwiftDriverJobs(for: targetDescription, jobs: jobs, inputs: inputs, resolver: resolver,
isMainModule: { driver.isExplicitMainModuleJob(job: $0)},
uniqueExplicitDependencyTracker: explicitDependencyJobTracker)
}
/// Collect a map from all target dependencies of the specified target to the build planning artifacts for said dependency,
/// in the form of a path to a .swiftmodule file and the dependency's InterModuleDependencyGraph.
private func collectTargetDependencyModuleDetails(
for target: ResolvedTarget,
dependencyModuleDetailsMap: inout SwiftDriver.ExternalTargetModuleDetailsMap
) throws {
for dependency in target.dependencies(satisfying: self.buildEnvironment) {
switch dependency {
case .product:
// Product dependencies are broken down into the targets that make them up.
guard let dependencyProduct = dependency.product else {
throw InternalError("unknown dependency product for \(dependency)")
}
for dependencyProductTarget in dependencyProduct.targets {
try self.addTargetDependencyInfo(for: dependencyProductTarget, dependencyModuleDetailsMap: &dependencyModuleDetailsMap)
}
case .target:
// Product dependencies are broken down into the targets that make them up.
guard let dependencyTarget = dependency.target else {
throw InternalError("unknown dependency target for \(dependency)")
}
try self.addTargetDependencyInfo(for: dependencyTarget, dependencyModuleDetailsMap: &dependencyModuleDetailsMap)
}
}
}
private func addTargetDependencyInfo(
for target: ResolvedTarget,
dependencyModuleDetailsMap: inout SwiftDriver.ExternalTargetModuleDetailsMap
) throws {
guard case .swift(let dependencySwiftTargetDescription) = plan.targetMap[target] else {
return
}
dependencyModuleDetailsMap[ModuleDependencyId.swiftPlaceholder(target.c99name)] =
SwiftDriver.ExternalTargetModuleDetails(path: dependencySwiftTargetDescription.moduleOutputPath, isFramework: false)
try self.collectTargetDependencyModuleDetails(for: target, dependencyModuleDetailsMap: &dependencyModuleDetailsMap)
}
private func addSwiftCmdsEmitSwiftModuleSeparately(
_ target: SwiftTargetBuildDescription,
inputs: [Node],
objectNodes: [Node],
moduleNode: Node
) throws {
// FIXME: We need to ingest the emitted dependencies.
manifest.addShellCmd(
name: target.moduleOutputPath.pathString,
description: "Emitting module for \(target.target.name)",
inputs: inputs,
outputs: [moduleNode],
arguments: try target.emitModuleCommandLine()
)
let cmdName = target.target.getCommandName(config: buildConfig)
manifest.addShellCmd(
name: cmdName,
description: "Compiling module \(target.target.name)",
inputs: inputs,
outputs: objectNodes,
arguments: try target.emitObjectsCommandLine()
)
}
private func addCmdWithBuiltinSwiftTool(
_ target: SwiftTargetBuildDescription,
inputs: [Node],
cmdOutputs: [Node]
) throws {
let isLibrary = target.target.type == .library || target.target.type == .test
let cmdName = target.target.getCommandName(config: buildConfig)
manifest.addSwiftCmd(
name: cmdName,
inputs: inputs,
outputs: cmdOutputs,
executable: buildParameters.toolchain.swiftCompilerPath,
moduleName: target.target.c99name,
moduleAliases: target.target.moduleAliases,
moduleOutputPath: target.moduleOutputPath,
importPath: buildParameters.buildPath,
tempsPath: target.tempsPath,
objects: try target.objects,
otherArguments: try target.compileArguments(),
sources: target.sources,
isLibrary: isLibrary,
wholeModuleOptimization: buildParameters.configuration == .release
)
}
private func computeSwiftCompileCmdInputs(
_ target: SwiftTargetBuildDescription
) throws -> [Node] {
var inputs = target.sources.map(Node.file)
// Add resources node as the input to the target. This isn't great because we
// don't need to block building of a module until its resources are assembled but
// we don't currently have a good way to express that resources should be built
// whenever a module is being built.
if let resourcesNode = createResourcesBundle(for: .swift(target)) {
inputs.append(resourcesNode)
}
func addStaticTargetInputs(_ target: ResolvedTarget) throws {
// Ignore C Modules.
if target.underlyingTarget is SystemLibraryTarget { return }
// Ignore Binary Modules.
if target.underlyingTarget is BinaryTarget { return }
// Ignore Plugin Targets.
if target.underlyingTarget is PluginTarget { return }
// Depend on the binary for executable targets.
if target.type == .executable {
// FIXME: Optimize.
let _product = try plan.graph.allProducts.first {
try $0.type == .executable && $0.executableTarget == target
}
if let product = _product {
guard let planProduct = plan.productMap[product] else {
throw InternalError("unknown product \(product)")
}
inputs.append(file: planProduct.binaryPath)
}
return
}
switch plan.targetMap[target] {
case .swift(let target)?:
inputs.append(file: target.moduleOutputPath)
case .clang(let target)?:
for object in try target.objects {
inputs.append(file: object)
}
case nil:
throw InternalError("unexpected: target \(target) not in target map \(plan.targetMap)")
}
}
for dependency in target.target.dependencies(satisfying: buildEnvironment) {
switch dependency {
case .target(let target, _):
try addStaticTargetInputs(target)
case .product(let product, _):
switch product.type {
case .executable, .snippet, .library(.dynamic):
guard let planProduct = plan.productMap[product] else {
throw InternalError("unknown product \(product)")
}
// Establish a dependency on binary of the product.
inputs.append(file: planProduct.binaryPath)
// For automatic and static libraries, and plugins, add their targets as static input.
case .library(.automatic), .library(.static), .plugin:
for target in product.targets {
try addStaticTargetInputs(target)
}
case .test:
break
}
}
}
for binaryPath in target.libraryBinaryPaths {
let path = destinationPath(forBinaryAt: binaryPath)
if self.fileSystem.isDirectory(binaryPath) {
inputs.append(directory: path)
} else {
inputs.append(file: path)
}
}
// Add any regular build commands created by plugins for the target.
for result in target.buildToolPluginInvocationResults {
// Only go through the regular build commands — prebuild commands are handled separately.
for command in result.buildCommands {
// Create a shell command to invoke the executable. We include the path of the executable as a dependency, and make sure the name is unique.
let execPath = command.configuration.executable
let uniquedName = ([execPath.pathString] + command.configuration.arguments).joined(separator: "|")
let displayName = command.configuration.displayName ?? execPath.basename
var commandLine = [execPath.pathString] + command.configuration.arguments
if !self.disableSandboxForPluginCommands {
commandLine = try Sandbox.apply(command: commandLine, strictness: .writableTemporaryDirectory, writableDirectories: [result.pluginOutputDirectory])
}
manifest.addShellCmd(
name: displayName + "-" + ByteString(encodingAsUTF8: uniquedName).sha256Checksum,
description: displayName,
inputs: command.inputFiles.map{ .file($0) },
outputs: command.outputFiles.map{ .file($0) },
arguments: commandLine,
environment: command.configuration.environment,
workingDirectory: command.configuration.workingDirectory?.pathString)
}
}
return inputs
}
/// Adds a top-level phony command that builds the entire target.
private func addTargetCmd(_ target: SwiftTargetBuildDescription, cmdOutputs: [Node]) {
// Create a phony node to represent the entire target.
let targetName = target.target.getLLBuildTargetName(config: buildConfig)
let targetOutput: Node = .virtual(targetName)
manifest.addNode(targetOutput, toTarget: targetName)
manifest.addPhonyCmd(
name: targetOutput.name,
inputs: cmdOutputs,
outputs: [targetOutput]
)
if plan.graph.isInRootPackages(target.target, satisfying: self.buildEnvironment) {
if !target.isTestTarget {
addNode(targetOutput, toTarget: .main)
}
addNode(targetOutput, toTarget: .test)
}
}
private func addModuleWrapCmd(_ target: SwiftTargetBuildDescription) throws {
// Add commands to perform the module wrapping Swift modules when debugging strategy is `modulewrap`.
guard buildParameters.debuggingStrategy == .modulewrap else { return }
var moduleWrapArgs = [
target.buildParameters.toolchain.swiftCompilerPath.pathString,
"-modulewrap", target.moduleOutputPath.pathString,
"-o", target.wrappedModuleOutputPath.pathString
]
moduleWrapArgs += try buildParameters.targetTripleArgs(for: target.target)
manifest.addShellCmd(
name: target.wrappedModuleOutputPath.pathString,
description: "Wrapping AST for \(target.target.name) for debugging",
inputs: [.file(target.moduleOutputPath)],
outputs: [.file(target.wrappedModuleOutputPath)],
arguments: moduleWrapArgs)
}
}
fileprivate extension SwiftDriver.Job {
var isExplicitDependencyPreBuildJob: Bool {
return (kind == .emitModule &&
inputs.contains { $0.file.extension == "swiftinterface" } ) ||
kind == .generatePCM
}
}
/// A simple mechanism to keep track of already-known explicit module pre-build jobs.
/// It uses the output filename of the job (either a `.swiftmodule` or a `.pcm`) for uniqueness,
/// because the SwiftDriver encodes the module's context hash into this filename. Any two jobs
/// producing an binary module file with an identical name are therefore duplicate
fileprivate class UniqueExplicitDependencyJobTracker {
private var uniqueDependencyModuleIDSet: Set<Int> = []
/// Registers the input Job with the tracker. Returns `false` if this job is already known
func registerExplicitDependencyBuildJob(_ job: SwiftDriver.Job) throws -> Bool {
guard job.isExplicitDependencyPreBuildJob,
let soleOutput = job.outputs.spm_only else {
throw InternalError("Expected explicit module dependency build job")
}
let jobUniqueID = soleOutput.file.basename.hashValue
let (new, _) = uniqueDependencyModuleIDSet.insert(jobUniqueID)
return new
}
}
// MARK:- Compile C-family
extension LLBuildManifestBuilder {
/// Create a llbuild target for a Clang target description.
private func createClangCompileCommand(
_ target: ClangTargetBuildDescription
) throws {
let standards = [
(target.clangTarget.cxxLanguageStandard, SupportedLanguageExtension.cppExtensions),
(target.clangTarget.cLanguageStandard, SupportedLanguageExtension.cExtensions),
]
var inputs: [Node] = []
// Add resources node as the input to the target. This isn't great because we
// don't need to block building of a module until its resources are assembled but
// we don't currently have a good way to express that resources should be built
// whenever a module is being built.
if let resourcesNode = createResourcesBundle(for: .clang(target)) {
inputs.append(resourcesNode)
}
func addStaticTargetInputs(_ target: ResolvedTarget) {
if case .swift(let desc)? = plan.targetMap[target], target.type == .library {
inputs.append(file: desc.moduleOutputPath)
}
}
for dependency in target.target.dependencies(satisfying: buildEnvironment) {
switch dependency {
case .target(let target, _):
addStaticTargetInputs(target)
case .product(let product, _):
switch product.type {
case .executable, .snippet, .library(.dynamic):
guard let planProduct = plan.productMap[product] else {
throw InternalError("unknown product \(product)")
}
// Establish a dependency on binary of the product.
let binary = planProduct.binaryPath
inputs.append(file: binary)
case .library(.automatic), .library(.static), .plugin:
for target in product.targets {
addStaticTargetInputs(target)
}
case .test:
break
}
}
}
for binaryPath in target.libraryBinaryPaths {
let path = destinationPath(forBinaryAt: binaryPath)
if self.fileSystem.isDirectory(binaryPath) {
inputs.append(directory: path)
} else {
inputs.append(file: path)
}
}
var objectFileNodes: [Node] = []
for path in try target.compilePaths() {
let isCXX = path.source.extension.map{ SupportedLanguageExtension.cppExtensions.contains($0) } ?? false
var args = try target.basicArguments(isCXX: isCXX)
args += ["-MD", "-MT", "dependencies", "-MF", path.deps.pathString]
// Add language standard flag if needed.
if let ext = path.source.extension {
for (standard, validExtensions) in standards {
if let languageStandard = standard, validExtensions.contains(ext) {
args += ["-std=\(languageStandard)"]
}
}
}
args += ["-c", path.source.pathString, "-o", path.object.pathString]
let clangCompiler = try buildParameters.toolchain.getClangCompiler().pathString
args.insert(clangCompiler, at: 0)
let objectFileNode: Node = .file(path.object)
objectFileNodes.append(objectFileNode)
manifest.addClangCmd(
name: path.object.pathString,
description: "Compiling \(target.target.name) \(path.filename)",
inputs: inputs + [.file(path.source)],
outputs: [objectFileNode],
arguments: args,
dependencies: path.deps.pathString
)
}
// Create a phony node to represent the entire target.
let targetName = target.target.getLLBuildTargetName(config: buildConfig)
let output: Node = .virtual(targetName)
manifest.addNode(output, toTarget: targetName)
manifest.addPhonyCmd(
name: output.name,
inputs: objectFileNodes,
outputs: [output]
)
if plan.graph.isInRootPackages(target.target, satisfying: self.buildEnvironment) {
if !target.isTestTarget {
addNode(output, toTarget: .main)
}
addNode(output, toTarget: .test)
}
}
}
// MARK:- Test File Generation
extension LLBuildManifestBuilder {
fileprivate func addTestDiscoveryGenerationCommand() throws {
for testDiscoveryTarget in plan.targets.compactMap(\.testDiscoveryTargetBuildDescription) {
let testTargets = testDiscoveryTarget.target.dependencies
.compactMap{ $0.target }.compactMap{ plan.targetMap[$0] }
let objectFiles = try testTargets.flatMap{ try $0.objects }.sorted().map(Node.file)
let outputs = testDiscoveryTarget.target.sources.paths
guard let mainOutput = (outputs.first{ $0.basename == TestDiscoveryTool.mainFileName }) else {
throw InternalError("main output (\(TestDiscoveryTool.mainFileName)) not found")
}
let cmdName = mainOutput.pathString
manifest.addTestDiscoveryCmd(
name: cmdName,
inputs: objectFiles,
outputs: outputs.map(Node.file)
)
}
}
fileprivate func addTestEntryPointGenerationCommand() throws {
for target in plan.targets {
guard case .swift(let target) = target,
case .entryPoint(let isSynthesized) = target.testTargetRole,
isSynthesized else { continue }
let testEntryPointTarget = target
// Get the Swift target build descriptions of all discovery targets this synthesized entry point target depends on.
let discoveredTargetDependencyBuildDescriptions = testEntryPointTarget.target.dependencies
.compactMap(\.target)
.compactMap { plan.targetMap[$0] }
.compactMap(\.testDiscoveryTargetBuildDescription)
// The module outputs of the discovery targets this synthesized entry point target depends on are
// considered the inputs to the entry point command.
let inputs = discoveredTargetDependencyBuildDescriptions.map { $0.moduleOutputPath }
let outputs = testEntryPointTarget.target.sources.paths
guard let mainOutput = (outputs.first{ $0.basename == TestEntryPointTool.mainFileName }) else {
throw InternalError("main output (\(TestEntryPointTool.mainFileName)) not found")
}
let cmdName = mainOutput.pathString
manifest.addTestEntryPointCmd(
name: cmdName,
inputs: inputs.map(Node.file),
outputs: outputs.map(Node.file)
)
}
}
}
private extension TargetBuildDescription {
/// If receiver represents a Swift target build description whose test target role is Discovery,
/// then this returns that Swift target build description, else returns nil.
var testDiscoveryTargetBuildDescription: SwiftTargetBuildDescription? {
guard case .swift(let targetBuildDescription) = self,
case .discovery = targetBuildDescription.testTargetRole else { return nil }
return targetBuildDescription
}
}
// MARK: - Product Command
extension LLBuildManifestBuilder {
private func createProductCommand(_ buildProduct: ProductBuildDescription) throws {
let cmdName = try buildProduct.product.getCommandName(config: buildConfig)
switch buildProduct.product.type {
case .library(.static):
manifest.addShellCmd(
name: cmdName,
description: "Archiving \(buildProduct.binaryPath.prettyPath())",
inputs: buildProduct.objects.map(Node.file),
outputs: [.file(buildProduct.binaryPath)],
arguments: try buildProduct.archiveArguments()
)
default:
let inputs = buildProduct.objects + buildProduct.dylibs.map({ $0.binaryPath })
manifest.addShellCmd(
name: cmdName,
description: "Linking \(buildProduct.binaryPath.prettyPath())",
inputs: inputs.map(Node.file),
outputs: [.file(buildProduct.binaryPath)],
arguments: try buildProduct.linkArguments()
)
}
// Create a phony node to represent the entire target.
let targetName = try buildProduct.product.getLLBuildTargetName(config: buildConfig)
let output: Node = .virtual(targetName)
manifest.addNode(output, toTarget: targetName)
manifest.addPhonyCmd(
name: output.name,
inputs: [.file(buildProduct.binaryPath)],
outputs: [output]
)
if plan.graph.reachableProducts.contains(buildProduct.product) {
if buildProduct.product.type != .test {
addNode(output, toTarget: .main)
}
addNode(output, toTarget: .test)
}
}
}
extension ResolvedTarget {
public func getCommandName(config: String) -> String {
return "C." + getLLBuildTargetName(config: config)
}
public func getLLBuildTargetName(config: String) -> String {
return "\(name)-\(config).module"
}
public func getLLBuildResourcesCmdName(config: String) -> String {
return "\(name)-\(config).module-resources"
}
}
extension ResolvedProduct {
public func getLLBuildTargetName(config: String) throws -> String {
switch type {
case .library(.dynamic):
return "\(name)-\(config).dylib"
case .test:
return "\(name)-\(config).test"
case .library(.static):
return "\(name)-\(config).a"
case .library(.automatic):
throw InternalError("automatic library not supported")
case .executable, .snippet:
return "\(name)-\(config).exe"
case .plugin:
throw InternalError("unexpectedly asked for the llbuild target name of a plugin product")
}
}
public func getCommandName(config: String) throws -> String {
return try "C." + self.getLLBuildTargetName(config: config)
}
}
// MARK: - Helper
extension LLBuildManifestBuilder {
@discardableResult
fileprivate func addCopyCommand(
from source: AbsolutePath,
to destination: AbsolutePath
) -> (inputNode: Node, outputNode: Node) {
let isDirectory = self.fileSystem.isDirectory(source)
let nodeType = isDirectory ? Node.directory : Node.file
let inputNode = nodeType(source)
let outputNode = nodeType(destination)
manifest.addCopyCmd(name: destination.pathString, inputs: [inputNode], outputs: [outputNode])
return (inputNode, outputNode)
}
fileprivate func destinationPath(forBinaryAt path: AbsolutePath) -> AbsolutePath {
plan.buildParameters.buildPath.appending(component: path.basename)
}
}
extension TypedVirtualPath {
/// Resolve a typed virtual path provided by the Swift driver to
/// a node in the build graph.
func resolveToNode(fileSystem: FileSystem) throws -> Node {
if let absolutePath = file.absolutePath {
return Node.file(absolutePath)
} else if let relativePath = file.relativePath {
guard let workingDirectory = fileSystem.currentWorkingDirectory else {
throw InternalError("unknown working directory")
}
return Node.file(workingDirectory.appending(relativePath))
} else if let temporaryFileName = file.temporaryFileName {
return Node.virtual(temporaryFileName.pathString)
} else {
throw InternalError("Cannot resolve VirtualPath: \(file)")
}
}
}
extension Sequence where Element: Hashable {
/// Unique the elements in a sequence.
func uniqued() -> [Element] {
var seen: Set<Element> = []
return filter { seen.insert($0).inserted }
}
}
| apache-2.0 | 40c07a31e7e54a6aedf1ff3f9384d699 | 43.030422 | 167 | 0.625092 | 5.212244 | false | false | false | false |
yhyuan/meteor-ios | Examples/Todos/Todos/SignUpViewController.swift | 8 | 3046 | // Copyright (c) 2014-2015 Martijn Walraven
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreData
import Meteor
class SignUpViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var passwordConfirmationField: UITextField!
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
errorMessageLabel.text = nil
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
emailField.becomeFirstResponder()
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == emailField {
passwordField.becomeFirstResponder()
} else if textField == passwordField {
passwordConfirmationField.becomeFirstResponder()
} else if textField == passwordConfirmationField {
passwordConfirmationField.resignFirstResponder()
signUp()
}
return false
}
// MARK: IBActions
@IBAction func signUp() {
errorMessageLabel.text = nil
let email = emailField.text
let password = passwordField.text
let passwordConfirmation = passwordConfirmationField.text
if email.isEmpty || password.isEmpty || passwordConfirmation.isEmpty {
errorMessageLabel.text = "Email, password and password confirmation are required"
return
} else if password != passwordConfirmation {
errorMessageLabel.text = "Password and password confirmation do not match"
return
}
Meteor.signUpWithEmail(email, password: password) { (error) -> Void in
if let error = error {
self.errorMessageLabel.text = error.localizedFailureReason
} else {
self.performSegueWithIdentifier("Unwind", sender: self)
}
}
}
}
| mit | 7187a4c670057d12c678f7775910a23f | 33.613636 | 87 | 0.728496 | 5.102178 | false | false | false | false |
grgcombs/objc-code-challenges | 12-word-wrap.swift | 2 | 4341 | /**
Given a string of words and a maxWidth, write a method that inserts new lines where appropriate to perform a word-wrap. (Wrap on word boundaries, assume " " is fine).
Now, assume that you must call a provided method -widthOfString: for any combination of words in a string. This is to account for the differences in letter kerning and glyph sizes in the font. For example, the width of "ham" + the width of "burger" is not the same as the width of "hamburger".
Now, how does your implementation handle string with multiple spaces between words ... Are those extra spaces lost or preserved? (Not necessary to actually preserve them, so long as you note the loss as a known caveat).
*/
import Foundation
/**
Wrap a given string to a maxWidth, at word boundaries.
- Requires a single grapheme for space and newline.
- Preserves extra spaces.
- Single words > maxWidth are not wrapped/clipped.
- No additional storage.
- O(N)
:param: string A string to word-wrap
:param: maxWidth The maximum width per line
:returns: A newly wrapped string
*/
func wrapStringToMaxWidth(string : String, maxWidth : Int) -> String
{
var str = string
let length = count(str)
assert(length > 0, "Invalid string length")
var previousSpace = str.endIndex
var i = str.startIndex
var lineWidth = 0
func wrapToSpaceAndResetNext(i: String.Index, space : String.Index) -> Int
{
let range = space...space;
str.replaceRange(range, with: "\n")
let width = distance(space.successor(), i)
return width
}
for i in str.startIndex ..< str.endIndex {
let char : Character = str[i]
if (char == Character(" ")) {
previousSpace = i
}
if (lineWidth >= maxWidth &&
previousSpace < str.endIndex)
{
lineWidth = wrapToSpaceAndResetNext(i, previousSpace)
previousSpace = str.endIndex
continue
}
lineWidth++
}
return str
}
/**
A mock function that would calculate the string with, with kerning. It would account for the differences in letter kerning and glyph sizes in the font. For example, the width of "ham" + the width of "burger" is not the same as the width of "hamburger".
:param: string A string to calculate the width. The string should not be an empty string.
:returns: The string's kerning width. This mock method simply returns the number of characters in the string.
*/
func kerningWidthOfString(string : String) -> Int {
return count(string)
}
/**
Wrap a given string to a maxWidth, at word boundaries.
- Requires a single grapheme for space and newline.
- Preserves extra spaces.
- Single words > maxWidth are not wrapped/clipped.
- Requires additional storage for current line.
- O(N)??? (excluding cost of kern width calculation)
:param: string A string to word-wrap
:param: maxWidth The maximum width per line
:returns: A newly wrapped string
*/
func wrapStringToMaxKerningWidth(string : String, maxWidth : Int) -> String
{
var str = string
let length = count(str)
assert(length > 0, "Invalid string length")
var previousSpace = str.endIndex
var i = str.startIndex
var lineWidth = 0
var lineStart = str.startIndex
var currentLine = ""
func wrapToSpaceAndResetNext(i: String.Index, space : String.Index) -> Int
{
let range = space...space;
str.replaceRange(range, with: "\n")
let nextRange = space.successor() ... i
currentLine = str.substringWithRange(nextRange)
return kerningWidthOfString(currentLine)
}
for i in str.startIndex ..< str.endIndex {
let char : Character = str[i]
if (char == Character(" ")) {
previousSpace = i
}
if (lineWidth >= maxWidth &&
previousSpace < str.endIndex)
{
lineWidth = wrapToSpaceAndResetNext(i, previousSpace)
previousSpace = str.endIndex
continue;
}
currentLine.append(char)
lineWidth = kerningWidthOfString(currentLine)
}
return str
}
let str = "This is a very long string which has to be converted"
let wrapped = wrapStringToMaxWidth(str, 10)
println(wrapped)
let kernWrapped = wrapStringToMaxKerningWidth(str, 10)
assert(wrapped == kernWrapped, "Results should be equal")
| cc0-1.0 | 1114ca2a72e31cd4e3582d6e0bc23297 | 30.686131 | 294 | 0.674038 | 4.226874 | false | false | false | false |
luckymore0520/GreenTea | Loyalty/Vendor/CityListView/Util/SpecifyArray.swift | 1 | 912 | //
// SpecifyArray.swift
// CityListDemo
//
// Created by ray on 15/12/10.
// Copyright © 2015年 ray. All rights reserved.
//
import UIKit
class SpecifyArray: NSObject {
var array:NSMutableArray = NSMutableArray();
var maxCount:Int = 10{
didSet{
if(maxCount <= 0){
maxCount = 10;
}
}
}
init(max:Int) {
super.init();
maxCount = max;
}
func addObject(object:NSObject){
array.addObject(object);
if(array.count > maxCount && array.count > 1){
array.removeObjectAtIndex(0);
}
}
func count()->Int{
return array.count;
}
func getaArray()->NSArray{
return array;
}
func addArray(arr:NSArray){
// self.array = array as! NSMutableArray;
self.array = NSMutableArray(array: arr);
}
}
| mit | f9be249e87821e3716a8c3d63b78d238 | 17.55102 | 54 | 0.520352 | 4.131818 | false | false | false | false |
Gagnant/Socket | Socket/ThreadComponent.swift | 1 | 1554 | //
// NetworkThread.swift
// Socket
//
// Created by Andrew Visotskyy on 1/30/17.
// Copyright © 2017 Andrew Visotskyy. All rights reserved.
//
import Foundation
internal class ThreadComponent: NSObject {
private var thread: Thread?
private let condition: NSLock
private let semaphore: DispatchSemaphore
internal static func detachNew() -> ThreadComponent {
let component = ThreadComponent()
component.start()
return component
}
internal override init() {
condition = NSLock()
semaphore = DispatchSemaphore(value: 0)
super.init()
}
deinit {
self.stop()
}
internal func start() {
condition.lock()
if thread == nil {
thread = Thread(with: threadProc)
thread?.start()
semaphore.wait()
}
condition.unlock()
}
internal func stop() {
self.condition.lock()
if let thread = self.thread {
thread.perform {
CFRunLoopStop(CFRunLoopGetCurrent())
}
self.thread = nil
}
condition.unlock()
}
@objc private func threadProc() {
var context = CFRunLoopSourceContext()
context.version = 0
context.perform = { pointer in }
var source = CFRunLoopSourceCreate(nil, 0, &context)
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, CFRunLoopMode.commonModes)
self.semaphore.signal()
CFRunLoopRun()
//Will get here after run loop will stop execution
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, CFRunLoopMode.commonModes)
source = nil
}
internal func perform(block: @escaping () -> Void) {
condition.lock()
thread?.perform(block)
condition.unlock()
}
}
| mit | 0af92a3d26ce46f9bc811be2381225f0 | 20.273973 | 81 | 0.702511 | 3.603248 | false | false | false | false |
iamyuiwong/swift-common | demos/StringUtilDEMO/StringUtilDEMO/main.swift | 1 | 3986 | // main.swift
// 15/10/2.
import Foundation
/* "" */
let es = ""
print("es:", es)
var ss = StringUtil.split(string: es, byCharacter: ",".characters.first!)
print("ss: ", ss)
ss = StringUtil.split(string: es, byString: ",")
print("2 ss: ", ss)
/* "xxx" */
var s = "你好,世界,⬆️"
print("s:", s)
ss = StringUtil.split(string: s, byString: ",")
print("ss: ", ss)
s = "你好0,2 xx /世界0,1/⬆️==0,1/😀"
print("s:", s)
ss = StringUtil.split(string: s, byString: "0,1/")
print("ss: ", ss)
ss = StringUtil.split(string: s, byString: "0,1/nnn")
print("2 ss: ", ss)
/* charsCount */
s = "123abc"
var csc = StringUtil.charsCount(ofString: s)
print("s:", s, "len: \(csc)")
s = "一二😓4"
csc = StringUtil.charsCount(ofString: s)
print("s:", s, "len: \(csc)")
/* cstringCount */
csc = StringUtil.cstringCount(ofString: s, whenEncoding: NSUTF8StringEncoding)
print("s:", s, "when utf8 len: \(csc)")
csc = StringUtil.cstringCount(ofString: s, whenEncoding: NSUTF16StringEncoding)
print("s:", s, "2 when utf16 len: \(csc)")
csc = StringUtil.cstringCount(ofString: "", whenEncoding: NSUTF8StringEncoding)
print("s:", "", "3 when utf8 len: \(csc)")
/* substring */
s = "am一二😓XX"
print("s:", s, "0, 0:", StringUtil.substring(ofString: s, fromCharIndex: 0,
to: 0))
let c = StringUtil.charsCount(ofString: s)
print("s:", s, "0, \(c):", StringUtil.substring(ofString: s, fromCharIndex: 0,
to: c))
print("s:", s, "1, 3:", StringUtil.substring(ofString: s, fromCharIndex: 1,
to: 3))
print("s:", s, "-1, \(c):", StringUtil.substring(ofString: s,
fromCharIndex: -1, to: c))
print("s:", s, "0, \(c + 1):", StringUtil.substring(ofString: s,
fromCharIndex: -1, to: (c + 1)))
print("s:", "", "0, 1:", StringUtil.substring(ofString: "", fromCharIndex: 0,
to: 1))
print("s:", s, "1, 5:", StringUtil.substring(ofString: s, fromCharIndex: 1,
count: 5))
print("s:", s, "0, 7:", StringUtil.substring(ofString: s, fromCharIndex: 0,
count: 7))
/* reverse */
print("s:", s, "reverse:", StringUtil.reverse(tostring: s))
print("s:", s, "2 reverse:", StringUtil.reverse(tocs: s))
print("s:", "", "3 reverse:", StringUtil.reverse(tostring: ""))
print("s:", "", "4 reverse:", StringUtil.reverse(tocs: ""))
/* toString fromStringArray */
var sa = ["111", "", "嚯嚯", "😋"]
s = StringUtil.toString(fromStringArray: sa)
print("sa:", sa, "toString(fromStringArray:)", s)
sa = [String]()
s = StringUtil.toString(fromStringArray: sa)
print("sa:", sa, "toString(fromStringArray:)", s)
/* toString fromStringArray and insert separator */
sa = ["111", "$%", "^", "嚯嚯", "😋"]
s = StringUtil.toString(fromStringArray: sa, insSeparator: " 分隔符 ",
hasTail: false)
print("sa:", sa, "toString(fromStringArray:insSeparator:false)", s)
s = StringUtil.toString(fromStringArray: sa, insSeparator: " 分隔符 ",
hasTail: true)
print("sa:", sa, "toString(fromStringArray:insSeparator:true)", s)
/* remove:inString:fromCharIndex:to */
var before = "xcvbnm中文"
s = StringUtil.remove(inString: before, fromCharIndex: 0, to: 0)
print(before, s)
before = s
s = StringUtil.remove(inString: before, fromCharIndex: -1, to: 0)
print(before, s)
before = s
s = StringUtil.remove(inString: before, fromCharIndex: 10, to: 0)
print(before, s)
s = StringUtil.remove(inString: before, fromCharIndex: 10, to: 10)
print(before, s)
s = StringUtil.remove(inString: before, fromCharIndex: 0, to: 6)
print(before, s)
before = s
s = StringUtil.remove(inString: before, fromCharIndex: 0, to: 0)
print(before, s)
/* remove:inString:fromCharIndex:count */
before = "xcvbnm中文"
s = StringUtil.remove(inString: before, fromCharIndex: 0, count: 0)
print(before, s)
before = s
s = StringUtil.remove(inString: before, fromCharIndex: 3, count: 2)
print(before, s)
before = s
s = StringUtil.remove(inString: before, fromCharIndex: 0, count: 6)
print(before, s)
before = s
s = StringUtil.remove(inString: before, fromCharIndex: 0, count: 1)
print(before, s) | lgpl-3.0 | be195d8c3c26ca707bdab5fcaf3fd682 | 24.272727 | 79 | 0.65613 | 2.836006 | false | false | false | false |
tjw/swift | test/SILOptimizer/access_enforcement_selection.swift | 3 | 4320 | // RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -parse-as-library %s -Xllvm -debug-only=access-enforcement-selection 2>&1 | %FileCheck %s
// REQUIRES: asserts
// This is a source-level test because it helps bring up the entire -Onone pipeline with the access markers.
public func takesInout(_ i: inout Int) {
i = 42
}
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection10takesInoutyySizF
// CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
// Helper taking a basic, no-escape closure.
func takeClosure(_: ()->Int) {}
// Helper taking a basic, no-escape closure.
func takeClosureAndInout(_: inout Int, _: ()->Int) {}
// Helper taking an escaping closure.
func takeEscapingClosure(_: @escaping ()->Int) {}
// Generate an alloc_stack that escapes into a closure.
public func captureStack() -> Int {
// Use a `var` so `x` isn't treated as a literal.
var x = 3
takeClosure { return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection12captureStackSiyF
// Dynamic access for `return x`. Since the closure is non-escaping, using
// dynamic enforcement here is more conservative than it needs to be -- static
// is sufficient here.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection12captureStackSiyFSiyXEfU_
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// Generate an alloc_stack that does not escape into a closure.
public func nocaptureStack() -> Int {
var x = 3
takeClosure { return 5 }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14nocaptureStackSiyF
// Static access for `return x`.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
//
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14nocaptureStackSiyFSiyXEfU_
// Generate an alloc_stack that escapes into a closure while an access is
// in progress.
public func captureStackWithInoutInProgress() -> Int {
// Use a `var` so `x` isn't treated as a literal.
var x = 3
takeClosureAndInout(&x) { return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection31captureStackWithInoutInProgressSiyF
// Static access for `&x`.
// CHECK-DAG: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
// Static access for `return x`.
// CHECK-DAG: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
//
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection31captureStackWithInoutInProgressSiyFSiyXEfU_
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// Generate an alloc_box that escapes into a closure.
// FIXME: `x` is eventually promoted to an alloc_stack even though it has dynamic enforcement.
// We should ensure that alloc_stack variables are statically enforced.
public func captureBox() -> Int {
var x = 3
takeEscapingClosure { x = 4; return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection10captureBoxSiyF
// Dynamic access for `return x`.
// CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
// CHECK-LABEL: $S28access_enforcement_selection10captureBoxSiyFSiycfU_
// Generate a closure in which the @inout_aliasing argument
// escapes to an @inout function `bar`.
public func recaptureStack() -> Int {
var x = 3
takeClosure { takesInout(&x); return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14recaptureStackSiyF
//
// Static access for `return x`.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// CHECK-LABEL: Access Enforcement Selection in $S28access_enforcement_selection14recaptureStackSiyFSiyXEfU_
//
// The first [modify] access inside the closure is static. It enforces the
// @inout argument.
// CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
//
// The second [read] access is static. Same as `captureStack` above.
//
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
| apache-2.0 | e1bc4a6405899b6ea708a59a37d99ae5 | 42.2 | 166 | 0.703472 | 3.763066 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.