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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wuzer/douyuTV
|
douyuTV/douyuTV/ViewModel/RecommendViewModel.swift
|
1
|
4413
|
//
// RecommendViewModel.swift
// douyuTV
//
// Created by Jefferson on 2016/10/22.
// Copyright © 2016年 Jefferson. All rights reserved.
//
import UIKit
import HandyJSON
class RecommendViewModel: BaseViewModel {
lazy var SlideModels : [SlideModel] = [SlideModel]()
fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup()
fileprivate lazy var verticalGroup : AnchorGroup = AnchorGroup()
}
extension RecommendViewModel {
func requestData(compelition: @escaping () -> ()) {
let parameter = ["limit": "4", "offset": "0", "time": NSDate.getCurrentTime()]
let globalGroup = DispatchGroup()
globalGroup.enter()
// get bigData
HttpClient.requestData(type: .get, Path: APIBigData, parameters: ["time": NSDate.getCurrentTime() as NSString]) { (response) in
// convert dict
guard let responseDict = response as? [String: Any] else { return }
// get data
guard let dataArray = responseDict["data"] as? [[String: Any]] else { return }
// let anchors = AnchorGroup()
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
// self.bigDataGroup.room_list
for dict in dataArray {
let anchor = JSONDeserializer<AnchorModel>.deserializeFrom(dict: dict as NSDictionary)
self.bigDataGroup.room_list.append(anchor!)
}
// print("请求--------0------")
globalGroup.leave()
}
globalGroup.enter()
// get vertical
HttpClient.requestData(type: .get, Path: APIVertical, parameters: parameter as [String : Any]?) { (response) in
// convert dict
guard let responseDict = response as? [String: Any] else { return }
// get data
guard let dataArray = responseDict["data"] as? [[String: Any]] else { return }
self.verticalGroup.tag_name = "颜值"
self.verticalGroup.icon_name = "home_header_phone"
for dict in dataArray {
let anchor = JSONDeserializer<AnchorModel>.deserializeFrom(dict: dict as NSDictionary)
self.verticalGroup.room_list.append(anchor!)
}
// print("请求--------1------")
globalGroup.leave()
}
globalGroup.enter()
// get hotcate
loadAnchorData(isGroup: true, path: APIHotcate, parameters: parameter) {
globalGroup.leave()
}
// HttpClient.requestData(type: .get, Path: APIHotcate, parameters: parameter as [String : Any]?) { (response) in
//// print(response)
//
// // convert dict
// guard let responseDict = response as? [String: Any] else { return }
//
// // get data
// guard let dataArray = responseDict["data"] as? [[String: Any]] else { return }
//
// for dict in dataArray {
// let anchor = JSONDeserializer<AnchorGroup>.deserializeFrom(dict: dict as NSDictionary)
// self.anchorGroups.append(anchor!)
// }
//// print("请求--------2-12------")
// globalGroup.leave()
// }
// request finish
globalGroup.notify(queue: DispatchQueue.main) {
// print("请求--------comeplition------")
self.anchorGroups.insert(self.verticalGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
compelition()
}
}
func requestCycleData(compelition: @escaping () -> ()) {
HttpClient.requestData(type: .get, Path: APISlide_6, parameters: ["version": "2.300"]) { (response) in
guard let response = response as? [String : Any] else { return }
guard let dataArray = response["data"] as? [[String : Any]] else { return }
for dict in dataArray {
let slideModel = JSONDeserializer<SlideModel>.deserializeFrom(dict: dict as NSDictionary)
self.SlideModels.append(slideModel!)
}
compelition()
}
}
}
|
mit
|
7ac858c83c6b1adbcf544d7c19a0bffe
| 34.370968 | 135 | 0.537392 | 4.798687 | false | false | false | false |
ljodal/SwiftTime
|
SwiftTimeTests/ISOChronologyTest.swift
|
1
|
4048
|
//
// ISOChronologyTest.swift
// SwiftTime
//
// Created by Sigurd Ljødal on 21.09.2015.
// Copyright © 2015 Sigurd Ljødal. All rights reserved.
//
import XCTest
@testable import SwiftTime
class ISOChronologyTest: XCTestCase {
func testFromEpoch() {
let instant: Int64 = 1442868907
let (year, month, day) = ISOChronology.instance.fromEpoch(instant)
XCTAssertEqual(2015, year)
XCTAssertEqual(9, month)
XCTAssertEqual(21, day)
}
func testFromEpochZero() {
let seconds: Int64 = 0
let (year, month, day) = ISOChronology.instance.fromEpoch(seconds)
XCTAssertEqual(1970, year)
XCTAssertEqual(1, month)
XCTAssertEqual(1, day)
}
func testFromEpochJan2() {
let seconds: Int64 = 86_400
let (year, month, day) = ISOChronology.instance.fromEpoch(seconds)
XCTAssertEqual(1970, year)
XCTAssertEqual(1, month)
XCTAssertEqual(2, day)
}
func testFromEpochNegativeSeconds1() {
let seconds: Int64 = -1
let (year, month, day) = ISOChronology.instance.fromEpoch(seconds)
XCTAssertEqual(1969, year)
XCTAssertEqual(12, month)
XCTAssertEqual(31, day)
}
func testFromEpochNegativeSeconds2() {
let seconds: Int64 = -86_400
let (year, month, day) = ISOChronology.instance.fromEpoch(seconds)
XCTAssertEqual(1969, year)
XCTAssertEqual(12, month)
XCTAssertEqual(31, day)
}
func testFromEpochNegativeSeconds3() {
let seconds: Int64 = -86_401
let (year, month, day) = ISOChronology.instance.fromEpoch(seconds)
XCTAssertEqual(1969, year)
XCTAssertEqual(12, month)
XCTAssertEqual(30, day)
}
func testToEpoch1() {
let seconds = ISOChronology.instance.toEpoch(year: 1970, month: 1, day: 1)
XCTAssertEqual(0, seconds)
}
func testToEpoch2() {
let seconds = ISOChronology.instance.toEpoch(year: 1969, month: 12, day: 31)
XCTAssertEqual(-86_400, seconds)
}
func testToEpoch3() {
let instant: Int64 = 1442868907 - 1442868907 % 86_400
let seconds = ISOChronology.instance.toEpoch(year: 2015, month: 9, day: 21)
XCTAssertEqual(instant, seconds)
}
func testLeapYearsBetween1() {
let c = ISOChronology.instance
let leaps = c.leapYears(from: 2000, to: 2016)
XCTAssertEqual(leaps, 4, "Expected 4 leap years, was: \(leaps)")
}
func testLeapYearsBetween2() {
let c = ISOChronology.instance
let leaps = c.leapYears(from: -2016, to: -2000)
XCTAssertEqual(leaps, 4, "Expected 4 leap years, was: \(leaps)")
}
func testLeapYearsBetween3() {
let c = ISOChronology.instance
let leaps = c.leapYears(from: 0, to: 400)
XCTAssertEqual(leaps, 97, "Expected 97 leap years, was: \(leaps)")
}
func testOrdinal1() {
let c = ISOChronology.instance
let (y, m, d) = c.ordinalDay(year: 2015, days: 366)
XCTAssertEqual(y, 2016)
XCTAssertEqual(m, 1)
XCTAssertEqual(d, 1)
}
func testOrdinal2() {
let c = ISOChronology.instance
let (y, m, d) = c.ordinalDay(year: 2015, days: 0)
XCTAssertEqual(y, 2014)
XCTAssertEqual(m, 12)
XCTAssertEqual(d, 31)
}
func testOrdinal3() {
let c = ISOChronology.instance
let (y, m, d) = c.ordinalDay(year: 2015, days: -1)
XCTAssertEqual(y, 2014)
XCTAssertEqual(m, 12)
XCTAssertEqual(d, 30)
}
func testOrdinal4() {
let c = ISOChronology.instance
let (y, m, d) = c.ordinalDay(year: 2010, days: 59)
XCTAssertEqual(y, 2010)
XCTAssertEqual(m, 2)
XCTAssertEqual(d, 28)
}
func testOrdinal5() {
let c = ISOChronology.instance
let (y, m, d) = c.ordinalDay(year: 2010, days: 60)
XCTAssertEqual(y, 2010)
XCTAssertEqual(m, 3)
XCTAssertEqual(d, 1)
}
}
|
mit
|
6247666fffd88f4f342ca43a3c3334d2
| 24.764331 | 84 | 0.608405 | 3.663949 | false | true | false | false |
thegoal/ISRadioButton
|
ISRadioButton/ISRadioButton.swift
|
1
|
12652
|
//
// ISRadioButton.swift
// DaynamicForm
//
// Created by Ishaq Shafiq on 09/12/2015.
// Copyright © 2015 TheGoal. All rights reserved.
//
import UIKit
@IBDesignable
public class ISRadioButton: UIButton {
var indexPath:IndexPath!
public var animationDuration:CFTimeInterval = 0.03
static let kGeneratedIconName:String = "Generated Icon"
static var _groupModifing:Bool = false
// Container for holding other buttons in same group.
@IBOutlet var otherButtons: Array<ISRadioButton>?
// Size of icon, default is 15.0.
@IBInspectable public var iconSize:CGFloat = 15.0
// Size of selection indicator, default is iconSize * 0.5.
@IBInspectable public var indicatorSize:CGFloat = 15.0 * 0.5
// Color of icon, default is black
@IBInspectable public var iconColor:UIColor = UIColor.black
// Stroke width of icon, default is iconSize / 9.
@IBInspectable public var iconStrokeWidth:CGFloat = 1.6
// Color of selection indicator, default is black
@IBInspectable public var indicatorColor:UIColor = UIColor.black
// Margin width between icon and title, default is 10. 0.
@IBInspectable public var marginWidth:CGFloat = 10.0
// Whether icon on the right side, default is NO.
@IBInspectable public var iconOnRight:Bool = false
// Whether use square icon, default is NO.
@IBInspectable public var iconSquare:Bool = false
// Image for radio button icon (optional).
@IBInspectable public var icon:UIImage!
// Image for radio button icon when selected (optional).
@IBInspectable public var iconSelected:UIImage!
// Whether enable multiple selection, default is NO.
@IBInspectable public var multipleSelectionEnabled:Bool = false
private var setOtherButtons:NSArray {
get{
return otherButtons! as NSArray
}
set (newValue) {
if (!self.isGroupModifing()){
self.groupModifing(chaining: true)
let otherNewButtons:Array<ISRadioButton>? = newValue as? Array<ISRadioButton>
for radioButton in otherNewButtons!{
let otherButtonsForCurrentButton:NSMutableArray = NSMutableArray(array:otherNewButtons!)
otherButtonsForCurrentButton.add(self)
otherButtonsForCurrentButton.remove(radioButton)
radioButton.setOtherButtons = otherButtonsForCurrentButton
}
self.groupModifing(chaining: false)
}
self.otherButtons = newValue as? Array<ISRadioButton>
}
}
@IBInspectable public var setIcon:UIImage {
// Avoid to use getter it can be nill
get{
return icon
}
set (newValue){
icon = newValue
self.setImage(icon, for: .normal)
}
}
@IBInspectable public var setIconSelected:UIImage {
// Avoid to use getter it can be nill
get{
return iconSelected
}
set (newValue){
iconSelected = newValue
self.setImage(iconSelected, for: .selected)
self.setImage(iconSelected, for: .highlighted)
}
}
public var setAnimationDuration:CFTimeInterval{
get {
return animationDuration
}
set(newValue) {
if (!self.isGroupModifing()){
self.groupModifing(chaining: true)
if self.otherButtons != nil {
for radioButton in self.otherButtons!{
radioButton.animationDuration = newValue
}
}
self.groupModifing(chaining: false)
}
animationDuration = newValue
}
}
public var setMultipleSelectionEnabled:Bool {
get{
return multipleSelectionEnabled
}
set (newValue) {
if (!self.isGroupModifing()){
self.groupModifing(chaining: true)
if self.otherButtons != nil {
for radioButton in self.otherButtons!{
radioButton.multipleSelectionEnabled = newValue
}
}
self.groupModifing(chaining: false)
}
multipleSelectionEnabled = newValue
}
}
// MARK: -- Helpers
func drawButton (){
if (self.icon == nil){
self.setIcon = self.drawIconWithSelection(false)
}else{
self.setIcon = self.icon ;
}
if (iconSelected == nil){
self.setIconSelected = self.drawIconWithSelection(true)
}else{
self.setIconSelected = self.iconSelected;
}
if self.otherButtons != nil {
self.setOtherButtons = self.otherButtons! as NSArray
}
if multipleSelectionEnabled {
self.setMultipleSelectionEnabled = multipleSelectionEnabled
}
if self.iconOnRight {
self.imageEdgeInsets = UIEdgeInsetsMake(0, self.frame.size.width - self.icon.size.width + marginWidth, 0, 0);
self.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, marginWidth + self.icon.size.width);
self.contentHorizontalAlignment = .right
} else {
self.titleEdgeInsets = UIEdgeInsetsMake(0, marginWidth, 0, 0);
self.titleLabel?.textAlignment = .left
self.contentHorizontalAlignment = .left
}
self.titleLabel?.adjustsFontSizeToFitWidth = false
}
func drawIconWithSelection (_ selected:Bool) -> UIImage{
let rect:CGRect = CGRect(x: 0, y: 0, width: iconSize, height: iconSize)
let context = UIGraphicsGetCurrentContext()
// UIGraphicsPushContext(context!)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0);
// draw icon
var iconPath:UIBezierPath!
let iconRect:CGRect = CGRect(x: iconStrokeWidth / 2, y: iconStrokeWidth / 2, width: iconSize - iconStrokeWidth, height: iconSize - iconStrokeWidth);
if self.iconSquare {
iconPath = UIBezierPath(rect:iconRect )
} else {
iconPath = UIBezierPath(ovalIn:iconRect)
}
iconColor.setStroke()
iconPath.lineWidth = iconStrokeWidth;
iconPath.stroke()
context?.addPath(iconPath.cgPath);
// draw indicator
if (selected) {
var indicatorPath:UIBezierPath!
let indicatorRect:CGRect = CGRect(x: (iconSize - indicatorSize) / 2, y: (iconSize - indicatorSize) / 2, width: indicatorSize, height: indicatorSize);
if self.iconSquare {
indicatorPath = UIBezierPath(rect:indicatorRect )
} else {
indicatorPath = UIBezierPath(ovalIn:indicatorRect)
}
indicatorColor.setStroke()
indicatorPath.lineWidth = iconStrokeWidth;
indicatorPath.stroke()
indicatorColor.setFill()
indicatorPath.fill()
context?.addPath(indicatorPath.cgPath);
}
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
// UIGraphicsPopContext()
UIGraphicsEndImageContext();
image.accessibilityIdentifier = ISRadioButton.kGeneratedIconName;
return image;
}
func touchDown () {
// if self.isSelected {
// self.isSelected = false
// }else{
self.isSelected = true
// }
}
func initRadioButton () {
super.addTarget(self, action:#selector(ISRadioButton.touchDown), for:.touchUpInside)
// self.isSelected = false
}
override public func prepareForInterfaceBuilder () {
self.initRadioButton()
self.drawButton()
}
// MARK: -- ISRadiobutton
func groupModifing(chaining:Bool) {
ISRadioButton._groupModifing = chaining
}
func isGroupModifing() -> Bool {
return ISRadioButton._groupModifing
}
// @return Selected button in same group.
public func selectedButton() -> ISRadioButton!{
if !self.multipleSelectionEnabled {
if self.isSelected {
return self
}
}else{
for isRadioButton in self.otherButtons! {
if isRadioButton.isSelected {
return isRadioButton
}
}
}
return nil
}
// @return Selected buttons in same group, use it only if multiple selection is enabled.
public func selectedButtons() -> NSMutableArray{
let selectedButtons:NSMutableArray = NSMutableArray ()
if self.isSelected {
selectedButtons.add(self)
}
for radioButton in self.otherButtons! {
if radioButton.isSelected {
selectedButtons .add(self)
}
}
return selectedButtons;
}
// Clears selection for other buttons in in same group.
public func deselectOtherButtons() {
if self.otherButtons != nil {
for radioButton in self.otherButtons! {
radioButton.isSelected = false
}
}
}
// @return unselected button in same group.
public func unSelectedButtons() -> NSArray{
let unSelectedButtons:NSMutableArray = NSMutableArray ()
if self.isSelected == false {
unSelectedButtons.add(self)
}
for isRadioButton in self.otherButtons! {
if isRadioButton.isSelected == false {
unSelectedButtons.add(self)
}
}
return unSelectedButtons ;
}
// MARK: -- UIButton
override public func titleColor(for state:UIControlState) -> UIColor{
if (state == UIControlState.selected || state == UIControlState.highlighted){
var selectedOrHighlightedColor:UIColor!
if (state == UIControlState.selected) {
selectedOrHighlightedColor = super.titleColor(for: .selected)
}else{
selectedOrHighlightedColor = super.titleColor(for: .highlighted)
}
self.setTitleColor(selectedOrHighlightedColor, for: .selected)
self.setTitleColor(selectedOrHighlightedColor, for: .highlighted)
}
return super.titleColor(for: state)!
}
// MARK: -- UIControl
override public var isSelected: Bool {
didSet {
if (multipleSelectionEnabled || oldValue != self.isSelected && self.animationDuration > 0.0) {
if self.iconSelected != nil && self.icon != nil {
let animation = CABasicAnimation(keyPath: "contents")
if self.isSelected {
animation.fromValue = self.iconSelected.cgImage
}else{
animation.fromValue = self.icon.cgImage
}
if self.isSelected {
animation.toValue = self.icon.cgImage
}else{
animation.toValue = self.iconSelected.cgImage
}
animation.duration = self.animationDuration
self.imageView?.layer.add(animation, forKey:"icon" )
}
}
if (multipleSelectionEnabled) {
if oldValue == true && self.isSelected == true {
super.isSelected = false
}else{
super.isSelected = true
}
}else {
if ( oldValue == false && self.isSelected == true ) {
self.deselectOtherButtons()
}
}
}
}
// MARK: -- UIView
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.initRadioButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initRadioButton()
}
override public func draw(_ rect:CGRect) {
super.draw(rect)
self.drawButton()
}
}
|
mit
|
1d3227a8739a06ea1738de6ca13c0056
| 31.027848 | 161 | 0.559561 | 5.306628 | false | false | false | false |
kesun421/firefox-ios
|
Client/Frontend/Intro/IntroViewController.swift
|
3
|
21928
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
struct IntroViewControllerUX {
static let Width = 375
static let Height = 667
static let SyncButtonTopPadding = 5
static let MinimumFontScale: CGFloat = 0.5
static let CardSlides = ["tour-Welcome", "tour-Search", "tour-Private", "tour-Mail", "tour-Sync"]
static let NumberOfCards = CardSlides.count
static let PagerCenterOffsetFromScrollViewBottom = UIScreen.main.bounds.width <= 320 ? 20 : 30
static let StartBrowsingButtonTitle = NSLocalizedString("Start Browsing", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo")
static let StartBrowsingButtonColor = UIColor(rgb: 0x4990E2)
static let StartBrowsingButtonHeight = 56
static let SignInButtonTitle = NSLocalizedString("Sign in to Firefox", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo")
static let SignInButtonColor = UIColor(rgb: 0x45A1FF)
static let SignInButtonHeight = 60
static let SignInButtonWidth = 290
static let CardTextLineHeight = UIScreen.main.bounds.width <= 320 ? CGFloat(2) : CGFloat(6)
static let CardTextWidth = UIScreen.main.bounds.width <= 320 ? 240 : 280
static let CardTitleHeight = 50
static let CardTitleWelcome = NSLocalizedString("Intro.Slides.Welcome.Title", tableName: "Intro", value: "Thanks for choosing Firefox!", comment: "Title for the first panel 'Welcome' in the First Run tour.")
static let CardTitleSearch = NSLocalizedString("Intro.Slides.Search.Title", tableName: "Intro", value: "Your search, your way", comment: "Title for the second panel 'Search' in the First Run tour.")
static let CardTitlePrivate = NSLocalizedString("Intro.Slides.Private.Title", tableName: "Intro", value: "Browse like no one’s watching", comment: "Title for the third panel 'Private Browsing' in the First Run tour.")
static let CardTitleMail = NSLocalizedString("Intro.Slides.Mail.Title", tableName: "Intro", value: "You’ve got mail… options", comment: "Title for the fourth panel 'Mail' in the First Run tour.")
static let CardTitleSync = NSLocalizedString("Intro.Slides.Sync.Title", tableName: "Intro", value: "Pick up where you left off", comment: "Title for the fifth panel 'Sync' in the First Run tour.")
static let CardTextWelcome = NSLocalizedString("Intro.Slides.Welcome.Description", tableName: "Intro", value: "A modern mobile browser from Mozilla, the non-profit committed to a free and open web.", comment: "Description for the 'Welcome' panel in the First Run tour.")
static let CardTextSearch = NSLocalizedString("Intro.Slides.Search.Description", tableName: "Intro", value: "Searching for something different? Choose another default search engine (or add your own) in Settings.", comment: "Description for the 'Favorite Search Engine' panel in the First Run tour.")
static let CardTextPrivate = NSLocalizedString("Intro.Slides.Private.Description", tableName: "Intro", value: "Tap the mask icon to slip into Private Browsing mode.", comment: "Description for the 'Private Browsing' panel in the First Run tour.")
static let CardTextMail = NSLocalizedString("Intro.Slides.Mail.Description", tableName: "Intro", value: "Use any email app — not just Mail — with Firefox.", comment: "Description for the 'Mail' panel in the First Run tour.")
static let CardTextSync = NSLocalizedString("Intro.Slides.Sync.Description", tableName: "Intro", value: "Use Sync to find the bookmarks, passwords, and other things you save to Firefox on all your devices.", comment: "Description for the 'Sync' panel in the First Run tour.")
static let FadeDuration = 0.25
}
let IntroViewControllerSeenProfileKey = "IntroViewControllerSeen"
protocol IntroViewControllerDelegate: class {
func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool)
}
class IntroViewController: UIViewController, UIScrollViewDelegate {
weak var delegate: IntroViewControllerDelegate?
var slides = [UIImage]()
var cards = [UIImageView]()
var introViews = [UIView]()
var titleLabels = [UILabel]()
var textLabels = [UILabel]()
var startBrowsingButton: UIButton!
var introView: UIView?
var slideContainer: UIView!
var pageControl: UIPageControl!
var backButton: UIButton!
var forwardButton: UIButton!
var signInButton: UIButton!
fileprivate var scrollView: IntroOverlayScrollView!
var slideVerticalScaleFactor: CGFloat = 1.0
override func viewDidLoad() {
view.backgroundColor = UIColor.white
// scale the slides down for iPhone 4S
if view.frame.height <= 480 {
slideVerticalScaleFactor = 1.33
slideVerticalScaleFactor = 1.33 //4S
} else if view.frame.height <= 568 {
slideVerticalScaleFactor = 1.15 //SE
}
for slideName in IntroViewControllerUX.CardSlides {
slides.append(UIImage(named: slideName)!)
}
startBrowsingButton = UIButton()
startBrowsingButton.backgroundColor = UIColor.clear
startBrowsingButton.setTitle(IntroViewControllerUX.StartBrowsingButtonTitle, for: UIControlState())
startBrowsingButton.setTitleColor(IntroViewControllerUX.StartBrowsingButtonColor, for: UIControlState())
startBrowsingButton.addTarget(self, action: #selector(IntroViewController.SELstartBrowsing), for: UIControlEvents.touchUpInside)
startBrowsingButton.accessibilityIdentifier = "IntroViewController.startBrowsingButton"
view.addSubview(startBrowsingButton)
startBrowsingButton.snp.makeConstraints { (make) -> Void in
make.left.right.bottom.equalTo(self.view)
make.height.equalTo(IntroViewControllerUX.StartBrowsingButtonHeight)
}
scrollView = IntroOverlayScrollView()
scrollView.backgroundColor = UIColor.clear
scrollView.accessibilityLabel = NSLocalizedString("Intro Tour Carousel", comment: "Accessibility label for the introduction tour carousel")
scrollView.delegate = self
scrollView.bounces = false
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.contentSize = CGSize(width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide)
scrollView.accessibilityIdentifier = "IntroViewController.scrollView"
view.addSubview(scrollView)
slideContainer = UIView()
for i in 0..<IntroViewControllerUX.NumberOfCards {
let imageView = UIImageView(frame: CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide))
imageView.image = slides[i]
slideContainer.addSubview(imageView)
}
scrollView.addSubview(slideContainer)
scrollView.snp.makeConstraints { (make) -> Void in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(startBrowsingButton.snp.top)
}
self.view.layoutIfNeeded()
self.scrollView.layoutIfNeeded()
pageControl = UIPageControl()
pageControl.pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.3)
pageControl.currentPageIndicatorTintColor = UIColor.black
pageControl.numberOfPages = IntroViewControllerUX.NumberOfCards
pageControl.accessibilityIdentifier = "IntroViewController.pageControl"
pageControl.addTarget(self, action: #selector(IntroViewController.changePage), for: UIControlEvents.valueChanged)
view.addSubview(pageControl)
pageControl.snp.makeConstraints { (make) -> Void in
make.centerX.equalTo(self.scrollView)
make.centerY.equalTo(self.startBrowsingButton.snp.top).offset(-IntroViewControllerUX.PagerCenterOffsetFromScrollViewBottom)
}
func addCard(title: String, text: String, introView: UIView) {
self.introViews.append(introView)
let titleLabel = UILabel()
titleLabel.numberOfLines = 2
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = IntroViewControllerUX.MinimumFontScale
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.text = title
titleLabels.append(titleLabel)
introView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make ) -> Void in
make.top.equalTo(introView).offset(20)
make.centerX.equalTo(introView)
make.height.equalTo(IntroViewControllerUX.CardTitleHeight)
make.width.equalTo(IntroViewControllerUX.CardTextWidth)
}
let textLabel = UILabel()
textLabel.numberOfLines = 5
textLabel.attributedText = attributedStringForLabel(text)
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = IntroViewControllerUX.MinimumFontScale
textLabel.lineBreakMode = .byTruncatingTail
textLabels.append(textLabel)
introView.addSubview(textLabel)
textLabel.snp.makeConstraints({ (make) -> Void in
make.top.equalTo(titleLabel.snp.bottom).offset(20)
make.centerX.equalTo(introView)
make.width.equalTo(IntroViewControllerUX.CardTextWidth)
})
}
addCard(title: IntroViewControllerUX.CardTitleWelcome, text: IntroViewControllerUX.CardTextWelcome, introView: UIView())
addCard(title: IntroViewControllerUX.CardTitleSearch, text: IntroViewControllerUX.CardTextSearch, introView: UIView())
addCard(title: IntroViewControllerUX.CardTitlePrivate, text: IntroViewControllerUX.CardTextPrivate, introView: UIView())
addCard(title: IntroViewControllerUX.CardTitleMail, text: IntroViewControllerUX.CardTextMail, introView: UIView())
// Sync card, with sign in to sync button.
signInButton = UIButton()
signInButton.backgroundColor = IntroViewControllerUX.SignInButtonColor
signInButton.setTitle(IntroViewControllerUX.SignInButtonTitle, for: UIControlState())
signInButton.setTitleColor(UIColor.white, for: UIControlState())
signInButton.clipsToBounds = true
signInButton.addTarget(self, action: #selector(IntroViewController.SELlogin), for: UIControlEvents.touchUpInside)
signInButton.snp.makeConstraints { (make) -> Void in
make.height.equalTo(IntroViewControllerUX.SignInButtonHeight)
}
let syncCardView = UIView()
// introViews.append(syncCardView)
addCard(title: IntroViewControllerUX.CardTitleSync, text: IntroViewControllerUX.CardTextSync, introView: syncCardView)
syncCardView.addSubview(signInButton)
syncCardView.bringSubview(toFront: signInButton)
signInButton.snp.makeConstraints { (make) -> Void in
make.centerX.equalTo(syncCardView)
make.width.equalTo(IntroViewControllerUX.CardTextWidth) // TODO Talk to UX about small screen sizes
make.bottom.equalTo(syncCardView)
}
// We need a reference to the sync pages textlabel so we can adjust the constraints
if let index = introViews.index(of: syncCardView), index < textLabels.count {
let syncTextLabel = textLabels[index]
syncTextLabel.snp.makeConstraints { make in
make.bottom.equalTo(signInButton.snp.top).offset(-IntroViewControllerUX.SyncButtonTopPadding)
}
}
// Add all the cards to the view, make them invisible with zero alpha
for introView in introViews {
introView.alpha = 0
self.view.addSubview(introView)
introView.snp.makeConstraints { (make) -> Void in
make.top.equalTo(self.slideContainer.snp.bottom)
make.bottom.equalTo(self.startBrowsingButton.snp.top)
make.left.right.equalTo(self.view)
}
}
// Make whole screen scrollable by bringing the scrollview to the top
view.bringSubview(toFront: scrollView)
view.sendSubview(toBack: pageControl)
scrollView?.bringSubview(toFront: syncCardView)
signInButton.superview?.bringSubview(toFront: signInButton)
// Activate the first card
setActiveIntroView(introViews[0], forPage: 0)
setupDynamicFonts()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
setupDynamicFonts()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.snp.remakeConstraints { (make) -> Void in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(self.startBrowsingButton.snp.top)
}
for i in 0..<IntroViewControllerUX.NumberOfCards {
if let imageView = slideContainer.subviews[i] as? UIImageView {
imageView.frame = CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide)
imageView.contentMode = UIViewContentMode.scaleAspectFit
}
}
slideContainer.frame = CGRect(x: 0, y: 0, width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide)
scrollView.contentSize = CGSize(width: slideContainer.frame.width, height: slideContainer.frame.height)
}
override var prefersStatusBarHidden: Bool {
return true
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return UIInterfaceOrientationMask.portrait
}
func SELstartBrowsing() {
LeanplumIntegration.sharedInstance.track(eventName: .dismissedOnboarding)
delegate?.introViewControllerDidFinish(self, requestToLogin: false)
}
func SELback() {
if introView == introViews[1] {
setActiveIntroView(introViews[0], forPage: 0)
scrollView.scrollRectToVisible(scrollView.subviews[0].frame, animated: true)
pageControl.currentPage = 0
} else if introView == introViews[2] {
setActiveIntroView(introViews[1], forPage: 1)
scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true)
pageControl.currentPage = 1
}
}
func SELforward() {
if introView == introViews[0] {
setActiveIntroView(introViews[1], forPage: 1)
scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true)
pageControl.currentPage = 1
} else if introView == introViews[1] {
setActiveIntroView(introViews[2], forPage: 2)
scrollView.scrollRectToVisible(scrollView.subviews[2].frame, animated: true)
pageControl.currentPage = 2
}
}
func SELlogin() {
delegate?.introViewControllerDidFinish(self, requestToLogin: true)
}
fileprivate var accessibilityScrollStatus: String {
let number = NSNumber(value: pageControl.currentPage + 1)
return String(format: NSLocalizedString("Introductory slide %@ of %@", tableName: "Intro", comment: "String spoken by assistive technology (like VoiceOver) stating on which page of the intro wizard we currently are. E.g. Introductory slide 1 of 3"), NumberFormatter.localizedString(from: number, number: .decimal), NumberFormatter.localizedString(from: NSNumber(value: IntroViewControllerUX.NumberOfCards), number: .decimal))
}
func changePage() {
let swipeCoordinate = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: swipeCoordinate, y: 0), animated: true)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// Need to add this method so that when forcibly dragging, instead of letting deceleration happen, should also calculate what card it's on.
// This especially affects sliding to the last or first slides.
if !decelerate {
scrollViewDidEndDecelerating(scrollView)
}
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
// Need to add this method so that tapping the pageControl will also change the card texts.
// scrollViewDidEndDecelerating waits until the end of the animation to calculate what card it's on.
scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
setActiveIntroView(introViews[page], forPage: page)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let maximumHorizontalOffset = scrollView.frame.width
let currentHorizontalOffset = scrollView.contentOffset.x
var percentageOfScroll = currentHorizontalOffset / maximumHorizontalOffset
percentageOfScroll = percentageOfScroll > 1.0 ? 1.0 : percentageOfScroll
let whiteComponent = UIColor.white.components
let grayComponent = UIColor(rgb: 0xF2F2F2).components
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = page
let newRed = (1.0 - percentageOfScroll) * whiteComponent.red + percentageOfScroll * grayComponent.red
let newGreen = (1.0 - percentageOfScroll) * whiteComponent.green + percentageOfScroll * grayComponent.green
let newBlue = (1.0 - percentageOfScroll) * whiteComponent.blue + percentageOfScroll * grayComponent.blue
let newColor = UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
slideContainer.backgroundColor = newColor
}
fileprivate func setActiveIntroView(_ newIntroView: UIView, forPage page: Int) {
if introView != newIntroView {
UIView.animate(withDuration: IntroViewControllerUX.FadeDuration, animations: { () -> Void in
self.introView?.alpha = 0
self.introView = newIntroView
newIntroView.alpha = 1.0
if page == 0 {
self.startBrowsingButton.alpha = 0
} else {
self.startBrowsingButton.alpha = 1
}
}, completion: { _ in
if page == (IntroViewControllerUX.NumberOfCards - 1) {
self.scrollView.signinButton = self.signInButton
} else {
self.scrollView.signinButton = nil
}
})
}
}
fileprivate var scaledWidthOfSlide: CGFloat {
return view.frame.width
}
fileprivate var scaledHeightOfSlide: CGFloat {
return (view.frame.width / slides[0].size.width) * slides[0].size.height / slideVerticalScaleFactor
}
fileprivate func attributedStringForLabel(_ text: String) -> NSMutableAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = IntroViewControllerUX.CardTextLineHeight
paragraphStyle.alignment = .center
let string = NSMutableAttributedString(string: text)
string.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: string.length))
return string
}
fileprivate func setupDynamicFonts() {
startBrowsingButton.titleLabel?.font = UIFont(name: "FiraSans-Regular", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize)
signInButton.titleLabel?.font = UIFont(name: "FiraSans-Regular", size: DynamicFontHelper.defaultHelper.IntroBigFontSize)
for titleLabel in titleLabels {
titleLabel.font = UIFont(name: "FiraSans-Medium", size: DynamicFontHelper.defaultHelper.IntroBigFontSize)
}
for label in textLabels {
label.font = UIFont(name: "FiraSans-UltraLight", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize)
}
}
}
fileprivate class IntroOverlayScrollView: UIScrollView {
weak var signinButton: UIButton?
fileprivate override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if let signinFrame = signinButton?.frame {
let convertedFrame = convert(signinFrame, from: signinButton?.superview)
if convertedFrame.contains(point) {
return false
}
}
return CGRect(origin: self.frame.origin, size: CGSize(width: self.contentSize.width, height: self.frame.size.height)).contains(point)
}
}
extension UIColor {
var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
}
|
mpl-2.0
|
99912bb8c24599813f31de8f20987739
| 49.618938 | 433 | 0.694771 | 5.046742 | false | false | false | false |
BruceDLong/CodeDog
|
LIBS/SwiftCode/RedBlackTree.swift
|
1
|
20451
|
//Copyright (c) 2016 Matthijs Hollemans and contributors
//
//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.
// Modified by Bruce Long to act as a fast map
import Foundation
private enum RBTreeColor {
case red
case black
}
private enum RotationDirection {
case left
case right
}
// MARK: - RBNode
public class RBTreeNode<Key: Comparable, Value>: Equatable {
public typealias RBNode = RBTreeNode<Key, Value>
fileprivate var ITEM:Value?
fileprivate var color: RBTreeColor = .black
fileprivate var key: Key?
var leftChild: RBNode?
var rightChild: RBNode?
fileprivate weak var parent: RBNode?
public init(key: Key?, leftChild: RBNode?, rightChild: RBNode?, parent: RBNode?) {
self.key = key
self.leftChild = leftChild
self.rightChild = rightChild
self.parent = parent
self.ITEM = nil
self.leftChild?.parent = self
self.rightChild?.parent = self
}
public convenience init(key: Key?) {
self.init(key: key, leftChild: RBNode(), rightChild: RBNode(), parent: RBNode())
}
// For initialising the nullLeaf
public convenience init() {
self.init(key: nil, leftChild: nil, rightChild: nil, parent: nil)
self.color = .black
}
var isRoot: Bool {
return parent == nil
}
var isLeaf: Bool {
return rightChild == nil && leftChild == nil
}
var isNullLeaf: Bool {
return key == nil && isLeaf && color == .black
}
var isLeftChild: Bool {
return parent?.leftChild === self
}
var isRightChild: Bool {
return parent?.rightChild === self
}
var grandparent: RBNode? {
return parent?.parent
}
var sibling: RBNode? {
if isLeftChild {
return parent?.rightChild
} else {
return parent?.leftChild
}
}
var uncle: RBNode? {
return parent?.sibling
}
}
// MARK: - RedBlackTree
public class RedBlackTree<Key: Comparable, Value> {
public typealias RBNode = RBTreeNode<Key, Value>
fileprivate(set) var root: RBNode
fileprivate(set) var size = 0
fileprivate let nullLeaf = RBNode()
public init() {
root = nullLeaf
}
}
// MARK: - Equatable protocol
extension RBTreeNode {
static public func == <Key>(lhs: RBTreeNode<Key>, rhs: RBTreeNode<Key>) -> Bool {
return lhs.key == rhs.key
}
}
// MARK: - Finding a nodes successor
extension RBTreeNode {
/*
* Returns the inorder successor node of a node
* The successor is a node with the next larger key value of the current node
*/
public func getSuccessor() -> RBNode? {
// If node has right child: successor min of this right tree
if let rightChild = self.rightChild {
if !rightChild.isNullLeaf {
return rightChild.minimum()
}
}
// Else go upward until node left child
var currentNode = self
var parent = currentNode.parent
while currentNode.isRightChild {
if let parent = parent {
currentNode = parent
}
parent = currentNode.parent
}
return parent
}
}
// MARK: - Searching
extension RBTreeNode {
/*
* Returns the node with the minimum key of the current subtree
*/
public func minimum() -> RBNode? {
if let leftChild = leftChild {
if !leftChild.isNullLeaf {
return leftChild.minimum()
}
return self
}
return self
}
/*
* Returns the node with the maximum key of the current subtree
*/
public func maximum() -> RBNode? {
if let rightChild = rightChild {
if !rightChild.isNullLeaf {
return rightChild.maximum()
}
return self
}
return self
}
}
extension RedBlackTree {
/*
* Returns the node with the given key |input| if existing
*/
public func search(input: Key) -> RBNode? {
return search(key: input, node: root)
}
/*
* Returns the node with given |key| in subtree of |node|
*/
fileprivate func search(key: Key, node: RBNode?) -> RBNode? {
// If node nil -> key not found
guard let node = node else {
return nil
}
// If node is nullLeaf == semantically same as if nil
if !node.isNullLeaf {
if let nodeKey = node.key {
// Node found
if key == nodeKey {
return node
} else if key < nodeKey {
return search(key: key, node: node.leftChild)
} else {
return search(key: key, node: node.rightChild)
}
}
}
return nil
}
}
// MARK: - Finding maximum and minimum value
extension RedBlackTree {
/*
* Returns the minimum key value of the whole tree
*/
public func minValue() -> Key? {
guard let minNode = root.minimum() else {
return nil
}
return minNode.key
}
/*
* Returns the maximum key value of the whole tree
*/
public func maxValue() -> Key? {
guard let maxNode = root.maximum() else {
return nil
}
return maxNode.key
}
}
// MARK: - Inserting new nodes
extension RedBlackTree {
/*
* Insert a node with key |key| into the tree
* 1. Perform normal insert operation as in a binary search tree
* 2. Fix red-black properties
* Runntime: O(log n)
*/
public func insert(key: Key) {
if root.isNullLeaf {
root = RBNode(key: key)
} else {
insert(input: RBNode(key: key), node: root)
}
size += 1
}
/*
* Nearly identical insert operation as in a binary search tree
* Differences: All nil pointers are replaced by the nullLeaf, we color the inserted node red,
* after inserting we call insertFixup to maintain the red-black properties
*/
private func insert(input: RBNode, node: RBNode) {
guard let inputKey = input.key, let nodeKey = node.key else {
return
}
if inputKey < nodeKey {
guard let child = node.leftChild else {
addAsLeftChild(child: input, parent: node)
return
}
if child.isNullLeaf {
addAsLeftChild(child: input, parent: node)
} else {
insert(input: input, node: child)
}
} else {
guard let child = node.rightChild else {
addAsRightChild(child: input, parent: node)
return
}
if child.isNullLeaf {
addAsRightChild(child: input, parent: node)
} else {
insert(input: input, node: child)
}
}
}
private func addAsLeftChild(child: RBNode, parent: RBNode) {
parent.leftChild = child
child.parent = parent
child.color = .red
insertFixup(node: child)
}
private func addAsRightChild(child: RBNode, parent: RBNode) {
parent.rightChild = child
child.parent = parent
child.color = .red
insertFixup(node: child)
}
/*
* Fixes possible violations of the red-black property after insertion
* Only violation of red-black properties occurs at inserted node |z| and z.parent
* We have 3 distinct cases: case 1, 2a and 2b
* - case 1: may repeat, but only h/2 steps, where h is the height of the tree
* - case 2a -> case 2b -> red-black tree
* - case 2b -> red-black tree
*/
private func insertFixup(node z: RBNode) {
if !z.isNullLeaf {
guard let parentZ = z.parent else {
return
}
// If both |z| and his parent are red -> violation of red-black property -> need to fix it
if parentZ.color == .red {
guard let uncle = z.uncle else {
return
}
// Case 1: Uncle red -> recolor + move z
if uncle.color == .red {
parentZ.color = .black
uncle.color = .black
if let grandparentZ = parentZ.parent {
grandparentZ.color = .red
// Move z to grandparent and check again
insertFixup(node: grandparentZ)
}
}
// Case 2: Uncle black
else {
var zNew = z
// Case 2.a: z right child -> rotate
if parentZ.isLeftChild && z.isRightChild {
zNew = parentZ
leftRotate(node: zNew)
} else if parentZ.isRightChild && z.isLeftChild {
zNew = parentZ
rightRotate(node: zNew)
}
// Case 2.b: z left child -> recolor + rotate
zNew.parent?.color = .black
if let grandparentZnew = zNew.grandparent {
grandparentZnew.color = .red
if z.isLeftChild {
rightRotate(node: grandparentZnew)
} else {
leftRotate(node: grandparentZnew)
}
// We have a valid red-black-tree
}
}
}
}
root.color = .black
}
}
// MARK: - Deleting a node
extension RedBlackTree {
/*
* Delete a node with key |key| from the tree
* 1. Perform standard delete operation as in a binary search tree
* 2. Fix red-black properties
* Runntime: O(log n)
*/
public func delete(key: Key) {
if size == 1 {
root = nullLeaf
size -= 1
} else if let node = search(key: key, node: root) {
if !node.isNullLeaf {
delete(node: node)
size -= 1
}
}
}
/*
* Nearly identical delete operation as in a binary search tree
* Differences: All nil pointers are replaced by the nullLeaf,
* after deleting we call insertFixup to maintain the red-black properties if the delted node was
* black (as if it was red -> no violation of red-black properties)
*/
private func delete(node z: RBNode) {
var nodeY = RBNode()
var nodeX = RBNode()
if let leftChild = z.leftChild, let rightChild = z.rightChild {
if leftChild.isNullLeaf || rightChild.isNullLeaf {
nodeY = z
} else {
if let successor = z.getSuccessor() {
nodeY = successor
}
}
}
if let leftChild = nodeY.leftChild {
if !leftChild.isNullLeaf {
nodeX = leftChild
} else if let rightChild = nodeY.rightChild {
nodeX = rightChild
}
}
nodeX.parent = nodeY.parent
if let parentY = nodeY.parent {
// Should never be the case, as parent of root = nil
if parentY.isNullLeaf {
root = nodeX
} else {
if nodeY.isLeftChild {
parentY.leftChild = nodeX
} else {
parentY.rightChild = nodeX
}
}
} else {
root = nodeX
}
if nodeY != z {
z.key = nodeY.key
}
// If sliced out node was red -> nothing to do as red-black-property holds
// If it was black -> fix red-black-property
if nodeY.color == .black {
deleteFixup(node: nodeX)
}
}
/*
* Fixes possible violations of the red-black property after deletion
* We have w distinct cases: only case 2 may repeat, but only h many steps, where h is the height
* of the tree
* - case 1 -> case 2 -> red-black tree
* case 1 -> case 3 -> case 4 -> red-black tree
* case 1 -> case 4 -> red-black tree
* - case 3 -> case 4 -> red-black tree
* - case 4 -> red-black tree
*/
private func deleteFixup(node x: RBNode) {
var xTmp = x
if !x.isRoot && x.color == .black {
guard var sibling = x.sibling else {
return
}
// Case 1: Sibling of x is red
if sibling.color == .red {
// Recolor
sibling.color = .black
if let parentX = x.parent {
parentX.color = .red
// Rotation
if x.isLeftChild {
leftRotate(node: parentX)
} else {
rightRotate(node: parentX)
}
// Update sibling
if let sibl = x.sibling {
sibling = sibl
}
}
}
// Case 2: Sibling is black with two black children
if sibling.leftChild?.color == .black && sibling.rightChild?.color == .black {
// Recolor
sibling.color = .red
// Move fake black unit upwards
if let parentX = x.parent {
deleteFixup(node: parentX)
}
// We have a valid red-black-tree
} else {
// Case 3: a. Sibling black with one black child to the right
if x.isLeftChild && sibling.rightChild?.color == .black {
// Recolor
sibling.leftChild?.color = .black
sibling.color = .red
// Rotate
rightRotate(node: sibling)
// Update sibling of x
if let sibl = x.sibling {
sibling = sibl
}
}
// Still case 3: b. One black child to the left
else if x.isRightChild && sibling.leftChild?.color == .black {
// Recolor
sibling.rightChild?.color = .black
sibling.color = .red
// Rotate
leftRotate(node: sibling)
// Update sibling of x
if let sibl = x.sibling {
sibling = sibl
}
}
// Case 4: Sibling is black with red right child
// Recolor
if let parentX = x.parent {
sibling.color = parentX.color
parentX.color = .black
// a. x left and sibling with red right child
if x.isLeftChild {
sibling.rightChild?.color = .black
// Rotate
leftRotate(node: parentX)
}
// b. x right and sibling with red left child
else {
sibling.leftChild?.color = .black
//Rotate
rightRotate(node: parentX)
}
// We have a valid red-black-tree
xTmp = root
}
}
}
xTmp.color = .black
}
}
// MARK: - Rotation
extension RedBlackTree {
/*
* Left rotation around node x
* Assumes that x.rightChild y is not a nullLeaf, rotates around the link from x to y,
* makes y the new root of the subtree with x as y's left child and y's left child as x's right
* child, where n = a node, [n] = a subtree
* | |
* x y
* / \ ~> / \
* [A] y x [C]
* / \ / \
* [B] [C] [A] [B]
*/
fileprivate func leftRotate(node x: RBNode) {
rotate(node: x, direction: .left)
}
/*
* Right rotation around node y
* Assumes that y.leftChild x is not a nullLeaf, rotates around the link from y to x,
* makes x the new root of the subtree with y as x's right child and x's right child as y's left
* child, where n = a node, [n] = a subtree
* | |
* x y
* / \ <~ / \
* [A] y x [C]
* / \ / \
* [B] [C] [A] [B]
*/
fileprivate func rightRotate(node x: RBNode) {
rotate(node: x, direction: .right)
}
/*
* Rotation around a node x
* Is a local operation preserving the binary-search-tree property that only exchanges pointers.
* Runntime: O(1)
*/
private func rotate(node x: RBNode, direction: RotationDirection) {
var nodeY: RBNode? = RBNode()
// Set |nodeY| and turn |nodeY|'s left/right subtree into |x|'s right/left subtree
switch direction {
case .left:
nodeY = x.rightChild
x.rightChild = nodeY?.leftChild
x.rightChild?.parent = x
case .right:
nodeY = x.leftChild
x.leftChild = nodeY?.rightChild
x.leftChild?.parent = x
}
// Link |x|'s parent to nodeY
nodeY?.parent = x.parent
if x.isRoot {
if let node = nodeY {
root = node
}
} else if x.isLeftChild {
x.parent?.leftChild = nodeY
} else if x.isRightChild {
x.parent?.rightChild = nodeY
}
// Put |x| on |nodeY|'s left
switch direction {
case .left:
nodeY?.leftChild = x
case .right:
nodeY?.rightChild = x
}
x.parent = nodeY
}
}
// MARK: - Verify
extension RedBlackTree {
/*
* Verifies that the existing tree fulfills all red-black properties
* Returns true if the tree is a valid red-black tree, false otherwise
*/
public func verify() -> Bool {
if root.isNullLeaf {
print("The tree is empty")
return true
}
return property2() && property4() && property5()
}
// Property 1: Every node is either red or black -> fullfilled through setting node.color of type
// RBTreeColor
// Property 2: The root is black
private func property2() -> Bool {
if root.color == .red {
print("Property-Error: Root is red")
return false
}
return true
}
// Property 3: Every nullLeaf is black -> fullfilled through initialising nullLeafs with color = black
// Property 4: If a node is red, then both its children are black
private func property4() -> Bool {
return property4(node: root)
}
private func property4(node: RBNode) -> Bool {
if node.isNullLeaf {
return true
}
if let leftChild = node.leftChild, let rightChild = node.rightChild {
if node.color == .red {
if !leftChild.isNullLeaf && leftChild.color == .red {
print("Property-Error: Red node with key \(String(describing: node.key)) has red left child")
return false
}
if !rightChild.isNullLeaf && rightChild.color == .red {
print("Property-Error: Red node with key \(String(describing: node.key)) has red right child")
return false
}
}
return property4(node: leftChild) && property4(node: rightChild)
}
return false
}
// Property 5: For each node, all paths from the node to descendant leaves contain the same number
// of black nodes (same blackheight)
private func property5() -> Bool {
if property5(node: root) == -1 {
return false
} else {
return true
}
}
private func property5(node: RBNode) -> Int {
if node.isNullLeaf {
return 0
}
guard let leftChild = node.leftChild, let rightChild = node.rightChild else {
return -1
}
let left = property5(node: leftChild)
let right = property5(node: rightChild)
if left == -1 || right == -1 {
return -1
} else if left == right {
let addedHeight = node.color == .black ? 1 : 0
return left + addedHeight
} else {
print("Property-Error: Black height violated at node with key \(String(describing: node.key))")
return -1
}
}
}
// MARK: - Debugging
extension RBTreeNode: CustomDebugStringConvertible {
public var debugDescription: String {
var s = ""
if isNullLeaf {
s = "nullLeaf"
} else {
if let key = key {
s = "key: \(key)"
} else {
s = "key: nil"
}
if let parent = parent {
s += ", parent: \(String(describing: parent.key))"
}
if let left = leftChild {
s += ", left = [" + left.debugDescription + "]"
}
if let right = rightChild {
s += ", right = [" + right.debugDescription + "]"
}
s += ", color = \(color)"
}
return s
}
}
extension RedBlackTree: CustomDebugStringConvertible {
public var debugDescription: String {
return root.debugDescription
}
}
extension RBTreeNode: CustomStringConvertible {
public var description: String {
var s = ""
if isNullLeaf {
s += "nullLeaf"
} else {
if let left = leftChild {
s += "(\(left.description)) <- "
}
if let key = key {
s += "\(key)"
} else {
s += "nil"
}
s += ", \(color)"
if let right = rightChild {
s += " -> (\(right.description))"
}
}
return s
}
}
extension RedBlackTree: CustomStringConvertible {
public var description: String {
if root.isNullLeaf {
return "[]"
} else {
return root.description
}
}
}
|
gpl-2.0
|
dcdd2f20f8448e92aec71f22f18eef51
| 26.123342 | 105 | 0.590191 | 3.9757 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceComponents/Tests/EventDetailComponentTests/Presenter Tests/Test Doubles/View Models/StubEventDescriptionViewModel.swift
|
1
|
701
|
import EventDetailComponent
struct StubEventDescriptionViewModel: EventDetailViewModel {
var numberOfComponents: Int = .random
private let eventDescription: EventDescriptionViewModel
private let expectedIndex: Int
init(eventDescription: EventDescriptionViewModel, at index: Int) {
self.eventDescription = eventDescription
expectedIndex = index
}
func setDelegate(_ delegate: EventDetailViewModelDelegate) {
}
func describe(componentAt index: Int, to visitor: EventDetailViewModelVisitor) {
visitor.visit(eventDescription.randomized(ifFalse: index == expectedIndex))
}
func favourite() {
}
func unfavourite() {
}
}
|
mit
|
d77c48ac75619377662cb57e574552e0
| 22.366667 | 84 | 0.721826 | 5.192593 | false | false | false | false |
emilstahl/swift
|
stdlib/public/core/ArrayBufferType.swift
|
9
|
7652
|
//===--- ArrayBufferType.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// The underlying buffer for an ArrayType conforms to
/// `_ArrayBufferType`. This buffer does not provide value semantics.
public protocol _ArrayBufferType : MutableCollectionType {
/// The type of elements stored in the buffer.
typealias Element
/// Create an empty buffer.
init()
/// Adopt the entire buffer, presenting it at the provided `startIndex`.
init(_ buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int)
/// Copy the given subRange of this buffer into uninitialized memory
/// starting at target. Return a pointer past-the-end of the
/// just-initialized memory.
func _uninitializedCopy(
subRange: Range<Int>, target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element>
/// Get or set the index'th element.
subscript(index: Int) -> Element { get nonmutating set}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self`
/// buffer store `minimumCapacity` elements, returns that buffer.
/// Otherwise, returns nil.
///
/// - Note: The result's firstElementAddress may not match ours, if we are a
/// _SliceBuffer.
///
/// - Note: This function must remain mutating; otherwise the buffer
/// may acquire spurious extra references, which will cause
/// unnecessary reallocation.
@warn_unused_result
mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)
-> _ContiguousArrayBuffer<Element>?
/// Returns true iff this buffer is backed by a uniquely-referenced mutable
/// _ContiguousArrayBuffer.
///
/// - Note: This function must remain mutating; otherwise the buffer
/// may acquire spurious extra references, which will cause
/// unnecessary reallocation.
@warn_unused_result
mutating func isMutableAndUniquelyReferenced() -> Bool
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@warn_unused_result
func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>?
/// Replace the given `subRange` with the first `newCount` elements of
/// the given collection.
///
/// - Requires: This buffer is backed by a uniquely-referenced
/// `_ContiguousArrayBuffer`.
mutating func replace<C: CollectionType where C.Generator.Element == Element>(
subRange subRange: Range<Int>, with newCount: Int, elementsOf newValues: C
)
/// Returns a `_SliceBuffer` containing the given `subRange` of values
/// from this buffer.
subscript(subRange: Range<Int>) -> _SliceBuffer<Element> {get}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
func withUnsafeBufferPointer<R>(
@noescape body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Requires: Such contiguous storage exists or the buffer is empty.
mutating func withUnsafeMutableBufferPointer<R>(
@noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R
/// The number of elements the buffer stores.
var count: Int {get set}
/// The number of elements the buffer can store without reallocation.
var capacity: Int {get}
/// An object that keeps the elements stored in this buffer alive.
var owner: AnyObject {get}
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var firstElementAddress: UnsafeMutablePointer<Element> {get}
/// Return a base address to which you can add an index `i` to get the address
/// of the corresponding element at `i`.
var subscriptBaseAddress: UnsafeMutablePointer<Element> {get}
/// Like `subscriptBaseAddress`, but can assume that `self` is a mutable,
/// uniquely referenced native representation.
/// - Precondition: `_isNative` is `true`.
var _unconditionalMutableSubscriptBaseAddress:
UnsafeMutablePointer<Element> {get}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
var identity: UnsafePointer<Void> {get}
var startIndex: Int {get}
}
extension _ArrayBufferType {
public var subscriptBaseAddress: UnsafeMutablePointer<Element> {
return firstElementAddress
}
public var _unconditionalMutableSubscriptBaseAddress:
UnsafeMutablePointer<Element> {
return subscriptBaseAddress
}
public mutating func replace<
C: CollectionType where C.Generator.Element == Element
>(subRange subRange: Range<Int>, with newCount: Int,
elementsOf newValues: C) {
_sanityCheck(startIndex == 0, "_SliceBuffer should override this function.")
let oldCount = self.count
let eraseCount = subRange.count
let growth = newCount - eraseCount
self.count = oldCount + growth
let elements = self.subscriptBaseAddress
_sanityCheck(elements != nil)
let oldTailIndex = subRange.endIndex
let oldTailStart = elements + oldTailIndex
let newTailIndex = oldTailIndex + growth
let newTailStart = oldTailStart + growth
let tailCount = oldCount - subRange.endIndex
if growth > 0 {
// Slide the tail part of the buffer forwards, in reverse order
// so as not to self-clobber.
newTailStart.moveInitializeBackwardFrom(oldTailStart, count: tailCount)
// Assign over the original subRange
var i = newValues.startIndex
for j in subRange {
elements[j] = newValues[i++]
}
// Initialize the hole left by sliding the tail forward
for j in oldTailIndex..<newTailIndex {
(elements + j).initialize(newValues[i++])
}
_expectEnd(i, newValues)
}
else { // We're not growing the buffer
// Assign all the new elements into the start of the subRange
var i = subRange.startIndex
var j = newValues.startIndex
for _ in 0..<newCount {
elements[i++] = newValues[j++]
}
_expectEnd(j, newValues)
// If the size didn't change, we're done.
if growth == 0 {
return
}
// Move the tail backward to cover the shrinkage.
let shrinkage = -growth
if tailCount > shrinkage { // If the tail length exceeds the shrinkage
// Assign over the rest of the replaced range with the first
// part of the tail.
newTailStart.moveAssignFrom(oldTailStart, count: shrinkage)
// slide the rest of the tail back
oldTailStart.moveInitializeFrom(
oldTailStart + shrinkage, count: tailCount - shrinkage)
}
else { // tail fits within erased elements
// Assign over the start of the replaced range with the tail
newTailStart.moveAssignFrom(oldTailStart, count: tailCount)
// destroy elements remaining after the tail in subRange
(newTailStart + tailCount).destroy(shrinkage - tailCount)
}
}
}
}
|
apache-2.0
|
5c70747faab2fb68296e6f76824ad696
| 36.326829 | 80 | 0.685834 | 4.824716 | false | false | false | false |
MaxKramer/Logger
|
Timber/Classes/LogFormat.swift
|
2
|
1969
|
//
// LogFormat.swift
// Logger
//
// Created by Max Kramer on 09/06/2016.
// Copyright © 2016 Max Kramer. All rights reserved.
//
import Foundation
/// Specifies the format to be used in the log message
public struct LogFormat {
/// The template string that contains how the log message should be formatted
public let template: String
/// The attributes to be used in the log message
public let attributes: [LogFormatter.Attributes]?
/**
Initialises an instance of LogFormat
- Parameter template: The template string that contains how the log message should be formatted
- Parameter attributes: The attributes to be used in the log message
*/
public init(template: String, attributes: [LogFormatter.Attributes]?) {
self.template = template
self.attributes = attributes
}
/**
The default log format
Logs will appear in the following format, in accordance with the specified template:
`i.e. [FATAL 16:12:24 ViewController.swift:21] ["TIFU by force unwrapping a nil optional"]`
*/
public static var defaultLogFormat = LogFormat(template: "[%@ %@ %@:%@] %@", attributes: [
LogFormatter.Attributes.Level,
LogFormatter.Attributes.Date(format: "HH:mm:ss"),
LogFormatter.Attributes.FileName(fullPath: false, fileExtension: true),
LogFormatter.Attributes.Line,
LogFormatter.Attributes.Message
])
}
extension LogFormat: Equatable {}
public func ==(lhs: LogFormat, rhs: LogFormat) -> Bool {
guard lhs.template == rhs.template else {
return false
}
guard let lhsAttr = lhs.attributes, rhsAttr = rhs.attributes where lhsAttr.count == rhsAttr.count else {
return false
}
var equalFlag = true
for (idx, attr) in lhsAttr.enumerate() {
if attr != rhsAttr[idx] {
equalFlag = false
break
}
}
return equalFlag
}
|
mit
|
ceb2ac9baed896bd7ab9c4db964b0fd4
| 29.292308 | 108 | 0.650407 | 4.608899 | false | false | false | false |
bananafish911/SmartReceiptsiOS
|
SmartReceipts/Modules/Generate Report/GenerateReportShareService.swift
|
1
|
4068
|
//
// GenerateReportShareService.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 08/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import MessageUI
class GenerateReportShareService: NSObject, MFMailComposeViewControllerDelegate {
private weak var presenter: GenerateReportPresenter!
private var trip: WBTrip!
init(presenter: GenerateReportPresenter, trip: WBTrip) {
super.init()
self.presenter = presenter
self.trip = trip
}
func emailFiles(_ files: [String]) {
guard MFMailComposeViewController.canSendMail() else {
self.presenter.presentAlert(title: LocalizedString("generate.report.email.not.configured.title"),
message: LocalizedString("generate.report.email.not.configured.message"))
return
}
let suffix = files.count > 0 ? NSLocalizedString("generate.report.multiple.attached.suffix", comment: "") : NSLocalizedString("generate.report.one.attached.suffix", comment: "")
let messageBody = "\(files.count) \(suffix)"
let composer = MFMailComposeViewController()
let subjectFormatter = SmartReceiptsFormattableString(fromOriginalText: WBPreferences.defaultEmailSubject())
composer.mailComposeDelegate = self
composer.setSubject(subjectFormatter.format(trip))
composer.setMessageBody(messageBody, isHTML: false)
composer.setToRecipients(split(WBPreferences.defaultEmailRecipient()))
composer.setCcRecipients(split(WBPreferences.defaultEmailCC()))
composer.setBccRecipients(split(WBPreferences.defaultEmailBCC()))
for file in files {
Logger.debug("func emailFiles: Attach \(file)")
guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else {
Logger.warning("func emailFiles: No data?")
continue
}
let mimeType: String
if file.hasSuffix("pdf") {
mimeType = "application/pdf"
} else if file.hasSuffix("csv") {
mimeType = "text/csv"
} else {
mimeType = "application/octet-stream"
}
composer.addAttachmentData(data, mimeType: mimeType, fileName: NSString(string: file).lastPathComponent)
}
composer.navigationBar.tintColor = UINavigationBar.appearance().tintColor
let barStyle = UIApplication.shared.statusBarStyle
presenter.present(vc: composer, animated: true) {
UIApplication.shared.setStatusBarStyle(barStyle, animated: false)
}
}
func shareFiles(_ files: [String]) {
var attached = [URL]()
for file in files {
attached.append(URL(fileURLWithPath: file))
}
let shareViewController = UIActivityViewController(activityItems: attached, applicationActivities: nil)
shareViewController.completionWithItemsHandler = {
type, success, returned, error in
Logger.debug("Type \(type.debugDescription) - \(success.description)")
Logger.debug("Returned \(returned?.count ?? 0)")
if let error = error {
Logger.error(error.localizedDescription)
}
if success {
self.presenter.close()
}
}
presenter.present(vc: shareViewController, animated: true, isPopover: true, completion: nil)
}
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if let error = error {
Logger.error("Send email error: \(error)")
}
controller.dismiss(animated: true) {
self.presenter.close()
}
}
fileprivate func split(_ string: String) -> [String] {
return string.components(separatedBy: ",")
}
}
|
agpl-3.0
|
fd8091280b0fb13625cb3e49b4298dc2
| 38.105769 | 185 | 0.620605 | 5.358366 | false | false | false | false |
thanhcuong1990/swift-sample-code
|
SampleCode/Singletons/APIClient.swift
|
1
|
1434
|
//
// APIClient.swift
// KuruMaerabi_swift
//
// Created by Cuong Lam on 11/09/15.
// Copyright (c) 2015 Cuong Lam. All rights reserved.
//
import Foundation
class APIClient {
var manager:AFHTTPRequestOperationManager?
class var sharedInstance : APIClient {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : APIClient? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = APIClient()
}
return Static.instance!
}
init(){
self.manager = AFHTTPRequestOperationManager()
}
func getImage(completed:(resObj:NSArray) -> ()){
let methodArguments = [
"method": "flickr.galleries.getPhotos",
"api_key": "ac1cafbb552920263ceae93cbaeb42be",
"gallery_id": "66911286-72157648514173258",
"extras": "url_m",
"format": "json",
"nojsoncallback": "1"
]
self.manager?.GET(Url.images, parameters: methodArguments, success: { (manager, response) -> Void in
let status = response.objectForKey("stat") as! String
if( status == "ok"){
let array:NSArray = response.objectForKey("photos")!.objectForKey("photo") as! NSArray
completed(resObj: array)
}
}, failure: { (manager, error) -> Void in
})
}
}
|
unlicense
|
b9bc9ccf26fd898870ef757d6786f361
| 28.285714 | 108 | 0.564156 | 4.255193 | false | false | false | false |
alitan2014/swift
|
Heath/Heath/views/WomenHeadView.swift
|
1
|
2279
|
//
// WomenHeadView.swift
// Heath
//
// Created by Mac on 15/8/21.
// Copyright (c) 2015年 Mac. All rights reserved.
//
import UIKit
typealias senderTouchBlock=(touch:UITouch,state:String)->Void
typealias senderButtonBlock=(sender:UIButton)->Void
class WomenHeadView: UIView {
var sendTouchBlock:senderTouchBlock!
var sendButtonBlock:senderButtonBlock!
@IBOutlet weak var mouthImageView: UIImageView!//嘴巴
@IBOutlet weak var noseImageView: UIImageView!//鼻子
@IBOutlet weak var faceImageView: UIImageView!//面部
@IBOutlet weak var eyesImageView: UIImageView!//眼睛
@IBOutlet weak var earsImageView: UIImageView!//耳朵
@IBOutlet weak var headImageView: UIImageView!//头部
@IBOutlet weak var backButton: UIButton!
func createUI()
{
self.backgroundColor=UIColor.whiteColor()
self.backButton.setTitleColor(UIColor(red: 64/255.0, green: 193/255.0, blue: 218/255.0, alpha: 1), forState: UIControlState.Normal)
mouthImageView.image=nil
mouthImageView.userInteractionEnabled=true
faceImageView.image=nil
noseImageView.image=nil
earsImageView.image=nil
eyesImageView.image=nil
headImageView.image=nil
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let set=touches as NSSet
let touch:UITouch=set.anyObject() as!UITouch
let state="began"
if (self.sendTouchBlock != nil)
{
self.sendTouchBlock(touch:touch,state:state)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
let set=touches as NSSet
let touch:UITouch=set.anyObject() as!UITouch
let state="ended"
if (self.sendTouchBlock != nil)
{
self.sendTouchBlock(touch:touch,state:state)
}
}
@IBAction func btnClick(sender: AnyObject) {
if (self.sendButtonBlock != nil)
{
self.sendButtonBlock(sender: sender as! UIButton)
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
gpl-2.0
|
210aa3783cdcd124e28fef6035541dd6
| 33.136364 | 139 | 0.668442 | 4.227017 | false | false | false | false |
christophhagen/Signal-iOS
|
SignalMessaging/Views/OWSFlatButton.swift
|
1
|
5440
|
//
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalServiceKit
@objc
public class OWSFlatButton: UIView {
let TAG = "[OWSFlatButton]"
private let button: UIButton
private var pressedBlock : (() -> Void)?
private var upColor: UIColor?
private var downColor: UIColor?
override public var backgroundColor: UIColor? {
willSet {
owsFail("Use setBackgroundColors(upColor:) instead.")
}
}
@objc
public init() {
AssertIsOnMainThread()
button = UIButton(type:.custom)
super.init(frame:CGRect.zero)
createContent()
}
@available(*, unavailable, message:"use other constructor instead.")
required public init?(coder aDecoder: NSCoder) {
fatalError("\(#function) is unimplemented.")
}
private func createContent() {
self.addSubview(button)
button.addTarget(self, action:#selector(buttonPressed), for:.touchUpInside)
button.autoPinToSuperviewEdges()
}
@objc
public class func button(title: String,
font: UIFont,
titleColor: UIColor,
backgroundColor: UIColor,
width: CGFloat,
height: CGFloat,
target:Any,
selector: Selector) -> OWSFlatButton {
let button = OWSFlatButton()
button.setTitle(title:title,
font: font,
titleColor: titleColor )
button.setBackgroundColors(upColor:backgroundColor)
button.useDefaultCornerRadius()
button.setSize(width:width, height:height)
button.addTarget(target:target, selector:selector)
return button
}
@objc
public class func button(title: String,
titleColor: UIColor,
backgroundColor: UIColor,
width: CGFloat,
height: CGFloat,
target:Any,
selector: Selector) -> OWSFlatButton {
return OWSFlatButton.button(title:title,
font:fontForHeight(height),
titleColor:titleColor,
backgroundColor:backgroundColor,
width:width,
height:height,
target:target,
selector:selector)
}
@objc
public class func button(title: String,
font: UIFont,
titleColor: UIColor,
backgroundColor: UIColor,
target:Any,
selector: Selector) -> OWSFlatButton {
let button = OWSFlatButton()
button.setTitle(title:title,
font: font,
titleColor: titleColor )
button.setBackgroundColors(upColor:backgroundColor)
button.useDefaultCornerRadius()
button.addTarget(target:target, selector:selector)
return button
}
@objc
public class func fontForHeight(_ height: CGFloat) -> UIFont {
// Cap the "button height" at 40pt or button text can look
// excessively large.
let fontPointSize = round(min(40, height) * 0.45)
return UIFont.ows_mediumFont(withSize:fontPointSize)!
}
// MARK: Methods
@objc
public func setTitle(title: String, font: UIFont,
titleColor: UIColor ) {
button.setTitle(title, for: .normal)
button.setTitleColor(titleColor, for: .normal)
button.titleLabel!.font = font
}
@objc
public func setBackgroundColors(upColor: UIColor,
downColor: UIColor ) {
button.setBackgroundImage(UIImage(color:upColor), for: .normal)
button.setBackgroundImage(UIImage(color:downColor), for: .highlighted)
}
@objc
public func setBackgroundColors(upColor: UIColor ) {
setBackgroundColors(upColor: upColor,
downColor: upColor.withAlphaComponent(0.7) )
}
@objc
public func setSize(width: CGFloat, height: CGFloat) {
button.autoSetDimension(.width, toSize:width)
button.autoSetDimension(.height, toSize:height)
}
@objc
public func useDefaultCornerRadius() {
// To my eye, this radius tends to look right regardless of button size
// (within reason) or device size.
button.layer.cornerRadius = 5
button.clipsToBounds = true
}
@objc
public func setEnabled(_ isEnabled: Bool) {
button.isEnabled = isEnabled
}
@objc
public func addTarget(target:Any,
selector: Selector) {
button.addTarget(target, action:selector, for:.touchUpInside)
}
@objc
public func setPressedBlock(_ pressedBlock: @escaping () -> Void) {
guard self.pressedBlock == nil else {
owsFail("Button already has pressed block.")
return
}
self.pressedBlock = pressedBlock
}
@objc
internal func buttonPressed() {
pressedBlock?()
}
}
|
gpl-3.0
|
ff5e369ddff2a63fe3a80f7cc3ef3c0c
| 30.812865 | 83 | 0.546324 | 5.456369 | false | false | false | false |
brentdax/swift
|
test/decl/protocol/req/associated_type_inference.swift
|
1
|
12180
|
// RUN: %target-typecheck-verify-swift
protocol P0 {
associatedtype Assoc1 : PSimple // expected-note{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-1{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-2{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
// expected-note@-3{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
func f0(_: Assoc1)
func g0(_: Assoc1)
}
protocol PSimple { }
extension Int : PSimple { }
extension Double : PSimple { }
struct X0a : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Int) { }
}
struct X0b : P0 { // expected-error{{type 'X0b' does not conform to protocol 'P0'}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { } // expected-note{{matching requirement 'g0' to this declaration inferred associated type to 'Double'}}
}
struct X0c : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0d : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Double) { } // viable, but no corresponding f0
func g0(_: Int) { }
}
struct X0e : P0 { // expected-error{{type 'X0e' does not conform to protocol 'P0'}}
func f0(_: Double) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Double}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { }
func g0(_: Int) { }
}
struct X0f : P0 { // okay: Assoc1 = Int because Float doesn't conform to PSimple
func f0(_: Float) { }
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0g : P0 { // expected-error{{type 'X0g' does not conform to protocol 'P0'}}
func f0(_: Float) { } // expected-note{{inferred type 'Float' (by matching requirement 'f0') is invalid: does not conform to 'PSimple'}}
func g0(_: Float) { } // expected-note{{inferred type 'Float' (by matching requirement 'g0') is invalid: does not conform to 'PSimple'}}
}
struct X0h<T : PSimple> : P0 {
func f0(_: T) { }
}
extension X0h {
func g0(_: T) { }
}
struct X0i<T : PSimple> {
}
extension X0i {
func g0(_: T) { }
}
extension X0i : P0 { }
extension X0i {
func f0(_: T) { }
}
// Protocol extension used to infer requirements
protocol P1 {
}
extension P1 {
func f0(_ x: Int) { }
func g0(_ x: Int) { }
}
struct X0j : P0, P1 { }
protocol P2 {
associatedtype P2Assoc
func h0(_ x: P2Assoc)
}
extension P2 where Self.P2Assoc : PSimple {
func f0(_ x: P2Assoc) { } // expected-note{{inferred type 'Float' (by matching requirement 'f0') is invalid: does not conform to 'PSimple'}}
func g0(_ x: P2Assoc) { } // expected-note{{inferred type 'Float' (by matching requirement 'g0') is invalid: does not conform to 'PSimple'}}
}
struct X0k : P0, P2 {
func h0(_ x: Int) { }
}
struct X0l : P0, P2 { // expected-error{{type 'X0l' does not conform to protocol 'P0'}}
func h0(_ x: Float) { }
}
// Prefer declarations in the type to those in protocol extensions
struct X0m : P0, P2 {
func f0(_ x: Double) { }
func g0(_ x: Double) { }
func h0(_ x: Double) { }
}
// Inference from properties.
protocol PropertyP0 {
associatedtype Prop : PSimple // expected-note{{unable to infer associated type 'Prop' for protocol 'PropertyP0'}}
var property: Prop { get }
}
struct XProp0a : PropertyP0 { // okay PropType = Int
var property: Int
}
struct XProp0b : PropertyP0 { // expected-error{{type 'XProp0b' does not conform to protocol 'PropertyP0'}}
var property: Float // expected-note{{inferred type 'Float' (by matching requirement 'property') is invalid: does not conform to 'PSimple'}}
}
// Inference from subscripts
protocol SubscriptP0 {
associatedtype Index
// expected-note@-1 2 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element : PSimple
// expected-note@-1 {{unable to infer associated type 'Element' for protocol 'SubscriptP0'}}
// expected-note@-2 2 {{protocol requires nested type 'Element'; do you want to add it?}}
subscript (i: Index) -> Element { get }
}
struct XSubP0a : SubscriptP0 {
subscript (i: Int) -> Int { get { return i } }
}
struct XSubP0b : SubscriptP0 {
// expected-error@-1{{type 'XSubP0b' does not conform to protocol 'SubscriptP0'}}
subscript (i: Int) -> Float { get { return Float(i) } } // expected-note{{inferred type 'Float' (by matching requirement 'subscript(_:)') is invalid: does not conform to 'PSimple'}}
}
struct XSubP0c : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0c' does not conform to protocol 'SubscriptP0'}}
subscript (i: Index) -> Element { get { } }
// expected-error@-1 {{reference to invalid associated type 'Element' of type 'XSubP0c'}}
}
struct XSubP0d : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0d' does not conform to protocol 'SubscriptP0'}}
subscript (i: XSubP0d.Index) -> XSubP0d.Element { get { } }
}
// Inference from properties and subscripts
protocol CollectionLikeP0 {
associatedtype Index
// expected-note@-1 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element
// expected-note@-1 {{protocol requires nested type 'Element'; do you want to add it?}}
var startIndex: Index { get }
var endIndex: Index { get }
subscript (i: Index) -> Element { get }
}
struct SomeSlice<T> { }
struct XCollectionLikeP0a<T> : CollectionLikeP0 {
var startIndex: Int
var endIndex: Int
subscript (i: Int) -> T { get { fatalError("blah") } }
subscript (r: Range<Int>) -> SomeSlice<T> { get { return SomeSlice() } }
}
struct XCollectionLikeP0b : CollectionLikeP0 {
// expected-error@-1 {{type 'XCollectionLikeP0b' does not conform to protocol 'CollectionLikeP0'}}
var startIndex: XCollectionLikeP0b.Index
// There was an error @-1 ("'startIndex' used within its own type"),
// but it disappeared and doesn't seem like much of a loss.
var startElement: XCollectionLikeP0b.Element
}
// rdar://problem/21304164
public protocol Thenable {
associatedtype T // expected-note{{protocol requires nested type 'T'}}
func then(_ success: (_: T) -> T) -> Self
}
public class CorePromise<U> : Thenable { // expected-error{{type 'CorePromise<U>' does not conform to protocol 'Thenable'}}
public func then(_ success: @escaping (_ t: U, _: CorePromise<U>) -> U) -> Self {
return self.then() { (t: U) -> U in // expected-error{{contextual closure type '(U, CorePromise<U>) -> U' expects 2 arguments, but 1 was used in closure body}}
return success(t: t, self)
}
}
}
// rdar://problem/21559670
protocol P3 {
associatedtype Assoc = Int
associatedtype Assoc2
func foo(_ x: Assoc2) -> Assoc?
}
protocol P4 : P3 { }
extension P4 {
func foo(_ x: Int) -> Float? { return 0 }
}
extension P3 where Assoc == Int {
func foo(_ x: Int) -> Assoc? { return nil }
}
struct X4 : P4 { }
// rdar://problem/21738889
protocol P5 {
associatedtype A = Int
}
struct X5<T : P5> : P5 {
typealias A = T.A
}
protocol P6 : P5 {
associatedtype A : P5 = X5<Self>
}
extension P6 where A == X5<Self> { }
// rdar://problem/21774092
protocol P7 {
associatedtype A
associatedtype B
func f() -> A
func g() -> B
}
struct X7<T> { }
extension P7 {
func g() -> X7<A> { return X7() }
}
struct Y7<T> : P7 {
func f() -> Int { return 0 }
}
struct MyAnySequence<Element> : MySequence {
typealias SubSequence = MyAnySequence<Element>
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
struct MyAnyIterator<T> : MyIteratorType {
typealias Element = T
}
protocol MyIteratorType {
associatedtype Element
}
protocol MySequence {
associatedtype Iterator : MyIteratorType
associatedtype SubSequence
func foo() -> SubSequence
func makeIterator() -> Iterator
}
extension MySequence {
func foo() -> MyAnySequence<Iterator.Element> {
return MyAnySequence()
}
}
struct SomeStruct<Element> : MySequence {
let element: Element
init(_ element: Element) {
self.element = element
}
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
// rdar://problem/21883828 - ranking of solutions
protocol P8 {
}
protocol P9 : P8 {
}
protocol P10 {
associatedtype A
func foo() -> A
}
struct P8A { }
struct P9A { }
extension P8 {
func foo() -> P8A { return P8A() }
}
extension P9 {
func foo() -> P9A { return P9A() }
}
struct Z10 : P9, P10 {
}
func testZ10() -> Z10.A {
var zA: Z10.A
zA = P9A()
return zA
}
// rdar://problem/21926788
protocol P11 {
associatedtype A
associatedtype B
func foo() -> B
}
extension P11 where A == Int {
func foo() -> Int { return 0 }
}
protocol P12 : P11 {
}
extension P12 {
func foo() -> String { return "" }
}
struct X12 : P12 {
typealias A = String
}
// Infinite recursion -- we would try to use the extension
// initializer's argument type of 'Dough' as a candidate for
// the associated type
protocol Cookie {
associatedtype Dough
// expected-note@-1 {{protocol requires nested type 'Dough'; do you want to add it?}}
init(t: Dough)
}
extension Cookie {
init(t: Dough?) {}
}
struct Thumbprint : Cookie {}
// expected-error@-1 {{type 'Thumbprint' does not conform to protocol 'Cookie'}}
// Looking through typealiases
protocol Vector {
associatedtype Element
typealias Elements = [Element]
func process(elements: Elements)
}
struct Int8Vector : Vector {
func process(elements: [Int8]) { }
}
// SR-4486
protocol P13 {
associatedtype Arg // expected-note{{protocol requires nested type 'Arg'; do you want to add it?}}
func foo(arg: Arg)
}
struct S13 : P13 { // expected-error{{type 'S13' does not conform to protocol 'P13'}}
func foo(arg: inout Int) {}
}
// "Infer" associated type from generic parameter.
protocol P14 {
associatedtype Value
}
struct P14a<Value>: P14 { }
struct P14b<Value> { }
extension P14b: P14 { }
// Associated type defaults in overridden associated types.
struct X15 { }
struct OtherX15 { }
protocol P15a {
associatedtype A = X15
}
protocol P15b : P15a {
associatedtype A
}
protocol P15c : P15b {
associatedtype A
}
protocol P15d {
associatedtype A = X15
}
protocol P15e : P15b, P15d {
associatedtype A
}
protocol P15f {
associatedtype A = OtherX15
}
protocol P15g: P15c, P15f {
associatedtype A // expected-note{{protocol requires nested type 'A'; do you want to add it?}}
}
struct X15a : P15a { }
struct X15b : P15b { }
struct X15c : P15c { }
struct X15d : P15d { }
// Ambiguity.
// FIXME: Better diagnostic here?
struct X15g : P15g { } // expected-error{{type 'X15g' does not conform to protocol 'P15g'}}
// Associated type defaults in overidden associated types that require
// substitution.
struct X16<T> { }
protocol P16 {
associatedtype A = X16<Self>
}
protocol P16a : P16 {
associatedtype A
}
protocol P16b : P16a {
associatedtype A
}
struct X16b : P16b { }
// Refined protocols that tie associated types to a fixed type.
protocol P17 {
associatedtype T
}
protocol Q17 : P17 where T == Int { }
struct S17 : Q17 { }
// Typealiases from protocol extensions should not inhibit associated type
// inference.
protocol P18 {
associatedtype A
}
protocol P19 : P18 {
associatedtype B
}
extension P18 where Self: P19 {
typealias A = B
}
struct X18<A> : P18 { }
// rdar://problem/16316115
protocol HasAssoc {
associatedtype Assoc
}
struct DefaultAssoc {}
protocol RefinesAssocWithDefault: HasAssoc {
associatedtype Assoc = DefaultAssoc
}
struct Foo: RefinesAssocWithDefault {
}
protocol P20 {
associatedtype T // expected-note{{protocol requires nested type 'T'; do you want to add it?}}
typealias TT = T?
}
struct S19 : P20 { // expected-error{{type 'S19' does not conform to protocol 'P20'}}
typealias TT = Int?
}
// rdar://problem/44777661
struct S30<T> where T : P30 {}
protocol P30 {
static func bar()
}
protocol P31 {
associatedtype T : P30
}
extension S30 : P31 where T : P31 {}
extension S30 {
func foo() {
T.bar()
}
}
|
apache-2.0
|
4123bfe1c965be0b9ee5a06317042c21
| 22.024575 | 183 | 0.666174 | 3.291002 | false | false | false | false |
rgkobashi/PhotoSearcher
|
PhotoViewer/Loader.swift
|
1
|
1750
|
//
// Loader.swift
// PhotoViewer
//
// Created by Rogelio Martinez Kobashi on 2/27/17.
// Copyright © 2017 Rogelio Martinez Kobashi. All rights reserved.
//
import Foundation
import UIKit
class Loader
{
fileprivate static let activityIndicator = UIActivityIndicatorView()
class func show()
{
let container = UIView()
container.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
container.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
let loadingView = UIView()
loadingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
loadingView.center = container.center
loadingView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
loadingView.layer.cornerRadius = 10
activityIndicator.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
activityIndicator.activityIndicatorViewStyle = .whiteLarge
activityIndicator.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2)
loadingView.addSubview(activityIndicator)
container.addSubview(loadingView)
UIApplication.shared.windows.first?.addSubview(container)
activityIndicator.startAnimating()
}
class func dismiss()
{
if let loadingView = activityIndicator.superview
{
if let container = loadingView.superview
{
activityIndicator.removeFromSuperview()
loadingView.removeFromSuperview()
container.removeFromSuperview()
activityIndicator.stopAnimating()
}
}
}
}
|
mit
|
958c6d3f9b495604f208afe0648e4389
| 32.634615 | 126 | 0.635792 | 4.727027 | false | false | false | false |
zhou9734/Warm
|
Warm/Classes/Tools/Common.swift
|
1
|
1798
|
//
// Common.swift
// Warm
//
// Created by zhoucj on 16/9/12.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
/// 友盟分享的APP key
let UMSharedAPPKey = "57e7e25767e58e33190022db"
//微信
//AppId
let WXAppId = "wx6ace5c4cd4178656"
let WXAppSerect = "488762a888d20c50119b104921b0e4ff"
//新浪App Key
let SinaAppKey = "1168605738"
let SinaAppSecret = "968fb67661aa1e811e171a6937a699c0"
//重定向url
let RedirectURL = "https://www.baidu.com/"
// 全局背景
let Color_GlobalBackground = UIColor.whiteColor()
let placeholderImage: UIImage = UIImage(named: "CoursePlaceholder_375x240_")!
let WarmBlueColor = UIColor(red: 87.0/255.0, green: 192.0/255.0, blue: 255.0/255.0, alpha: 1)
let SpliteColor = UIColor(red: 250.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 1)
let ScreenWidth = UIScreen.mainScreen().bounds.width
let ScreenHeight = UIScreen.mainScreen().bounds.height
let ScreenBounds = UIScreen.mainScreen().bounds
let cityCodeKey = "cityCodeKey"
//每页加载数量
let pageSize = 10
//登录通知
let LoginNotication = "LoginNotication"
//切换视图
let SwitchRootViewController = "SwitchRootViewController"
//日志输出
func CJLog<T>(message: T, fileName: String = __FILE__, methodName: String = __FUNCTION__, lineNumber: Int = __LINE__){
//只有在DEBUG模式下才会打印. 需要在Build Settig中设置
#if DEBUG
var _fileName = (fileName as NSString).pathComponents.last!
_fileName = _fileName.substringToIndex((_fileName.rangeOfString(".swift")?.startIndex)!)
print("\(_fileName).\(methodName).[\(lineNumber)]: \(message)")
#endif
}
//提示框
func alert(msg: String){
let alertView = UIAlertView(title: nil, message: msg, delegate: nil, cancelButtonTitle: "确定")
alertView.show()
}
|
mit
|
25b9993410b23e8edfcfb1d83e3ed579
| 32.039216 | 118 | 0.721068 | 3.13197 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/Model/Option/PollutedGarden/Plant/StrategyCollect/MOptionPollutedGardenPlantCollectStrategyWait.swift
|
1
|
971
|
import Foundation
class MOptionPollutedGardenPlantCollectStrategyWait:MGameStrategy<
MOptionPollutedGardenPlantCollect,
MOptionPollutedGarden>
{
private var elapsedTime:TimeInterval?
private let kDelay:TimeInterval = 0.3
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionPollutedGarden>)
{
if let startTime:TimeInterval = self.elapsedTime
{
let deltaTime:TimeInterval = elapsedTime - startTime
if deltaTime > kDelay
{
model.fade()
}
}
else
{
self.elapsedTime = elapsedTime
guard
let scene:VOptionPollutedGardenScene = scene as? VOptionPollutedGardenScene
else
{
return
}
scene.addCollect(model:model)
}
}
}
|
mit
|
6ad1126c8c4265c2eff7b2b2b6693f12
| 23.897436 | 91 | 0.53965 | 6.224359 | false | false | false | false |
LKY769215561/KYHandMade
|
KYHandMade/KYHandMade/Class/Home(首页)/Controller/KYHomController.swift
|
1
|
1474
|
//
// KYHomController.swift
// KYHandMade
//
// Created by Kerain on 2017/6/12.
// Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved.
//
import UIKit
import Kingfisher
class KYHomController: UIViewController {
lazy var pageView : KYPageView = {
let pageFrame = CGRect(x:0,y:NAVBAR_HEIGHT,width:SCREEN_WIDTH,height:(SCREEN_HEIGHT - NAVBAR_HEIGHT - TABBAR_HEIGHT))
let titles = ["精选","关注","达人","活动"]
var pageStyle = KYPageStyle()
let pgView = KYPageView(frame:pageFrame,titles:titles,style:pageStyle)
pgView.delegate = self
return pgView
}()
lazy var contentViews : [UIView] = {
let contentFrame = CGRect(x:0, y:0, width:SCREEN_WIDTH, height:self.pageView.frame.height - self.pageView.style.tabHeight)
var contents = [UIView]() //添加子控件
contents.append(KYFeaturedView(frame:contentFrame))
contents.append(KYFocusView(frame:contentFrame))
contents.append(KYDaRenView(frame:contentFrame))
contents.append(KYEventView(frame:contentFrame))
return contents
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(pageView)
}
}
extension KYHomController : KYPageViewDelegate{
func pageViewDidShowContentView(currentIndex: Int, title: String) -> UIView {
return contentViews[currentIndex]
}
}
|
apache-2.0
|
88f1cdf21e5653e8d15684f8dfbcac7c
| 28.5625 | 130 | 0.654686 | 4.008475 | false | false | false | false |
narner/AudioKit
|
Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Connecting Nodes Part 2.xcplaygroundpage/Contents.swift
|
1
|
2098
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Connecting Nodes Part 2
//:
//: The intention of most of the AudioKit Playgrounds is to highlight a particular
//: concept. To keep things clear, we have kept the amount of code to a minimum.
//: But the flipside of that decision is that code from playgrounds will look a little
//: different from production. In general, to see best practices, you can check out
//: the AudioKit examples project, but here in this playground we're going to redo
//: the code from the "Connecting Nodes" playground in a way that is more like how
//: the code would appear in a project.
import AudioKitPlaygrounds
//: Here we begin the code how it would appear in a project
import AudioKit
// Create a class to handle the audio set up
class AudioEngine {
// Declare your nodes as instance variables
var player: AKAudioPlayer!
var delay: AKDelay!
var reverb: AKReverb!
init() {
// Set up a player to the loop the file's playback
do {
let file = try AKAudioFile(readFileName: "drumloop.wav")
player = try AKAudioPlayer(file: file)
} catch {
AKLog("File Not Found")
return
}
player.looping = true
// Next we'll connect the audio player to a delay effect
delay = AKDelay(player)
// Set the parameters of the delay here
delay.time = 0.1 // seconds
delay.feedback = 0.8 // Normalized Value 0 - 1
delay.dryWetMix = 0.2 // Normalized Value 0 - 1
// Continue adding more nodes as you wish, for example, reverb:
reverb = AKReverb(delay)
reverb.loadFactoryPreset(.cathedral)
AudioKit.output = reverb
AudioKit.start()
}
}
// Create your engine and start the player
let engine = AudioEngine()
engine.player.play()
//: The next few lines are also just for playgrounds
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
mit
|
d3b5eacb7ddcde75cb7e0eb672404088
| 32.301587 | 86 | 0.663966 | 4.389121 | false | false | false | false |
alblue/swift
|
test/SILGen/pointer_conversion.swift
|
1
|
27593
|
// RUN: %target-swift-emit-silgen -enable-sil-ownership -module-name pointer_conversion -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
func sideEffect1() -> Int { return 1 }
func sideEffect2() -> Int { return 2 }
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(_ x: UnsafePointer<Int>) {}
func takesOptConstPointer(_ x: UnsafePointer<Int>?, and: Int) {}
func takesOptOptConstPointer(_ x: UnsafePointer<Int>??, and: Int) {}
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>, and: Int) {}
func takesConstPointer(_ x: UnsafePointer<Int>, and: Int) {}
func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstVoidPointer(_ x: UnsafeRawPointer) {}
func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstRawPointer(_ x: UnsafeRawPointer) {}
func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {}
func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {}
// CHECK-LABEL: sil hidden @$s18pointer_conversion0A9ToPointeryySpySiG_SPySiGSvtF
// CHECK: bb0([[MP:%.*]] : @trivial $UnsafeMutablePointer<Int>, [[CP:%.*]] : @trivial $UnsafePointer<Int>, [[MRP:%.*]] : @trivial $UnsafeMutableRawPointer):
func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion23takesMutableVoidPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesMutableRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
takesConstPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstPointer(cp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
takesConstVoidPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstRawPointer(mrp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
}
// CHECK-LABEL: sil hidden @$s18pointer_conversion14arrayToPointeryyF
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutablePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesMutableRawPointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstPointer(ints, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @$s18pointer_conversion15stringToPointeryySSF
func stringToPointer(_ s: String) {
takesConstVoidPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstRawPointer(s, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @$s18pointer_conversion14inoutToPointeryyF
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
takesMutableRawPointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
takesMutableRawPointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden @$s18pointer_conversion19classInoutToPointeryyF
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box ${ var C }
// CHECK: [[PB:%.*]] = project_box [[VAR]]
takesPlusOnePointer(&c)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @$s18pointer_conversion19takesPlusOnePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load_borrow [[PB]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @$s18pointer_conversion20takesPlusZeroPointeryySAyAA1CCGF
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT_COPY]] to [[PB]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil hidden [thunk] @$s18pointer_conversion18ObjCMethodBridgingC0A4Args{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(_ x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden @$s18pointer_conversion22functionInoutToPointeryyF
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_guaranteed () -> () }
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_guaranteed () -> @out ()
// CHECK: address_to_pointer [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
// rdar://problem/31781386
// CHECK-LABEL: sil hidden @$s18pointer_conversion20inoutPointerOrderingyyF
func inoutPointerOrdering() {
// CHECK: [[ARRAY_BOX:%.*]] = alloc_box ${ var Array<Int> }
// CHECK: [[ARRAY:%.*]] = project_box [[ARRAY_BOX]] :
// CHECK: store {{.*}} to [init] [[ARRAY]]
var array = [Int]()
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$s18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer_3andySpySiG_SitF
// CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesMutablePointer(&array[sideEffect1()], and: sideEffect2())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$s18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_CONST:%.*]] = function_ref @$s18pointer_conversion17takesConstPointer_3andySPySiG_SitF
// CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesConstPointer(&array[sideEffect1()], and: sideEffect2())
}
// rdar://problem/31542269
// CHECK-LABEL: sil hidden @$s18pointer_conversion20optArrayToOptPointer5arrayySaySiGSg_tF
func optArrayToOptPointer(array: [Int]?) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<Array<Int>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : @trivial $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @$s18pointer_conversion013optOptArrayTodD7Pointer5arrayySaySiGSgSg_tF
func optOptArrayToOptOptPointer(array: [Int]??) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<Optional<Array<Int>>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: switch_enum [[SOME_VALUE]] : $Optional<Array<Int>>, case #Optional.some!enumelt.1: [[SOME_SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[SOME_NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_SOME_BB]]([[SOME_SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : @trivial $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : @trivial $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion08takesOptD12ConstPointer_3andySPySiGSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[SOME_NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafePointer<Int>>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @$s18pointer_conversion21optStringToOptPointer6stringySSSg_tF
func optStringToOptPointer(string: String?) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[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]]([[SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : @trivial $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstRawPointer(string, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @$s18pointer_conversion014optOptStringTodD7Pointer6stringySSSgSg_tF
func optOptStringToOptOptPointer(string: String??) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// FIXME: this should really go somewhere that will make nil, not some(nil)
// CHECK: switch_enum [[COPY]] : $Optional<Optional<String>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: switch_enum [[SOME_VALUE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]([[SOME_SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : @trivial $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : @trivial $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion08takesOptD15ConstRawPointer_3andySVSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[SOME_NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafeRawPointer>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstRawPointer(string, and: sideEffect1())
}
|
apache-2.0
|
73d9bd848df6441312a6ba29e33e7543
| 61.427602 | 259 | 0.651071 | 3.695821 | false | false | false | false |
BaiduCloudTeam/PaperInSwift
|
PaperInSwift/CHTransitionLayout.swift
|
1
|
2263
|
//
// CHTransitionLayout.swift
// PaperInSwift
//
// Created by HX_Wang on 15/10/10.
// Copyright © 2015年 Team_ChineseHamburger. All rights reserved.
//
let kOffsetH = "offsetH"
let kOffsetV = "offsetV"
import UIKit
public class CHTransitionLayout : UICollectionViewTransitionLayout {
public var progress : CGFloat?
public var itemSize : CGSize?
public var offset : UIOffset? {
set {
updateValue((newValue!.horizontal), forAnimatedKey:kOffsetH)
updateValue((newValue!.vertical), forAnimatedKey:kOffsetV)
self.offset = newValue
}
get {
return self.offset
}
}
override public var transitionProgress : CGFloat {
didSet {
super.transitionProgress = transitionProgress
let offSetH = self.valueForAnimatedKey(kOffsetH)
let offsetV = self.valueForAnimatedKey(kOffsetV)
offset = UIOffsetMake(offSetH, offsetV)
}
}
//Compile Error
override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElementsInRect(rect)
for attribute in attributes! {
if let currentAttribute = attribute as? UICollectionViewLayoutAttributes {
if currentAttribute.representedElementCategory != .SupplementaryView {
let currentCenter = currentAttribute.center
let updatedCenter = CGPointMake(currentCenter.x, currentCenter.y)
currentAttribute.center = updatedCenter
}else {
currentAttribute.frame = (self.collectionView?.bounds)!
}
}
}
return attributes
}
override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)
let currentCenter = attributes?.center
let updatedCenter = CGPointMake((currentCenter?.x)! + (offset?.horizontal)!, (currentCenter?.y)! + (offset?.vertical)!)
attributes?.center = updatedCenter
return attributes
}
}
|
mit
|
6b5c0b10c4b800d8e2e1d1d90871382d
| 34.873016 | 127 | 0.645575 | 5.445783 | false | false | false | false |
xpush/lib-xpush-ios
|
XpushFramework/Source/MultipartFormData.swift
|
1
|
26938
|
// MultipartFormData.swift
//
// Copyright (c) 2014–2015 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
#if os(iOS) || os(watchOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
/**
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
and the w3 form documentation.
- https://www.ietf.org/rfc/rfc2388.txt
- https://www.ietf.org/rfc/rfc2045.txt
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
*/
public class MultipartFormData {
// MARK: - Helper Types
struct EncodingCharacters {
static let CRLF = "\r\n"
}
struct BoundaryGenerator {
enum BoundaryType {
case Initial, Encapsulated, Final
}
static func randomBoundary() -> String {
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
}
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
let boundaryText: String
switch boundaryType {
case .Initial:
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
case .Encapsulated:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
case .Final:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
}
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
class BodyPart {
let headers: [String: String]
let bodyStream: NSInputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
private var bodyParts: [BodyPart]
private var bodyPartError: NSError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/**
Creates a multipart form data object.
- returns: The multipart form data object.
*/
public init() {
self.boundary = BoundaryGenerator.randomBoundary()
self.bodyParts = []
/**
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* information, please refer to the following article:
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
*/
self.streamBufferSize = 1024
}
// MARK: - Body Parts
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String) {
let headers = contentHeaders(name: name)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
let headers = contentHeaders(name: name, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
system associated MIME type.
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
if let
fileName = fileURL.lastPathComponent,
pathExtension = fileURL.pathExtension
{
let mimeType = mimeTypeForPathExtension(pathExtension)
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason))
}
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
- Content-Type: #{mimeType} (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
var isReachable = true
if #available(iOS 8.0, *) {
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
} else {
// Fallback on earlier versions
}
guard isReachable else {
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
setBodyPartError(error)
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
guard let
path = fileURL.path
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return
}
//============================================================
// Check 4 - can the file size be extracted?
//============================================================
var bodyContentLength: UInt64?
do {
if let
path = fileURL.path,
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
{
bodyContentLength = fileSize.unsignedLongLongValue
}
} catch {
// No-op
}
guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return
}
//============================================================
// Check 5 - can a stream be created from file URL?
//============================================================
guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
setBodyPartError(error)
return
}
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the stream and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(
stream stream: NSInputStream,
length: UInt64,
name: String,
fileName: String,
mimeType: String)
{
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- HTTP headers
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter headers: The HTTP headers for the body part.
*/
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
bodyParts.append(bodyPart)
}
// MARK: - Data Encoding
/**
Encodes all the appended body parts into a single `NSData` object.
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
- throws: An `NSError` if encoding encounters an error.
- returns: The encoded `NSData` if encoding is successful.
*/
public func encode() throws -> NSData {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
let encoded = NSMutableData()
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
let encodedData = try encodeBodyPart(bodyPart)
encoded.appendData(encodedData)
}
return encoded
}
/**
Writes the appended body parts into the given file URL.
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
this approach is very memory efficient and should be used for large body part data.
- parameter fileURL: The file URL to write the multipart form data into.
- throws: An `NSError` if encoding encounters an error.
*/
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
}
let outputStream: NSOutputStream
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
outputStream = possibleOutputStream
} else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
}
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
for bodyPart in self.bodyParts {
try writeBodyPart(bodyPart, toOutputStream: outputStream)
}
outputStream.close()
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
// MARK: - Private - Body Part Encoding
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
let encoded = NSMutableData()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.appendData(initialData)
let headerData = encodeHeaderDataForBodyPart(bodyPart)
encoded.appendData(headerData)
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
encoded.appendData(bodyStreamData)
if bodyPart.hasFinalBoundary {
encoded.appendData(finalBoundaryData())
}
return encoded
}
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
var headerText = ""
for (key, value) in bodyPart.headers {
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
}
headerText += EncodingCharacters.CRLF
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
var error: NSError?
let encoded = NSMutableData()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if inputStream.streamError != nil {
error = inputStream.streamError
break
}
if bytesRead > 0 {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
break
} else {
break
}
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error {
throw error
}
return encoded
}
// MARK: - Private - Writing Body Part to Output Stream
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
}
private func writeInitialBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws
{
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return try writeData(initialData, toOutputStream: outputStream)
}
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let headerData = encodeHeaderDataForBodyPart(bodyPart)
return try writeData(headerData, toOutputStream: outputStream)
}
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw streamError
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
} else {
break
}
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
private func writeFinalBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws
{
if bodyPart.hasFinalBoundary {
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
}
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
var buffer = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&buffer, length: data.length)
return try writeBuffer(&buffer, toOutputStream: outputStream)
}
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
var bytesToWrite = buffer.count
while bytesToWrite > 0 {
if outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if let streamError = outputStream.streamError {
throw streamError
}
if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason)
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten..<buffer.count])
}
} else if let streamError = outputStream.streamError {
throw streamError
}
}
}
// MARK: - Private - Mime Type
private func mimeTypeForPathExtension(pathExtension: String) -> String {
if let
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
{
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(name name: String) -> [String: String] {
return ["Content-Disposition": "form-data; name=\"\(name)\""]
}
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"",
"Content-Type": "\(mimeType)"
]
}
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
"Content-Type": "\(mimeType)"
]
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
}
// MARK: - Private - Errors
private func setBodyPartError(error: NSError) {
if bodyPartError == nil {
bodyPartError = error
}
}
}
|
mit
|
5c91c485ffd328184c0583624b48b56b
| 39.14307 | 128 | 0.638588 | 5.223192 | false | false | false | false |
dreamsxin/swift
|
stdlib/public/core/Sequence.swift
|
1
|
47713
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that supplies the values of a sequence one at a time.
///
/// The `IteratorProtocol` protocol is tightly linked with the `Sequence`
/// protocol. Sequences provide access to their elements by creating an
/// iterator, which keeps track of its iteration process and returns one
/// element at a time as it advances through the sequence.
///
/// Whenever you use a `for`-`in` loop with an array, set, or any other
/// collection or sequence, you're using that type's iterator. Swift uses a
/// sequence's or collection's iterator internally to enable the `for`-`in`
/// loop language construct.
///
/// Using a sequence's iterator directly gives you access to the same elements
/// in the same order as iterating over that sequence using a `for`-`in` loop.
/// For example, you might typically use a `for`-`in` loop to print each of
/// the elements in an array.
///
/// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]
/// for animal in animals {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// Behind the scenes, Swift uses the `animals` array's iterator to loop over
/// the contents of the array.
///
/// var animalIterator = animals.makeIterator()
/// while let animal = animalIterator.next() {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// The call to `animals.makeIterator()` returns an instance of the array's
/// iterator. Next, the `while` loop calls the iterator's `next()` method
/// repeatedly, binding each element that is returned to `animal` and exiting
/// when the `next()` method returns `nil`.
///
/// Using Iterators Directly
/// ========================
///
/// You rarely need to use iterators directly, because a `for`-`in` loop is the
/// more idiomatic approach to traversing a sequence in Swift. Some
/// algorithms, however, may call for direct iterator use.
///
/// One example is the `reduce1(_:)` method. Similar to the
/// `reduce(_:combine:)` method defined in the standard library, which takes
/// an initial value and a combining closure, `reduce1(_:)` uses the first
/// element of the sequence as the initial value.
///
/// Here's an implementation of the `reduce1(_:)` method. The sequence's
/// iterator is used directly to retrieve the initial value before looping
/// over the rest of the sequence.
///
/// extension Sequence {
/// func reduce1(
/// combine: (Iterator.Element, Iterator.Element) -> Iterator.Element
/// ) -> Iterator.Element?
/// {
/// var i = makeIterator()
/// guard var accumulated = i.next() else {
/// return nil
/// }
///
/// while let element = i.next() {
/// accumulated = combine(accumulated, element)
/// }
/// return accumulated
/// }
/// }
///
/// The `reduce1(_:)` method makes certain kinds of sequence operations
/// simpler. Here's how to find the longest string in a sequence, using the
/// `animals` array introduced earlier as an example:
///
/// let longestAnimal = animals.reduce1 { current, element in
/// if current.characters.count > element.characters.count {
/// return current
/// } else {
/// return element
/// }
/// }
/// print(longestAnimal)
/// // Prints "Butterfly"
///
/// Using Multiple Iterators
/// ========================
///
/// Whenever you use multiple iterators (or `for`-`in` loops) over a single
/// sequence, be sure you know that the specific sequence supports repeated
/// iteration, either because you know its concrete type or because the
/// sequence is also constrained to the `Collection` protocol.
///
/// Obtain each separate iterator from separate calls to the sequence's
/// `makeIterator()` method rather than by copying. Copying an iterator is
/// safe, but advancing one copy of an iterator by calling its `next()` method
/// may invalidate other copies of that iterator. `for`-`in` loops are safe in
/// this regard.
///
/// Adding IteratorProtocol Conformance to Your Type
/// ================================================
///
/// Implementing an iterator that conforms to `IteratorProtocol` is simple.
/// Declare a `next()` method that advances one step in the related sequence
/// and returns the current element. When the sequence has been exhausted, the
/// `next()` method returns `nil`.
///
/// For example, consider a custom `Countdown` sequence. You can initialize the
/// `Countdown` sequence with a starting integer and then iterate over the
/// count down to zero. The `Countdown` structure's definition is short: It
/// contains only the starting count and the `makeIterator()` method required
/// by the `Sequence` protocol.
///
/// struct Countdown: Sequence {
/// let start: Int
///
/// func makeIterator() -> CountdownIterator {
/// return CountdownIterator(self)
/// }
/// }
///
/// The `makeIterator()` method returns another custom type, an iterator named
/// `CountdownIterator`. The `CountdownIterator` type keeps track of both the
/// `Countdown` sequence that it's iterating and the number of times it has
/// returned a value.
///
/// struct CountdownIterator: IteratorProtocol {
/// let countdown: Countdown
/// var times = 0
///
/// init(_ countdown: Countdown) {
/// self.countdown = countdown
/// }
///
/// mutating func next() -> Int? {
/// let nextNumber = countdown.start - times
/// guard nextNumber > 0
/// else { return nil }
///
/// times += 1
/// return nextNumber
/// }
/// }
///
/// Each time the `next()` method is called on a `CountdownIterator` instance,
/// it calculates the new next value, checks to see whether it has reached
/// zero, and then returns either the number, or `nil` if the iterator is
/// finished returning elements of the sequence.
///
/// Creating and iterating over a `Countdown` sequence uses a
/// `CountdownGenerator` to handle the iteration.
///
/// let threeTwoOne = Countdown(start: 3)
/// for count in threeTwoOne {
/// print("\(count)...")
/// }
/// // Prints "3..."
/// // Prints "2..."
/// // Prints "1..."
public protocol IteratorProtocol {
/// The type of element traversed by the iterator.
associatedtype Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists. Once `nil` has been returned, all subsequent calls return `nil`.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
mutating func next() -> Element?
}
/// A type that provides sequential, iterated access to its elements.
///
/// Sequences are lists of values that let you step over their values
/// one at a time. The most common way to iterate over the elements of a
/// sequence is to use a `for`-`in` loop:
///
/// let oneTwoThree = 1...3
/// for number in oneTwoThree {
/// print(number)
/// }
/// // Prints "1"
/// // Prints "2"
/// // Prints "3"
///
/// While seemingly simple, this capability gives you access to a large number
/// of operations that you can perform on any sequence. As an example, to
/// check whether a sequence includes a particular value, you can test each
/// value sequentially until you've found a match or reached the end of the
/// sequence. This example checks to see whether a particular insect is in an
/// array.
///
/// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// var hasMosquito = false
/// for bug in bugs {
/// if bug == "Mosquito" {
/// hasMosquito = true
/// break
/// }
/// }
/// print("'bugs' has a mosquito: \(hasMosquito)")
/// // Prints "'bugs' has a mosquito: false"
///
/// The `Sequence` protocol provides default implementations for many common
/// operations that depend on sequential access to a sequence's values. For
/// clearer, more concise code, the example above could use the array's
/// `contains(_:)` method, which every sequence inherits from `Sequence`,
/// instead of iterating manually:
///
/// if bugs.contains("Mosquito") {
/// print("Break out the bug spray.")
/// } else {
/// print("Whew, no mosquitos!")
/// }
/// // Prints "Whew, no mosquitos!"
///
/// Repeated Access
/// ===============
///
/// The `Sequence` protocol makes no requirement on conforming types regarding
/// whether they will be destructively "consumed" by iteration. As a
/// consequence, don't assume that multiple `for`-`in` loops on a sequence
/// will either "resume" iteration or restart from the beginning:
///
/// for element in sequence {
/// if ... some condition { break }
/// }
///
/// for element in sequence {
/// // No defined behavior
/// }
///
/// In this case, you cannot assume that a sequence will either be
/// "consumable" and will resume iteration, or that a sequence is a
/// collection and will restart iteration from the first element. A
/// conforming sequence that is not a collection is allowed to produce an
/// arbitrary sequence of elements in the second `for`-`in` loop.
///
/// To establish that a type you've created supports nondestructive
/// iteration, add conformance to the `Collection` protocol.
///
/// Conforming to the Sequence Protocol
/// ===================================
///
/// Making your own custom types conform to `Sequence` enables many useful
/// operations, like `for`-`in` looping and the `contains` method, without
/// much effort. To add `Sequence` conformance to your own custom type, add
/// a `makeIterator()` method that returns an iterator.
///
/// Alternatively, if your type can act as its own iterator, implementing the
/// requirements of the `IteratorProtocol` protocol and declaring conformance
/// to both `Sequence` and `IteratorProtocol` are sufficient.
///
/// Here's a definition of a `Countdown` sequence that serves as its own
/// iterator. The `makeIterator()` method is provided as a default
/// implementation.
///
/// struct Countdown: Sequence, IteratorProtocol {
/// var count: Int
///
/// mutating func next() -> Int? {
/// if count == 0 {
/// return nil
/// } else {
/// defer { count -= 1 }
/// return count
/// }
/// }
/// }
///
/// let threeToGo = Countdown(count: 3)
/// for i in threeToGo {
/// print(i)
/// }
/// // Prints "3"
/// // Prints "2"
/// // Prints "1"
///
/// Expected Performance
/// ====================
///
/// A sequence should provide its iterator in O(1). The `Sequence` protocol
/// makes no other requirements about element access, so routines that
/// traverse a sequence should be considered O(*n*) unless documented
/// otherwise.
///
/// - SeeAlso: `IteratorProtocol`, `Collection`
public protocol Sequence {
//@available(*, unavailable, renamed: "Iterator")
//typealias Generator = ()
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
associatedtype Iterator : IteratorProtocol
/// A type that represents a subsequence of some of the sequence's elements.
associatedtype SubSequence
// FIXME(compiler limitation):
// associatedtype SubSequence : Sequence
// where
// Iterator.Element == SubSequence.Iterator.Element,
// SubSequence.SubSequence == SubSequence
//
// (<rdar://problem/20715009> Implement recursive protocol
// constraints)
//
// These constraints allow processing collections in generic code by
// repeatedly slicing them in a loop.
/// Returns an iterator over the elements of this sequence.
func makeIterator() -> Iterator
/// A value less than or equal to the number of elements in
/// the sequence, calculated nondestructively.
///
/// - Complexity: O(1)
var underestimatedCount: Int { get }
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercaseString }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.characters.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
func map<T>(
_ transform: @noescape (Iterator.Element) throws -> T
) rethrows -> [T]
/// Returns an array containing, in order, the elements of the sequence
/// that satisfy the given predicate.
///
/// In this example, `filter` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.characters.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter includeElement: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `includeElement` allowed.
func filter(
_ includeElement: @noescape (Iterator.Element) throws -> Bool
) rethrows -> [Iterator.Element]
/// Calls the given closure on each element in the sequence in the same order
/// as a `for`-`in` loop.
///
/// The two loops in the following example produce the same output:
///
/// let numberWords = ["one", "two", "three"]
/// for word in numberWords {
/// print(word)
/// }
/// // Prints "one"
/// // Prints "two"
/// // Prints "three"
///
/// numberWords.forEach { word in
/// print(word)
/// }
/// // Same as above
///
/// Using the `forEach` method is distinct from a `for`-`in` loop in two
/// important ways:
///
/// 1. You cannot use a `break` or `continue` statement to exit the current
/// call of the `body` closure or skip subsequent calls.
/// 2. Using the `return` statement in the `body` closure will exit only from
/// the current call to `body`, not from any outer scope, and won't skip
/// subsequent calls.
///
/// - Parameter body: A closure that takes an element of the sequence as a
/// parameter.
func forEach(_ body: @noescape (Iterator.Element) throws -> Void) rethrows
// Note: The complexity of Sequence.dropFirst(_:) requirement
// is documented as O(n) because Collection.dropFirst(_:) is
// implemented in O(n), even though the default
// implementation for Sequence.dropFirst(_:) is O(1).
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the sequence, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the sequence. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the sequence.
func dropFirst(_ n: Int) -> SubSequence
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// The sequence must be finite. If the number of elements to drop exceeds
/// the number of elements in the sequence, the result is an empty
/// subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// sequence. `n` must be greater than or equal to zero.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
func dropLast(_ n: Int) -> SubSequence
/// Returns a subsequence, up to the specified maximum length, containing
/// the initial elements of the sequence.
///
/// If the maximum length exceeds the number of elements in the sequence,
/// the result contains all the elements in the sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this sequence
/// with at most `maxLength` elements.
func prefix(_ maxLength: Int) -> SubSequence
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the sequence.
///
/// The sequence must be finite. If the maximum length exceeds the number
/// of elements in the sequence, the result contains all the elements in
/// the sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of this sequence with
/// at most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
func suffix(_ maxLength: Int) -> SubSequence
/// Returns the longest possible subsequences of the sequence, in order, that
/// don't contain elements satisfying the given predicate. Elements that are
/// used to split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don't", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.characters.split(maxSplits: 1, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(omittingEmptySubsequences: false, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero. The default value is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator` predicate.
/// If `true`, only nonempty subsequences are returned. The default
/// value is `true`.
/// - isSeparator: A closure that returns `true` if its argument should be
/// used to split the sequence; otherwise, `false`.
/// - Returns: An array of subsequences, split from this sequence's elements.
func split(
maxSplits: Int, omittingEmptySubsequences: Bool,
isSeparator: @noescape (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence]
/// Returns the first element of the sequence that satisfies the given
/// predicate or nil if no such element is found.
///
/// - Parameter where: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element is a match.
/// - Returns: The first match or `nil` if there was no match.
func first(
where: @noescape (Iterator.Element) throws -> Bool
) rethrows -> Iterator.Element?
func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool?
/// If `self` is multi-pass (i.e., a `Collection`), invoke `preprocess` and
/// return its result. Otherwise, return `nil`.
func _preprocessingPass<R>(
_ preprocess: @noescape () throws -> R
) rethrows -> R?
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Iterator.Element>
/// Copy a Sequence into an array, returning one past the last
/// element initialized.
@discardableResult
func _copyContents(initializing ptr: UnsafeMutablePointer<Iterator.Element>)
-> UnsafeMutablePointer<Iterator.Element>
}
/// A default makeIterator() function for `IteratorProtocol` instances that
/// are declared to conform to `Sequence`
extension Sequence
where Self.Iterator == Self, Self : IteratorProtocol {
/// Returns an iterator over the elements of this sequence.
public func makeIterator() -> Self {
return self
}
}
/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already dropped from the underlying sequence.
internal class _DropFirstSequence<Base : IteratorProtocol>
: Sequence, IteratorProtocol {
internal var _iterator: Base
internal let _limit: Int
internal var _dropped: Int
internal init(_iterator: Base, limit: Int, dropped: Int = 0) {
self._iterator = _iterator
self._limit = limit
self._dropped = dropped
}
internal func makeIterator() -> _DropFirstSequence<Base> {
return self
}
internal func next() -> Base.Element? {
while _dropped < _limit {
if _iterator.next() == nil {
_dropped = _limit
return nil
}
_dropped += 1
}
return _iterator.next()
}
internal func dropFirst(_ n: Int) -> AnySequence<Base.Element> {
// If this is already a _DropFirstSequence, we need to fold in
// the current drop count and drop limit so no data is lost.
//
// i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to
// [1,2,3,4].dropFirst(2).
return AnySequence(
_DropFirstSequence(
_iterator: _iterator, limit: _limit + n, dropped: _dropped))
}
}
/// A sequence that only consumes up to `n` elements from an underlying
/// `Base` iterator.
///
/// The underlying iterator's sequence may be infinite.
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already taken from the underlying sequence.
internal class _PrefixSequence<Base : IteratorProtocol>
: Sequence, IteratorProtocol {
internal let _maxLength: Int
internal var _iterator: Base
internal var _taken: Int
internal init(_iterator: Base, maxLength: Int, taken: Int = 0) {
self._iterator = _iterator
self._maxLength = maxLength
self._taken = taken
}
internal func makeIterator() -> _PrefixSequence<Base> {
return self
}
internal func next() -> Base.Element? {
if _taken >= _maxLength { return nil }
_taken += 1
if let next = _iterator.next() {
return next
}
_taken = _maxLength
return nil
}
internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> {
return AnySequence(
_PrefixSequence(
_iterator: _iterator,
maxLength: Swift.min(maxLength, self._maxLength),
taken: _taken))
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Sequence
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercaseString }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.characters.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
public func map<T>(
_ transform: @noescape (Iterator.Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimatedCount
var result = ContiguousArray<T>()
result.reserveCapacity(initialCapacity)
var iterator = self.makeIterator()
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
result.append(try transform(iterator.next()!))
}
// Add remaining elements, if any.
while let element = iterator.next() {
result.append(try transform(element))
}
return Array(result)
}
/// Returns an array containing, in order, the elements of the sequence
/// that satisfy the given predicate.
///
/// In this example, `filter` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.characters.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter includeElement: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `includeElement` allowed.
public func filter(
_ includeElement: @noescape (Iterator.Element) throws -> Bool
) rethrows -> [Iterator.Element] {
var result = ContiguousArray<Iterator.Element>()
var iterator = self.makeIterator()
while let element = iterator.next() {
if try includeElement(element) {
result.append(element)
}
}
return Array(result)
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the sequence.
///
/// The sequence must be finite. If the maximum length exceeds the number of
/// elements in the sequence, the result contains all the elements in the
/// sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Complexity: O(*n*), where *n* is the length of the sequence.
public func suffix(_ maxLength: Int) -> AnySequence<Iterator.Element> {
_precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
if maxLength == 0 { return AnySequence([]) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements into a ring buffer to save space. Once all
// elements are consumed, reorder the ring buffer into an `Array`
// and return it. This saves memory for sequences particularly longer
// than `maxLength`.
var ringBuffer: [Iterator.Element] = []
ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i = ringBuffer.index(after: i) % maxLength
}
}
if i != ringBuffer.startIndex {
return AnySequence(
[ringBuffer[i..<ringBuffer.endIndex], ringBuffer[0..<i]].flatten())
}
return AnySequence(ringBuffer)
}
/// Returns the longest possible subsequences of the sequence, in order, that
/// don't contain elements satisfying the given predicate. Elements that are
/// used to split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don't", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.characters.split(maxSplits: 1, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `true` for the `allowEmptySlices` parameter, so
/// the returned array contains empty strings where spaces were repeated.
///
/// print(line.characters.split(omittingEmptySubsequences: false, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero. The default value is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator` predicate.
/// If `true`, only nonempty subsequences are returned. The default
/// value is `true`.
/// - isSeparator: A closure that returns `true` if its argument should be
/// used to split the sequence; otherwise, `false`.
/// - Returns: An array of subsequences, split from this sequence's elements.
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
isSeparator: @noescape (Iterator.Element) throws -> Bool
) rethrows -> [AnySequence<Iterator.Element>] {
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [AnySequence<Iterator.Element>] = []
var subSequence: [Iterator.Element] = []
@discardableResult
func appendSubsequence() -> Bool {
if subSequence.isEmpty && omittingEmptySubsequences {
return false
}
result.append(AnySequence(subSequence))
subSequence = []
return true
}
if maxSplits == 0 {
// We aren't really splitting the sequence. Convert `self` into an
// `Array` using a fast entry point.
subSequence = Array(self)
appendSubsequence()
return result
}
var iterator = self.makeIterator()
while let element = iterator.next() {
if try isSeparator(element) {
if !appendSubsequence() {
continue
}
if result.count == maxSplits {
break
}
} else {
subSequence.append(element)
}
}
while let element = iterator.next() {
subSequence.append(element)
}
appendSubsequence()
return result
}
/// Returns a value less than or equal to the number of elements in
/// the sequence, nondestructively.
///
/// - Complexity: O(N).
public var underestimatedCount: Int {
return 0
}
public func _preprocessingPass<R>(
_ preprocess: @noescape () throws -> R
) rethrows -> R? {
return nil
}
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
return nil
}
/// Calls the given closure on each element in the sequence in the same order
/// as a `for`-`in` loop.
///
/// The two loops in the following example produce the same output:
///
/// let numberWords = ["one", "two", "three"]
/// for word in numberWords {
/// print(word)
/// }
/// // Prints "one"
/// // Prints "two"
/// // Prints "three"
///
/// numberWords.forEach { word in
/// print(word)
/// }
/// // Same as above
///
/// Using the `forEach` method is distinct from a `for`-`in` loop in two
/// important ways:
///
/// 1. You cannot use a `break` or `continue` statement to exit the current
/// call of the `body` closure or skip subsequent calls.
/// 2. Using the `return` statement in the `body` closure will exit only from
/// the current call to `body`, not from any outer scope, and won't skip
/// subsequent calls.
///
/// - Parameter body: A closure that takes an element of the sequence as a
/// parameter.
public func forEach(
_ body: @noescape (Iterator.Element) throws -> Void
) rethrows {
for element in self {
try body(element)
}
}
}
internal enum _StopIteration : ErrorProtocol {
case stop
}
extension Sequence {
/// Returns the first element of the sequence that satisfies the given
/// predicate or nil if no such element is found.
///
/// - Parameter where: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element is a match.
/// - Returns: The first match or `nil` if there was no match.
public func first(
where predicate: @noescape (Iterator.Element) throws -> Bool
) rethrows -> Iterator.Element? {
var foundElement: Iterator.Element? = nil
do {
try self.forEach {
if try predicate($0) {
foundElement = $0
throw _StopIteration.stop
}
}
} catch is _StopIteration { }
return foundElement
}
}
extension Sequence where Iterator.Element : Equatable {
/// Returns the longest possible subsequences of the sequence, in order,
/// around elements equal to the given element. Elements that are used to
/// split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(separator: " ")
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don't", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.characters.split(separator: " ", maxSplits: 1)
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(separator: " ", omittingEmptySubsequences: false)
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero. The default value is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the sequence and for each instance of `separator` at the
/// start or end of the sequence. If `true`, only nonempty subsequences
/// are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this sequence's elements.
public func split(
separator: Iterator.Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [AnySequence<Iterator.Element>] {
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
isSeparator: { $0 == separator })
}
}
extension Sequence where
SubSequence : Sequence,
SubSequence.Iterator.Element == Iterator.Element,
SubSequence.SubSequence == SubSequence {
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the sequence, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the sequence. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(1).
public func dropFirst(_ n: Int) -> AnySequence<Iterator.Element> {
_precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n))
}
/// Returns a subsequence containing all but the given number of final
/// elements.
///
/// The sequence must be finite. If the number of elements to drop exceeds
/// the number of elements in the sequence, the result is an empty
/// subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// sequence. `n` must be greater than or equal to zero.
/// - Complexity: O(*n*), where *n* is the length of the sequence.
public func dropLast(_ n: Int) -> AnySequence<Iterator.Element> {
_precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements from this sequence in a holding tank, a ring buffer
// of size <= n. If more elements keep coming in, pull them out of the
// holding tank into the result, an `Array`. This saves
// `n` * sizeof(Iterator.Element) of memory, because slices keep the entire
// memory of an `Array` alive.
var result: [Iterator.Element] = []
var ringBuffer: [Iterator.Element] = []
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < n {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = ringBuffer.index(after: i) % n
}
}
return AnySequence(result)
}
/// Returns a subsequence, up to the specified maximum length, containing the
/// initial elements of the sequence.
///
/// If the maximum length exceeds the number of elements in the sequence,
/// the result contains all the elements in the sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this sequence
/// with at most `maxLength` elements.
///
/// - Complexity: O(1)
public func prefix(_ maxLength: Int) -> AnySequence<Iterator.Element> {
_precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence")
if maxLength == 0 {
return AnySequence(EmptyCollection<Iterator.Element>())
}
return AnySequence(
_PrefixSequence(_iterator: makeIterator(), maxLength: maxLength))
}
}
extension Sequence {
/// Returns a subsequence containing all but the first element of the
/// sequence.
///
/// For example:
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
///
/// - Complexity: O(1)
public func dropFirst() -> SubSequence { return dropFirst(1) }
/// Returns a subsequence containing all but the last element of the sequence.
///
/// The sequence must be finite.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
public func dropLast() -> SubSequence { return dropLast(1) }
}
extension Sequence {
@discardableResult
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Iterator.Element>
) -> UnsafeMutablePointer<Iterator.Element> {
var p = UnsafeMutablePointer<Iterator.Element>(ptr)
for x in IteratorSequence(self.makeIterator()) {
p.initialize(with: x)
p += 1
}
return p
}
}
// Pending <rdar://problem/14011860> and <rdar://problem/14396120>,
// pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness"
/// A sequence built around an iterator of type `Base`.
///
/// Useful mostly to recover the ability to use `for`...`in`,
/// given just an iterator `i`:
///
/// for x in IteratorSequence(i) { ... }
public struct IteratorSequence<
Base : IteratorProtocol
> : IteratorProtocol, Sequence {
/// Construct an instance whose iterator is a copy of `base`.
public init(_ base: Base) {
_base = base
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
public mutating func next() -> Base.Element? {
return _base.next()
}
internal var _base: Base
}
@available(*, unavailable, renamed: "IteratorProtocol")
public typealias GeneratorType = IteratorProtocol
@available(*, unavailable, renamed: "Sequence")
public typealias SequenceType = Sequence
extension Sequence {
@available(*, unavailable, renamed: "makeIterator()")
func generate() -> Iterator {
Builtin.unreachable()
}
@available(*, unavailable, message: "it became a property 'underestimatedCount'")
func underestimateCount() -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "call 'split(_:omittingEmptySubsequences:isSeparator:)' and invert the 'allowEmptySlices' argument")
func split(_ maxSplit: Int, allowEmptySlices: Bool,
isSeparator: @noescape (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
Builtin.unreachable()
}
}
extension Sequence where Iterator.Element : Equatable {
@available(*, unavailable, message: "call 'split(separator:omittingEmptySubsequences:isSeparator:)' and invert the 'allowEmptySlices' argument")
public func split(
_ separator: Iterator.Element,
maxSplit: Int = Int.max,
allowEmptySlices: Bool = false
) -> [AnySequence<Iterator.Element>] {
Builtin.unreachable()
}
}
@available(*, unavailable, renamed: "IteratorSequence")
public struct GeneratorSequence<Base : IteratorProtocol> {}
|
apache-2.0
|
d85fd64115ff4ba8f7e5a695169491a0
| 37.200961 | 146 | 0.631757 | 4.276125 | false | false | false | false |
onmyway133/Github.swift
|
Sources/Classes/Key/Client+Key.swift
|
1
|
1505
|
//
// Client+Key.swift
// GithubSwift
//
// Created by Khoa Pham on 22/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import RxSwift
import Construction
public extension Client {
// Fetches the public keys for the current `user`.
//
// Returns a signal which sends zero or more OCTPublicKey objects. Unverified
// keys will only be included if the client is `authenticated`. If no `user` is
// set, the signal will error immediately.
public func fetchPublicKeys() -> Observable<[PublicKey]> {
if !isAuthenticated {
return Observable<[PublicKey]>.error(Error.authenticationRequiredError())
}
let requestDescriptor: RequestDescriptor = construct {
$0.path = "/keys"
}
return enqueueUser(requestDescriptor).map {
return Parser.all($0)
}
}
// Adds a new public key to the current user's profile.
//
// Returns a signal which sends the new OCTPublicKey. If the client is not
// `authenticated`, the signal will error immediately.
public func postPublicKey(key: String, title: String) -> Observable<PublicKey> {
if !isAuthenticated {
return Observable<PublicKey>.error(Error.authenticationRequiredError())
}
let requestDescriptor: RequestDescriptor = construct {
$0.method = .POST
$0.path = "user/keys"
$0.parameters = [
"key": key,
"title": title
]
}
return enqueue(requestDescriptor).map {
return Parser.one($0)
}
}
}
|
mit
|
faedb7680b1d186c9cd3ff1a3754f7c7
| 25.857143 | 82 | 0.668883 | 4.272727 | false | false | false | false |
MegaManX32/CD
|
CD/CD/Model/RiderList+Additions.swift
|
1
|
5780
|
//
// RiderList+Additions.swift
// CD
//
// Created by Vladislav Simovic on 12/3/16.
// Copyright © 2016 CustomDeal. All rights reserved.
//
import Foundation
import CoreData
extension RiderList {
// MARK: - RiderList CRUD
static func createOrUpdateRiderListWith(JSON:[String : Any], context:NSManagedObjectContext) -> RiderList {
// fetch RiderList or create new one
var riderList = RiderList.findRiderListWith(uid: JSON["uid"] as! String, context: context)
riderList = riderList ?? RiderList(context: context)
riderList!.initWith(JSON: JSON, context: context)
return riderList!
}
static func findRiderListWith(uid: String, context: NSManagedObjectContext) -> RiderList? {
let fetchRequest: NSFetchRequest<RiderList> = RiderList.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "uid == %@", uid)
return try! context.fetch(fetchRequest).first
}
// MARK: - JSON serialization
func initWith(JSON:[String : Any], context: NSManagedObjectContext) {
// update simple properties from JSON
self.uid = JSON["uid"] as? String ?? self.uid
self.country = JSON["country"] as? String ?? self.country
self.city = JSON["city"] as? String ?? self.city
self.details = JSON["details"] as? String ?? self.details
self.desc = JSON["description"] as? String ?? "WARNING ASSERTION - NO DESCRIPTION RETURNED FROM SERVER"
self.gender = JSON["gender"] as? String ?? self.gender
self.userUid = JSON["userUid"] as? String ?? self.userUid
// age range
if let ageRangeDictionary = JSON["ageRange"] as? [String : NSNumber] {
self.ageRangeFrom = ageRangeDictionary["from"] ?? self.ageRangeFrom
self.ageRangeTo = ageRangeDictionary["to"] ?? self.ageRangeTo
}
// check in and check out
if let checkInDateString = JSON["checkIn"] as? String, let checkOutDateString = JSON["checkOut"] as? String {
self.checkIn = StandardDateFormatter.dateFrom(dateString: checkInDateString)
self.checkOut = StandardDateFormatter.dateFrom(dateString: checkOutDateString)
}
// create relationships
if let interests = JSON["interestList"] as? [[String : Any]] {
self.interests = NSSet.init()
for interestJSON in interests {
self.addToInterests(Interest.createOrUpdateInterestWith(JSON: interestJSON, context: context))
}
}
if let languages = JSON["languageList"] as? [[String : Any]] {
self.languages = NSSet.init()
for languageJSON in languages {
self.addToLanguages(Language.createOrUpdateLanguageWith(JSON: languageJSON, context: context))
}
}
if let riderListOffers = JSON["offerList"] as? [[String : Any]] {
self.riderListOffers = NSSet.init()
for riderListOfferJSON in riderListOffers {
self.addToRiderListOffers(RiderListOffer.createOrUpdateRiderListOfferWith(JSON: riderListOfferJSON, context: context))
}
}
// self.selectedRiderListOffer = nil
if let selectedRiderListOfferJSON = JSON["selectedOffer"] as? [String : Any] {
self.selectedRiderListOffer = RiderListOffer.createOrUpdateRiderListOfferWith(JSON: selectedRiderListOfferJSON, context: context)
}
}
func asJSON() -> [String : Any] {
// create JSON from properties
var JSON = [String : Any]()
JSON["uid"] = self.uid
JSON["country"] = self.country
JSON["city"] = self.city
JSON["checkIn"] = self.checkIn
JSON["checkOut"] = self.checkOut
JSON["details"] = self.details
JSON["description"] = self.desc
JSON["gender"] = self.gender
JSON["userUid"] = self.userUid
// age range
if let ageRangeFrom = self.ageRangeFrom, let ageRangeTo = self.ageRangeTo {
var ageRangeDictionary = [String : NSNumber]()
ageRangeDictionary["from"] = ageRangeFrom
ageRangeDictionary["to"] = ageRangeTo
JSON["ageRange"] = ageRangeDictionary
}
// check in and check out
if let checkInDate = self.checkIn, let checkOutDate = self.checkOut {
JSON["checkIn"] = StandardDateFormatter.stringFrom(date: checkInDate)
JSON["checkOut"] = StandardDateFormatter.stringFrom(date: checkOutDate)
}
// create relationships
if let interests = self.interests {
var interestsArray = [[String : Any]]()
for interest in interests {
interestsArray.append((interest as! Interest).asJSON())
}
JSON["interestList"] = interestsArray
}
if let languages = self.languages {
var languagesArray = [[String : Any]]()
for language in languages {
languagesArray.append((language as! Language).asJSON())
}
JSON["languageList"] = languagesArray
}
if let riderListOffers = self.riderListOffers {
var riderListOffersArray = [[String : Any]]()
for riderListOffer in riderListOffers {
riderListOffersArray.append((riderListOffer as! RiderListOffer).asJSON())
}
JSON["offerList"] = riderListOffersArray
}
if let selectedRiderListOffer = self.selectedRiderListOffer {
JSON["selectedOffer"] = selectedRiderListOffer.asJSON()
}
return JSON
}
}
|
mit
|
787ceed9cd5a68b6c03970f2affdc30f
| 39.131944 | 141 | 0.604776 | 4.612131 | false | false | false | false |
WickedColdfront/Slide-iOS
|
Pods/ImageViewer/ImageViewer/Source/VideoScrubber.swift
|
1
|
8168
|
//
// VideoScrubber.swift
// ImageViewer
//
// Created by Kristian Angyal on 08/08/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
import AVFoundation
open class VideoScrubber: UIControl {
let playButton = UIButton.playButton(width: 50, height: 40)
let pauseButton = UIButton.pauseButton(width: 50, height: 40)
let replayButton = UIButton.replayButton(width: 50, height: 40)
let scrubber = Slider.createSlider(320, height: 20, pointerDiameter: 10, barHeight: 2)
let timeLabel = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 50, height: 20)))
var duration: TimeInterval?
fileprivate var periodicObserver: AnyObject?
fileprivate var stoppedSlidingTimeStamp = Date()
weak var player: AVPlayer? {
willSet {
if newValue == nil {
if let player = player {
///KVO
player.removeObserver(self, forKeyPath: "status")
player.removeObserver(self, forKeyPath: "rate")
///NC
NotificationCenter.default.removeObserver(self)
///TIMER
if let periodicObserver = self.periodicObserver {
player.removeTimeObserver(periodicObserver)
self.periodicObserver = nil
}
}
}
}
didSet {
if let player = player {
///KVO
player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
///NC
NotificationCenter.default.addObserver(self, selector: #selector(didEndPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
///TIMER
periodicObserver = player.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1), queue: nil, using: { [weak self] time in
self?.update()
}) as AnyObject?
self.update()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
deinit {
player?.removeObserver(self, forKeyPath: "status")
player?.removeObserver(self, forKeyPath: "rate")
scrubber.removeObserver(self, forKeyPath: "isSliding")
if let periodicObserver = self.periodicObserver {
player?.removeTimeObserver(periodicObserver)
self.periodicObserver = nil
}
}
func didEndPlaying() {
self.playButton.isHidden = true
self.pauseButton.isHidden = true
self.replayButton.isHidden = false
}
func setup() {
self.clipsToBounds = true
pauseButton.isHidden = true
replayButton.isHidden = true
scrubber.minimumValue = 0
scrubber.maximumValue = 1000
scrubber.value = 0
timeLabel.attributedText = NSAttributedString(string: "--:--", attributes: [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.systemFont(ofSize: 12)])
timeLabel.textAlignment = .center
playButton.addTarget(self, action: #selector(play), for: UIControlEvents.touchUpInside)
pauseButton.addTarget(self, action: #selector(pause), for: UIControlEvents.touchUpInside)
replayButton.addTarget(self, action: #selector(replay), for: UIControlEvents.touchUpInside)
scrubber.addTarget(self, action: #selector(updateCurrentTime), for: UIControlEvents.valueChanged)
scrubber.addTarget(self, action: #selector(seekToTime), for: [UIControlEvents.touchUpInside, UIControlEvents.touchUpOutside])
self.addSubviews(playButton, pauseButton, replayButton, scrubber, timeLabel)
scrubber.addObserver(self, forKeyPath: "isSliding", options: NSKeyValueObservingOptions.new, context: nil)
}
open override func layoutSubviews() {
super.layoutSubviews()
playButton.center = self.boundsCenter
playButton.frame.origin.x = 0
pauseButton.frame = playButton.frame
replayButton.frame = playButton.frame
timeLabel.center = self.boundsCenter
timeLabel.frame.origin.x = self.bounds.maxX - timeLabel.bounds.width
scrubber.bounds.size.width = self.bounds.width - playButton.bounds.width - timeLabel.bounds.width
scrubber.bounds.size.height = 20
scrubber.center = self.boundsCenter
scrubber.frame.origin.x = playButton.frame.maxX
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "isSliding" {
if scrubber.isSliding == false {
stoppedSlidingTimeStamp = Date()
}
}
else if keyPath == "rate" || keyPath == "status" {
self.update()
}
}
func play() {
self.player?.play()
}
func replay() {
self.player?.seek(to: CMTime(value:0 , timescale: 1))
self.player?.play()
}
func pause() {
self.player?.pause()
}
func seekToTime() {
let progress = scrubber.value / scrubber.maximumValue //naturally will be between 0 to 1
if let player = self.player, let currentItem = player.currentItem {
let time = currentItem.duration.seconds * Double(progress)
player.seek(to: CMTime(seconds: time, preferredTimescale: 1))
}
}
func update() {
updateButtons()
updateDuration()
updateScrubber()
updateCurrentTime()
}
func updateButtons() {
if let player = self.player {
self.playButton.isHidden = player.isPlaying()
self.pauseButton.isHidden = !self.playButton.isHidden
self.replayButton.isHidden = true
}
}
func updateDuration() {
if let duration = self.player?.currentItem?.duration {
self.duration = (duration.isNumeric) ? duration.seconds : nil
}
}
func updateScrubber() {
guard scrubber.isSliding == false else { return }
let timeElapsed = Date().timeIntervalSince( stoppedSlidingTimeStamp)
guard timeElapsed > 1 else {
return
}
if let player = self.player, let duration = self.duration {
let progress = player.currentTime().seconds / duration
UIView.animate(withDuration: 0.9, animations: { [weak self] in
if let strongSelf = self {
strongSelf.scrubber.value = Float(progress) * strongSelf.scrubber.maximumValue
}
})
}
}
func updateCurrentTime() {
if let duration = self.duration , self.duration != nil {
let sliderProgress = scrubber.value / scrubber.maximumValue
let currentTime = Double(sliderProgress) * duration
let timeString = stringFromTimeInterval(currentTime as TimeInterval)
timeLabel.attributedText = NSAttributedString(string: timeString, attributes: [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.systemFont(ofSize: 12)])
}
else {
timeLabel.attributedText = NSAttributedString(string: "--:--", attributes: [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.systemFont(ofSize: 12)])
}
}
func stringFromTimeInterval(_ interval:TimeInterval) -> String {
let timeInterval = NSInteger(interval)
let seconds = timeInterval % 60
let minutes = (timeInterval / 60) % 60
//let hours = (timeInterval / 3600)
return NSString(format: "%0.2d:%0.2d",minutes,seconds) as String
//return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds) as String
}
}
|
apache-2.0
|
b3708f346eb81cdf4d39f7904b05a77a
| 30.171756 | 192 | 0.620056 | 4.955704 | false | false | false | false |
slavapestov/swift
|
test/SILGen/scalar_to_tuple_args.swift
|
1
|
3356
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func inoutWithDefaults(inout x: Int, y: Int = 0, z: Int = 0) {}
func inoutWithCallerSideDefaults(inout x: Int, y: Int = #line) {}
func scalarWithDefaults(x: Int, y: Int = 0, z: Int = 0) {}
func scalarWithCallerSideDefaults(x: Int, y: Int = #line) {}
func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {}
func variadicFirst(x: Int...) {}
func variadicSecond(x: Int, _ y: Int...) {}
var x = 0
// CHECK: [[X_ADDR:%.*]] = global_addr @_Tv20scalar_to_tuple_args1xSi : $*Int
// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args17inoutWithDefaultsFTRSi1ySi1zSi_T_
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[INOUT_WITH_DEFAULTS]]([[X_ADDR]], [[DEFAULT_Y]], [[DEFAULT_Z]])
inoutWithDefaults(&x)
// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args27inoutWithCallerSideDefaultsFTRSi1ySi_T_
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[X_ADDR]], [[LINE]])
inoutWithCallerSideDefaults(&x)
// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args18scalarWithDefaultsFTSi1ySi1zSi_T_
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]])
scalarWithDefaults(x)
// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args28scalarWithCallerSideDefaultsFTSi1ySi_T_
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]])
scalarWithCallerSideDefaults(x)
// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args17tupleWithDefaultsFT1xTSiSi_1ySi1zSi_T_
// CHECK: [[X1:%.*]] = load [[X_ADDR]]
// CHECK: [[X2:%.*]] = load [[X_ADDR]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]])
tupleWithDefaults(x: (x,x))
// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_TF20scalar_to_tuple_args13variadicFirstFtGSaSi__T_
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> @owned (Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[MEMORY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 1
// CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]]
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: store [[X]] to [[ADDR]]
// CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
variadicFirst(x)
// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_TF20scalar_to_tuple_args14variadicSecondFtSiGSaSi__T_
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> @owned (Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
variadicSecond(x)
|
apache-2.0
|
9dcea606f248a1877c555b762d4c795d
| 50.6 | 128 | 0.605546 | 3.122905 | false | false | false | false |
CompassSoftware/pocket-turchin
|
PocketTurchin/CurrentTableViewController.swift
|
1
|
10266
|
//
// CurrentTableViewController.swift
// PocketTurchin
//
// Created by Owner on 5/10/16.
// Copyright © 2016 shuffleres. All rights reserved.
//
import UIKit
class CurrentTableViewController: UITableViewController {
var currents = [Archive]()
var photo: UIImage = UIImage(named: "defaultImage")!
var desc: String = ""
var name: String = ""
var archive_count = -1
var picture_count = 0
func loadAllCurrent() {
print("Loading all current")
self.count_selection { (archive) in
self.archive_count = archive[0] as! Int
print(String(archive[0]))
}
func load_all() {
self.load_all_archives { (archive) in
var url_string = archive[2] as! String
if (!url_string.isEmpty) {
self.getImageFromServerById(String(archive[2])) { image in
func call_seque()
{
//self.photo = image!
self.currents[self.picture_count].photo = image!
self.picture_count = self.picture_count + 1
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.log("Reloading UI for image")
})
}
dispatch_async(dispatch_get_main_queue(),call_seque)
}
}
else {
self.picture_count = self.picture_count + 1
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
self.desc = archive[1] as! String
self.name = archive[0] as! String
let archive_temp = Archive(name: self.name, desc: self.desc,photo: self.photo)
self.currents += [archive_temp]
}
}
dispatch_async(dispatch_get_main_queue(),load_all)
}
override func viewDidLoad() {
super.viewDidLoad()
loadAllCurrent()
// 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 numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return currents.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CurrentTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CurrentTableViewCell
// Fetches the appropriate meal for the data source layout.
let current = currents[indexPath.row]
cell.archiveLabel.text = current.name
cell.photoImageView.image = current.photo
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// 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 == "ShowDetail" {
let currentDetailViewController = segue.destinationViewController as! ArchiveViewController
// Get the cell that generated this segue.
if let selectedCurrentCell = sender as? CurrentTableViewCell {
let indexPath = tableView.indexPathForCell(selectedCurrentCell)!
let selectedCurrent = currents[indexPath.row]
currentDetailViewController.archive = selectedCurrent
}
}
}
func load_all_archives(completionHandler: (archive: NSArray) -> ()) {
let requestURL: NSURL = NSURL(string: "http://cs.appstate.edu/Turchin/currentGetter.php")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let datas = json["data"] as? [[String: AnyObject]] {
print(datas)
for data in datas {
if let name = data["name"] as? String {
if let desc = data["description"] as? String {
if let picture = data["url"] as? String {
let results = [name, desc, picture]
//NSLog(" Name: %@ Description: %@ URL: %@",name,desc,picture)
completionHandler(archive: results)
}
else {
let results = [name, desc, "null"]
completionHandler(archive: results)
}
}
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
func count_selection(completionHandler: (archive: NSArray) -> ()) {
let requestURL: NSURL = NSURL(string: "http://cs.appstate.edu/Turchin/currentGetter.php")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let datas = json["data"] as? [[String: AnyObject]] {
let results = [datas.count]
completionHandler(archive: results)
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
func getImageFromServerById(imageId: String, completion: ((image: UIImage?) -> Void)) {
let url:String = "\(imageId)"
//print("URL is: "+url)
let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {(data, response, error) in
//print(data?.description)
if (data != nil) {
self.log("Downloading image")
completion(image: UIImage(data: data!))
}
//completion(image: UIImage(data: data!))
}
task.resume()
}
func log(text: String)
{
let isMain = NSThread.currentThread().isMainThread
let name_of_thread = isMain ? "{Main }" : "{Child}"
print("\(name_of_thread) \(text)")
}
}
|
apache-2.0
|
3f9f5ccef6accc3c81fdf088e53e8539
| 38.633205 | 157 | 0.545153 | 5.646315 | false | false | false | false |
PrestonV/ios-cannonball
|
Cannonball/Poem.swift
|
1
|
3296
|
//
// Copyright (C) 2014 Twitter, Inc. and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public class Poem: NSObject, NSCoding {
// MARK: Types
// String constants used to archive the stored properties of a poem.
private struct SerializationKeys {
static let words = "words"
static let picture = "picture"
static let theme = "theme"
static let date = "date"
static let uuid = "uuid"
}
// The words composing a poem.
public var words: [String] = []
// The picture used as a background of a poem.
public var picture: String = ""
// The theme name of the poem.
public var theme: String = ""
// The date a poem is completed.
public var date = NSDate()
// An underlying identifier for each poem.
public private(set) var UUID = NSUUID()
// MARK: Initialization
override init() {
super.init()
}
// Initialize a Poem instance will all its properties, including a UUID.
private init(words: [String], picture: String, theme: String, date: NSDate, UUID: NSUUID) {
self.words = words
self.picture = picture
self.theme = theme
self.date = date
self.UUID = UUID
}
// Initialize a Poem instance with all its public properties.
convenience init(words: [String], picture: String, theme: String, date: NSDate) {
self.init(words: words, picture: picture, theme: theme, date: date, UUID: NSUUID())
}
// Retrieve the poem words as one sentence.
func getSentence() -> String {
return " ".join(words)
}
// MARK: NSCoding
required public init(coder aDecoder: NSCoder) {
words = aDecoder.decodeObjectForKey(SerializationKeys.words) as [String]
picture = aDecoder.decodeObjectForKey(SerializationKeys.picture) as String
theme = aDecoder.decodeObjectForKey(SerializationKeys.theme) as String
date = aDecoder.decodeObjectForKey(SerializationKeys.date) as NSDate
UUID = aDecoder.decodeObjectForKey(SerializationKeys.uuid) as NSUUID
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(words, forKey: SerializationKeys.words)
aCoder.encodeObject(picture, forKey: SerializationKeys.picture)
aCoder.encodeObject(theme, forKey: SerializationKeys.theme)
aCoder.encodeObject(date, forKey: SerializationKeys.date)
aCoder.encodeObject(UUID, forKey: SerializationKeys.uuid)
}
// MARK: Overrides
// Two poems are equal only if their UUIDs match.
override public func isEqual(object: AnyObject?) -> Bool {
if let poem = object as? Poem {
return UUID == poem.UUID
}
return false
}
}
|
apache-2.0
|
575b68ad02245bdca9e40a9d5e7501f4
| 31.633663 | 95 | 0.667476 | 4.539945 | false | false | false | false |
songzhw/2iOS
|
SwiftUiDemo/SwiftUiDemo/utils/ColorExt.swift
|
1
|
839
|
import UIKit
extension UIColor {
// hex: rgba
public convenience init(hex: String) {
let r, g, b, a: CGFloat
if hex.hasPrefix("#") {
let start = hex.index(hex.startIndex, offsetBy: 1)
let hexColor = String(hex[start...])
if hexColor.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
self.init(red: 1, green: 1, blue: 1, alpha: 1)
return
}
}
|
apache-2.0
|
ddb163483401a41327a69ab8dd49ae4d
| 26.064516 | 59 | 0.531585 | 3.712389 | false | false | false | false |
benlangmuir/swift
|
test/Generics/sr11997.swift
|
2
|
1013
|
// RUN: %target-typecheck-verify-swift -debug-generic-signatures 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/54431
// CHECK: sr11997.(file).A@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[A]X.[B]Y, Self.[A]X : B>
protocol A {
associatedtype X: B where X.Y == Self
}
// CHECK: sr11997.(file).B@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[B]Y.[A]X, Self.[B]Y : A>
protocol B {
associatedtype Y: A where Y.X == Self
}
// CHECK: sr11997.(file).AA@
// CHECK-NEXT: Requirement signature: <Self where Self : A, Self.[A]X : BB>
protocol AA: A where X: BB { }
// CHECK: sr11997.(file).BB@
// CHECK-NEXT: Requirement signature: <Self where Self : B, Self == Self.[BB]Z.[C]T, Self.[B]Y : AA, Self.[BB]Z : C>
protocol BB: B where Y: AA {
associatedtype Z: C where Z.T == Self
}
// CHECK: sr11997.(file).C@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[C]T.[BB]Z, Self.[C]T : BB>
protocol C {
associatedtype T: BB where T.Z == Self
}
|
apache-2.0
|
dad0d108be4df2ae258d28939eb38fe0
| 30.65625 | 116 | 0.646594 | 2.829609 | false | false | false | false |
DrabWeb/Azusa
|
Source/Mio/Mio/Sources/MIMPD.swift
|
1
|
44229
|
//
// MIMPD.swift
// Azusa.Mio
//
// Created by Ushio on 12/7/16.
//
import Foundation
import MPD
import Yui
// TODO: Make `MIMPDError` convertible to `MusicSourceError`
/// The different errors that `MIMPD` can throw
///
/// - Success
/// - disconnected: The `MIMPD` object is not connected to any servers
/// - outOfMemory: Out of memory
/// - argument: A function was called with an uncrecognized or invalid argument
/// - state: A function was called which is not available in the current state of libmpdclient
/// - timeout: Timeout trying to talk to MPD
/// - system: System error
/// - resolver: Unknown host
/// - malformed: Malformed response received from MPD
/// - connectionClosed: Connection closed by MPD
/// - serverError: The server has returned an error code, which can be queried with `mpd_connection_get_server_error()`
/// - other: An error not handled by Mio
public enum MIMPDError: String, Error, CustomStringConvertible {
public var description: String {
return rawValue;
}
case success = "Success"
case disconnected = "The MIMPD object is not connected to any servers"
case outOfMemory = "Out of memory"
case argument = "A function was called with an uncrecognized or invalid argument"
case state = "A function was called which is not available in the current state of libmpdclient"
case timeout = "Timeout trying to talk to MPD"
case system = "System error"
case resolver = "Unknown host"
case malformed = "Malformed response received from MPD"
case connectionClosed = "Connection closed by MPD"
case serverError = "The server has returned an error code"
case other = "Error not handled"
}
/// libmpdclient interaction handler in Mio
public class MIMPD {
// MARK: - Properties
// MARK: Public Properties
/// The event manager for this MPD server
var eventManager : EventManager = EventManager();
/// Is this MPD object connected to a server?
var connected : Bool = false;
/// The server info to connect to
var serverInfo : MIServerInfo = MIServerInfo();
// MARK: Private Properties
/// The connection to MPD for this object(`mpd_connection`)
private var connection: OpaquePointer? = nil;
/// The connection to MPD for idle events for this object(`mpd_connection`)
private var idleConnection: OpaquePointer? = nil;
/// The default amount of seconds to timeout connections
private var connectionTimeout : Int = 30;
// MARK: - Functions
// MARK: - Connection
/// Connects to the server set in `serverInfo`
///
/// - Returns: Returns if the connection was successful
func connect() -> Bool {
return connect(address: serverInfo.address, port: serverInfo.port);
}
/// Connects to the server at the given address and port
///
/// - Parameters:
/// - address: The address of the server(e.g. `127.0.0.1`)
/// - port: The port of the server(e.g. `6600`)
/// - Returns: If the connection was successful
private func connect(address : String, port : Int) -> Bool {
Logger.log("MIMPD: Connecting to \(address):\(port)...");
self.connection = mpd_connection_new(address, UInt32(port), UInt32(self.connectionTimeout * 1000));
self.idleConnection = mpd_connection_new(address, UInt32(port), UInt32(self.connectionTimeout * 1000));
if mpd_connection_get_error(connection) != MPD_ERROR_SUCCESS {
Logger.log("MIMPD: Error connecting to server at \(address):\(port), \(self.currentErrorMessage())");
self.connection = nil;
return false;
}
if mpd_connection_get_error(idleConnection) != MPD_ERROR_SUCCESS {
Logger.log("MIMPD: Error connecting to idle server at \(address):\(port), \(self.currentErrorMessage())");
self.idleConnection = nil;
return false;
}
Logger.log("MIMPD: Connected to \(address):\(port)");
Logger.log("MIMPD: Starting event idle thread");
// Idle loops are done in another thread
DispatchQueue.global(qos: .background).async {
self.idle();
}
self.connected = true;
return true;
}
/// Disconnects from MPD(if it's connected)
func disconnect() {
if self.connection != nil {
mpd_connection_free(self.connection);
self.connection = nil;
}
self.connected = false;
}
// MARK: - Idle Events
/// The while loop for catching idle events from MPD
private func idle() {
while self.idleConnection != nil {
let currentEvent : mpd_idle = mpd_run_idle(self.idleConnection!);
switch currentEvent {
case MPD_IDLE_UPDATE:
eventManager.emit(event: .database);
break;
case MPD_IDLE_OPTIONS:
eventManager.emit(event: .options);
break;
case MPD_IDLE_PLAYER:
eventManager.emit(event: .player);
break;
case MPD_IDLE_QUEUE:
eventManager.emit(event: .queue);
break;
case MPD_IDLE_MIXER:
eventManager.emit(event: .volume);
break;
default:
// For some reason idle "12" is called when the playlist is cleared, not `MPD_IDLE_QUEUE`, so this is the handler for that
if(currentEvent.rawValue == UInt32(12)) {
eventManager.emit(event: .queue);
}
break;
}
}
}
// MARK: - Player
/// Gets the current player status of this MPD server
///
/// - Returns: An `MIPlayerStatus` object representing the current status of this MPD server
/// - Throws: An `MIMPDError`
func getPlayerStatus() throws -> MIPlayerStatus {
if connection != nil {
let playerStatusObject : MIPlayerStatus = MIPlayerStatus();
do {
if let status = mpd_run_status(self.connection!) {
playerStatusObject.currentSong = try getCurrentSong() ?? MISong.empty;
playerStatusObject.volume = Int(mpd_status_get_volume(status));
playerStatusObject.isRandom = mpd_status_get_random(status);
playerStatusObject.isRepeating = mpd_status_get_repeat(status);
playerStatusObject.isSingle = mpd_status_get_single(status);
playerStatusObject.isConsuming = mpd_status_get_consume(status);
playerStatusObject.queueLength = try getQueueLength();
playerStatusObject.playingState = try getPlayingState();
playerStatusObject.currentSongPosition = try getCurrentSongPosition();
playerStatusObject.nextSongPosition = Int(mpd_status_get_next_song_pos(status));
playerStatusObject.timeElapsed = try getElapsed();
mpd_status_free(status);
return playerStatusObject;
}
else {
throw self.currentError();
}
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets the current `PlayingState` of this MPD server
///
/// - Returns: The current `PlayingState`
/// - Throws: An `MIMPDError`
func getPlayingState() throws -> PlayingState {
if(connection != nil) {
if let status = mpd_run_status(self.connection!) {
let playingState : PlayingState = self.playingStateFrom(mpdState: mpd_status_get_state(status));
mpd_status_free(status);
return playingState;
}
else {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Sets if this MPD server is paused
///
/// - Parameter pause: The pause state to set(`true` for play, `false` for pause)
/// - Throws: An `MIMPDError`
func setPaused(_ pause : Bool) throws {
if connection != nil {
Logger.log("MIMPD: \((pause == true) ? "Pausing" : "Playing")");
do {
if try getCurrentSong() != nil {
// Start the song if the player is stopped
if try self.getPlayingState() == .stopped {
try self.seek(to: 0);
}
if !mpd_run_pause(self.connection!, pause) {
throw self.currentError();
}
}
else {
// Play the first song in the queue if there's no current song
try self.seek(to: 0, trackPosition: 0);
}
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Toggles pause for this MPD server
///
/// - Returns: The paused state that was set
/// - Throws: An `MIMPDError`
func togglePaused() throws -> Bool {
if connection != nil {
Logger.log("MIMPD: Toggling pause");
do {
if (try? getCurrentSong()) != nil {
// Start playing the current song if stopped
if try self.getPlayingState() == .stopped {
try self.seek(to: 0, trackPosition: try getCurrentSongPosition());
}
if !mpd_run_toggle_pause(self.connection!) {
throw self.currentError();
}
}
else {
// Play the first song in the queue if there's no current song
try self.seek(to: 0, trackPosition: 0);
}
return try self.getPlayingState() == .playing;
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Stops playback for this MPD server
///
/// - Throws: An `MIMPDError`
func stop() throws {
if connection != nil {
Logger.log("MIMPD: Stopping playback");
if(!mpd_run_stop(self.connection!)) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Skips to the previous song in the queue
///
/// - Throws: An `MIMPDError`
func skipPrevious() throws {
if(connection != nil) {
Logger.log("MIMPD: Skipping to the previous song");
if !mpd_run_previous(self.connection!) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Skips to the previous song in the queue while maintaining playing state
///
/// - Throws: An `MIMPDError`
func skipPreviousAndMaintainPlayingState() throws {
if connection != nil {
Logger.log("MIMPD: Skipping to the previous song");
do {
let playingState : PlayingState = try getPlayingState();
try self.skipPrevious();
if playingState == .paused {
try self.setPaused(true);
}
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Skips to the next song
///
/// - Throws: An `MIMPDError`
func skipNext() throws {
if connection != nil {
Logger.log("MIMPD: Skipping to the next song");
if !mpd_run_next(self.connection!) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Skips to the next song in the queue while maintaining playing state
///
/// - Throws: An `MIMPDError`
func skipNextAndMaintainPlayingState() throws {
if connection != nil {
Logger.log("MIMPD: Skipping to the next song");
do {
let playingState : PlayingState = try getPlayingState();
try self.skipNext();
if playingState == .paused {
try self.setPaused(true);
}
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Sets the volume to the given value
///
/// - Parameter to: The value to set the volume to
/// - Throws: An `MIMPDError`
func setVolume(to : Int) throws {
if connection != nil {
Logger.log("MIMPD: Setting volume to \(to)");
if !mpd_run_set_volume(self.connection!, UInt32(to)) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
// TODO: Make this return the new volume
/// Adds the given volume to the current volume
///
/// - Parameter to: The value to add to the volume, relative to the current volume(-100 to 100)
/// - Throws: An `MIMPDError`
func setRelativeVolume(to : Int) throws {
if connection != nil {
Logger.log("MIMPD: Adding \(to) to volume");
if !mpd_run_change_volume(self.connection!, Int32(to)) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Returns the elapsed time and duration of the current song in seconds
///
/// - Returns: The elapsed time in seconds for the current song
/// - Throws: An `MIMPDError`
func getElapsed() throws -> Int {
if connection != nil {
Logger.log("MIMPD: Getting elapsed time", level: .full);
if let status = mpd_run_status(self.connection!) {
let elapsedTime : Int = Int(mpd_status_get_elapsed_time(status));
mpd_status_free(status);
return elapsedTime;
}
else {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Seeks to the given position in seconds in the song at the given queue position
///
/// - Parameter to: The time in seconds to seek to
/// - Parameter trackPosition: The position of the track in
/// - Throws: An `MIMPDError`
func seek(to : Int, trackPosition : Int) throws {
if connection != nil {
Logger.log("MIMPD: Seeking to \(MusicUtilities.displayTime(from: to)) in #\(trackPosition)");
// Make sure `trackPosition` is in range of the queue
if(trackPosition < (try self.getQueueLength()) && trackPosition >= 0) {
if !mpd_run_seek_pos(self.connection!, UInt32(trackPosition), UInt32(to)) {
throw self.currentError();
}
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Seeks to the given position in seconds in the current song
///
/// - Parameter to: The time in seconds to seek to
/// - Throws: An `MIMPDError`
func seek(to : Int) throws {
do {
try self.seek(to: to, trackPosition: try self.getCurrentSongPosition());
}
catch let error as MIMPDError {
throw error;
}
}
/// Seeks to and plays song at the given index in the queue
///
/// - Parameter at: The position of the song in the queue to play
/// - Throws: An `MIMPDError`
func playSongInQueue(at : Int) throws {
if connection != nil {
Logger.log("MIMPD: Playing #\(at) in queue");
if !mpd_run_play_pos(self.connection, UInt32(at)) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
func setRepeatMode(to mode : RepeatMode) throws {
if connection != nil {
Logger.log("MIMPD: Setting repeat mode to \(mode)");
if !mpd_run_repeat(self.connection!, mode != .none) {
throw self.currentError();
}
if !mpd_run_single(self.connection!, mode == .single) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
// MARK: - Queue
/// Gets all the songs in the current queue and returns them
///
/// - Returns: All the `MISong`s in the current queue
/// - Throws: An `MIMPDError`
func getCurrentQueue() throws -> [MISong] {
if connection != nil {
var currentQueue : [MISong] = [];
let currentQueueLength : Int = (try? self.getQueueLength()) ?? 0;
mpd_send_list_queue_meta(self.connection!);
if currentQueueLength > 0 {
for _ in 0...(currentQueueLength - 1) {
if let song = mpd_recv_song(self.connection!) {
currentQueue.append(self.songFrom(mpdSong: song));
}
else {
throw self.currentError();
}
}
}
mpd_response_finish(self.connection!);
return currentQueue;
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets the current playing song and returns it as an `MISong`(nil if there is none)
///
/// - Returns: The current playing song as an `MISong`(nil if there is none)
/// - Throws: An `MIMPDError`
func getCurrentSong() throws -> MISong? {
if connection != nil {
if let currentSong = mpd_run_current_song(self.connection!) {
return self.songFrom(mpdSong: currentSong);
}
else {
return nil;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets the position of the current song in the queue and returns it
///
/// - Returns: The position of the current playing song in the queue, defaults to -1 if there's no current song
/// - Throws: An `MIMPDError`
func getCurrentSongPosition() throws -> Int {
if connection != nil {
if let currentSong = mpd_run_current_song(self.connection!) {
let position : Int = Int(mpd_song_get_pos(currentSong));
mpd_song_free(currentSong);
return position;
}
else {
return -1;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets the length of the current queue and returns it
///
/// - Returns: The length of the current queue, defaults to -1
/// - Throws: An `MIMPDError`
func getQueueLength() throws -> Int {
if connection != nil {
if let status = mpd_run_status(self.connection!) {
let length : Int = Int(mpd_status_get_queue_length(status));
mpd_status_free(status);
return length;
}
else {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Moves the given `MISong`s in the queue to `to`
///
/// - Parameters:
/// - queueSongs: The `MISong`s in the queue to move
/// - to: The index in the queue to move them to
/// - Throws: An `MIMPDError`
func move(_ queueSongs : [MISong], to : Int) throws {
if connection != nil {
do {
var moveToPosition : Int = to;
let queueLength : Int = try self.getQueueLength();
var movingToEnd : Bool = false;
if to == queueLength {
// Subtract one from `moveToPosition` so it moves to the end instead of one over the end(which would cause a crash)
moveToPosition = to - 1;
movingToEnd = true;
}
Logger.log("MIMPD: Moving \(queueSongs) to \(moveToPosition)");
var successful : Bool = true;
mpd_command_list_begin(self.connection!, true);
for (currentIndex, currentSong) in queueSongs.reversed().enumerated() {
if !mpd_send_move(self.connection!, UInt32((movingToEnd) ? currentSong.position - currentIndex : currentSong.position + currentIndex), UInt32(moveToPosition)) {
throw self.currentError();
}
}
mpd_command_list_end(self.connection!);
// I forget why this only sets if true, but I'm sure there's a reason
// TODO: See why this is neccessary
let responseFinishSuccessful : Bool = mpd_response_finish(self.connection!);
if successful {
successful = responseFinishSuccessful;
}
if !successful {
throw self.currentError();
}
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Moves the given `MISong`s in the queue to after the current song
///
/// - Parameter songs: The array of `MISong`s to move
/// - Throws: An `MIMPDError`
func moveAfterCurrent(songs : [MISong]) throws {
if connection != nil {
Logger.log("MIMPD: Moving \(songs) to after the current song");
do {
let currentSongPosition : Int = try self.getCurrentSongPosition();
// Only move if there is a current song
if currentSongPosition != -1 {
try self.move(songs, to: currentSongPosition + 1);
}
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Adds the given array of `MISong`'s to the queue
///
/// - Parameters:
/// - songs: The `MISong`s to add to the queue
/// - at: The position to insert the songs at(optional)
/// - Throws: An `MIMPDError`
func addToQueue(songs : [MISong], at : Int = -1) throws {
if connection != nil {
Logger.log("MIMPD: Adding \(songs) to queue at \(((at == -1) ? "end" : "\(at)"))");
var successful : Bool = true;
mpd_command_list_begin(self.connection!, true);
// Reverse `songs` so it stays in proper order
for (_, currentSong) in ((at > -1) ? songs.reversed() : songs).enumerated() {
if at != -1 {
if !mpd_send_add_id_to(self.connection!, currentSong.uri, UInt32(at)) {
throw self.currentError();
}
}
else {
if !mpd_send_add_id(self.connection!, currentSong.uri) {
throw self.currentError();
}
}
}
mpd_command_list_end(self.connection!);
// TODO: Same as above
let responseFinishSuccessful : Bool = mpd_response_finish(self.connection!);
if successful {
successful = responseFinishSuccessful;
}
if !successful {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Removes the given `MISong`s from the current queue
///
/// - Parameter songs: The array of `MISong`s to remove from the queue
/// - Throws: An `MIMPDError`
func removeFromQueue(songs : [MISong]) throws {
if connection != nil {
Logger.log("MIMPD: Removing \(songs) from the queue");
var successful : Bool = true;
mpd_command_list_begin(self.connection!, true);
for (_, currentSong) in songs.enumerated() {
if(!mpd_send_delete_id(self.connection!, UInt32(currentSong.id))) {
throw self.currentError();
}
}
// TODO: And once more
let responseFinishSuccessful : Bool = mpd_response_finish(self.connection!);
if successful {
successful = responseFinishSuccessful;
}
if !successful {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Clears the current queue
///
/// - Throws: An `MIMPDError`
func clearQueue() throws {
if connection != nil {
Logger.log("MIMPD: Clearing queue");
if !mpd_run_clear(self.connection!) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Shuffles the current queue
///
/// - Throws: An `MIMPDError`
func shuffleQueue() throws {
if connection != nil {
Logger.log("MIMPD: Shuffling queue");
if !mpd_run_shuffle(self.connection!) {
throw self.currentError();
}
}
else {
throw MIMPDError.disconnected;
}
}
// MARK: - Database
/// Gets the stats of this MPD server
///
/// - Returns: An `MIStats` object that has the current stats of this MPD server
/// - Throws: An `MIMPDError`
func getStats() throws -> MIStats {
if connection != nil {
let stats = mpd_run_stats(self.connection!);
if stats == nil {
throw self.currentError();
}
let albumCount : Int = Int(mpd_stats_get_number_of_albums(stats));
let artistCount : Int = Int(mpd_stats_get_number_of_artists(stats));
let songCount : Int = Int(mpd_stats_get_number_of_songs(stats));
let databasePlayTime : Int = Int(mpd_stats_get_db_play_time(stats));
let mpdUptime : Int = Int(mpd_stats_get_uptime(stats));
let mpdPlayTime : Int = Int(mpd_stats_get_play_time(stats));
let lastMpdDatabaseUpdateTimestamp : Int = Int(mpd_stats_get_db_update_time(stats));
mpd_stats_free(stats);
return MIStats(albumCount: albumCount,
artistCount: artistCount,
songCount: songCount,
databasePlayTime: databasePlayTime,
mpdUptime: mpdUptime,
mpdPlayTime: mpdPlayTime,
lastMpdDatabaseUpdate: NSDate(timeIntervalSince1970: TimeInterval(lastMpdDatabaseUpdateTimestamp)));
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets all the artists in the MPD database
///
/// - Returns: An array of `Artist`s containing all the artists in the MPD database(only the name is set)
/// - Throws: An `MIMPDError`
func getAllArtists() throws -> [Artist] {
if connection != nil {
var artists : [Artist] = [];
for (_, currentArtistName) in self.getAllValues(of: MPD_TAG_ARTIST).enumerated() {
artists.append(Artist(name: currentArtistName));
}
return artists;
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets all the albums in the MPD database
///
/// - Returns: An array of `Album`s containing all the albums in the MPD database
/// - Throws: An `MIMPDError`
func getAllAlbums() throws -> [Album] {
if connection != nil {
var albums : [Album] = [];
for (_, currentAlbumName) in self.getAllValues(of: MPD_TAG_ALBUM).enumerated() {
albums.append(Album(name: currentAlbumName));
do {
albums.last!.songs = try getAllSongsFor(album: albums.last!);
}
catch let error as MIMPDError {
throw error;
}
}
return albums;
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets all the genres in the MPD database
///
/// - Returns: An array of `Genre`s containing all the genres in the MPD database(only the name is set)
/// - Throws: An `MIMPDError`
func getAllGenres() throws -> [Genre] {
if connection != nil {
var genres : [Genre] = [];
for (_, currentGenreName) in self.getAllValues(of: MPD_TAG_GENRE).enumerated() {
genres.append(Genre(name: currentGenreName));
}
return genres;
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets all the albums for the given artist, also stores the albums in `artist.albums`
///
/// - Parameter artist: The `Artist` to get the albums of
/// - Returns: All the `Album`s for the given `Artist`
/// - Throws: An `MIMPDError`
func getAllAlbumsFor(artist : Artist) throws -> [Album] {
if connection != nil {
Logger.log("MIMPD: Getting all albums for \(artist)");
var albums : [Album] = [];
if !mpd_search_db_tags(self.connection!, MPD_TAG_ALBUM) {
throw self.currentError();
}
if !mpd_search_add_tag_constraint(self.connection!, MPD_OPERATOR_DEFAULT, MPD_TAG_ARTIST, artist.name) {
throw self.currentError();
}
if !mpd_search_commit(self.connection!) {
throw self.currentError();
}
var resultsKeyValuePair = mpd_recv_pair_tag(self.connection!, MPD_TAG_ALBUM);
while resultsKeyValuePair != nil {
albums.append(Album(name: String(cString: resultsKeyValuePair!.pointee.value)));
mpd_return_pair(self.connection!, resultsKeyValuePair);
resultsKeyValuePair = mpd_recv_pair_tag(self.connection!, MPD_TAG_ALBUM);
}
if mpd_connection_get_error(self.connection!) != MPD_ERROR_SUCCESS || !mpd_response_finish(self.connection) {
throw self.currentError();
}
artist.albums = albums;
// TODO: I don't like this very much
// Thinking like a MusicSource stores fetched stuff or something
for(_, currentAlbum) in artist.albums.enumerated() {
do {
currentAlbum.songs = try self.getAllSongsFor(album: currentAlbum);
}
catch let error as MIMPDError {
throw error;
}
}
return artist.albums;
}
else {
throw MIMPDError.disconnected;
}
}
/// Gets all the songs for the given album
///
/// - Parameter album: The `Album` to get the songs of
/// - Returns: All the `MISong`s for the given `Album`
/// - Throws: An `MIMPDError`
func getAllSongsFor(album : Album) throws -> [MISong] {
if connection != nil {
Logger.log("MIMPD: Getting all songs for album \(album)");
do {
return try self.searchForSongs(with: album.name, within: MPD_TAG_ALBUM, exact: true);
}
catch let error as MIMPDError {
throw error;
}
}
else {
throw MIMPDError.disconnected;
}
}
/// Searches for songs in the database with the given paramaters
///
/// - Parameters:
/// - query: The string to search for
/// - tags: The tags to limit the query to, `MPD_TAG_UNKNOWN` is used to denote an any search
/// - exact: Should the search use exact matching?
/// - Returns: The results of the search as an array of `MISong`s
/// - Throws: An `MIMPDError`
func searchForSongs(with query : String, within tag : mpd_tag_type, exact : Bool) throws -> [MISong] {
if connection != nil {
Logger.log("MIMPD: Searching for songs with query \"\(query)\" within tag \(((tag == MPD_TAG_UNKNOWN) ? "Any" : String(cString: mpd_tag_name(tag)))), exact: \(exact)");
var results : [MISong] = [];
if !mpd_search_db_songs(self.connection!, exact) {
throw self.currentError();
}
if tag == MPD_TAG_UNKNOWN {
if !mpd_search_add_any_tag_constraint(self.connection!, MPD_OPERATOR_DEFAULT, query) {
throw self.currentError();
}
}
else {
if !mpd_search_add_tag_constraint(self.connection!, MPD_OPERATOR_DEFAULT, tag, query) {
throw self.currentError();
}
}
if !mpd_search_commit(self.connection!) {
throw self.currentError();
}
var song = mpd_recv_song(self.connection!);
while song != nil {
results.append(self.songFrom(mpdSong: song!));
song = mpd_recv_song(self.connection!);
}
if mpd_connection_get_error(self.connection!) != MPD_ERROR_SUCCESS || !mpd_response_finish(self.connection) {
throw self.currentError();
}
return results;
}
else {
throw MIMPDError.disconnected;
}
}
// MARK: - Utilities
/// Returns an `MISong` from the given `mpd_song`
/// Automatically frees the given `mpd_song` from memory after usage
///
/// - Parameter mpdSong: The MPD song to get the `MISong` of
/// - Returns: The `MISong` of `mpdSong`
private func songFrom(mpdSong: OpaquePointer) -> MISong {
let returnSong : MISong = MISong();
// Load all the values
let uriObject = mpd_song_get_uri(mpdSong);
if uriObject != nil {
let uriData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: uriObject!), count: Int(strlen(uriObject)), deallocator: .none);
returnSong.uri = String(data: uriData, encoding: .utf8) ?? "";
}
returnSong.id = Int(mpd_song_get_id(mpdSong));
returnSong.artist = Artist(name: tagFrom(mpdSong, tag: MPD_TAG_ARTIST) ?? "");
returnSong.album = Album(name: tagFrom(mpdSong, tag: MPD_TAG_ALBUM) ?? "");
returnSong.albumArtist = Artist(name: tagFrom(mpdSong, tag: MPD_TAG_ALBUM_ARTIST) ?? "");
returnSong.title = tagFrom(mpdSong, tag: MPD_TAG_TITLE) ?? "";
returnSong.track = Int(NSString(string: tagFrom(mpdSong, tag: MPD_TAG_TRACK) ?? "").intValue);
returnSong.genre = Genre(name: tagFrom(mpdSong, tag: MPD_TAG_GENRE) ?? "");
returnSong.year = Int(NSString(string: tagFrom(mpdSong, tag: MPD_TAG_DATE) ?? "").intValue);
returnSong.composer = tagFrom(mpdSong, tag: MPD_TAG_COMPOSER) ?? "";
returnSong.performer = tagFrom(mpdSong, tag: MPD_TAG_PERFORMER) ?? "";
returnSong.file = "\(serverInfo.directory)/\(returnSong.uri)";
/// The string from the output of the disc metadata, either blank or "#/#"
let discString = self.tagFrom(mpdSong, tag: MPD_TAG_DISC) ?? "";
if discString != "" && discString.contains("/") {
returnSong.disc = Int(NSString(string: discString.components(separatedBy: "/").first!).intValue);
returnSong.discCount = Int(NSString(string: discString.components(separatedBy: "/").last!).intValue);
}
returnSong.duration = Int(mpd_song_get_duration(mpdSong));
returnSong.position = Int(mpd_song_get_pos(mpdSong));
mpd_song_free(mpdSong);
return returnSong;
}
/// Gets the value of the given tag for the given `mpd_song`
///
/// - Parameters:
/// - mpdSong: The song to get the tag value from
/// - tag: The tag to get the value of
/// - Returns: The string value of the `tag` tag from `mpdSong`, nil if the tag was nil
private func tagFrom(_ mpdSong : OpaquePointer, tag : mpd_tag_type) -> String? {
let tagObject = mpd_song_get_tag(mpdSong, tag, 0);
if tagObject != nil {
let tagData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: tagObject!), count: Int(strlen(tagObject)), deallocator: .none);
return String(data: tagData, encoding: .utf8);
}
else {
return nil;
}
}
/// Returns the `PlayingState` from the given `mpd_state`
///
/// - Parameter state: The `mpd_state` to get the `PlayingState` of
/// - Returns: The `PlayingState` of `state`
private func playingStateFrom(mpdState : mpd_state) -> PlayingState {
switch(mpdState) {
case MPD_STATE_PLAY:
return .playing;
case MPD_STATE_PAUSE:
return .paused;
case MPD_STATE_STOP, MPD_STATE_UNKNOWN:
return .stopped;
default:
return .stopped;
}
}
/// Returns all the values of the given tag type in the user's database
///
/// - Parameter tag: The `mpd_tag_type` to get the values of
/// - Returns: The string of all the values of `tag`
private func getAllValues(of tag : mpd_tag_type) -> [String] {
var values : [String] = [];
if !mpd_search_db_tags(self.connection!, tag) || !mpd_search_commit(self.connection!) {
Logger.log("MIMPD: Error retrieving all values for tag \"\(tag)\", \(self.currentErrorMessage())");
return [];
}
var tagKeyValuePair = mpd_recv_pair_tag(self.connection!, tag);
while tagKeyValuePair != nil {
if let string = String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: (tagKeyValuePair?.pointee.value)!), count: Int(strlen(tagKeyValuePair?.pointee.value)), deallocator: .none), encoding: .utf8) {
values.append(string);
}
mpd_return_pair(self.connection!, tagKeyValuePair);
tagKeyValuePair = mpd_recv_pair_tag(self.connection!, tag);
}
return values;
}
/// Returns the current error message
///
/// - Returns: The current error message
private func currentErrorMessage() -> String {
if connection != nil {
return self.errorMessageFor(connection: self.connection!);
}
return "No Error Message";
}
/// Returns the current error from MPD
///
/// - Returns: The current `MIMPDError` from MPD
func currentError() -> MIMPDError {
var error : MIMPDError = .disconnected;
if self.connection != nil {
let mpdError : mpd_error = mpd_connection_get_error(self.connection!);
switch mpdError {
case MPD_ERROR_SUCCESS:
error = .success;
break;
case MPD_ERROR_OOM:
error = .outOfMemory;
break;
case MPD_ERROR_ARGUMENT:
error = .argument;
break;
case MPD_ERROR_STATE:
error = .state;
break;
case MPD_ERROR_TIMEOUT:
error = .timeout;
break;
case MPD_ERROR_SYSTEM:
error = .system;
break;
case MPD_ERROR_RESOLVER:
error = .resolver;
break;
case MPD_ERROR_MALFORMED:
error = .malformed;
break;
case MPD_ERROR_CLOSED:
error = .connectionClosed;
break;
case MPD_ERROR_SERVER:
error = .serverError;
break;
default:
error = .other;
break;
}
}
return error;
}
/// Returns the error message for the given MPD connection
///
/// - Parameter connection: The `mpd_connection` to get the error from
/// - Returns: The error message, defaults to `"No Error Message"`
private func errorMessageFor(connection: OpaquePointer) -> String {
let error = mpd_connection_get_error_message(connection);
if error != nil {
if let message = String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: error!), count: Int(strlen(error!)), deallocator: .none), encoding: .utf8) {
return message;
}
}
return "No Error Message";
}
// MARK: - Initialization and Deinitialization
init(serverInfo : MIServerInfo) {
self.serverInfo = serverInfo;
}
deinit {
self.disconnect();
}
}
struct MIServerInfo: CustomStringConvertible {
var address : String = "127.0.0.1";
var port : Int = 6600;
/// No trailing slash
var directory : String = "\(NSHomeDirectory())/Music";
var description: String {
return "MIServerInfo: \(address):\(port) \(directory)"
}
init(address : String, port : Int, directory : String) {
self.address = address;
self.port = port;
self.directory = directory;
}
init() {
self.address = "127.0.0.1";
self.port = 6600;
self.directory = "\(NSHomeDirectory())/Music";
}
}
|
gpl-3.0
|
3acbf9134db9c5d1202be5f5ec690edc
| 33.963636 | 220 | 0.513261 | 4.713235 | false | false | false | false |
harlanhaskins/swift
|
test/Sema/diag_ambiguous_overloads.swift
|
1
|
4430
|
// RUN: %target-typecheck-verify-swift
enum E : String {
case foo = "foo"
case bar = "bar" // expected-note {{'bar' declared here}}
}
func fe(_: E) {}
func fe(_: Int) {}
func fe(_: Int, _: E) {}
func fe(_: Int, _: Int) {}
fe(E.baz) // expected-error {{type 'E' has no member 'baz'; did you mean 'bar'?}}
fe(.baz) // expected-error {{reference to member 'baz' cannot be resolved without a contextual type}}
fe(.nope, .nyet) // expected-error {{type 'Int' has no member 'nope'}}
// expected-error@-1 {{reference to member 'nyet' cannot be resolved without a contextual type}}
func fg<T>(_ f: (T) -> T) -> Void {}
fg({x in x}) // expected-error {{unable to infer type of a closure parameter 'x' in the current context}}
struct S {
func f<T>(_ i: (T) -> T, _ j: Int) -> Void {}
func f(_ d: (Double) -> Double) -> Void {}
func test() -> Void {
f({x in x}, 2) // expected-error {{unable to infer type of a closure parameter 'x' in the current context}}
}
func g<T>(_ a: T, _ b: Int) -> Void {}
func g(_ a: String) -> Void {}
func test2() -> Void {
g(.notAThing, 7) // expected-error {{cannot infer contextual base in reference to member 'notAThing'}}
}
func h(_ a: Int, _ b: Int) -> Void {}
func h(_ a: String) -> Void {}
func test3() -> Void {
h(.notAThing, 3) // expected-error {{type 'Int' has no member 'notAThing'}}
h(.notAThing) // expected-error {{type 'String' has no member 'notAThing'}}
}
}
struct School {
var name: String
}
func testDiagnoseForAmbiguityCrash(schools: [School]) {
schools.map({ $0.name }).sorted(by: { $0.nothing < $1.notAThing })
// expected-error@-1 {{value of type 'String' has no member 'nothing'}}
// expected-error@-2 {{value of type 'String' has no member 'notAThing'}}
}
class DefaultValue {
static func foo(_ a: Int) {}
static func foo(_ a: Int, _ b: Int = 1) {}
static func foo(_ a: Int, _ b: Int = 1, _ c: Int = 2) {}
}
DefaultValue.foo(1.0, 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
class Variadic {
static func foo(_ a: Int) {}
static func foo(_ a: Int, _ b: Double...) {}
}
Variadic.foo(1.0, 2.0, 3.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
//=-------------- SR-7918 --------------=/
class sr7918_Suit {
static func foo<T: Any>(_ :inout T) {}
static func foo() {}
}
class sr7918_RandomNumberGenerator {}
let myRNG = sr7918_RandomNumberGenerator() // expected-note {{change 'let' to 'var' to make it mutable}}
_ = sr7918_Suit.foo(&myRNG) // expected-error {{cannot pass immutable value as inout argument: 'myRNG' is a 'let' constant}}
//=-------------- SR-7786 --------------=/
struct sr7786 {
func foo() -> UInt { return 0 }
func foo<T: UnsignedInteger>(bar: T) -> T { // expected-note {{where 'T' = 'Int'}}
return bar
}
}
let s = sr7786()
let a = s.foo()
let b = s.foo(bar: 123) // expected-error {{instance method 'foo(bar:)' requires that 'Int' conform to 'UnsignedInteger'}}
let c: UInt = s.foo(bar: 123)
let d = s.foo(bar: 123 as UInt)
//=-------------- SR-7440 --------------=/
struct sr7440_ITunesGenre {
let genre: Int // expected-note {{'genre' declared here}}
let name: String
}
class sr7440_Genre {
static func fetch<B: BinaryInteger>(genreID: B, name: String) {}
static func fetch(_ iTunesGenre: sr7440_ITunesGenre) -> sr7440_Genre {
return sr7440_Genre.fetch(genreID: iTunesGenre.genreID, name: iTunesGenre.name)
// expected-error@-1 {{value of type 'sr7440_ITunesGenre' has no member 'genreID'; did you mean 'genre'?}}
// expected-error@-2 {{cannot convert return expression of type '()' to return type 'sr7440_Genre'}}
}
}
//=-------------- SR-5154 --------------=/
protocol sr5154_Scheduler {
func inBackground(run task: @escaping () -> Void)
}
extension sr5154_Scheduler {
func inBackground(run task: @escaping () -> [Count], completedBy resultHandler: @escaping ([Count]) -> Void) {}
}
struct Count { // expected-note {{'init(title:)' declared here}}
let title: String
}
func getCounts(_ scheduler: sr5154_Scheduler, _ handler: @escaping ([Count]) -> Void) {
scheduler.inBackground(run: {
return [Count()] // expected-error {{missing argument for parameter 'title' in call}}
}, completedBy: { // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{20-20= _ in}}
})
}
|
apache-2.0
|
d55c8846ae0d05f250d4f6d4eb195440
| 33.609375 | 154 | 0.624831 | 3.328325 | false | false | false | false |
CWFred/RainMaker
|
RainMaker/MapViewController.swift
|
1
|
2758
|
//
// MapViewController.swift
// RainMaker
//
// Created by Jean Piard on 12/11/16.
// Copyright © 2016 Jean Piard. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
var locationDevice: CLLocation!
var locationUser: CLLocation!
class MapViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
let manager = CLLocationManager()
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.02, 0.02)
@IBOutlet weak var viewDevButton: UIButton!
@IBAction func displayUser(_ sender: Any) {
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationUser.coordinate.latitude, locationUser.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
}
@IBAction func displayDevice(_ sender: Any) {
let dropPin = MKPointAnnotation()
dropPin.coordinate = locationDevice.coordinate
dropPin.title = "Device Location"
mapView.addAnnotation(dropPin)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationDevice.coordinate.latitude, locationDevice.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
locationUser = locations[0];
}
override func viewDidLoad()
{
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
mapView.mapType = .hybrid
if ((locationinString) != nil){
var latlong : [String]
latlong = locationinString.components(separatedBy: ",")
locationDevice = CLLocation(latitude: Double(latlong[0])!, longitude: Double(latlong[1])!)
}
else{
viewDevButton.isEnabled = false
viewDevButton.isHidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
9c4f9bf07f79915725912f189c369ed0
| 29.633333 | 151 | 0.585419 | 6.019651 | false | false | false | false |
Antondomashnev/FBSnapshotsViewer
|
FBSnapshotsViewer/Event Filters/FolderEventFilter.swift
|
1
|
1269
|
//
// FolderEventFilter.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 18/02/2017.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Foundation
indirect enum FolderEventFilter {
case known
case pathRegex(String)
case type(FolderEventObject)
case compound(FolderEventFilter, FolderEventFilter)
func apply(to event: FolderEvent) -> Bool {
switch self {
case let .type(type):
guard let object = event.object else {
return false
}
return object == type
case let .pathRegex(regex):
guard let path = event.path else {
return false
}
return path.range(of: regex, options: NSString.CompareOptions.regularExpression) != nil
case .known:
switch event {
case .unknown:
return false
default: return true
}
case let .compound(filter1, filter2):
return filter1.apply(to: event) && filter2.apply(to: event)
}
}
}
extension FolderEventFilter: AutoEquatable {}
func & (lhs: FolderEventFilter, rhs: FolderEventFilter) -> FolderEventFilter {
return FolderEventFilter.compound(lhs, rhs)
}
|
mit
|
2eba48abd5a376685ffbea2d16c83035
| 27.177778 | 99 | 0.606467 | 4.480565 | false | false | false | false |
netguru/inbbbox-ios
|
Inbbbox/Source Files/Views/UITableViewCell/DetailsCell.swift
|
1
|
1959
|
//
// DetailsCell.swift
// Inbbbox
//
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
import PureLayout
class DetailsCell: UITableViewCell, Reusable {
let detailLabel = UILabel.newAutoLayout()
let titleLabel = UILabel.newAutoLayout()
fileprivate var didSetConstraints = false
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
accessoryType = .disclosureIndicator
titleLabel.font = UIFont.systemFont(ofSize: 17, weight: UIFontWeightRegular)
titleLabel.adjustsFontSizeToFitWidth = true
contentView.addSubview(titleLabel)
detailLabel.textColor = UIColor.followeeTextGrayColor()
detailLabel.textAlignment = .right
contentView.addSubview(detailLabel)
setNeedsUpdateConstraints()
}
@available(*, unavailable, message: "Use init(style:reuseIdentifier:) method instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
if !didSetConstraints {
didSetConstraints = true
titleLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: 16)
titleLabel.autoAlignAxis(toSuperviewAxis: .horizontal)
detailLabel.autoPinEdge(.leading, to: .trailing, of: titleLabel, withOffset: 5)
detailLabel.autoPinEdge(toSuperviewEdge: .trailing)
detailLabel.autoPinEdge(toSuperviewEdge: .top, withInset: 12)
}
super.updateConstraints()
}
func setDetailText(_ text: String) {
detailLabel.text = text
}
}
extension DetailsCell: ColorModeAdaptable {
func adaptColorMode(_ mode: ColorModeType) {
titleLabel.textColor = mode.tableViewCellTextColor
selectedBackgroundView = UIView.withColor(mode.settingsSelectedCellBackgound)
}
}
|
gpl-3.0
|
80046bd7910fb1043a7d783b3c7e329f
| 29.59375 | 91 | 0.696629 | 5.277628 | false | false | false | false |
aquarchitect/MyKit
|
Sources/Shared/Extensions/Foundation/Bundle+.swift
|
1
|
1085
|
//
// Bundle+.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2015 Hai Nguyen.
//
import Foundation
public extension Bundle {
var productName: String {
return (self.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String) ?? "Unknown"
}
var version: String {
return self.infoDictionary?[kCFBundleVersionKey as String] as? String ?? "Unknown"
}
var shortVersion: String {
return self.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
}
func launchImageName(isPortrait: Bool, size: CGSize) -> String? {
let orientation = isPortrait ? "Portrait" : "Landscape"
return self.infoDictionary?["UILaunchImages"]
.flatMap({ $0 as? [[String: Any]] })?
.first {
($0["UILaunchImageSize"] as? String) == (NSStringFromCGSize(size) as String)
&& ($0["UILaunchImageOrientation"] as? String) == orientation
}.flatMap {
$0["UILaunchImageName"] as? String
}
}
}
|
mit
|
b7af0290c8fbb72782546d4b22e46d69
| 28.324324 | 102 | 0.591705 | 4.539749 | false | false | false | false |
tjw/swift
|
stdlib/public/core/ImplicitlyUnwrappedOptional.swift
|
3
|
1078
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An optional type that allows implicit member access.
///
/// The `ImplicitlyUnwrappedOptional` type is deprecated. To create an optional
/// value that is implicitly unwrapped, place an exclamation mark (`!`) after
/// the type that you want to denote as optional.
///
/// // An implicitly unwrapped optional integer
/// let guaranteedNumber: Int! = 6
///
/// // An optional integer
/// let possibleNumber: Int? = 5
@available(*, unavailable, renamed: "Optional")
public typealias ImplicitlyUnwrappedOptional<Wrapped> = Optional<Wrapped>
|
apache-2.0
|
5b2484c838e0a1bf347c6ad13029f93a
| 42.12 | 80 | 0.615028 | 5.061033 | false | false | false | false |
MiezelKat/AWSense
|
AWSenseConnect/Shared/DataTransmissionMode.swift
|
1
|
928
|
//
// DataTransmissionMode.swift
// AWSenseConnect
//
// Created by Katrin Haensel on 02/03/2017.
// Copyright © 2017 Katrin Haensel. All rights reserved.
//
import Foundation
//public enum DataTransmissionMode : String{
// case shortIntervall
// case longIntervall
//}
public struct DataTransmissionInterval{
public static let standard = DataTransmissionInterval(10)
private let lowerBound = 1.0
private let upperBound = 30.0
private var _intervallSeconds : Double = 10.0
/// The Interval in Seconds. Lower Bound 1, Upper bound 30
public var intervallSeconds : Double {
get{
return _intervallSeconds
}
set (val){
if(val > lowerBound && val < upperBound){
_intervallSeconds = val
}
}
}
public init(_ interv: Double){
intervallSeconds = interv
}
}
|
mit
|
7445372608506a16b0735bcd31233284
| 21.071429 | 62 | 0.606257 | 4.156951 | false | false | false | false |
mluisbrown/Memories
|
Memories/Settings/SettingsViewModel.swift
|
1
|
2441
|
import Foundation
import Core
import ReactiveSwift
import PHAssetHelper
import Photos
struct SettingsViewModel {
let assetHelper = PHAssetHelper()
let notificationsEnabled = MutableProperty<Bool>(false)
let notificationTime = MutableProperty(Current.notificationsController.notificationTime())
let sourceIncludeCurrentYear: MutableProperty<Bool>
let sourcePhotoLibrary: MutableProperty<Bool>
let sourceICloudShare: MutableProperty<Bool>
let sourceITunes: MutableProperty<Bool>
init() {
let sources = assetHelper.assetSourceTypes
self.sourceIncludeCurrentYear = MutableProperty(assetHelper.includeCurrentYear)
self.sourcePhotoLibrary = MutableProperty(sources.contains(.typeUserLibrary))
self.sourceICloudShare = MutableProperty(sources.contains(.typeCloudShared))
self.sourceITunes = MutableProperty(sources.contains(.typeiTunesSynced))
Current.notificationsController.notificationsAllowed()
.map { $0 && Current.notificationsController.notificationsEnabled() }
.startWithValues { [notificationsEnabled] enabled in
notificationsEnabled.swap(enabled)
}
}
func persist() {
// schedule or disable notifications
if notificationsEnabled.value {
Current.notificationsController.setNotificationTime(notificationTime.value.hour, notificationTime.value.minute)
Current.notificationsController.scheduleNotifications()
} else {
Current.notificationsController.disableNotifications()
}
// save the chosen source types
var sources = PHAssetSourceType(rawValue: 0)
if sourcePhotoLibrary.value { _ = sources.insert(.typeUserLibrary) }
if sourceICloudShare.value { _ = sources.insert(.typeCloudShared) }
if sourceITunes.value { _ = sources.insert(.typeiTunesSynced) }
let includeCurrentYear = sourceIncludeCurrentYear.value
if sources != assetHelper.assetSourceTypes ||
includeCurrentYear != assetHelper.includeCurrentYear {
assetHelper.assetSourceTypes = sources
assetHelper.includeCurrentYear = includeCurrentYear
assetHelper.refreshDatesMapCache()
NotificationCenter.default.post(name: Notification.Name(rawValue: PHAssetHelper.sourceTypesChangedNotification), object: self)
}
}
}
|
mit
|
91ed226cfa482e3c5dab0ccb5997959d
| 41.824561 | 138 | 0.713232 | 5.535147 | false | false | false | false |
S-Shimotori/Chalcedony
|
Chalcedony/ChalcedonyTests/CCDStayLaboDataProcessorTests.swift
|
1
|
26243
|
//
// CCDStayLaboDataProcessorTestCase.swift
// Chalcedony
//
// Created by S-Shimotori on 7/4/15.
// Copyright (c) 2015 S-Shimotori. All rights reserved.
//
import UIKit
import XCTest
import Nimble
import Quick
class CCDStayLaboDataProcessorTests: QuickSpec {
private enum IT: String {
case ProceededValue = "has processed correctly data"
case NumberOfDay = "has the correct number of data"
}
override func spec() {
describe("data when you laboin and laborida") {
var processedData: CCDCalculatedData!
context("when you get one data per day") {
beforeEach {
let stayLaboDataList = [
//Sunday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 0, minute: 0, second: 10)),
//Monday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 10, second: 0)),
//Tuesday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 23, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 23, hour: 10, minute: 0, second: 0)),
//Wednesday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 24, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 24, hour: 0, minute: 10, second: 10)),
//Thursday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 25, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 25, hour: 10, minute: 0, second: 10)),
//Friday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 26, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 26, hour: 10, minute: 10, second: 0)),
//Saturday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 27, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 27, hour: 10, minute: 10, second: 10)),
]
let dataProcessor = CCDStayLaboDataProcessor(stayLaboDataList: stayLaboDataList)
processedData = dataProcessor.processStayLaboData()
}
it(IT.ProceededValue.rawValue) {
expect(processedData.totalByMonth[CCDMonth.June.hashValue]).to(equal( 40 * 3600 + 40 * 60 + 40))
expect(processedData.totalByWeekday[CCDWeekday.Sunday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Monday.hashValue]).to(equal( 0 * 3600 + 10 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Tuesday.hashValue]).to(equal( 10 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Wednesday.hashValue]).to(equal( 0 * 3600 + 10 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Thursday.hashValue]).to(equal( 10 * 3600 + 0 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Friday.hashValue]).to(equal( 10 * 3600 + 10 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Saturday.hashValue]).to(equal( 10 * 3600 + 10 * 60 + 10))
}
it(IT.NumberOfDay.rawValue) {
expect(processedData.numberByMonth).to(equal([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
expect(processedData.numberByWeekday).to(equal([1, 1, 1, 1, 1, 1, 1]))
}
}
context("when data extends the following day") {
beforeEach {
let stayLaboDataList = [
//Sunday -> Monday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 0, second: 10)),
//Tuesday -> Wednesday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 23, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 24, hour: 0, minute: 10, second: 0)),
//Thursday -> Friday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 25, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 26, hour: 10, minute: 0, second: 10)),
//Saturday -> Sunday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 27, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 28, hour: 10, minute: 10, second: 10)),
]
let dataProcessor = CCDStayLaboDataProcessor(stayLaboDataList: stayLaboDataList)
processedData = dataProcessor.processStayLaboData()
}
it(IT.ProceededValue.rawValue) {
expect(processedData.totalByMonth[CCDMonth.June.hashValue]).to(equal( 116 * 3600 + 20 * 60 + 30))
expect(processedData.totalByWeekday[CCDWeekday.Sunday.hashValue]).to(equal( 34 * 3600 + 10 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Monday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Tuesday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Wednesday.hashValue]).to(equal( 0 * 3600 + 10 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Thursday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Friday.hashValue]).to(equal( 10 * 3600 + 0 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Saturday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
}
it(IT.NumberOfDay.rawValue) {
expect(processedData.numberByMonth).to(equal([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
expect(processedData.numberByWeekday).to(equal([2, 1, 1, 1, 1, 1, 1]))
}
}
context("when data's order is reversed") {
beforeEach {
let stayLaboDataList = [
//Saturday -> Sunday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 27, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 28, hour: 10, minute: 10, second: 10)),
//Thursday -> Friday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 25, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 26, hour: 10, minute: 0, second: 10)),
//Tuesday -> Wednesday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 23, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 24, hour: 0, minute: 10, second: 0)),
//Sunday -> Monday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 0, second: 10)),
]
let dataProcessor = CCDStayLaboDataProcessor(stayLaboDataList: stayLaboDataList)
processedData = dataProcessor.processStayLaboData()
}
it(IT.ProceededValue.rawValue) {
expect(processedData.totalByMonth[CCDMonth.June.hashValue]).to(equal( 116 * 3600 + 20 * 60 + 30))
expect(processedData.totalByWeekday[CCDWeekday.Sunday.hashValue]).to(equal( 34 * 3600 + 10 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Monday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Tuesday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Wednesday.hashValue]).to(equal( 0 * 3600 + 10 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Thursday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Friday.hashValue]).to(equal( 10 * 3600 + 0 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Saturday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
}
it(IT.NumberOfDay.rawValue) {
expect(processedData.numberByMonth).to(equal([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
expect(processedData.numberByWeekday).to(equal([2, 1, 1, 1, 1, 1, 1]))
}
}
context("when data are duplicate") {
beforeEach {
let stayLaboDataList = [
//Sunday -> Monday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 0, second: 10)),
//Monday -> Tuesday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 23, hour: 0, minute: 10, second: 0)),
//Tuesday -> Wednesday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 23, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 24, hour: 10, minute: 0, second: 0)),
//Wednesday -> Thursday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 24, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 25, hour: 0, minute: 10, second: 10)),
//Thursday -> Friday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 25, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 26, hour: 10, minute: 0, second: 10)),
//Friday -> Saturday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 26, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 27, hour: 10, minute: 10, second: 0)),
//Saturday -> Sunday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 27, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 28, hour: 10, minute: 10, second: 10)),
]
let dataProcessor = CCDStayLaboDataProcessor(stayLaboDataList: stayLaboDataList)
processedData = dataProcessor.processStayLaboData()
}
it(IT.ProceededValue.rawValue) {
expect(processedData.totalByMonth[CCDMonth.June.hashValue]).to(equal( 178 * 3600 + 10 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Sunday.hashValue]).to(equal( 34 * 3600 + 10 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Monday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Tuesday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Wednesday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Thursday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Friday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Saturday.hashValue]).to(equal( 24 * 3600 + 0 * 60 + 0))
}
it(IT.NumberOfDay.rawValue) {
expect(processedData.numberByMonth).to(equal([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
expect(processedData.numberByWeekday).to(equal([2, 1, 1, 1, 1, 1, 1]))
}
}
context("when data are redundant") {
beforeEach {
let stayLaboDataList = [
//Sunday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 9, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 17, minute: 0, second: 0)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 10, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 12, minute: 0, second: 0)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 11, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 13, minute: 0, second: 0)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 14, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 16, minute: 0, second: 0)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 16, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 17, minute: 0, second: 0)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 17, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 18, minute: 0, second: 0)),
]
let dataProcessor = CCDStayLaboDataProcessor(stayLaboDataList: stayLaboDataList)
processedData = dataProcessor.processStayLaboData()
}
it(IT.ProceededValue.rawValue) {
expect(processedData.totalByMonth[CCDMonth.June.hashValue]).to(equal( 9 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Sunday.hashValue]).to(equal( 9 * 3600 + 0 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Monday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Tuesday.hashValue]).to(equal( 0 * 3600 + 0 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Wednesday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Thursday.hashValue]).to(equal( 0 * 3600 + 0 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Friday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Saturday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
}
it(IT.NumberOfDay.rawValue) {
expect(processedData.numberByMonth).to(equal([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
expect(processedData.numberByWeekday).to(equal([1, 0, 0, 0, 0, 0, 0]))
}
}
context("when data are on the same day") {
beforeEach {
let stayLaboDataList = [
//Sunday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 0, minute: 0, second: 10)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 21, hour: 1, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 21, hour: 1, minute: 0, second: 10)),
//Monday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 22, hour: 0, minute: 10, second: 0)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 22, hour: 1, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 22, hour: 1, minute: 10, second: 0)),
//Wednesday
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 24, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 24, hour: 0, minute: 10, second: 10)),
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 24, hour: 1, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 24, hour: 1, minute: 10, second: 10)),
]
let dataProcessor = CCDStayLaboDataProcessor(stayLaboDataList: stayLaboDataList)
processedData = dataProcessor.processStayLaboData()
}
it(IT.ProceededValue.rawValue) {
expect(processedData.totalByMonth[CCDMonth.June.hashValue]).to(equal( 0 * 3600 + 40 * 60 + 40))
expect(processedData.totalByWeekday[CCDWeekday.Sunday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 20))
expect(processedData.totalByWeekday[CCDWeekday.Monday.hashValue]).to(equal( 0 * 3600 + 20 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Tuesday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Wednesday.hashValue]).to(equal( 0 * 3600 + 20 * 60 + 20))
expect(processedData.totalByWeekday[CCDWeekday.Thursday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Friday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Saturday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
}
it(IT.NumberOfDay.rawValue) {
expect(processedData.numberByMonth).to(equal([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
expect(processedData.numberByWeekday).to(equal([1, 1, 1, 1, 0, 0, 0]))
}
}
context("when data extends the following month") {
beforeEach {
let stayLaboDataList = [
//Tuesday(June)
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 30, hour: 0, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .June , day: 30, hour: 0, minute: 0, second: 10)),
//Tuesday(June) -> Wednesday(July)
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 30, hour: 20, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .July , day: 1, hour: 5, minute: 0, second: 0)),
//Tuesday(June) -> Wednesday(July)
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 30, hour: 22, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .July , day: 1, hour: 4, minute: 0, second: 0)),
//Tuesday(June) -> Wednesday(July)
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .June , day: 30, hour: 23, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .July , day: 1, hour: 6, minute: 0, second: 0)),
//Wednesday(July)
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .July , day: 1, hour: 9, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .July , day: 1, hour: 17, minute: 0, second: 0)),
//Wednesday(July)
CCDStayLaboData(
laboinDate: self.makeNSDate(2015, month: .July , day: 1, hour: 18, minute: 0, second: 0),
laboridaDate: self.makeNSDate(2015, month: .July , day: 1, hour: 19, minute: 0, second: 0)),
]
let dataProcessor = CCDStayLaboDataProcessor(stayLaboDataList: stayLaboDataList)
processedData = dataProcessor.processStayLaboData()
}
it(IT.ProceededValue.rawValue) {
expect(processedData.totalByMonth[CCDMonth.June.hashValue]).to(equal( 4 * 3600 + 0 * 60 + 10))
expect(processedData.totalByMonth[CCDMonth.July.hashValue]).to(equal( 15 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Sunday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Monday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Tuesday.hashValue]).to(equal( 4 * 3600 + 0 * 60 + 10))
expect(processedData.totalByWeekday[CCDWeekday.Wednesday.hashValue]).to(equal( 15 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Thursday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Friday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
expect(processedData.totalByWeekday[CCDWeekday.Saturday.hashValue]).to(equal( 0 * 3600 + 0 * 60 + 0))
}
it(IT.NumberOfDay.rawValue) {
expect(processedData.numberByMonth).to(equal([0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0]))
expect(processedData.numberByWeekday).to(equal([0, 0, 1, 1, 0, 0, 0]))
}
}
}
}
private func makeNSDate(year: Int, month: CCDMonth, day: Int, hour: Int, minute: Int, second: Int) -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.year = year
components.month = month.rawValue
components.day = day
components.hour = hour
components.minute = minute
components.second = second
return calendar.dateFromComponents(components)!
}
}
|
mit
|
716e6e3d87bffb487fc0c4642160dbbb
| 73.769231 | 128 | 0.505963 | 3.932714 | false | false | false | false |
hatjs880328/DZHTTPRequest
|
HTTPRequest/HTTPRequestWithAlamofire.swift
|
1
|
6643
|
//
// AlamofireDatatool.swift
// DataPresistenceLayer
// is 1.0.3
// Created by MrShan on 16/6/13.
// Copyright © 2016年 Mrshan. All rights reserved.
//
import Foundation
import Alamofire
import RealReachability
/// 每个实例化网络请求的成功执行闭包
var HTTPRequestSuccessAction: [Int : (response:ResponseClass)->Void] = [:]
/// 每个实例化网络请求的错误执行闭包
var HTTPRequestErrorAction: [Int: (errorType:ERRORMsgType)->Void] = [:]
/// 网络请求类
public class HTTPRequestWithAlamofire: NSObject {
var GLOBAL_THIS_APPID = "082D63FA-B62F-4228-B758-B4D573AC2870"
//MARK:参数列表声明
/// 变量记录是否需要提示错误信息
var alertinfoShouldShow:HTTPERRORInfoShow!
/// 记录哪个页面发起的调用,可以为NIL
var viewcontroller:UIViewController?
/// 发起请求的URL
var url:String!
/// 参数列表可以为NIL
var params:[String:AnyObject]?
/// 请求头部可以为NIL
var header:[String : String]?
//MARK:构造方法声明
/**
init
- returns: self
*/
public override init() {
super.init()
}
/**
需要准确判断网络,成功、失败俩闭包的网络请求方法
- parameter alertinfoShouleShow: 是否需要展示错误信息
- parameter viewcontroller: 那个控制器调用的此方法
- parameter url: URL
- parameter params: 参数
- parameter header: HEADER
- parameter successAction: 成功闭包
- parameter errorAction: 失败闭包
*/
public func startRequest(alertinfoShouldShow:HTTPERRORInfoShow = HTTPERRORInfoShow.shouldShow,viewcontroller:UIViewController?,url:String, params:[String:AnyObject]?,header:[String : String]?,successAction:(response:ResponseClass)->Void,errorAction:(errorType:ERRORMsgType)->Void) {
self.alertinfoShouldShow = alertinfoShouldShow
self.viewcontroller = viewcontroller
self.url = url
self.params = params
self.header = header
HTTPRequestSuccessAction[self.hashValue] = successAction
HTTPRequestErrorAction[self.hashValue] = errorAction
//09.8 调用了新的PING功能
RealReachability.sharedInstance().hostForPing = "www.baidu.com"
RealReachability.sharedInstance().startNotifier()
RealReachability.sharedInstance().reachabilityWithBlock { (statue) -> Void in
if statue != ReachabilityStatus.RealStatusNotReachable {
self.AlamofireRequestwithSuccessAndErrorClosure(self.alertinfoShouldShow, viewcontroller: self.viewcontroller, url: self.url, params: self.params, header: self.header, successAction: HTTPRequestSuccessAction[self.hashValue]!, errorAction: HTTPRequestErrorAction[self.hashValue]!)
}else{
//一次PING失败会发起第二次ping,两次PING连续失败的几率可以忽略<这里需要放到主线程中操作,因为有可能是主线程操作!>
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
RealReachability.sharedInstance().reachabilityWithBlock { (statue) -> Void in
if statue != ReachabilityStatus.RealStatusNotReachable {
self.AlamofireRequestwithSuccessAndErrorClosure(self.alertinfoShouldShow, viewcontroller: self.viewcontroller, url: self.url, params: self.params, header: self.header, successAction: HTTPRequestSuccessAction[self.hashValue]!, errorAction: HTTPRequestErrorAction[self.hashValue]!)
}else{
NETWORKErrorProgress().errorMsgProgress(ERRORMsgType.networkCannotuse,ifcanshow: self.alertinfoShouldShow,errormsg:"",errorAction:HTTPRequestErrorAction[self.hashValue]!)
}
}
})
}
}
}
//MARK:真正的网络请求方法
/**
网络请求,包含成功、失败两个闭包
- parameter url: 请求URL
- parameter params: 参数列表
- parameter successAction: 成功闭包
- parameter errorAction: 失败闭包
*/
private func AlamofireRequestwithSuccessAndErrorClosure(alertinfoShouleShow:HTTPERRORInfoShow = HTTPERRORInfoShow.shouldShow,viewcontroller:UIViewController?,url:String, params:[String:AnyObject]?,header:[String : String]?,successAction:(response:ResponseClass)->Void,errorAction:(errorType:ERRORMsgType)->Void) {
//在参数列表中添加全局变量
dispatch_async(dispatch_get_main_queue()) { () -> Void in
Alamofire.request(.POST, url, parameters: params!, encoding: ParameterEncoding.JSON, headers: header).responseData { (response) -> Void in
if nil == response.data {
//返回数据为nil,在这里处理,不需要返回每个页面处理,进行ALERT即可 [ 非20x 返回值,应当查看Response的确切说明!]
NETWORKErrorProgress().errorMsgProgress(ERRORMsgType.responseError, ifcanshow: alertinfoShouleShow,errormsg:"",errorAction:errorAction)
return
}
do {
let changeData = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions.MutableContainers)
if changeData.isKindOfClass(NSDictionary) {
successAction(response: ResponseFactoary().responseInstance(ResponseType.DIC,data: changeData as! NSDictionary,alertinfoshouldshow: alertinfoShouleShow,errorAction:errorAction))
}
if changeData.isKindOfClass(NSArray) {
successAction(response: ResponseFactoary().responseInstance(ResponseType.ARRAY,data: changeData as! NSArray,alertinfoshouldshow: alertinfoShouleShow,errorAction:errorAction))
}
if changeData.isKindOfClass(NSString) {
successAction(response: ResponseFactoary().responseInstance(ResponseType.STRING,data: changeData as! String,alertinfoshouldshow: alertinfoShouleShow,errorAction:errorAction))
}
}catch let error as NSError{
//转换数据失败,多为JSON字符问题,可发送到 http://www.bejson.com/ 进行校验,analyze
NETWORKErrorProgress().errorMsgProgress(ERRORMsgType.progressError,ifcanshow: alertinfoShouleShow,errormsg: "\(error)",errorAction:errorAction)
}
}
}
}
}
|
mit
|
302565a4dc5cae0d36991f973e336b4c
| 47.306452 | 317 | 0.66177 | 4.572519 | false | false | false | false |
maxadamski/SwiftyHTTP
|
SwiftyHTTP/Parser/HTTPParser.swift
|
1
|
15566
|
//
// HTTPParser.swift
// SwiftyHTTP
//
// Created by Helge Heß on 6/18/14.
// Copyright (c) 2014 Always Right Institute. All rights reserved.
//
public enum HTTPParserType {
case Request, Response, Both
}
public final class HTTPParser {
enum ParseState {
case Idle, URL, HeaderName, HeaderValue, Body
}
var parser = http_parser()
var settings = http_parser_settings()
let buffer = RawByteBuffer(capacity: 4096)
var parseState = ParseState.Idle
var isWiredUp = false
var url : String?
var lastName : String?
var headers = Dictionary<String, String>(minimumCapacity: 32)
var body : [UInt8]?
var message : HTTPMessage?
public init(type: HTTPParserType = .Both) {
var cType: http_parser_type
switch type {
case .Request: cType = HTTP_REQUEST
case .Response: cType = HTTP_RESPONSE
case .Both: cType = HTTP_BOTH
}
http_parser_init(&parser, cType)
/* configure callbacks */
// TBD: what is the better way to do this?
let ud = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
parser.data = ud
}
/* callbacks */
public func onRequest(cb: ((HTTPRequest) -> Void)?) -> Self {
requestCB = cb
return self
}
public func onResponse(cb: ((HTTPResponse) -> Void)?) -> Self {
responseCB = cb
return self
}
public func onHeaders(cb: ((HTTPMessage) -> Bool)?) -> Self {
headersCB = cb
return self
}
public func onBodyData
(cb: ((HTTPMessage, UnsafePointer<CChar>, UInt) -> Bool)?) -> Self
{
bodyDataCB = cb
return self
}
public func resetEventHandlers() {
requestCB = nil
responseCB = nil
headersCB = nil
bodyDataCB = nil
}
var requestCB : ((HTTPRequest) -> Void)?
var responseCB : ((HTTPResponse) -> Void)?
var headersCB : ((HTTPMessage) -> Bool)?
var bodyDataCB : ((HTTPMessage, UnsafePointer<CChar>, UInt) -> Bool)?
/* write */
public var bodyIsFinal: Bool {
return http_body_is_final(&parser) == 0 ? false:true
}
public func write
(buffer: UnsafePointer<CChar>, _ count: Int) -> HTTPParserError
{
// Note: the parser doesn't expect this to be 0-terminated.
let len = count
if !isWiredUp {
wireUpCallbacks()
}
let bytesConsumed = http_parser_execute(&parser, &settings, buffer, len)
let errno = http_errno(parser.http_errno)
let err = HTTPParserError(errno)
if err != .OK {
// Now hitting this, not quite sure why. Maybe a Safari feature?
let s = http_errno_name(errno)
let d = http_errno_description(errno)
debugPrint("BYTES consumed \(bytesConsumed) from \(buffer)[\(len)] " +
"ERRNO: \(err) \(s) \(d)")
}
return err
}
public func write(buffer: [CChar]) -> HTTPParserError {
let count = buffer.count
return write(buffer, count)
}
/* pending data handling */
func clearState() {
self.url = nil
self.lastName = nil
self.body = nil
self.headers.removeAll(keepCapacity: true)
}
public func addData(data: UnsafePointer<Int8>, length: Int) -> Int32 {
if parseState == .Body && bodyDataCB != nil && message != nil {
return bodyDataCB!(message!, data, UInt(length)) ? 42 : 0
}
else {
buffer.add(data, length: length)
}
return 0
}
func processDataForState
(state: ParseState, d: UnsafePointer<Int8>, l: Int) -> Int32
{
if (state == parseState) { // more data for same field
return addData(d, length: l)
}
switch parseState {
case .HeaderValue:
// finished parsing a header
assert(lastName != nil)
if let n = lastName {
headers[n] = buffer.asString()
}
buffer.reset()
lastName = nil
case .HeaderName:
assert(lastName == nil)
lastName = buffer.asString()
buffer.reset()
case .URL:
assert(url == nil)
url = buffer.asString()
buffer.reset()
case .Body:
if bodyDataCB == nil {
body = buffer.asByteArray()
}
buffer.reset()
default: // needs some block, no empty default possible
break
}
/* start a new state */
parseState = state
buffer.reset()
return addData(d, length: l)
}
public var isRequest : Bool { return parser.type == 0 }
public var isResponse : Bool { return parser.type == 1 }
public class func parserCodeToMethod(rq: UInt8) -> HTTPMethod? {
return parserCodeToMethod(http_method(CUnsignedInt(rq)))
}
public class func parserCodeToMethod(rq: http_method) -> HTTPMethod? {
var method : HTTPMethod?
// Trying to use HTTP_DELETE gives http_method not convertible to
// _OptionalNilComparisonType
switch rq { // hardcode C enum value, defines from http_parser n/a
case HTTP_DELETE: method = HTTPMethod.DELETE
case HTTP_GET: method = HTTPMethod.GET
case HTTP_HEAD: method = HTTPMethod.HEAD
case HTTP_POST: method = HTTPMethod.POST
case HTTP_PUT: method = HTTPMethod.PUT
case HTTP_CONNECT: method = HTTPMethod.CONNECT
case HTTP_OPTIONS: method = HTTPMethod.OPTIONS
case HTTP_TRACE: method = HTTPMethod.TRACE
case HTTP_COPY: method = HTTPMethod.COPY
case HTTP_LOCK: method = HTTPMethod.LOCK
case HTTP_MKCOL: method = HTTPMethod.MKCOL
case HTTP_MOVE: method = HTTPMethod.MOVE
case HTTP_PROPFIND: method = HTTPMethod.PROPFIND
case HTTP_PROPPATCH: method = HTTPMethod.PROPPATCH
case HTTP_SEARCH: method = HTTPMethod.SEARCH
case HTTP_UNLOCK: method = HTTPMethod.UNLOCK
case HTTP_REPORT: method = HTTPMethod.REPORT((nil, nil))
// FIXME: peek body ..
case HTTP_MKACTIVITY: method = HTTPMethod.MKACTIVITY
case HTTP_CHECKOUT: method = HTTPMethod.CHECKOUT
case HTTP_MERGE: method = HTTPMethod.MERGE
case HTTP_MSEARCH: method = HTTPMethod.MSEARCH
case HTTP_NOTIFY: method = HTTPMethod.NOTIFY
case HTTP_SUBSCRIBE: method = HTTPMethod.SUBSCRIBE
case HTTP_UNSUBSCRIBE: method = HTTPMethod.UNSUBSCRIBE
case HTTP_PATCH: method = HTTPMethod.PATCH
case HTTP_PURGE: method = HTTPMethod.PURGE
case HTTP_MKCALENDAR: method = HTTPMethod.MKCALENDAR
default:
// Note: extra custom methods don't work (I think)
method = nil
}
return method
}
func headerFinished() -> Int32 {
self.processDataForState(.Body, d: "", l: 0)
message = nil
let major = parser.http_major
let minor = parser.http_minor
if isRequest {
let method = HTTPParser.parserCodeToMethod(http_method(parser.method))
message = HTTPRequest(method: method!, url: url!,
version: ( Int(major), Int(minor) ),
headers: headers)
self.clearState()
}
else if isResponse {
let status = parser.status_code
// TBD: also grab status text? Doesn't matter in the real world ...
message = HTTPResponse(status: HTTPStatus(rawValue: Int(status))!,
version: ( Int(major), Int(minor) ),
headers: headers)
self.clearState()
}
else { // FIXME: PS style great error handling
debugPrint("Unexpected message? \(parser.type)")
assert(parser.type == 0 || parser.type == 1)
}
if let m = message {
if let cb = headersCB {
return cb(m) ? 0 : 42
}
}
return 0
}
func messageFinished() -> Int32 {
self.processDataForState(.Idle, d: "", l: 0)
if let m = message {
m.bodyAsByteArray = body
if let rq = m as? HTTPRequest {
if let cb = requestCB {
cb(rq)
}
}
else if let res = m as? HTTPResponse {
if let cb = responseCB {
cb(res)
}
}
else {
assert(false, "Expected Request or Response object")
}
return 0
}
else {
debugPrint("did not parse a message ...")
return 42
}
}
/* callbacks */
func wireUpCallbacks() {
// Note: CString is NOT a real C string, it's length terminated
settings.on_message_begin = { parser in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.message = nil
me.clearState()
return 0
}
settings.on_message_complete = { parser in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.messageFinished()
return 0
}
settings.on_headers_complete = { parser in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.headerFinished()
return 0
}
settings.on_url = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.URL, d: data, l: len)
return 0
}
settings.on_header_field = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.HeaderName, d: data, l: len)
return 0
}
settings.on_header_value = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.HeaderValue, d: data, l: len)
return 0
}
settings.on_body = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.Body, d: data, l: len)
return 0
}
}
}
extension HTTPParser : CustomStringConvertible {
public var description : String {
return "<HTTPParser \(parseState) @\(buffer.count)>"
}
}
public enum HTTPParserError : CustomStringConvertible {
// manual mapping, Swift doesn't directly bridge the http_parser macros but
// rather creates constants for them
case OK
case cbMessageBegin, cbURL, cbBody, cbMessageComplete, cbStatus
case cbHeaderField, cbHeaderValue, cbHeadersComplete
case InvalidEOFState, HeaderOverflow, ClosedConnection
case InvalidVersion, InvalidStatus, InvalidMethod, InvalidURL
case InvalidHost, InvalidPort, InvalidPath, InvalidQueryString
case InvalidFragment
case LineFeedExpected
case InvalidHeaderToken, InvalidContentLength, InvalidChunkSize
case InvalidConstant, InvalidInternalState
case NotStrict, Paused
case Unknown
public init(_ errcode: http_errno) {
switch (errcode) {
case HPE_OK: self = .OK
case HPE_CB_message_begin: self = .cbMessageBegin
case HPE_CB_url: self = .cbURL
case HPE_CB_header_field: self = .cbHeaderField
case HPE_CB_header_value: self = .cbHeaderValue
case HPE_CB_headers_complete: self = .cbHeadersComplete
case HPE_CB_body: self = .cbBody
case HPE_CB_message_complete: self = .cbMessageComplete
case HPE_CB_status: self = .cbStatus
case HPE_INVALID_EOF_STATE: self = .InvalidEOFState
case HPE_HEADER_OVERFLOW: self = .HeaderOverflow
case HPE_CLOSED_CONNECTION: self = .ClosedConnection
case HPE_INVALID_VERSION: self = .InvalidVersion
case HPE_INVALID_STATUS: self = .InvalidStatus
case HPE_INVALID_METHOD: self = .InvalidMethod
case HPE_INVALID_URL: self = .InvalidURL
case HPE_INVALID_HOST: self = .InvalidHost
case HPE_INVALID_PORT: self = .InvalidPort
case HPE_INVALID_PATH: self = .InvalidPath
case HPE_INVALID_QUERY_STRING: self = .InvalidQueryString
case HPE_INVALID_FRAGMENT: self = .InvalidFragment
case HPE_LF_EXPECTED: self = .LineFeedExpected
case HPE_INVALID_HEADER_TOKEN: self = .InvalidHeaderToken
case HPE_INVALID_CONTENT_LENGTH: self = .InvalidContentLength
case HPE_INVALID_CHUNK_SIZE: self = .InvalidChunkSize
case HPE_INVALID_CONSTANT: self = .InvalidConstant
case HPE_INVALID_INTERNAL_STATE: self = .InvalidInternalState
case HPE_STRICT: self = .NotStrict
case HPE_PAUSED: self = .Paused
case HPE_UNKNOWN: self = .Unknown
default: self = .Unknown
}
}
public var description : String { return errorDescription }
public var errorDescription : String {
switch self {
case OK: return "Success"
case cbMessageBegin: return "The on_message_begin callback failed"
case cbURL: return "The on_url callback failed"
case cbBody: return "The on_body callback failed"
case cbMessageComplete:
return "The on_message_complete callback failed"
case cbStatus: return "The on_status callback failed"
case cbHeaderField: return "The on_header_field callback failed"
case cbHeaderValue: return "The on_header_value callback failed"
case cbHeadersComplete:
return "The on_headers_complete callback failed"
case InvalidEOFState: return "Stream ended at an unexpected time"
case HeaderOverflow:
return "Too many header bytes seen; overflow detected"
case ClosedConnection:
return "Data received after completed connection: close message"
case InvalidVersion: return "Invalid HTTP version"
case InvalidStatus: return "Invalid HTTP status code"
case InvalidMethod: return "Invalid HTTP method"
case InvalidURL: return "Invalid URL"
case InvalidHost: return "Invalid host"
case InvalidPort: return "Invalid port"
case InvalidPath: return "Invalid path"
case InvalidQueryString: return "Invalid query string"
case InvalidFragment: return "Invalid fragment"
case LineFeedExpected: return "LF character expected"
case InvalidHeaderToken: return "Invalid character in header"
case InvalidContentLength:
return "Invalid character in content-length header"
case InvalidChunkSize: return "Invalid character in chunk size header"
case InvalidConstant: return "Invalid constant string"
case InvalidInternalState: return "Encountered unexpected internal state"
case NotStrict: return "Strict mode assertion failed"
case Paused: return "Parser is paused"
default: return "Unknown Error"
}
}
}
/* hack to make some structs work */
// FIXME: can't figure out how to access errcode.value. Maybe because it
// is not 'public'?
extension http_errno : Equatable {
// struct: init(_ value: UInt32); var value: UInt32;
}
extension http_method : Equatable {
// struct: init(_ value: UInt32); var value: UInt32;
}
public func ==(lhs: http_errno, rhs: http_errno) -> Bool {
// this just recurses (of course):
// return lhs == rhs
// this failes, maybe because it's not public?:
// return lhs.value == rhs.value
// Hard hack, does it actually work? :-)
return isByteEqual(lhs, rhs: rhs)
}
public func ==(lhs: http_method, rhs: http_method) -> Bool {
return isByteEqual(lhs, rhs: rhs)
}
|
mit
|
77fbe9c793ffe73d9bb737359719c821
| 32.187633 | 80 | 0.616833 | 4.306862 | false | false | false | false |
caronae/caronae-ios
|
Caronae/Extras/PhoneNumberActionSheet.swift
|
1
|
1573
|
import Foundation
import ContactsUI
class PhoneNumberAlert {
func actionSheet(view: UIViewController, buttonText: String, user: User) -> UIAlertController? {
guard let phoneNumber = user.phoneNumber else {
return nil
}
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Ligar para \(buttonText)", style: .default) { _ in
if let url = URL(string: "tel://\(phoneNumber)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
})
alert.addAction(UIAlertAction(title: "Adicionar aos Contatos", style: .default) { _ in
let contact = CNMutableContact()
contact.givenName = user.firstName
contact.familyName = user.lastName
contact.phoneNumbers = [CNLabeledValue(
label: CNLabelPhoneNumberMobile,
value: CNPhoneNumber(stringValue: phoneNumber))]
let store = CNContactStore()
let contactController = CNContactViewController(forUnknownContact: contact)
contactController.contactStore = store
view.self.navigationController?.show(contactController, sender: nil)
})
alert.addAction(UIAlertAction(title: "Copiar", style: .default) { _ in
UIPasteboard.general.string = phoneNumber
})
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel))
return alert
}
}
|
gpl-3.0
|
3cb0efac5310de8f976eca090de443f1
| 42.694444 | 100 | 0.625556 | 5.107143 | false | false | false | false |
Sherlouk/monzo-vapor
|
Sources/Client.swift
|
1
|
4212
|
import Foundation
import Vapor
public final class MonzoClient {
let publicKey: String
let privateKey: String
let httpClient: Responder
lazy var provider: Provider = { return Provider(client: self) }()
// Leaving this code as something that should be investigated! Getting errors with Vapor though.
// public convenience init(publicKey: String, privateKey: String, clientFactory: ClientFactoryProtocol) {
// let responder: Responder = {
// // Attempt to re-use the same client (better performance)
// if let port = URI.defaultPorts["https"],
// let client = try? clientFactory.makeClient(hostname: "api.monzo.com", port: port, securityLayer: .none) {
// return client
// }
//
// // Default Implementation (Will create a new client for every request)
// return clientFactory
// }()
//
// self.init(publicKey: publicKey, privateKey: privateKey, httpClient: responder)
// }
public init(publicKey: String, privateKey: String, httpClient: Responder) {
self.publicKey = publicKey
self.privateKey = privateKey
self.httpClient = httpClient
Monzo.setup()
}
/// Creates a new user with the provided access token required for authenticating all requests
public func createUser(userId: String, accessToken: String, refreshToken: String?) -> User {
return User(client: self, userId: userId, accessToken: accessToken, refreshToken: refreshToken)
}
/// Pings the Monzo API and returns true if a valid response was fired back
public func ping() -> Bool {
let response: String? = try? provider.request(.ping).value(forKey: "ping")
return response == "pong"
}
/// Creates a URI to Monzo's authorisation page, you should redirect users to it in order to authorise usage of their accounts
///
/// - Parameters:
/// - redirectUrl: The URL that Monzo will redirect the user back to, where you should validate and obtain the access token
/// - nonce: An unguessable/random string to prevent against CSRF attacks. Optional, but **recommended**!
/// - Returns: The URI to redirect users to
public func authorizationURI(redirectUrl: URL, nonce: String?) -> URI {
var parameters: [Parameters] = [
.basic("client_id", publicKey),
.basic("redirect_uri", redirectUrl.absoluteString),
.basic("response_type", "code")
]
if let nonce = nonce { parameters.append(.basic("state", nonce)) }
let query = parameters.map({ $0.encoded(.urlQuery) }).joined(separator: "&")
return URI(scheme: "https", hostname: "auth.getmondo.co.uk", query: query)
}
/// Validates the user has successfully authorised your client and is capable of making requests
///
/// - Parameters:
/// - req: The request when the user was redirected back to your server
/// - nonce: The nonce used when redirecting the user to Monzo
/// - Returns: On success, returns an authenticated user object for further requests
public func authenticateUser(_ req: Request, nonce: String?) throws -> User {
guard let code = req.query?["code"]?.string,
let state = req.query?["state"]?.string else { throw MonzoAuthError.missingParameters }
guard state == nonce ?? "" else { throw MonzoAuthError.conflictedNonce }
var uri = req.uri
uri.query = nil // Remove the query to just get the base URL for comparison
let url = try uri.makeFoundationURL()
let response = try provider.request(.exchangeToken(self, url, code))
let userId: String = try response.value(forKey: "user_id")
let accessToken: String = try response.value(forKey: "access_token")
let refreshToken: String? = try? response.value(forKey: "refresh_token")
return createUser(userId: userId, accessToken: accessToken, refreshToken: refreshToken)
}
}
final class Monzo {
static func setup() {
Date.incomingDateFormatters.insert(.rfc3339, at: 0)
}
}
|
mit
|
4089a1f4bc2ad63b4e22f275afae11b7
| 44.290323 | 130 | 0.641026 | 4.598253 | false | false | false | false |
phanviet/AppState
|
Example/AppState/ViewController.swift
|
1
|
1962
|
//
// ViewController.swift
// AppState
//
// Created by Viet Phan on 11/27/2015.
// Copyright (c) 2015 Viet Phan. All rights reserved.
//
import UIKit
import AppState
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func backLandingPage(context: StateContext?) {
AppWorkflow.currentViewControllerPushOrPopController(self)
}
private func showLandingPage(context: StateContext?) {
if let context = context, window = context["window"] as? UIWindow {
let nav = UINavigationController()
nav.viewControllers = [self]
window.rootViewController = nav
window.makeKeyAndVisible()
AppWorkflow.currentViewController = self
}
}
@IBAction func signInDidTouch(sender: AnyObject) {
var context = [String: AnyObject]()
context["isClearInput"] = true
AppWorkflow.sharedInstance.transitTo("showSignInPage", context: context)
}
}
extension ViewController: AppStateDelegate {
func onEnterState(eventName: String, currentState: String, from: String, to: String, context: StateContext?) {
print("@onEnter")
print("@eventName: \(eventName)")
print("@currentState: \(currentState)")
print("@from: \(from)")
print("@to: \(to)")
print("@context: \(context)")
switch eventName {
case "showLandingPage":
showLandingPage(context)
break
case "backLandingPage":
backLandingPage(context)
default:
break
}
}
func onLeaveState(eventName: String, currentState: String, from: String, to: String, context: StateContext?) {
print("@onLeave")
print("@eventName: \(eventName)")
print("@currentState: \(currentState)")
print("@from: \(from)")
print("@to: \(to)")
print("@context: \(context)")
}
}
|
mit
|
d6d90feea7844a18ea992d094a781e47
| 25.890411 | 112 | 0.667176 | 4.510345 | false | false | false | false |
yhyuan/WeatherMap
|
WeatherAroundUs/WeatherAroundUs/CitySQL.swift
|
9
|
1548
|
//
// WeatherCoreData.swift
// WeatherAroundUs
//
// Created by Kedan Li on 15/4/10.
// Copyright (c) 2015年 Kedan Li. All rights reserved.
//
/*
import UIKit
import FMDB
class CitySQL: NSObject{
var queue = FMDatabaseQueue()
override init() {
super.init()
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let dbPath = paths.stringByAppendingPathComponent("citiesInfo.db")
queue = FMDatabaseQueue(path: dbPath)
}
func saveCity(name: String, cityID: String, location: CLLocationCoordinate2D) {
queue.inDatabase { (db) -> Void in
//var search = db.executeQuery("SELECT * FROM City WHERE id LIKE ?", withArgumentsInArray: [cityID])
let sql = "insert into City(id, name, longitude, latitude) values (?, ?, ?, ?)"
db.executeUpdate(sql, withArgumentsInArray: [cityID, name, location.longitude, location.latitude])
}
}
func loadDataToTree(tree: QTree){
queue.inDatabase { (db) -> Void in
let resultSet = db.executeQuery("select * from City", withArgumentsInArray: nil)
while resultSet.next() {
let element = WeatherDataQTree(position: CLLocationCoordinate2DMake(resultSet.doubleForColumn("latitude"), resultSet.doubleForColumn("longitude")), cityID: resultSet.stringForColumn("id"))
tree.insertObject(element)
}
}
}
}
*/
|
apache-2.0
|
afd6843359aa50bf01806a0fc220b8af
| 30.571429 | 204 | 0.619017 | 4.727829 | false | false | false | false |
kstaring/swift
|
stdlib/public/SDK/Foundation/URL.swift
|
3
|
62362
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// Keys used in the result of `URLResourceValues.thumbnailDictionary`.
@available(OSX 10.10, iOS 8.0, *)
public struct URLThumbnailSizeKey : RawRepresentable, Hashable {
public typealias RawValue = String
public init(rawValue: RawValue) { self.rawValue = rawValue }
private(set) public var rawValue: RawValue
/// Key for a 1024 x 1024 thumbnail image.
static public let none: URLThumbnailSizeKey = URLThumbnailSizeKey(rawValue: URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue)
public var hashValue: Int {
return rawValue.hashValue
}
}
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
fileprivate var _values: [URLResourceKey: Any]
fileprivate var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(OSX 10.11, iOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(OSX)
/// True if the resource is scriptable. Only applies to applications.
@available(OSX 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(OSX)
/// The array of Tag names.
public var tagNames: [String]? { return _get(.tagNamesKey) }
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(OSX)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(OSX 10.10, *)
public var quarantineProperties: [String : Any]? {
get {
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if let isNull = _values[.quarantinePropertiesKey] as? NSNull {
return nil
} else {
return _values[.quarantinePropertiesKey] as? [String : Any]
}
}
set {
if let v = newValue {
_set(.quarantinePropertiesKey, newValue: newValue as NSObject?)
} else {
// Set to NSNull, a special case for deleting quarantine properties
_set(.quarantinePropertiesKey, newValue: NSNull())
}
}
}
#endif
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
/// Total number of resources on the volume.
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
/// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// true if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// true if the volume format supports hard links.
public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) }
/// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) }
/// true if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) }
/// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// true if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// true if the volume can be renamed.
public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) }
/// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// true if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) }
/// true if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) }
/// true if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) }
/// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) }
/// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) }
/// true if the volume is stored on a local device.
public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) }
/// true if the volume is read-only.
public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName : String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) }
/// true if the volume is encrypted.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) }
/// true if the volume is the root filesystem.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) }
/// true if the volume supports transparent decompression of compressed files using decmpfs.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
/// true if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
/// true if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// true if data is being downloaded for this item.
public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// true if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// true if data is being uploaded for this item.
public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// returns the download status of this item.
public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// returns the name of this item's container as displayed to users.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
#if !os(OSX)
/// The protection level for this file
@available(iOS 9.0, *)
public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) }
#endif
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL : ReferenceConvertible, Equatable {
public typealias ReferenceType = NSURL
fileprivate var _url : NSURL
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String, relativeTo url: URL?) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string, relativeTo: url) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: String, isDirectory: Bool) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(OSX 10.11, iOS 9.0, *)
public init?(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) {
guard dataRepresentation.count > 0 else { return nil }
if isAbsolute {
_url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
} else {
_url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url))
}
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
public init?(resolvingBookmarkData data: Data, options: BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method.
@available(OSX 10.10, iOS 8.0, *)
public init(resolvingAliasFileAt url: URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: URL?) {
_url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL))
}
public var hashValue: Int {
return _url.hash
}
// MARK: -
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(OSX 10.11, iOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
// MARK: -
// Future implementation note:
// NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult.
// Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API.
/// Returns the absolute string for the URL.
public var absoluteString: String {
if let string = _url.absoluteString {
return string
} else {
// This should never fail for non-file reference URLs
return ""
}
}
/// The relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
if let url = _url.absoluteURL {
return url
} else {
// This should never fail for non-file reference URLs
return self
}
}
// MARK: -
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
// This thing was never really part of the URL specs
@available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead")
public var resourceSpecifier: String {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var host: String? {
return _url.host
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port?.intValue
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var user: String? {
return _url.user
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var password: String? {
return _url.password
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string.
///
/// If the URL contains a parameter string, it is appended to the path with a `;`.
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
public var path: String {
if let parameterString = _url.parameterString {
if let path = _url.path {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.path {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// If the URL contains a parameter string, it is appended to the path with a `;`.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
if let parameterString = _url.parameterString {
if let path = _url.relativePath {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.relativePath {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var fragment: String? {
return _url.fragment
}
@available(*, unavailable, message: "use the 'path' property")
public var parameterString: String? {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var query: String? {
return _url.query
}
/// Returns true if the URL path represents a directory.
@available(OSX 10.11, iOS 9.0, *)
public var hasDirectoryPath: Bool {
return _url.hasDirectoryPath
}
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
@available(OSX 10.9, iOS 7.0, *)
public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
return try block(_url.fileSystemRepresentation)
}
// MARK: -
// MARK: Path manipulation
/// Returns the path components of the URL, or an empty array if the path is an empty string.
public var pathComponents: [String] {
// In accordance with our above change to never return a nil path, here we return an empty array.
return _url.pathComponents ?? []
}
/// Returns the last path component of the URL, or an empty string if the path is an empty string.
public var lastPathComponent: String {
return _url.lastPathComponent ?? ""
}
/// Returns the path extension of the URL, or an empty string if the path is an empty string.
public var pathExtension: String {
return _url.pathExtension ?? ""
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL {
if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
return self
}
}
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public func appendingPathComponent(_ pathComponent: String) -> URL {
if let result = _url.appendingPathComponent(pathComponent) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
// Ultimate fallback:
return self
}
}
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingLastPathComponent() -> URL {
// This is a slight behavior change from NSURL, but better than returning "http://www.example.com../".
if path.isEmpty {
return self
}
if let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Returns a URL constructed by appending the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
///
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public func appendingPathExtension(_ pathExtension: String) -> URL {
if path.isEmpty {
return self
}
if let result = _url.appendingPathExtension(pathExtension) {
return result
} else {
return self
}
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingPathExtension() -> URL {
if path.isEmpty {
return self
}
if let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Appends a path component to the URL.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: Use `true` if the resulting path is a directory.
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) {
self = appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
/// Appends a path component to the URL.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public mutating func appendPathComponent(_ pathComponent: String) {
self = appendingPathComponent(pathComponent)
}
/// Appends the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public mutating func appendPathExtension(_ pathExtension: String) {
self = appendingPathExtension(pathExtension)
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deleteLastPathComponent() {
self = deletingLastPathComponent()
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deletePathExtension() {
self = deletingPathExtension()
}
/// Returns a `URL` with any instances of ".." or "." removed from its path.
public var standardized : URL {
// The NSURL API can only return nil in case of file reference URL, which we should not be
if let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func standardize() {
self = self.standardized
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public var standardizedFileURL : URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public func resolvingSymlinksInPath() -> URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func resolveSymlinksInPath() {
self = self.resolvingSymlinksInPath()
}
// MARK: - Reachability
/// Returns whether the URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
public func checkResourceIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkResourceIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
/// Returns whether the promised item URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
@available(OSX 10.10, iOS 8.0, *)
public func checkPromisedItemIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkPromisedItemIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
// MARK: - Resource Values
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
/// Get resource values from URLs of 'promised' items.
///
/// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently:
/// NSMetadataQueryUbiquitousDataScope
/// NSMetadataQueryUbiquitousDocumentsScope
/// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof
///
/// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true:
/// You are using a URL that you know came directly from one of the above APIs
/// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly
///
/// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.
@available(OSX 10.10, iOS 8.0, *)
public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys)))
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.resourceValues(forKeys:) instead")
public func resourceValues(forKeys keys: [URLResourceKey]) throws -> [URLResourceKey : AnyObject] {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws {
fatalError()
}
// MARK: - Bookmarks and Alias Files
/// Returns bookmark data for the URL, created with specified options and resource values.
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
return result as Data
}
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? {
return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) }
}
/// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.
public static func writeBookmarkData(_ data : Data, to url: URL) throws {
// Options are unused
try NSURL.writeBookmarkData(data, to: url, options: 0)
}
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
let result = try NSURL.bookmarkData(withContentsOf: url)
return result as Data
}
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).
@available(OSX 10.7, iOS 8.0, *)
public func startAccessingSecurityScopedResource() -> Bool {
return _url.startAccessingSecurityScopedResource()
}
/// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.
@available(OSX 10.7, iOS 8.0, *)
public func stopAccessingSecurityScopedResource() {
_url.stopAccessingSecurityScopedResource()
}
// MARK: - Bridging Support
/// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions.
private static func _converted(from url: NSURL) -> NSURL {
// Future readers: file reference URL here is not the same as playgrounds "file reference"
if url.isFileReferenceURL() {
// Convert to a file path URL, or use an invalid scheme
return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL
} else {
return url
}
}
fileprivate init(reference: NSURL) {
_url = URL._converted(from: reference).copy() as! NSURL
}
private var reference : NSURL {
return _url
}
public static func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
}
extension URL : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURL {
return _url
}
public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool {
result = URL(reference: source)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL {
var result: URL?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension URL : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
}
extension NSURL : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URL)
}
}
extension URL : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
//===----------------------------------------------------------------------===//
// File references, for playgrounds.
//===----------------------------------------------------------------------===//
extension URL : _ExpressibleByFileReferenceLiteral {
public init(fileReferenceLiteralResourceName name: String) {
self = Bundle.main.url(forResource: name, withExtension: nil)!
}
}
public typealias _FileReferenceLiteralType = URL
|
apache-2.0
|
577bf047044159c5cc4ba3da7cfef632
| 50.624172 | 765 | 0.681681 | 4.992555 | false | false | false | false |
natecook1000/swift
|
test/Profiler/pgo_guard.swift
|
1
|
2030
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_guard -o %t/main
// This unusual use of 'sh' allows the path of the profraw file to be
// substituted by %target-run.
// RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main
// RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_guard -o - | %FileCheck %s --check-prefix=SIL
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_guard -o - | %FileCheck %s --check-prefix=IR
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_guard -o - | %FileCheck %s --check-prefix=SIL-OPT
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_guard -o - | %FileCheck %s --check-prefix=IR-OPT
// REQUIRES: profile_runtime
// REQUIRES: executable_test
// REQUIRES: OS=macosx
// SIL-LABEL: // pgo_guard.guess1
// SIL-LABEL: sil @$S9pgo_guard6guess11xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(5002) {
// IR-LABEL: define swiftcc i32 @"$S9pgo_guard6guess11xs5Int32VAE_tF"
// IR-OPT-LABEL: define swiftcc i32 @"$S9pgo_guard6guess11xs5Int32VAE_tF"
public func guess1(x: Int32) -> Int32 {
// SIL: cond_br {{.*}} !true_count(5000) !false_count(2)
// SIL-OPT: cond_br {{.*}} !true_count(5000) !false_count(2)
// IR: br {{.*}}, !prof ![[BWMD:[0-9]+]]
guard (x == 10) else {
return 30
}
return 20
}
func main() {
var guesses : Int32 = 0;
guesses += guess1(x: 0)
guesses += guess1(x: 42)
for _ in 1...5000 {
guesses += guess1(x: 10)
}
}
main()
// IR: !{!"branch_weights", i32 5001, i32 3}
// IR-OPT: !{!"branch_weights", i32 5001, i32 3}
|
apache-2.0
|
18aac2341af47a1dbadae7d774603439
| 40.428571 | 189 | 0.669951 | 2.777018 | false | false | false | false |
dbruzzone/wishing-tree
|
iOS/Measure/Microsoft-Band/Microsoft-Band/ViewController.swift
|
1
|
1581
|
//
// ViewController.swift
// Microsoft-Band
//
// Created by Davide Bruzzone on 11/4/15.
// Copyright © 2015 Bitwise Samurai. All rights reserved.
//
import UIKit
class ViewController: UIViewController, MSBClientManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let sharedManager = MSBClientManager.sharedManager()
sharedManager.delegate = self
let attachedClients = sharedManager.attachedClients()
if attachedClients.count == 1 {
let client = attachedClients.first as! MSBClient
sharedManager.connectClient(client)
} else {
// TODO
for attachedClient in attachedClients {
print("Client name/description: \(attachedClient.name)/\(attachedClient.description)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - MSBClientManagerDelegate
func clientManager(clientManager: MSBClientManager!, clientDidConnect client: MSBClient!) {
print("clientDidConnect")
}
func clientManager(clientManager: MSBClientManager!, clientDidDisconnect client: MSBClient!) {
print("clientDidDisconnect")
}
func clientManager(clientManager: MSBClientManager!, client: MSBClient!, didFailToConnectWithError error: NSError!) {
print("clientDidFailToConnectWithError")
}
}
|
gpl-3.0
|
1631cd80a5601ad1a76b08410658b0b2
| 28.259259 | 121 | 0.670253 | 4.968553 | false | false | false | false |
bazelbuild/tulsi
|
src/Tulsi/AnnouncementBanner.swift
|
1
|
4658
|
// Copyright 2022 The Tulsi 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 Cocoa
/// Banner used for presenting users with announcements.
class AnnouncementBanner: NSView {
let announcement: Announcement
var delegate: AnnouncementBannerDelegate?
let messageView = NSView(frame: CGRect.zero)
let messageLabel = NSTextField(wrappingLabelWithString: "Placeholder")
let dismissButton = NSButton(frame: CGRect.zero)
let margin = CGFloat(8)
// MARK: - Initializers
init(announcement: Announcement) {
self.announcement = announcement
super.init(frame: CGRect.zero)
wantsLayer = true
translatesAutoresizingMaskIntoConstraints = false
messageView.translatesAutoresizingMaskIntoConstraints = false
messageLabel.stringValue = announcement.bannerMessage
messageLabel.setAccessibilityLabel(announcement.bannerMessage)
messageLabel.isBezeled = false
messageLabel.isEditable = false
messageLabel.isSelectable = false
messageLabel.translatesAutoresizingMaskIntoConstraints = false
if announcement.link != nil {
let gestureRecognizer = NSClickGestureRecognizer(
target: self,
action: #selector(openUrl(_:)))
messageView.addGestureRecognizer(gestureRecognizer)
}
dismissButton.target = self
dismissButton.action = #selector(didClickDismissButton(_:))
dismissButton.wantsLayer = true
dismissButton.layer?.backgroundColor = NSColor.clear.cgColor
dismissButton.isBordered = false
dismissButton.translatesAutoresizingMaskIntoConstraints = false
let accessiblityComment = "Dismisses the announcement banner."
let dismissButtonAccessibilityLabel = NSLocalizedString(
"AnnouncementBanner_DismissButtonAccessibilityLabel", comment: accessiblityComment)
dismissButton.setAccessibilityLabel(dismissButtonAccessibilityLabel)
dismissButton.image = NSImage(
systemSymbolName: "xmark.circle.fill", accessibilityDescription: accessiblityComment)
dismissButton.contentTintColor = NSColor.white
layer?.backgroundColor = NSColor.systemGray.cgColor
messageLabel.textColor = NSColor.white
self.addSubview(messageView)
messageView.addSubview(messageLabel)
self.addSubview(dismissButton)
activateConstraints()
}
required init?(coder: NSCoder) {
fatalError("This class does not support NSCoding.")
}
// MARK: - IBActions
/// Pressing the dismiss button will write to UserDefaults to indicate that the user has seen
/// this announcement and dismissed it
@objc func didClickDismissButton(_ sender: NSButton) {
announcement.recordDismissal()
self.removeFromSuperview()
self.delegate?.announcementBannerWasDismissed(banner: self)
}
@objc func openUrl(_ sender: Any?) {
if let link = announcement.link, let url = URL(string: link) {
NSWorkspace.shared.open(url)
}
}
// Mark - Private Setup Functions
func activateConstraints() {
removeConstraints(self.constraints)
let views = ["view": messageView, "btn": dismissButton]
let labels = ["msg": messageLabel]
messageView.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-8-[msg]-8-|", options: .alignAllCenterX, metrics: nil,
views: labels))
messageView.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-8-[msg]-8-|", options: .directionLeadingToTrailing, metrics: nil,
views: labels))
self.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view]-0-[btn]-8-|",
options: NSLayoutConstraint.FormatOptions.alignAllCenterY, metrics: nil, views: views))
messageView.setContentHuggingPriority(.defaultLow, for: .horizontal)
dismissButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
self.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil,
views: views))
}
}
protocol AnnouncementBannerDelegate {
func announcementBannerWasDismissed(banner: AnnouncementBanner)
}
|
apache-2.0
|
967e58e132a14336cbda2a592221399c
| 34.287879 | 97 | 0.742808 | 5.192865 | false | false | false | false |
ericcole/Quill
|
Quill/Quill.swift
|
1
|
40358
|
//
// Quill.swift
// Quill
//
// Created by Cole, Eric on 8/20/15.
// Copyright © 2015 Cole, Eric. All rights reserved.
//
import Foundation
// MARK: BindableValue
public enum BindableValue {
case Null
case Boolean(Bool)
case Integer(Int)
case Long(Int64)
case Real(Double)
case Text(String)
case Data(NSData)
case UTF8(UnsafePointer<Void>,byteCount:Int)
case UTF16(UnsafePointer<Void>,byteCount:Int)
case Blob(UnsafePointer<Void>,byteCount:Int)
case Zero(byteCount:Int32)
case Preserve
}
// MARK: Bindable
public protocol Bindable {
var bindableValue:BindableValue { get }
}
// MARK: QueryValue Type
public enum QueryValue : Int32 {
case Long = 1 // SQLITE_INTEGER Int64
case Real = 2 // SQLITE_FLOAT Double
case Text = 3 // SQLITE_TEXT NSString
case Data = 4 // SQLITE_BLOB NSData
case Null = 5 // SQLITE_NULL AnyObject
case Boolean = 8 // Bool
}
// MARK: QueryRow
public protocol BinaryRepresentable {}
public protocol QueryRow {
/** number of columns in select results **/
var columnCount:Int { get }
/** names of columns in select results **/
var columnNames:[String] { get }
func columnType( column:Int ) -> QueryValue
func columnIsNull( column:Int ) -> Bool
func columnBoolean( column:Int ) -> Bool
func columnInteger( column:Int ) -> Int
func columnLong( column:Int ) -> Int64
func columnDouble( column:Int ) -> Double
func columnString( column:Int ) -> String?
func columnData( column:Int ) -> NSData?
func columnValue<T>( column:Int ) -> T?
func columnObject( column:Int, null:AnyObject, pool:NSMutableSet? ) -> AnyObject
func columnArray<T where T:BinaryRepresentable>( column:Int ) -> [T]
subscript( column:Int ) -> Bool { get }
subscript( column:Int ) -> Int64 { get }
subscript( column:Int ) -> Double { get }
subscript( column:Int ) -> String? { get }
subscript( column:Int ) -> NSData? { get }
}
public protocol QueryAppendable {
/** add value to appendable **/
mutating func queryAppend<T>( value:T )
mutating func removeAll( keepCapacity keepCapacity:Bool )
var isEmpty:Bool { get }
var prefersQueryValue:QueryValue? { get }
}
// MARK: -
public struct Error : ErrorType, CustomStringConvertible {
public let code:Int32
public let message:String
public let detail:String
public var description:String { return "SQLITE \(code) - \(message)" + ( !detail.isEmpty ? "\n\n\"" + detail + "\"\n" : "" ) }
}
// MARK: -
public class Connection {
private var connection:COpaquePointer = nil // struct sqlite3 *
// MARK: Initialization
public init() {}
public init( location:String, immutable:Bool = false ) throws { try openThrows( location, immutable:immutable ) }
public init( connection:COpaquePointer ) { self.connection = connection; prepareConnection() }
deinit { if connection != nil { sqlite3_close( connection ) } }
// MARK: Statements
public func prepareStatement( sql:String ) throws -> Statement { return try Statement( sql:sql, connection:connection ) }
public func prepareStatement( sql:String, bind:[Bindable?] ) throws -> Statement { return try prepareStatement( sql ).with( bind ) }
public func prepareStatement( sql:String, bind:[String:Bindable] ) throws -> Statement { return try prepareStatement( sql ).with( bind ) }
// MARK: Statement Convenience
public func execute( sql:String, _ bind:Bindable?... ) throws -> Bool { return try prepareStatement( sql, bind:bind ).execute() == SQLITE_DONE }
public func insert( sql:String, _ bind:Bindable?... ) throws -> Int64 { return try prepareStatement( sql, bind:bind ).executeInsert() }
public func insert( sql:String, bind:[String:Bindable] ) throws -> Int64 { return try prepareStatement( sql, bind:bind ).executeInsert() }
public func update( sql:String, _ bind:Bindable?... ) throws -> Int { return try prepareStatement( sql, bind:bind ).executeUpdate() }
public func update( sql:String, bind:[String:Bindable] ) throws -> Int { return try prepareStatement( sql, bind:bind ).executeUpdate() }
public func select( sql:String, _ bind:Bindable?... ) throws -> Statement { return try prepareStatement( sql ).with( bind ) }
public func select<T>( sql:String, transform:(QueryRow) -> T, _ bind:Bindable?... ) throws -> [T] { return try prepareStatement( sql, bind:bind ).map( transform ) }
public func filter<T>( sql:String, transform:(QueryRow) -> T?, _ bind:Bindable?... ) throws -> [T] { return try prepareStatement( sql, bind:bind ).filter( transform ) }
public func gather( sql:String, _ bind:Bindable?... ) throws -> (columns:[[AnyObject]],names:[String]) { let s = try prepareStatement( sql, bind:bind ); return try (s.columnMajorResults(),s.columnNames) }
public func gather( sql:String, inout columns:[QueryAppendable], _ bind:Bindable?... ) throws { try prepareStatement( sql, bind:bind ).columnMajorResults( &columns ) }
// MARK: Connection Information
public var isOpen:Bool { return nil != connection }
public var hasStatements:Bool { return nil != connection && nil != sqlite3_next_stmt( connection, nil ) }
public var hasTransaction:Bool { return nil == connection ? false : sqlite3_get_autocommit( connection ) == 0 }
public var rowInserted:Int64 { return nil == connection ? -1 : sqlite3_last_insert_rowid( connection ) }
public var changesSinceExecute:Int32 { return nil == connection ? -1 : sqlite3_changes( connection ) }
public var changesSinceOpen:Int32 { return nil == connection ? -1 : sqlite3_total_changes( connection ) }
public var errorCode:Int32 { return sqlite3_extended_errcode( connection ) }
public var errorMessage:String? { let utf8 = sqlite3_errmsg( connection ); return ( nil == utf8 ) ? nil : String( UTF8String:utf8 ) }
public var filePath:String? { let utf8 = nil == connection ? nil : sqlite3_db_filename( connection, "main" ); return ( nil == utf8 ) ? nil : String( UTF8String:utf8 ) }
public static func memoryUsed() -> Int64 { return sqlite3_memory_used() }
public static func memoryPeak( reset:Bool = false ) -> Int64 { return sqlite3_memory_highwater( reset ? 1 : 0 ) }
// MARK: Connection Management
public static func errorDescription( code:Int32, connection:COpaquePointer ) -> String? {
var utf8 = ( nil != connection ) ? sqlite3_errmsg( connection ) : nil
if nil == utf8 { utf8 = sqlite3_errstr( code ) }
return nil != utf8 ? String( UTF8String:utf8 ) : nil
}
/**
open connection to sqlite database
location: file path, file uri or empty string for in memory
immutable: open database as read only and do not create
returns: error code and description or (SQLITE_OK,nil) for no error
*/
public func open( location:String = "", immutable:Bool = false ) -> (code:Int32,String?) {
close()
var flags:Int32 = ( !immutable || location.isEmpty ) ? SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE : SQLITE_OPEN_READONLY
if location.isEmpty { flags |= SQLITE_OPEN_MEMORY }
else if nil != location.rangeOfString( ":" ) { flags |= SQLITE_OPEN_URI }
// database connections are not thread safe and should only be accessed from their original thread
// flags |= SQLITE_OPEN_NOMUTEX
let status = sqlite3_open_v2( location, &connection, flags, nil )
var string:String? = nil
if ( nil == connection || !( SQLITE_OK == status ) ) {
string = Connection.errorDescription( status, connection:connection ) ?? "open failed"
if nil != connection && !( SQLITE_NOTICE == status || SQLITE_WARNING == status ) {
sqlite3_close_v2( connection )
connection = nil
}
}
if nil != connection {
prepareConnection()
}
return (status,string)
}
public func openThrows( location:String , immutable:Bool ) throws -> (code:Int32,String?) {
let (code,string) = open( location, immutable:immutable )
if !( SQLITE_OK == code || SQLITE_NOTICE == code || SQLITE_WARNING == code ) {
if let description = string {
throw Error( code:code, message:description, detail:location )
}
}
return (code,string)
}
public func close() -> Int32 {
var result = SQLITE_OK
if connection != nil {
result = sqlite3_close_v2( connection )
connection = nil
}
return result
}
private func prepareConnection() {
prepareCollation()
}
// MARK: Connection Options
public func abort() { sqlite3_interrupt( connection ) }
public func releaseMemoryCache() { sqlite3_db_release_memory( connection ) }
public func setTimeToSleepWhileBusy( milliseconds:Int32 ) { sqlite3_busy_timeout( connection, milliseconds ) }
public func accessLimit( what:Int32, value:Int32 = -1 ) -> Int32 { return sqlite3_limit( connection, what, value ) }
public var maximumStatement:Int32 {
get { return accessLimit( SQLITE_LIMIT_SQL_LENGTH ) }
set { accessLimit( SQLITE_LIMIT_SQL_LENGTH, value:newValue ) }
}
// MARK: Connection Delegate
/// Enclose collation names in single quotes
public struct Collation {
public static let CaseDiacriticWidthInsensitive = "equivalent"
public static let DiacriticWidthInsensitive = "case"
public static let CaseWidthInsensitive = "mark"
public static let CaseDiacriticInsensitive = "width"
public static let WidthInsensitive = "glyph"
public static let DiacriticInsensitive = "base"
public static let CaseInsensitive = "alphabet"
public static let CaseDiacriticWidthSensitive = "strict"
public static let Natural = "natural"
public static let Literal = "literal"
public static let Numeric = "numeric"
public static let Backword = "backword"
public static let Ordered = "ordered"
}
static func collationCompareOptions( name:String ) -> UInt {
var result:UInt = 0
if nil != name.rangeOfString(Collation.Literal) { result |= NSStringCompareOptions.LiteralSearch.rawValue }
else if nil != name.rangeOfString(Collation.CaseDiacriticWidthInsensitive) || nil != name.rangeOfString(Collation.Natural) { result |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue | NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue | NSStringCompareOptions.WidthInsensitiveSearch.rawValue }
else if nil != name.rangeOfString(Collation.DiacriticWidthInsensitive) { NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue | NSStringCompareOptions.WidthInsensitiveSearch.rawValue }
else if nil != name.rangeOfString(Collation.CaseWidthInsensitive) { result |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue | NSStringCompareOptions.WidthInsensitiveSearch.rawValue }
else if nil != name.rangeOfString(Collation.CaseDiacriticInsensitive) { result |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue | NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }
else if nil != name.rangeOfString(Collation.CaseInsensitive) { result |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue }
else if nil != name.rangeOfString(Collation.DiacriticInsensitive) { result |= NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }
else if nil != name.rangeOfString(Collation.WidthInsensitive) { result |= NSStringCompareOptions.WidthInsensitiveSearch.rawValue }
else if nil == name.rangeOfString(Collation.CaseDiacriticWidthSensitive) { result |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue | NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }
if nil != name.rangeOfString(Collation.Numeric) || nil != name.rangeOfString(Collation.Natural) { result |= NSStringCompareOptions.NumericSearch.rawValue }
if nil != name.rangeOfString(Collation.Backword) { result |= NSStringCompareOptions.BackwardsSearch.rawValue }
if nil != name.rangeOfString(Collation.Ordered) { result |= NSStringCompareOptions.ForcedOrderingSearch.rawValue }
return result
}
func prepareCollation() {
sqlite3_collation_needed( connection, nil ) { (_, connection, representation, name_utf8) -> Void in
let name = String( UTF8String:name_utf8 )?.lowercaseString ?? ""
let options = Connection.collationCompareOptions( name )
let context = UnsafeMutablePointer<UInt>.alloc(2)
let encoding:UInt
switch representation {
case SQLITE_UTF8: encoding = NSUTF8StringEncoding
case SQLITE_UTF16BE: encoding = NSUTF16BigEndianStringEncoding
case SQLITE_UTF16LE: encoding = NSUTF16LittleEndianStringEncoding
default: encoding = NSUTF16StringEncoding
}
context[0] = encoding
context[1] = options
sqlite3_create_collation_v2(connection, name_utf8, representation, context, { (pointer, a_length, a_bytes, b_length, b_bytes) -> Int32 in
let context:UnsafeMutablePointer<UInt> = UnsafeMutablePointer(pointer)
let encoding = context[0]
let options = NSStringCompareOptions( rawValue:context[1] )
let a = NSString( bytesNoCopy:UnsafeMutablePointer(a_bytes), length:Int(a_length), encoding:encoding, freeWhenDone:false )
let b = String( bytesNoCopy:UnsafeMutablePointer(b_bytes), length:Int(b_length), encoding:encoding, freeWhenDone:false )
return ( nil != a ) ? ( nil != b ) ? Int32( a!.compare( b!, options:options ).rawValue ) : 1 : 0
},{ pointer in
pointer.dealloc(2)
})
}
}
func traceExecution( trace:Bool = true ) {
sqlite3_trace( connection, trace ? {_,utf8 in print( "SQLITE-TRACE " + String( UTF8String:utf8 )! )} : nil, nil )
}
func profileExecution( profile:Bool = true ) {
sqlite3_profile( connection, profile ? {_,utf8,nanoseconds in print( "SQLITE-PROFILE " + String( format:"%.3f seconds ", Double(nanoseconds)/1000000000.0 ) + String( UTF8String:utf8 )! ) } : nil, nil )
}
func traceHooks( trace:Bool = true ) {
sqlite3_commit_hook( connection, trace ? { _ -> Int32 in print( "SQLITE-COMMIT" ); return 0 } : nil, nil )
sqlite3_rollback_hook( connection, trace ? { _ in print( "SQLITE-ROLLBACK" ) } : nil, nil )
sqlite3_update_hook( connection, trace ? { _, what, database_utf8, table_utf8, row in
let label = ( SQLITE_DELETE == what ? "DELETE" : SQLITE_INSERT == what ? "INSERT" : SQLITE_UPDATE == what ? "UPDATE" : "HOOK-\(what)" )
let table = ( String( UTF8String:database_utf8 ) ?? "" ) + "." + ( String( UTF8String:table_utf8 ) ?? "" )
print( "SQLITE-" + label + " " + table + " row \(row)" )
} : nil, nil )
sqlite3_wal_hook( connection, trace ? { (_, connection, database_utf8, pages) -> Int32 in print( "SQLITE-WAL " + ( String( UTF8String:database_utf8 ) ?? "" ) + " pages \(pages)" ); return 0 } : nil, nil )
}
// sqlite3_busy_handler
// sqlite3_set_authorizer
// sqlite3_progress_handler
// sqlite3_create_function
// sqlite3_commit_hook
// sqlite3_rollback_hook
// sqlite3_update_hook
// sqlite3_wal_hook
}
// MARK: -
public class Statement {
private var statement:COpaquePointer = nil
private(set) public var message:String? = nil
private(set) public var status:Int32 = 0
private(set) public var row:Int = -1
public init( sql:String, connection:COpaquePointer ) throws { try prepareThrows( sql, connection:connection ) }
public init( statement:COpaquePointer ) { self.statement = statement }
deinit { if nil != statement { sqlite3_finalize( statement ) } }
// MARK: Statement Control
public func reset() { rewind(); unbind() }
public func rewind() { if nil != statement { status = sqlite3_reset( statement ); row = -1 } }
public func invalidate() { if nil != statement { status = sqlite3_finalize( statement ); statement = nil } }
public func advance() throws -> Bool { return try step() == SQLITE_ROW }
public func step() throws -> Int32 {
let result = sqlite3_step( statement )
status = result
if SQLITE_ROW == result || SQLITE_DONE == result {
row += 1
} else {
message = nil == statement ? "invalid statement" : Connection.errorDescription( status, connection:sqlite3_db_handle( statement ) ) ?? "execute error"
if !( SQLITE_NOTICE == result || SQLITE_WARNING == result ) {
throw Error( code:result, message:message!, detail:( sql ?? "" ) )
}
}
return result
}
public func execute() throws -> Int32 { return ( row < 0 ? try step() : SQLITE_MISUSE ) }
public func executeInsert() throws -> Int64 { return ( row < 0 ? try step() == SQLITE_DONE : false ) ? inserted : -1 }
public func executeUpdate() throws -> Int { return ( row < 0 ? try step() == SQLITE_DONE : false ) ? changes : -1 }
// MARK: Statement Information
public var hasRow:Bool { return SQLITE_ROW == status && sqlite3_data_count( statement ) > 0 }
public var canAdvance:Bool { return SQLITE_ROW == status || ( row < 0 && nil != statement ) }
public var readonly:Bool { return sqlite3_stmt_readonly( statement ) != 0 }
public var isBusy:Bool { return sqlite3_stmt_busy( statement ) != 0 }
public var sql:String? { let utf8 = sqlite3_sql( statement ); return ( nil == utf8 ) ? nil : String( UTF8String:utf8 ) }
public var inserted:Int64 { return sqlite3_last_insert_rowid( sqlite3_db_handle( statement ) ) }
public var changes:Int { return Int(sqlite3_changes( sqlite3_db_handle( statement ) )) }
// MARK: Bind Variables
public func unbind() -> Int32 { return sqlite3_clear_bindings( statement ) }
// bind parameters may be ordered from 1 to bindableCount
public var bindableCount:Int32 { return sqlite3_bind_parameter_count( statement ) }
public func require( values:Bindable?... ) throws -> Statement { return try with( values ) }
public func with( values:[Bindable?] ) throws -> Statement { try bind( values, startingAt:-1 ); return self }
public func with( values:[String:Bindable] ) throws -> Statement { try bind( values, throwing:.MissingParameters ); return self }
public func bind( order:Int32, value bindable:Bindable ) -> (code:Int32,String?) {
var result = SQLITE_OK
switch bindable.bindableValue {
case .Preserve: result = SQLITE_OK // preserve previously bound value for order
case .Null: result = sqlite3_bind_null( statement, order )
case .Boolean(let b): result = sqlite3_bind_int( statement, order, b ? 1 : 0 )
case .Integer(let i): result = sqlite3_bind_int64( statement, order, sqlite3_int64(i) )
case .Long(let l): result = sqlite3_bind_int64( statement, order, l )
case .Real(let r): result = sqlite3_bind_double( statement, order, r )
case .Text(let s):
let text = s.bindableText
result = ( nil == text.utf8 || text.byteCount < 0 )
? sqlite3_bind_null( statement, order )
: sqlite3_bind_text( statement, order, UnsafePointer<Int8>(text.utf8), Int32(text.byteCount), SQLITE_TRANSIENT )
case .UTF8(let utf8, let byteCount):
result = ( nil == utf8 || byteCount < 0 )
? sqlite3_bind_null( statement, order )
: sqlite3_bind_text( statement, order, UnsafePointer<Int8>(utf8), Int32(byteCount), SQLITE_TRANSIENT )
case .UTF16(let utf16, let byteCount):
result = ( nil == utf16 || byteCount < 0 )
? sqlite3_bind_null( statement, order )
: sqlite3_bind_text16( statement, order, utf16, Int32(byteCount), SQLITE_TRANSIENT )
case .Data(let data):
let blob = data.bindableBlob
result = ( nil == blob.data || blob.byteCount < 0 )
? sqlite3_bind_null( statement, order )
: sqlite3_bind_blob( statement, order, blob.data, Int32(blob.byteCount), SQLITE_TRANSIENT )
case .Blob(let data, let byteCount):
result = ( nil == data || byteCount < 0 )
? sqlite3_bind_null( statement, order )
: sqlite3_bind_blob( statement, order, data, Int32(byteCount), SQLITE_TRANSIENT )
case .Zero(let byteCount):
result = ( byteCount < 0 )
? sqlite3_bind_null( statement, order )
: sqlite3_bind_zeroblob( statement, order, byteCount )
}
if SQLITE_OK != result {
status = result
message = Connection.errorDescription( result, connection:sqlite3_db_handle( statement ) )
return (status,message)
}
return (result,nil)
}
public func bind( name:String, value bindable:Bindable ) -> (code:Int32,String?) {
let order = sqlite3_bind_parameter_index( statement, name )
return order > 0 ? bind( order, value:bindable ) : (SQLITE_MISMATCH,"no parameter named '\(name)'")
}
public enum BindingThrows { case No, Errors, MissingParameters }
/**
bind named parameters
values: parameter values by name ("name",":name","$name","@name") or number ("1","?1")
throwing: when to throw, defaults to not throwing
returns: number of bound parameters
*/
public func bind( values:[String:Bindable], throwing:BindingThrows = .No ) throws -> Int {
var result = 0
let limit = bindableCount
var order:Int32
let null = NSNull()
for ( order = 1 ; order <= limit ; ++order ) {
let utf8 = sqlite3_bind_parameter_name( statement, order )
let anonymous = nil == utf8 || 0 == utf8.memory
let name = ( anonymous ? nil : String( UTF8String:utf8 ) ) ?? String( order )
var bindable = values[name]
if anonymous && nil == bindable {
bindable = values[name.lowercaseString]
if nil == bindable {
let key = name.substringFromIndex( name.startIndex.successor() )
bindable = values[key]
if nil == bindable { bindable = values[key.lowercaseString] }
if nil == bindable { bindable = values[key.uppercaseString] }
}
}
if nil == bindable {
if throwing == .MissingParameters { throw Error( code:SQLITE_MISMATCH, message:"missing parameter '\(name)'", detail:( sql ?? "" ) ) }
} else {
result += 1
}
let (code,string) = bind( order , value:bindable ?? null )
if !( SQLITE_OK == code || SQLITE_NOTICE == code || SQLITE_WARNING == code ) {
if throwing != .No { throw Error( code:code, message:( string ?? "bad parameter for '\(name)'" ), detail:( sql ?? "" ) ) }
}
}
return result
}
/**
bind ordered parameters
values: values to bind in statement order ignoring names
startingAt: first parameter position to bind starting at 1
returns: zero if all parameters bound otherwise next parameter to bind
throws: nothing unless startingAt is negative
*/
public func bind( values:[Bindable?], startingAt:Int32 = 1 ) throws -> Int32 {
let limit = bindableCount
var order:Int32 = max(abs( startingAt ),1)
let require = startingAt < 0
let null = NSNull()
if require && Int32(values.count) + order != limit + 1 {
throw Error( code:SQLITE_RANGE, message:"expecting \(limit + 1 - order) parameters", detail:( sql ?? "" ) )
}
for value in values {
if ( order > limit ) { return -1 }
let (code,string) = bind( order , value:( value ?? null ) )
if !( SQLITE_OK == code || SQLITE_NOTICE == code || SQLITE_WARNING == code ) {
if require { throw Error( code:code, message:( string ?? "bad parameter #'\(order)'" ), detail:( sql ?? "" ) ) }
return order
}
order += 1
}
return order > limit ? 0 : order
}
// MARK: Column Information
/// columns are ordered starting from zero and less than columnCount
public var columnCount:Int { return Int(sqlite3_column_count( statement )) }
/// only meaningful after advance and before value retrieved from column
public func columnType( column:Int ) -> QueryValue {
var result = sqlite3_column_type( statement, Int32(column) )
if ( SQLITE_INTEGER == result ) {
let declared = sqlite3_column_decltype( statement, Int32(column) )
if nil != declared && 0 == sqlite3_strnicmp( "bool", declared, 4 ) {
result = SQLITE_BOOL
}
}
return QueryValue( rawValue:result )!
}
public func columnDeclared( column:Int32 ) -> String? {
let utf8 = sqlite3_column_decltype( statement, column )
return ( nil == utf8 ) ? nil : String( UTF8String:utf8 )
}
public func columnName( column:Int ) -> String? {
let names = columnNames
return column < 0 || column >= names.count ? nil : names[column]
}
private var columnNameArray:[String]? = nil
public var columnNames:[String] {
if nil == columnNameArray {
var names = [String]()
let count = columnCount
for var index = 0 ; index < count ; ++index {
let utf8 = sqlite3_column_name( statement, Int32(index) )
//if nil == utf8 { utf8 = sqlite3_column_origin_name( statement, Int32(column) ) }
let name = ( nil == utf8 ) ? nil : String( UTF8String:utf8 )
names.append( name ?? "\(index + 1)" )
}
columnNameArray = names
}
return columnNameArray!
}
// MARK: Column Values
/// only meaningful after advance and before value retrieved from column
public func columnIsNull( column:Int ) -> Bool {
return ( SQLITE_NULL == sqlite3_column_type( statement, Int32(column) ) )
}
/// only meaningful after value retrieved from column and before advance
public func columnWasNull( column:Int ) -> Bool {
return nil == sqlite3_column_text( statement, Int32(column) )
}
public func columnBoolean( column:Int ) -> Bool {
return sqlite3_column_int( statement, Int32(column) ) != 0
}
public func columnInteger( column:Int ) -> Int {
return Int(sqlite3_column_int64( statement, Int32(column) ))
}
public func columnLong( column:Int ) -> Int64 {
return sqlite3_column_int64( statement, Int32(column) )
}
public func columnDouble( column:Int ) -> Double {
return sqlite3_column_double( statement, Int32(column) )
}
public func nullableBoolean( column:Int ) -> Bool? {
return columnIsNull( column ) ? nil : columnBoolean( column )
}
public func nullableLong( column:Int ) -> Int64? {
return columnIsNull( column ) ? nil : columnLong( column )
}
public func nullableDouble( column:Int ) -> Double? {
return columnIsNull( column ) ? nil : columnDouble( column )
}
public func columnString( column:Int ) -> String? {
let order = Int32(column)
let utf8 = sqlite3_column_text( statement, order )
return ( nil == utf8 ) ? nil : String( UTF8String:UnsafePointer<Int8>(utf8) )
}
public func columnString16( column:Int ) -> String? {
let order = Int32(column)
let utf16 = sqlite3_column_text16( statement, order )
let length = sqlite3_column_bytes( statement, order )
return ( nil == utf16 ) ? nil : String( utf16CodeUnits:UnsafePointer<UInt16>(utf16), count:Int(length)/sizeof(UInt16) )
}
public func columnStringObject( column:Int ) -> NSString? {
let order = Int32(column)
let utf8 = sqlite3_column_text( statement, order )
let length = sqlite3_column_bytes( statement, order )
return ( nil == utf8 ) ? nil : NSString( bytes:utf8, length:Int(length), encoding:NSUTF8StringEncoding )
}
public func columnData( column:Int ) -> NSData? {
let order = Int32(column)
let blob = sqlite3_column_blob( statement, order )
let length = sqlite3_column_bytes( statement, order )
return ( nil == blob || 0 == length ) ? nil : NSData(bytes: blob, length: Int(length))
}
public func columnArray<T where T:BinaryRepresentable>( column:Int ) -> [T] {
let order = Int32(column)
let blob = sqlite3_column_blob( statement, order )
let length = Int(sqlite3_column_bytes( statement, order ))
let size = sizeof(T)
guard size > 0 && length > 0 && nil != blob else { return [T]() }
return Array<T>( UnsafeBufferPointer<T>( start:UnsafePointer<T>(blob), count:length / size ) )
}
public func columnBindableValue( column:Int ) -> BindableValue {
let type = columnType( column )
switch type {
case .Null: return .Null
case .Boolean: return .Boolean( columnBoolean( column ) )
case .Long: return .Long( columnLong( column ) )
case .Real: return .Real( columnDouble( column ) )
case .Text: return .Text( columnString( column ) ?? "" )
case .Data: return .Data( columnData( column ) ?? NSData() )
}
}
public func columnValue<T>( column:Int ) -> T? {
if let _ = 0.0 as? T { return columnDouble( column ) as? T }
else if let _ = Int64(0) as? T { return columnLong( column ) as? T }
else if let _ = 0 as? T { return columnInteger( column ) as? T }
else if let _ = false as? T { return columnBoolean( column ) as? T }
else if let _ = "" as? T { return columnString( column ) as? T }
else if let _ = NSData() as? T { return columnData( column ) as? T }
else { return nil }
}
public func columnObject( column:Int, null:AnyObject, pool:NSMutableSet? = nil ) -> AnyObject {
var result:AnyObject
let type = columnType( column )
switch ( type ) {
case .Boolean: result = columnBoolean( column )
case .Long: result = NSNumber( longLong:columnLong( column ) )
case .Real: result = columnDouble( column )
case .Text: result = columnStringObject( column ) ?? null
case .Data: result = columnData( column ) ?? null
default: result = null
}
if null !== result {
if let pool = pool {
if let prior = pool.member( result ) { result = prior }
else { pool.addObject( result ) }
}
}
return result
}
// MARK: Single Column Convenience
public func oneColumn( inout values:[Int] ) throws { while try advance() { values.append( columnInteger( 0 ) ) } }
public func oneColumn( inout values:[Double] ) throws { while try advance() { values.append( columnDouble( 0 ) ) } }
public func oneColumn( inout values:[String], null:String = "" ) throws { while try advance() { values.append( columnString( 0 ) ?? null ) } }
public func oneColumn( inout values:[NSData], null:NSData = NSData() ) throws { while try advance() { values.append( columnData( 0 ) ?? null ) } }
// MARK: Convenience
public func columnMajorResults( null:AnyObject = NSNull() ) throws -> [[AnyObject]] {
let count = columnCount
var index:Int
var result = [[AnyObject]]( count:count, repeatedValue:[AnyObject]() )
let pool = NSMutableSet()
while ( try advance() ) {
for ( index = 0 ; index < count ; ++index ) {
result[index].append( columnObject( index, null:null, pool:pool ) )
}
}
pool.removeAllObjects()
return result
}
func columnMajorResults( inout columns:[QueryAppendable], preferTypes:[QueryValue]? = nil ) throws -> [QueryAppendable] {
guard try advance() else { return columns }
// columnType only meaningful after first advance
let count = columnCount
let limit = preferTypes?.count ?? 0
let known = columns.count
var index:Int
var types = [QueryValue]( count:count, repeatedValue:.Null )
let pool = NSMutableSet()
let stringNull = NSString()
let dataNull = NSData()
let null = NSNull()
for ( index = known ; index-- > count ; ) {
columns.removeAtIndex( index )
}
for ( index = 0 ; index < count ; ++index ) {
if index < known {
if let prefers = columns[index].prefersQueryValue {
columns[index].removeAll( keepCapacity:true )
types[index] = prefers
continue
}
}
let preferType = ( index < limit ) ? preferTypes![index] : .Null
let type = ( .Null == preferType ) ? columnType( index ) : preferType
var column:QueryAppendable
switch type {
case .Boolean: column = [Bool]()
case .Long: column = [Int64]()
case .Real: column = [Double]()
case .Text: column = [NSString]()
case .Data: column = [NSData]()
case .Null: column = [AnyObject]()
}
if index < columns.count { columns[index] = column }
else { columns.append( column ) }
types[index] = type
}
repeat {
for ( index = 0 ; index < count ; ++index ) {
switch types[index] {
case .Boolean: columns[index].queryAppend( columnBoolean( index ) )
case .Long: columns[index].queryAppend( columnLong( index ) )
case .Real: columns[index].queryAppend( columnDouble( index ) )
case .Text: columns[index].queryAppend( columnStringObject( index ) ?? stringNull )
case .Data: columns[index].queryAppend( columnData( index ) ?? dataNull )
case .Null: columns[index].queryAppend( columnObject( index, null:null, pool:pool ) )
}
}
} while try advance()
return columns
}
// MARK: Statement Management
public static func prepare( inout statement:COpaquePointer, sql:String, connection:COpaquePointer ) -> (code:Int32,String?) {
var code:Int32
var message:String?
if nil == connection {
code = SQLITE_MISUSE
} else {
let utf8 = ( sql as NSString ).UTF8String
code = sqlite3_prepare_v2( connection, utf8, -1, &statement, nil )
}
if nil == statement {
message = ( nil == connection ) ? "connection required" : Connection.errorDescription( code, connection:connection ) ?? "prepare error"
} else {
message = nil
}
return (code,message)
}
private func prepareThrows( sql:String, connection:COpaquePointer ) throws -> (code:Int32,String?) {
let (code,string) = Statement.prepare( &statement, sql:sql, connection:connection )
status = code
message = string
if !( SQLITE_OK == code || SQLITE_NOTICE == code || SQLITE_WARNING == code ) {
if let description = string {
throw Error( code:code, message:description, detail:sql )
}
}
return (code,string)
}
}
extension Statement : SequenceType, GeneratorType {
public typealias Generator = Statement
public typealias Element = QueryRow
public func generate() -> Generator { return self }
public func next() -> Element? { do { return try advance() ? self : nil } catch { return nil } }
public func another() throws -> QueryRow? { return try advance() ? self : nil }
public func underestimateCount() -> Int { return 0 }
public func forEach( @noescape body:(Element) throws -> Void ) throws {
while try advance() { try body( self ) }
}
public func map<T>( @noescape transform:(Element) throws -> T) throws -> [T] {
var result = [T]()
while try advance() { result.append( try transform( self ) ) }
return result
}
public func filter<T>( @noescape transform:(Element) -> T?) throws -> [T] {
var result = [T]()
while try advance() { if let t = transform( self ) { result.append( t ) } }
return result
}
public func filter( @noescape includeElement:(Element) -> Bool ) throws -> [Element] {
throw Error( code:SQLITE_MISUSE, message:"filter unsupported", detail:"" )
}
}
extension Statement : QueryRow {
public subscript( column:Int ) -> Bool { return columnBoolean( column ) }
public subscript( column:Int ) -> Int64 { return columnLong( column ) }
public subscript( column:Int ) -> Double { return columnDouble( column ) }
public subscript( column:Int ) -> String? { return columnString( column ) }
public subscript( column:Int ) -> NSData? { return columnData( column ) }
}
// MARK: - Bindable Extensions
extension QueryValue {
static func forType<T>( value:T? ) -> QueryValue? {
if value is Any.Type {
if Double.self is T { return .Real }
if Int64.self is T { return .Long }
if Bool.self is T { return .Boolean }
if AnyObject.self is T || NSObject.self is T { return .Null }
if String.self is T || NSString.self is T { return .Text }
if NSData.self is T { return .Data }
} else {
if Double.self is T.Type { return .Real }
if Int64.self is T.Type { return .Long }
if Bool.self is T.Type { return .Boolean }
if AnyObject.self is T.Type || NSObject.self is T.Type { return .Null }
if String.self is T.Type || NSString.self is T.Type { return .Text }
if NSData.self is T.Type { return .Data }
}
return nil
}
}
func toVoid( memory:UnsafePointer<Void> ) -> UnsafePointer<Void> { return memory }
func isBinaryRepresentable<T>( it:T? = nil ) -> Bool {
if T.self is AnyObject { return false }
if T.self is _PointerType.Type { return false }
if T.self is BinaryRepresentable.Type { return true }
let deepType = "\(T.self.dynamicType)"
if deepType.hasSuffix( ").Type" ) { return false } // tuple or closure
if deepType.hasSuffix( ".Protocol" ) { return false }
if deepType.hasSuffix( ".Type.Type" ) { return false }
if let t = it {
if let displayStyle = Mirror(reflecting:t).displayStyle {
if Mirror.DisplayStyle.Struct != displayStyle { return false }
}
} else {
if deepType.hasPrefix( "Swift.Optional<" ) { return false }
if deepType.hasPrefix( "Swift.ImplicitlyUnwrappedOptional<" ) { return false }
}
return true
}
extension BindableValue : Bindable { public var bindableValue:BindableValue { return self } }
extension Bool : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Boolean(self) } }
extension Int : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(self) } }
extension UInt : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(Int(self)) } }
extension Int8 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(Int(self)) } }
extension UInt8 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(Int(self)) } }
extension Int16 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(Int(self)) } }
extension UInt16 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(Int(self)) } }
extension Int32 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(Int(self)) } }
extension UInt32 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Integer(Int(self)) } }
extension Int64 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Long(self) } }
extension UInt64 : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Long(Int64(self)) } }
extension Double : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Real(self) } }
extension Float : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Real(Double(self)) } }
extension NSNull : Bindable { public var bindableValue:BindableValue { return .Null } }
extension NSDate : Bindable { public var bindableValue:BindableValue { return .Real(self.timeIntervalSince1970) } }
extension String : Bindable {
public var bindableValue:BindableValue { return .UTF8(toVoid(self),byteCount:self.utf8.count) }
public var bindableText:(utf8:UnsafePointer<Void>,byteCount:Int) { return (toVoid(self),self.utf8.count) }
}
extension NSNumber : Bindable {
public var bindableValue:BindableValue { return CFNumberIsFloatType( self ) ? BindableValue.Real(self.doubleValue) : BindableValue.Long(self.longLongValue) }
}
extension NSString : Bindable {
public var bindableValue:BindableValue { let utf8 = UTF8String; return .UTF8(toVoid(utf8),byteCount:Int(strlen(utf8))) }
public var bindableText:(utf8:UnsafePointer<Void>,byteCount:Int) { let utf8 = UTF8String; return (toVoid(utf8),Int(strlen(utf8))) }
}
extension NSData : Bindable {
public var bindableValue:BindableValue { return .Blob(bytes,byteCount:length) }
public var bindableBlob:(data:UnsafePointer<Void>,byteCount:Int) { return (bytes,byteCount:length) }
public var bindableString:NSString { return NSString( data:self, encoding:NSUTF8StringEncoding )! }
}
extension Array : Bindable /* where Element : BinaryRepresentable */ {
public var bindableSize:Int { return self.count*sizeof(Element.self) }
public var bindableValue:BindableValue { return bindableSize > 0 && Element.self is BinaryRepresentable.Type ? .Blob(toVoid(self),byteCount:bindableSize) : .Null }
}
extension UnsafeBufferPointer : Bindable {
public var bindableSize:Int { return self.count*sizeof(Element.self) }
public var bindableValue:BindableValue { return .Blob(self.baseAddress,byteCount:bindableSize) }
}
extension UnsafePointer : Bindable {
public var bindableValue:BindableValue { return .Blob(self,byteCount:sizeof(Memory.self)) }
}
public struct BindableZeroData : Bindable {
public let length:Int32
public var bindableValue:BindableValue { return .Zero(byteCount:Int32(length)) }
}
extension Array : QueryAppendable {
public var prefersQueryValue:QueryValue? { return QueryValue.forType( first ) }
mutating public func queryAppend<T>( value:T ) { append( value as! Element ) }
}
extension Set : QueryAppendable {
public var prefersQueryValue:QueryValue? { return QueryValue.forType( first ) }
mutating public func queryAppend<T>( value:T ) { insert( value as! Element ) }
}
private let SQLITE_BOOL:Int32 = 8
private let SQLITE_STATIC = unsafeBitCast( intptr_t(0), sqlite3_destructor_type.self )
private let SQLITE_TRANSIENT = unsafeBitCast( intptr_t(-1), sqlite3_destructor_type.self )
/*
import CoreGraphics
extension CGFloat : Bindable, BinaryRepresentable { public var bindableValue:BindableValue { return .Real(Double(self)) } }
extension CGSize : BinaryRepresentable {}
extension CGPoint : BinaryRepresentable {}
extension CGRect : BinaryRepresentable {}
extension CGVector : BinaryRepresentable {}
extension CGAffineTransform : BinaryRepresentable {}
*/
|
mit
|
c16efe8516201f167214fee65fde374a
| 39.397397 | 310 | 0.693535 | 3.637076 | false | false | false | false |
antitypical/Manifold
|
Manifold/Module+PropositionalEquality.swift
|
1
|
576
|
// Copyright © 2015 Rob Rix. All rights reserved.
extension Module {
public static var propositionalEquality: Module {
let Identical = Declaration("≡",
type: nil => { A in A --> A --> .Type },
value: nil => { A in (A, A) => { x, y in .Type => { Motive in (A --> A --> Motive) --> Motive } } })
let refl = Declaration("refl",
type: nil => { A in A => { a in Identical.ref[A, a, a] } },
value: nil => { A in A => { a in nil => { Motive in (A --> A --> Motive) => { f in f[a, a] } } } })
return Module("PropositionalEquality", [ Identical, refl ])
}
}
|
mit
|
bb9da0ec462ff4e0bd6c92c32ac8c3eb
| 37.2 | 103 | 0.544503 | 2.984375 | false | false | false | false |
recruit-lifestyle/Sidebox
|
Pod/Classes/Model/SBDataModel.swift
|
1
|
915
|
//
// SBDataModel.swift
// Pods
//
// Created by Nonchalant on 2015/07/30.
// Copyright (c) 2015 Nonchalant. All rights reserved.
//
import Foundation
class SBDataModel: NSObject {
static let sharedInstance = SBDataModel()
private(set) var array = [SBDataObject]()
final func sbDataAdd(data: SBDataObject) {
data.id = array.count
array.append(data)
}
final func sbDataRemove(id: Int) {
for (var i = 0 ; i < array.count ; i++) {
if (array[i].id == id) {
array.removeAtIndex(i)
sbDataAlign(id)
NSNotificationCenter.defaultCenter().postNotificationName("sbRemove", object: nil, userInfo: ["id": i])
break
}
}
}
private func sbDataAlign(id: Int) {
for (var i = id ; i < array.count ; i++) {
array[i].id = i
}
}
}
|
mit
|
a69f564e4cb49da8885d40fdec2dabdb
| 23.72973 | 119 | 0.537705 | 3.860759 | false | false | false | false |
zasia3/archivervapor
|
Sources/App/Controllers/AuthController.swift
|
1
|
2478
|
//
// AuthController.swift
// Archiver
//
// Created by Joanna Zatorska on 31/05/2017.
//
//
import Vapor
import HTTP
final class AuthController {
func addRoutes(to builder: RouteBuilder) {
builder.post("login", handler: loginUser)
builder.post("register", handler: registerUser)
builder.post("logout", handler: logout)
}
func registerUser(_ request: Request) throws -> ResponseRepresentable {
let user = try request.user()
if try User.makeQuery().filter("name", user.name).first() == nil {
try user.save()
let token = try userToken(username: user.name, password: user.password, id: user.id!)
try token.save()
return token
} else {
throw RequestError.userExists
}
}
func loginUser(_ request: Request) throws -> ResponseRepresentable {
guard let password = request.json?["password"]?.string,
let name = request.json?["name"]?.string else {
throw Abort(.badRequest)
}
guard let existingUser = try User.makeQuery().filter("name", name).first() else {
throw RequestError.userNotExisting
}
if try User.hasher().verify(password: password, matches: existingUser.password) {
let authToken = try AuthToken.makeQuery().filter("user_id", existingUser.id).first()
let token = try userToken(username: existingUser.name, password: existingUser.password, id: existingUser.id!)
try token.save()
try authToken?.delete()
return token
}
throw RequestError.invalidPassword
}
func logout(_ request: Request) throws -> ResponseRepresentable {
guard let name = request.json?["name"]?.string else {
throw Abort(.badRequest)
}
guard let existingUser = try User.makeQuery().filter("name", name).first() else {
throw RequestError.userNotExisting
}
let userToken = try AuthToken.makeQuery().filter("user_id", existingUser.id!)
try userToken.delete()
return "Logged out"
}
private func userToken(username: String, password: String, id: Identifier) throws -> AuthToken {
let token = try TokenCreator.token(username: username, userPassword: password)
let userToken = AuthToken(token: token, userId: id)
return userToken
}
}
|
mit
|
2c2b2831742abf1bb7905795e836c2fe
| 32.486486 | 121 | 0.60573 | 4.729008 | false | false | false | false |
aichamorro/fitness-tracker
|
Clients/Apple/FitnessTracker/FitnessTracker/Data/FitnessInfo+Operators.swift
|
1
|
1022
|
//
// FitnessInfo+Operators.swift
// FitnessTracker
//
// Created by Alberto Chamorro - Personal on 23/12/2016.
// Copyright © 2016 OnsetBits. All rights reserved.
//
import Foundation
func == (lhs: IFitnessInfo, rhs: IFitnessInfo) -> Bool {
if lhs.height != rhs.height { return false }
if lhs.weight != rhs.weight { return false }
let errorTolerance = 0.000001
if abs(lhs.bodyFatPercentage - rhs.bodyFatPercentage) >= errorTolerance { return false }
if abs(lhs.musclePercentage - rhs.musclePercentage) >= errorTolerance { return false }
return true
}
func - (lhs: IFitnessInfo, rhs: IFitnessInfo) -> IFitnessInfo {
return FitnessInfo(weight: lhs.weight - rhs.weight,
height: lhs.height - lhs.height,
bodyFatPercentage: lhs.bodyFatPercentage - rhs.bodyFatPercentage,
musclePercentage: lhs.musclePercentage - rhs.musclePercentage,
waterPercentage: lhs.waterPercentage - rhs.waterPercentage)
}
|
gpl-3.0
|
7f7647a8ebb6ca0b0aa6e2b50c01f89b
| 35.464286 | 92 | 0.666993 | 4.201646 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio
|
uoregon-cis-399/finalProject/TotalTime/Source/Service/TimeService.swift
|
1
|
1930
|
//
// TimeService.swift
// TotalTime
//
// Created by Dylan Secreast on 3/1/17.
// Copyright © 2017 Dylan Secreast. All rights reserved.
//
import CoreData
class TimeService {
func jobData() -> NSFetchedResultsController<Job> {
let fetchRequest: NSFetchRequest<Job> = Job.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key:"title", ascending: false)]
return fetchedResultsController(for: fetchRequest)
}
func clientData() -> NSFetchedResultsController<Client> {
let fetchRequest: NSFetchRequest<Client> = Client.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key:"email", ascending: false)]
return fetchedResultsController(for: fetchRequest)
}
// MARK: Private
func fetchedResultsController<T>(for fetchRequest: NSFetchRequest<T>) -> NSFetchedResultsController<T> {
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchedResultsController.performFetch()
}
catch let error {
fatalError("Could not perform fetch for fetched results controller: \(error)")
}
return fetchedResultsController
}
// MARK: Initialization
private init() {
persistentContainer = NSPersistentContainer(name: "TotalTime")
persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
let context = self.persistentContainer.viewContext
context.perform {
// DO SOMETHING
// try! context.save()
}
})
}
// MARK: Private
private let persistentContainer: NSPersistentContainer
// MARK: Properties (Static)
static let shared = TimeService()
}
|
gpl-3.0
|
2fab2b783c3975f6c8edd8b92c097f8b
| 32.842105 | 189 | 0.666667 | 5.690265 | false | false | false | false |
carabina/ReviewTime
|
ReviewTime/Extensions/NSDate/NSDate.swift
|
1
|
5874
|
//
// NSDate.swift
//
// Created by Nathan Hegedus on 27/05/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
extension NSDate {
var formatted: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return formatter.stringFromDate(self)
}
// MARK: - Public Methods
// MARK: Difference From Dates
func yearsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear, fromDate: date, toDate: self, options: nil).year
}
func monthsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date, toDate: self, options: nil).month
}
func weeksFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: date, toDate: self, options: nil).weekOfYear
}
func daysFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitDay, fromDate: date, toDate: self, options: nil).day
}
func hoursFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitHour, fromDate: date, toDate: self, options: nil).hour
}
func minutesFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMinute, fromDate: date, toDate: self, options: nil).minute
}
func secondsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitSecond, fromDate: date, toDate: self, options: nil).second
}
func offsetFrom(date:NSDate) -> (offSet: Int, newDateWithOffset: NSDate)? {
let yearsOffset = yearsFrom(date)
if yearsOffset > 0 { return (yearsOffset, NSDate.sumYears(yearsOffset, toDate: date)) }
let monthsOffset = monthsFrom(date)
if monthsOffset > 0 { return (monthsOffset, NSDate.sumMonths(monthsOffset, toDate: date)) }
let weeksOffset = weeksFrom(date)
if weeksOffset > 0 { return (weeksOffset, NSDate.sumWeeks(weeksOffset, toDate: date)) }
let daysOffset = daysFrom(date)
if daysOffset > 0 { return (daysOffset, NSDate.sumDays(daysOffset, toDate: date)) }
let hoursOffset = hoursFrom(date)
if hoursOffset > 0 { return (hoursOffset, NSDate.sumHours(hoursOffset, toDate: date)) }
let minutesOffset = minutesFrom(date)
if minutesOffset > 0 { return (minutesOffset, NSDate.sumMinutes(minutesOffset, toDate: date)) }
let secondsOffset = secondsFrom(date)
if secondsOffset > 0 { return (secondsOffset, NSDate.sumSeconds(secondsOffset, toDate: date)) }
return nil
}
// MARK: Compare Date
func isGreaterThanDate(dateToCompare : NSDate) -> Bool {
return self.compareDate(dateToCompare, withComparisonResult: .OrderedDescending)
}
func isLessThanDate(dateToCompare : NSDate) -> Bool {
return self.compareDate(dateToCompare, withComparisonResult: .OrderedAscending)
}
func isDateEqualsToDate(dateToCompare : NSDate) -> Bool {
return self.compareDate(dateToCompare, withComparisonResult: .OrderedSame)
}
private func compareDate(date: NSDate, withComparisonResult: NSComparisonResult) -> Bool {
return self.compare(date) == withComparisonResult
}
// MARK: - Public Static Methods
// MARK: Changing Date
class func sumYears(year: Int, toDate date: NSDate) -> NSDate {
return self.editDateByAddingUnit(.CalendarUnitYear, value: year, toDate: date)
}
class func sumMonths(months: Int, toDate date: NSDate) -> NSDate {
return self.editDateByAddingUnit(.CalendarUnitMonth, value: months, toDate: date)
}
class func sumWeeks(weeks: Int, toDate date: NSDate) -> NSDate {
return self.editDateByAddingUnit(.CalendarUnitWeekOfYear, value: weeks, toDate: date)
}
class func sumDays(days: Int, toDate date: NSDate) -> NSDate {
return self.editDateByAddingUnit(.CalendarUnitDay, value: days, toDate: date)
}
class func sumHours(hours: Int, toDate date: NSDate) -> NSDate {
return self.editDateByAddingUnit(.CalendarUnitHour, value: hours, toDate: date)
}
class func sumMinutes(minutes: Int, toDate date: NSDate) -> NSDate {
return self.editDateByAddingUnit(.CalendarUnitMinute, value: minutes, toDate: date)
}
class func sumSeconds(seconds: Int, toDate date: NSDate) -> NSDate {
return self.editDateByAddingUnit(.CalendarUnitSecond, value: seconds, toDate: date)
}
// MARK: Localization
class func localeDateStringFromDate(date: NSDate) -> String {
return self.localeDateStringFromDate(date, withStyle: .ShortStyle)
}
class func localeDateStringFromDate(date: NSDate, withStyle style: NSDateFormatterStyle) -> String {
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = style
dateFormatter.locale = NSLocale.currentLocale()
return dateFormatter.stringFromDate(date)
}
// MARK: - Private Static Methods
private class func editDateByAddingUnit(unit: NSCalendarUnit, value: Int, toDate date: NSDate) -> NSDate {
var newDate = NSCalendar.currentCalendar().dateByAddingUnit(
unit,
value: value,
toDate: date,
options: NSCalendarOptions(0))
return newDate!
}
}
|
mit
|
c02c4de1e88fc62a3e4efb2b271899f2
| 43.847328 | 148 | 0.681648 | 4.525424 | false | false | false | false |
ONode/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Dialogs/DialogsViewController.swift
|
9
|
9740
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class DialogsViewController: EngineListController, UISearchBarDelegate, UISearchDisplayDelegate {
var tableView: UITableView!
var searchView: UISearchBar?
var searchDisplay: UISearchDisplayController?
var searchSource: DialogsSearchSource?
var binder = Binder()
init() {
super.init(contentSection: 0)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabMessages", comment: "Messages Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("ic_chats_outline"),
selectedImage: MainAppTheme.tab.createSelectedIcon("ic_chats_filled"))
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
self.extendedLayoutIncludesOpaqueBars = true
tableView = UITableView()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.rowHeight = 76
tableView.backgroundColor = MainAppTheme.list.backyardColor
view.addSubview(tableView)
// view = tableView
}
override func buildDisplayList() -> ARBindedDisplayList {
return Actor.getDialogsDisplayList()
}
func isTableEditing() -> Bool {
return self.tableView.editing;
}
override func viewDidLoad() {
// Footer
var footer = TableViewHeader(frame: CGRectMake(0, 0, 320, 80));
var footerHint = UILabel(frame: CGRectMake(0, 0, 320, 60));
footerHint.textAlignment = NSTextAlignment.Center;
footerHint.font = UIFont.systemFontOfSize(16);
footerHint.textColor = MainAppTheme.list.hintColor
footerHint.text = NSLocalizedString("DialogsHint", comment: "Swipe hint")
footer.addSubview(footerHint);
var shadow = UIImageView(image: UIImage(named: "CardBottom2"));
shadow.frame = CGRectMake(0, 0, 320, 4);
shadow.contentMode = UIViewContentMode.ScaleToFill;
footer.addSubview(shadow);
self.tableView.tableFooterView = footer;
bindTable(tableView, fade: true);
searchView = UISearchBar()
searchView!.delegate = self
searchView!.frame = CGRectMake(0, 0, 320, 44)
searchView!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
MainAppTheme.search.styleSearchBar(searchView!)
searchDisplay = UISearchDisplayController(searchBar: searchView, contentsController: self)
searchDisplay?.searchResultsDelegate = self
searchDisplay?.searchResultsTableView.rowHeight = 76
searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
searchDisplay?.searchResultsTableView.backgroundColor = MainAppTheme.list.backyardColor
searchDisplay?.searchResultsTableView.frame = tableView.frame
var header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(searchDisplay!.searchBar)
// var headerShadow = UIImageView(frame: CGRectMake(0, -4, 320, 4));
// headerShadow.image = UIImage(named: "CardTop2");
// headerShadow.contentMode = UIViewContentMode.ScaleToFill;
// header.addSubview(headerShadow);
tableView.tableHeaderView = header
searchSource = DialogsSearchSource(searchDisplay: searchDisplay!)
super.viewDidLoad();
navigationItem.title = NSLocalizedString("TabMessages", comment: "Messages Title")
navigationItem.leftBarButtonItem = editButtonItem()
navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title");
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose")
placeholder.setImage(
UIImage(named: "chat_list_placeholder"),
title: NSLocalizedString("Placeholder_Dialogs_Title", comment: "Placeholder Title"),
subtitle: NSLocalizedString("Placeholder_Dialogs_Message", comment: "Placeholder Message"))
binder.bind(Actor.getAppState().getIsDialogsEmpty(), closure: { (value: Any?) -> () in
if let empty = value as? JavaLangBoolean {
if Bool(empty.booleanValue()) == true {
self.navigationItem.leftBarButtonItem = nil
self.showPlaceholder()
} else {
self.hidePlaceholder()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
}
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
Actor.onDialogsOpen();
}
override func viewDidDisappear(animated: Bool) {
Actor.onDialogsClosed();
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// SearchBar hack
var searchBar = searchDisplay!.searchBar
var superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
// Header hack
tableView.tableHeaderView?.setNeedsLayout()
tableView.tableFooterView?.setNeedsLayout()
// tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
if (searchDisplay != nil && searchDisplay!.active) {
MainAppTheme.search.applyStatusBar()
} else {
MainAppTheme.navigation.applyStatusBar()
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
searchDisplay?.setActive(false, animated: animated)
}
// MARK: -
// MARK: Setters
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: animated)
if (editing) {
self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationDone", comment: "Done Title");
self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Done;
navigationItem.rightBarButtonItem = nil
}
else {
self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title");
self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Bordered;
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose")
}
if editing == true {
navigationItem.rightBarButtonItem = nil
} else {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose")
}
}
// MARK: -
// MARK: UITableView
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
var dialog = objectAtIndexPath(indexPath) as! ACDialog
execute(Actor.deleteChatCommandWithPeer(dialog.getPeer()));
}
}
override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
let reuseKey = "cell_dialog";
var cell = tableView.dequeueReusableCellWithIdentifier(reuseKey) as! DialogCell?;
if (cell == nil){
cell = DialogCell(reuseIdentifier: reuseKey);
cell?.awakeFromNib();
}
return cell!;
}
override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
var dialog = item as! ACDialog;
let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section)-1;
(cell as! DialogCell).bindDialog(dialog, isLast: isLast);
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (tableView == self.tableView) {
var dialog = objectAtIndexPath(indexPath) as! ACDialog
navigateToMessagesWithPeer(dialog.getPeer())
} else {
var searchEntity = searchSource!.objectAtIndexPath(indexPath) as! ACSearchEntity
navigateToMessagesWithPeer(searchEntity.getPeer())
}
}
// MARK: -
// MARK: Navigation
func navigateToCompose() {
navigateDetail(ComposeController())
}
private func navigateToMessagesWithPeer(peer: ACPeer) {
navigateDetail(ConversationViewController(peer: peer))
MainAppTheme.navigation.applyStatusBar()
}
}
|
mit
|
add18518f9218c4bac247890c09fd9ca
| 36.898833 | 158 | 0.64271 | 5.633314 | false | false | false | false |
LoopKit/LoopKit
|
LoopKit/InsulinKit/ManualBolusRecommendation.swift
|
1
|
4759
|
//
// ManualBolusRecommendation.swift
// LoopKit
//
// Created by Pete Schwamb on 1/2/17.
// Copyright © 2017 LoopKit Authors. All rights reserved.
//
import Foundation
import HealthKit
public enum BolusRecommendationNotice {
case glucoseBelowSuspendThreshold(minGlucose: GlucoseValue)
case currentGlucoseBelowTarget(glucose: GlucoseValue)
case predictedGlucoseBelowTarget(minGlucose: GlucoseValue)
case predictedGlucoseInRange
case allGlucoseBelowTarget(minGlucose: GlucoseValue)
}
extension BolusRecommendationNotice: Codable {
public init(from decoder: Decoder) throws {
if let string = try? decoder.singleValueContainer().decode(String.self) {
switch string {
case CodableKeys.predictedGlucoseInRange.rawValue:
self = .predictedGlucoseInRange
default:
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "invalid enumeration"))
}
} else {
let container = try decoder.container(keyedBy: CodableKeys.self)
if let glucoseBelowSuspendThreshold = try container.decodeIfPresent(GlucoseBelowSuspendThreshold.self, forKey: .glucoseBelowSuspendThreshold) {
self = .glucoseBelowSuspendThreshold(minGlucose: glucoseBelowSuspendThreshold.minGlucose)
} else if let currentGlucoseBelowTarget = try container.decodeIfPresent(CurrentGlucoseBelowTarget.self, forKey: .currentGlucoseBelowTarget) {
self = .currentGlucoseBelowTarget(glucose: currentGlucoseBelowTarget.glucose)
} else if let predictedGlucoseBelowTarget = try container.decodeIfPresent(PredictedGlucoseBelowTarget.self, forKey: .predictedGlucoseBelowTarget) {
self = .predictedGlucoseBelowTarget(minGlucose: predictedGlucoseBelowTarget.minGlucose)
} else if let allGlucoseBelowTarget = try container.decodeIfPresent(AllGlucoseBelowTarget.self, forKey: .allGlucoseBelowTarget) {
self = .allGlucoseBelowTarget(minGlucose: allGlucoseBelowTarget.minGlucose)
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "invalid enumeration"))
}
}
}
public func encode(to encoder: Encoder) throws {
switch self {
case .glucoseBelowSuspendThreshold(let minGlucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(GlucoseBelowSuspendThreshold(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .glucoseBelowSuspendThreshold)
case .currentGlucoseBelowTarget(let glucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(CurrentGlucoseBelowTarget(glucose: SimpleGlucoseValue(glucose)), forKey: .currentGlucoseBelowTarget)
case .predictedGlucoseBelowTarget(let minGlucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(PredictedGlucoseBelowTarget(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .predictedGlucoseBelowTarget)
case .predictedGlucoseInRange:
var container = encoder.singleValueContainer()
try container.encode(CodableKeys.predictedGlucoseInRange.rawValue)
case .allGlucoseBelowTarget(minGlucose: let minGlucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(AllGlucoseBelowTarget(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .allGlucoseBelowTarget)
}
}
private struct GlucoseBelowSuspendThreshold: Codable {
let minGlucose: SimpleGlucoseValue
}
private struct CurrentGlucoseBelowTarget: Codable {
let glucose: SimpleGlucoseValue
}
private struct PredictedGlucoseBelowTarget: Codable {
let minGlucose: SimpleGlucoseValue
}
private struct AllGlucoseBelowTarget: Codable {
let minGlucose: SimpleGlucoseValue
}
private enum CodableKeys: String, CodingKey {
case glucoseBelowSuspendThreshold
case currentGlucoseBelowTarget
case predictedGlucoseBelowTarget
case predictedGlucoseInRange
case allGlucoseBelowTarget
}
}
public struct ManualBolusRecommendation {
public let amount: Double
public let pendingInsulin: Double
public var notice: BolusRecommendationNotice?
public init(amount: Double, pendingInsulin: Double, notice: BolusRecommendationNotice? = nil) {
self.amount = amount
self.pendingInsulin = pendingInsulin
self.notice = notice
}
}
extension ManualBolusRecommendation: Codable {}
|
mit
|
2a5a65370d8d53f76ec121a5a6d2b828
| 45.647059 | 159 | 0.729508 | 5.149351 | false | false | false | false |
ndagrawal/YelpApp
|
Yelp/BusinessesViewController.swift
|
1
|
6808
|
//
// BusinessesViewController.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class BusinessesViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,FiltersViewControllerDelegate{
var businesses: [Business]!
var searchBar:UISearchBar!
var filterButton:UIBarButtonItem!
var filteredData: [String]!
var data:[String]! = [String]()
var filters:FilterViewController = FilterViewController()
//IBOutlets
@IBOutlet weak var tableView: UITableView!
//MARK: - View Controller Methods
override func viewDidLoad() {
super.viewDidLoad()
self.setupDelegates()
self.setUpUI()
self.searchFilters()
filters.delegate = self
filteredData = data
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.addSearchBarAndFilterButton()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
searchBar.removeFromSuperview()
}
//MARK: - Setup Methods
func setupDelegates(){
//Setting up the tableview delegates and data source
tableView.delegate = self;
tableView.dataSource = self;
}
func addSearchBarAndFilterButton(){
//Setting up the search bar
self.automaticallyAdjustsScrollViewInsets = false
searchBar = UISearchBar()
searchBar.delegate = self
let width:CGFloat = (self.navigationController?.navigationBar.bounds.size.width)!-120
let height:CGFloat = (self.navigationController?.navigationBar.bounds.size.height)!
searchBar.frame = CGRectMake(40, 0,width,height)
self.navigationController?.navigationBar.addSubview(searchBar)
self.navigationController?.navigationBar.bringSubviewToFront(searchBar)
self.navigationController?.navigationBar.clipsToBounds = false
searchBar.backgroundColor = UIColor.redColor()
self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
//Setting up the filter button
filterButton = UIBarButtonItem.init(title: "Filter", style: UIBarButtonItemStyle.Plain, target: self, action: "filterButtonPressed")
filterButton.tintColor = UIColor.whiteColor()
self.navigationItem.rightBarButtonItem = filterButton
}
func filterButtonPressed(){
let filerViewController:FilterViewController = self.storyboard?.instantiateViewControllerWithIdentifier("FilterViewController") as! FilterViewController
filerViewController.delegate = self
// self.presentViewController(filerViewController, animated: true, completion: nil)
self.navigationController?.pushViewController(filerViewController, animated: true)
}
func setUpUI(){
//Setting up the table View
tableView.rowHeight = 140
}
func setUpInitialValues(){
}
func searchFilters(){
Business.searchWithTerm("Thai", completion: { (businesses: [Business]!, error: NSError!) -> Void in
self.businesses = businesses
self.tableView.reloadData()
for business in businesses {
print(business.name!)
business.name!
self.data.append("\(business.name!)")
print(business.address!)
}
filteredData = data
})
}
//MARK: - Table View Delegate Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if let businesses = businesses{
return businesses.count
}else{
return 0;
}
}
func filtersViewController(filterSviewController:FilterViewController,didUpdateFilters filters:NSMutableDictionary){
var filteredCategories:[String]? = [""]
var filteredDealsString:String! = "off"
var filterSortMode:String! = "bestmatch"
var filterDeal:Bool!
var sortMode:YelpSortMode!
filteredCategories = filters.objectForKey("categories") as! [String]!
filteredDealsString = filters.objectForKey("deal") as! String!
filterSortMode = filters.objectForKey("sortBy") as! String!
if (filteredDealsString != nil && filteredDealsString == "on") {
filterDeal = true
}else{
filterDeal = false
}
if (filterSortMode != nil && filterSortMode == "bestmatch"){
sortMode = YelpSortMode.BestMatched
}else if (filterSortMode != nil && filterSortMode == "distance"){
sortMode = YelpSortMode.Distance
}else{
sortMode = YelpSortMode.HighestRated
}
Business.searchWithTerm("Restaurants", sort: sortMode, categories: filteredCategories, deals:filterDeal) {(businesses: [Business]!, error: NSError!) -> Void in
self.businesses = businesses
self.tableView.reloadData()
self.data.removeAll()
for business in businesses {
self.data.append("\(business.name!)")
print(business.name!)
print(business.address!)
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("BusinessCell", forIndexPath: indexPath) as! BusinessListTableViewCell
cell.business = businesses[indexPath.row];
return cell;
}
//MARK: - SearchBar
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = searchText.isEmpty ? data : data.filter({(dataString: String) -> Bool in
return dataString.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
})
tableView.reloadData()
}
func hideKeyBoardWithSearchBar(searchBar:UISearchBar){
searchBar.resignFirstResponder()
}
// 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.
}
*/
//MARK: - Memory Warnings
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
ea1829d674919a9831b87b5c5cf866e4
| 33.912821 | 167 | 0.65658 | 5.424701 | false | false | false | false |
DroidsOnRoids/DORSidebar
|
SidebarMenu/Views/DORSidebarMenuView.swift
|
1
|
1606
|
//
// DORSidebarMenuView.swift
// SidebarMenu
//
// Created by Piotr Sochalewski on 20.01.2016.
// Copyright © 2016 Droids On Roids. All rights reserved.
//
import UIKit
class DORSidebarMenuView: UIView {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var dismissButton: UIButton!
var visible: Bool {
return CGRectGetMidX(view.frame) >= 0.0
}
var view: UIView!
init(width: CGFloat) {
super.init(frame: CGRect(x: -width, y: 0.0, width: width, height: CGRectGetHeight(UIScreen.mainScreen().bounds)))
view = NSBundle.mainBundle().loadNibNamed(String(self.dynamicType), owner: self, options: nil).first as! UIView
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view)
tableView.separatorStyle = .None
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(duration duration: NSTimeInterval) {
UIView.animateWithDuration(duration) {
self.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.width, height: CGRectGetHeight(UIScreen.mainScreen().bounds))
}
}
func dismiss(duration duration: NSTimeInterval, finished: ((Bool) -> Void)?) {
UIView.animateWithDuration(duration,
animations: {
self.frame = CGRect(x: -self.frame.width, y: 0.0, width: self.frame.width, height: CGRectGetHeight(UIScreen.mainScreen().bounds))
},
completion: finished
)
}
}
|
mit
|
013e03cd9f877447930460942e05bdb2
| 30.490196 | 145 | 0.631153 | 4.268617 | false | false | false | false |
ryanipete/AmericanChronicle
|
AmericanChronicle/Code/Modules/Page/PageWireframe.swift
|
1
|
3136
|
import PDFKit
import UIKit
// MARK: -
// MARK: PageWireframeInterface protocol
protocol PageWireframeInterface: AnyObject {
func present(from: UIViewController?,
withSearchTerm: String?,
remoteURL: URL,
id: String,
thumbnail: UIImageView)
func dismiss()
func showShareScreen(withPDF pdf: PDFPage)
}
// MARK: -
// MARK: PageWireframeDelegate protocol
protocol PageWireframeDelegate: AnyObject {
func pageWireframeDidFinish()
}
typealias UIConstructor = () -> PageUserInterface?
// MARK: -
// MARK: PageWireframe class
final class PageWireframe: NSObject, PageWireframeInterface {
// MARK: Properties
private weak var delegate: PageWireframeDelegate?
private let presenter: PagePresenterInterface
private let uiConstructor: UIConstructor
private var pageTransitioner: PageTransitioningDelegate?
private var presentedUI: PageUserInterface?
private var presentingViewController: UIViewController?
// MARK: Init methods
init(delegate: PageWireframeDelegate,
presenter: PagePresenterInterface = PagePresenter(),
uiConstructor: @escaping UIConstructor = defaultUIConstructor) {
self.delegate = delegate
self.presenter = presenter
self.uiConstructor = uiConstructor
super.init()
presenter.wireframe = self
}
// MARK: PageWireframeInterface conformance
func present(from presentingViewController: UIViewController?,
withSearchTerm searchTerm: String?,
remoteURL: URL,
id: String,
thumbnail: UIImageView) {
guard let ui = uiConstructor() else {
return
}
ui.thumbnailImage = thumbnail.image
ui.modalPresentationStyle = .custom
pageTransitioner = PageTransitioningDelegate(originThumbnail: thumbnail)
ui.transitioningDelegate = pageTransitioner
ui.delegate = presenter
presenter.configure(userInterface: ui,
withSearchTerm: searchTerm,
remoteDownloadURL: remoteURL,
id: id)
if let vc = ui as? UIViewController {
presentingViewController?.present(vc, animated: true, completion: nil)
}
presentedUI = ui
self.presentingViewController = presentingViewController
}
func dismiss() {
presentingViewController?.dismiss(animated: true) {
self.delegate?.pageWireframeDidFinish()
}
}
func showShareScreen(withPDF pdf: PDFPage) {
guard let data = pdf.dataRepresentation else {
assertionFailure()
return
}
let vc = UIActivityViewController(activityItems: [data], applicationActivities: [])
presentedUI?.present(vc, animated: true, completion: nil)
}
private static func defaultUIConstructor() -> PageUserInterface? {
let storyboard = UIStoryboard(name: "Page", bundle: nil)
return storyboard.instantiateInitialViewController() as? PageViewController
}
}
|
mit
|
30c137ed61930bfb1c5d185bb9c80ce7
| 31.329897 | 91 | 0.654656 | 5.580071 | false | false | false | false |
rudkx/swift
|
test/Generics/concrete_contraction_unrelated_typealias.swift
|
1
|
2922
|
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s
// Another GenericSignatureBuilder oddity, reduced from RxSwift.
//
// The requirements 'Proxy.Parent == P' and 'Proxy.Delegate == D' in the
// init() below refer to both the typealias and the associated type,
// despite the class being unrelated to the protocol; it just happens to
// define typealiases with the same name.
//
// In the Requirement Machine, the concrete contraction pre-processing
// pass would eagerly substitute the concrete type into these two
// requirements, producing the useless requirements 'P == P' and 'D == D'.
//
// Make sure concrete contraction keeps these requirements as-is by
// checking the generic signature with and without concrete contraction.
class GenericDelegateProxy<P : AnyObject, D> {
typealias Parent = P
typealias Delegate = D
// Here if we resolve Proxy.Parent and Proxy.Delegate to the typealiases,
// we get vacuous requirements 'P == P' and 'D == D'. By keeping both
// the substituted and original requirement, we ensure that the
// unrelated associated type 'Parent' is constrained instead.
// CHECK-LABEL: .GenericDelegateProxy.init(_:)@
// CHECK-NEXT: <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : GenericDelegateProxy<P, D>, Proxy : DelegateProxyType>
init<Proxy: DelegateProxyType>(_: Proxy.Type)
where Proxy: GenericDelegateProxy<P, D>,
Proxy.Parent == P,
Proxy.Delegate == D {}
}
class SomeClass {}
struct SomeStruct {}
class ConcreteDelegateProxy {
typealias Parent = SomeClass
typealias Delegate = SomeStruct
// An even more esoteric edge case. Note that this one I made up; only
// the first one is relevant for compatibility with RxSwift.
//
// Here unfortunately we produce a different result from the GSB, because
// the hack for keeping both the substituted and original requirement means
// the substituted requirements become 'P == SomeClass' and 'D == SomeStruct'.
//
// The GSB does not constrain P and D in this way and instead produced the
// following minimized signature:
//
// <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType>!
// CHECK-LABEL: .ConcreteDelegateProxy.init(_:_:_:)@
// CHECK-NEXT: <P, D, Proxy where P == SomeClass, D == SomeStruct, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType, Proxy.[DelegateProxyType]Delegate == SomeStruct, Proxy.[DelegateProxyType]Parent == SomeClass>
init<P, D, Proxy: DelegateProxyType>(_: P, _: D, _: Proxy.Type)
where Proxy: ConcreteDelegateProxy,
Proxy.Parent == P,
Proxy.Delegate == D {}
}
protocol DelegateProxyType {
associatedtype Parent : AnyObject
associatedtype Delegate
}
|
apache-2.0
|
7b2cfee352ef02bf567b4b58ae0b7123
| 43.953846 | 221 | 0.723819 | 4.509259 | false | false | false | false |
michael-groble/Geohash
|
Sources/Geohash/GeohashBits.swift
|
1
|
8771
|
//
// GeohashBits.swift
// Geohash
//
// Created by michael groble on 1/6/17.
//
//
import Foundation
public enum Precision {
case bits(UInt8)
case characters(UInt8)
func binaryPrecision() -> UInt8 {
switch self {
case .bits(let n):
return n
case .characters(let n):
return UInt8(ceil(0.5 * Double(5 * n)))
}
}
func characterPrecision() -> UInt8 {
switch self {
case .bits(let n):
return UInt8(0.4 * Double(n))
case .characters(let n):
return n
}
}
func maxBinaryValue() -> Double {
return Double(UInt64(1) << UInt64(binaryPrecision()))
}
func isOddCharacters() -> Bool {
switch self {
case .bits:
return false
case .characters(let n):
return (n % 2) > 0
}
}
}
public struct GeohashBits {
public let bits : UInt64
public let precision : Precision
init(bits: UInt64, precision: Precision) throws {
guard precision.binaryPrecision() <= 32 else {
throw GeohashError.invalidPrecision
}
self.bits = bits
self.precision = precision
}
public init(location: Location, precision: Precision) throws {
guard precision.binaryPrecision() <= 32 else {
throw GeohashError.invalidPrecision
}
guard longitudeRange.contains(location.longitude) &&
latitudeRange.contains(location.latitude) else {
throw GeohashError.invalidLocation
}
let latitudeBits = doubleToBits(location.latitude, range: latitudeRange, maxBinaryValue: precision.maxBinaryValue())
let longitudeBits = doubleToBits(location.longitude, range: longitudeRange, maxBinaryValue: precision.maxBinaryValue())
self.bits = interleave(evenBits: latitudeBits, oddBits: longitudeBits)
self.precision = precision
}
public init(hash: String) throws {
let precision = Precision.characters(UInt8(hash.count))
let totalBinaryPrecision = UInt64(2 * precision.binaryPrecision())
var bits = UInt64(0)
for (i, c) in hash.enumerated() {
bits |= (base32Bits[c]! << (totalBinaryPrecision - (UInt64(i) + 1) * 5))
}
try self.init(bits: bits, precision: precision)
}
public func hash() -> String {
var hash = ""
let characterPrecision = self.precision.characterPrecision();
let totalBinaryPrecision = 2 * self.precision.binaryPrecision();
for i in 1...characterPrecision {
let index = (self.bits >> UInt64(totalBinaryPrecision - i * 5)) & 0x1f
hash += String(base32Characters[Int(index)])
}
return hash
}
public func boundingBox() -> BoundingBox {
var (latBits, lonBits) = deinterleave(self.bits)
var latPrecision = self.precision
if (self.precision.isOddCharacters()) {
latBits >>= 1;
latPrecision = Precision.bits(latPrecision.binaryPrecision() - 1);
}
return try! BoundingBox(
min: Location(longitude: bitsToDouble(lonBits, range: longitudeRange, maxBinaryValue: self.precision.maxBinaryValue()),
latitude: bitsToDouble(latBits, range: latitudeRange, maxBinaryValue: latPrecision.maxBinaryValue())),
max: Location(longitude: bitsToDouble(lonBits + 1, range: longitudeRange, maxBinaryValue: self.precision.maxBinaryValue()),
latitude: bitsToDouble(latBits + 1, range: latitudeRange, maxBinaryValue: latPrecision.maxBinaryValue()))
)
}
public enum Neighbor {
case west
case east
case south
case north
}
public func neighbor(_ neighbor: Neighbor) -> GeohashBits {
switch neighbor {
case .north:
return incremented(set: .evens, direction: +1)
case .south:
return incremented(set: .evens, direction: -1)
case .east:
return incremented(set: .odds, direction: +1)
case .west:
return incremented(set: .odds, direction: -1)
}
}
enum InterleaveSet : UInt64 {
case odds
case evens
func modifyMask() -> UInt64 {
switch self {
case .evens:
return 0x5555555555555555
case .odds:
return 0xaaaaaaaaaaaaaaaa
}
}
func keepMask() -> UInt64 {
switch self {
case .evens:
return 0xaaaaaaaaaaaaaaaa
case .odds:
return 0x5555555555555555
}
}
}
func incremented(set: InterleaveSet, direction: Int) -> GeohashBits {
if direction == 0 {
return self
}
var modifyBits = self.bits & set.modifyMask()
let keepBits = self.bits & set.keepMask()
let binaryPrecision = UInt64(self.precision.binaryPrecision())
let increment = set.keepMask() >> (64 - 2 * binaryPrecision)
let shiftBits = set == .evens && self.precision.isOddCharacters()
if shiftBits {
modifyBits >>= 2;
}
if direction > 0 {
modifyBits += (increment + 1)
}
else {
modifyBits |= increment
modifyBits -= (increment + 1)
}
if shiftBits {
modifyBits <<= 2;
}
modifyBits &= set.modifyMask() >> (64 - 2 * binaryPrecision)
return try! GeohashBits(bits: modifyBits | keepBits, precision: self.precision)
}
}
fileprivate let longitudeRange = -180.0...180.0
fileprivate let latitudeRange = -90.0...90.0
fileprivate func doubleToBits(_ x: Double, range: ClosedRange<Double>, maxBinaryValue: Double) -> UInt32 {
let fraction = (x - range.lowerBound) / (range.upperBound - range.lowerBound)
return UInt32(fraction * maxBinaryValue)
}
fileprivate func bitsToDouble(_ bits: UInt32, range: ClosedRange<Double>, maxBinaryValue: Double) -> Double {
let fraction = Double(bits) / maxBinaryValue
return range.lowerBound + fraction * (range.upperBound - range.lowerBound)
}
#if canImport(simd)
import simd
fileprivate func interleave(evenBits: UInt32, oddBits: UInt32) -> UInt64 {
var bits = SIMD2<UInt64>(UInt64(evenBits), UInt64(oddBits));
bits = (bits | (bits &<< UInt64(16))) & SIMD2<UInt64>(0x0000FFFF0000FFFF, 0x0000FFFF0000FFFF);
bits = (bits | (bits &<< UInt64( 8))) & SIMD2<UInt64>(0x00FF00FF00FF00FF, 0x00FF00FF00FF00FF);
bits = (bits | (bits &<< UInt64( 4))) & SIMD2<UInt64>(0x0F0F0F0F0F0F0F0F, 0x0F0F0F0F0F0F0F0F);
bits = (bits | (bits &<< UInt64( 2))) & SIMD2<UInt64>(0x3333333333333333, 0x3333333333333333);
bits = (bits | (bits &<< UInt64( 1))) & SIMD2<UInt64>(0x5555555555555555, 0x5555555555555555);
return bits.x | (bits.y << 1)
}
fileprivate func deinterleave(_ interleaved: UInt64) -> (evenBits: UInt32, oddBits: UInt32) {
var bits = SIMD2<UInt64>(
interleaved & 0x5555555555555555,
(interleaved >> 1) & 0x5555555555555555
)
bits = (bits | (bits &>> UInt64( 1))) & SIMD2<UInt64>(0x3333333333333333, 0x3333333333333333);
bits = (bits | (bits &>> UInt64( 2))) & SIMD2<UInt64>(0x0F0F0F0F0F0F0F0F, 0x0F0F0F0F0F0F0F0F);
bits = (bits | (bits &>> UInt64( 4))) & SIMD2<UInt64>(0x00FF00FF00FF00FF, 0x00FF00FF00FF00FF);
bits = (bits | (bits &>> UInt64( 8))) & SIMD2<UInt64>(0x0000FFFF0000FFFF, 0x0000FFFF0000FFFF);
bits = (bits | (bits &>> UInt64(16))) & SIMD2<UInt64>(0x00000000FFFFFFFF, 0x00000000FFFFFFFF);
return (evenBits: UInt32(bits.x), oddBits: UInt32(bits.y))
}
#else
fileprivate func interleave(evenBits: UInt32, oddBits: UInt32) -> UInt64 {
// swift doesn't expose vector_ulong2, otherwise we would try that
var e = UInt64(evenBits)
var o = UInt64(oddBits)
e = (e | (e << 16)) & 0x0000FFFF0000FFFF
o = (o | (o << 16)) & 0x0000FFFF0000FFFF
e = (e | (e << 8)) & 0x00FF00FF00FF00FF
o = (o | (o << 8)) & 0x00FF00FF00FF00FF
e = (e | (e << 4)) & 0x0F0F0F0F0F0F0F0F
o = (o | (o << 4)) & 0x0F0F0F0F0F0F0F0F
e = (e | (e << 2)) & 0x3333333333333333
o = (o | (o << 2)) & 0x3333333333333333
e = (e | (e << 1)) & 0x5555555555555555
o = (o | (o << 1)) & 0x5555555555555555
return e | (o << 1)
}
fileprivate func deinterleave(_ interleaved: UInt64) -> (evenBits: UInt32, oddBits: UInt32) {
var e = interleaved & 0x5555555555555555
var o = (interleaved >> 1) & 0x5555555555555555
e = (e | (e >> 1)) & 0x3333333333333333
o = (o | (o >> 1)) & 0x3333333333333333
e = (e | (e >> 2)) & 0x0F0F0F0F0F0F0F0F
o = (o | (o >> 2)) & 0x0F0F0F0F0F0F0F0F
e = (e | (e >> 4)) & 0x00FF00FF00FF00FF
o = (o | (o >> 4)) & 0x00FF00FF00FF00FF
e = (e | (e >> 8)) & 0x0000FFFF0000FFFF
o = (o | (o >> 8)) & 0x0000FFFF0000FFFF
e = (e | (e >> 16)) & 0x00000000FFFFFFFF
o = (o | (o >> 16)) & 0x00000000FFFFFFFF
return (evenBits: UInt32(e), oddBits: UInt32(o))
}
#endif
fileprivate let base32Characters = Array("0123456789bcdefghjkmnpqrstuvwxyz")
fileprivate let base32Bits = { () -> [Character: UInt64] in
// reduce does not work here since the accumulator is not inout
var hash = [Character: UInt64]()
for (i, c) in base32Characters.enumerated() {
hash[c] = UInt64(i)
}
return hash
}()
|
bsd-3-clause
|
49c323f12a44a9c92929c93e7b240a71
| 28.236667 | 129 | 0.648843 | 3.298608 | false | false | false | false |
cozkurt/coframework
|
COFramework/COFramework/Swift/Extentions/UINib+Load.swift
|
1
|
1577
|
//
// UINib+Load.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 10/07/19.
// Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved.
//
import UIKit
extension UINib {
@objc func loadIntoView(_ view: UIView) {
guard let content =
instantiate(withOwner: view, options: nil).first as? UIView else { return }
content.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(content)
view.addConstraint(NSLayoutConstraint(item: content, attribute: .top,
relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: content, attribute: .bottom,
relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: content, attribute: .left,
relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: content, attribute: .right,
relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0))
}
}
internal extension UINib {
static func loadXIBFromClassBundle<T: UIView>(_ view: T.Type) -> UINib {
let bundle = Bundle(for: T.self)
return loadXIB(view, bundle: bundle)
}
static func loadXIB<T: UIView>(_ view: T.Type, bundle: Bundle = .main) -> UINib {
let identifier = NSStringFromClass(T.self).components(separatedBy: ".").last!
return UINib(nibName: identifier, bundle: bundle)
}
}
|
gpl-3.0
|
244985da491ea99c8c1fb039f8ebfc1b
| 35.651163 | 93 | 0.662437 | 4.147368 | false | false | false | false |
ahoppen/swift
|
stdlib/public/core/SequenceAlgorithms.swift
|
4
|
31782
|
//===--- SequenceAlgorithms.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// enumerated()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence of pairs (*n*, *x*), where *n* represents a
/// consecutive integer starting at zero and *x* represents an element of
/// the sequence.
///
/// This example enumerates the characters of the string "Swift" and prints
/// each character along with its place in the string.
///
/// for (n, c) in "Swift".enumerated() {
/// print("\(n): '\(c)'")
/// }
/// // Prints "0: 'S'"
/// // Prints "1: 'w'"
/// // Prints "2: 'i'"
/// // Prints "3: 'f'"
/// // Prints "4: 't'"
///
/// When you enumerate a collection, the integer part of each pair is a counter
/// for the enumeration, but is not necessarily the index of the paired value.
/// These counters can be used as indices only in instances of zero-based,
/// integer-indexed collections, such as `Array` and `ContiguousArray`. For
/// other collections the counters may be out of range or of the wrong type
/// to use as an index. To iterate over the elements of a collection with its
/// indices, use the `zip(_:_:)` function.
///
/// This example iterates over the indices and elements of a set, building a
/// list consisting of indices of names with five or fewer letters.
///
/// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// var shorterIndices: [Set<String>.Index] = []
/// for (i, name) in zip(names.indices, names) {
/// if name.count <= 5 {
/// shorterIndices.append(i)
/// }
/// }
///
/// Now that the `shorterIndices` array holds the indices of the shorter
/// names in the `names` set, you can use those indices to access elements in
/// the set.
///
/// for i in shorterIndices {
/// print(names[i])
/// }
/// // Prints "Sofia"
/// // Prints "Mateo"
///
/// - Returns: A sequence of pairs enumerating the sequence.
///
/// - Complexity: O(1)
@inlinable // protocol-only
public func enumerated() -> EnumeratedSequence<Self> {
return EnumeratedSequence(_base: self)
}
}
//===----------------------------------------------------------------------===//
// min(), max()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the minimum element in the sequence, using the given predicate as
/// the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `min(by:)` method on a
/// dictionary to find the key-value pair with the lowest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let leastHue = hues.min { a, b in a.value < b.value }
/// print(leastHue)
/// // Prints "Optional((key: "Coral", value: 16))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The sequence's minimum element, according to
/// `areInIncreasingOrder`. If the sequence has no elements, returns
/// `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func min(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(e, result) { result = e }
}
return result
}
/// Returns the maximum element in the sequence, using the given predicate
/// as the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `max(by:)` method on a
/// dictionary to find the key-value pair with the highest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let greatestHue = hues.max { a, b in a.value < b.value }
/// print(greatestHue)
/// // Prints "Optional((key: "Heliotrope", value: 296))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: The sequence's maximum element if the sequence is not empty;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func max(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(result, e) { result = e }
}
return result
}
}
extension Sequence where Element: Comparable {
/// Returns the minimum element in the sequence.
///
/// This example finds the smallest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let lowestHeight = heights.min()
/// print(lowestHeight)
/// // Prints "Optional(58.5)"
///
/// - Returns: The sequence's minimum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func min() -> Element? {
return self.min(by: <)
}
/// Returns the maximum element in the sequence.
///
/// This example finds the largest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let greatestHeight = heights.max()
/// print(greatestHeight)
/// // Prints "Optional(67.5)"
///
/// - Returns: The sequence's maximum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func max() -> Element? {
return self.max(by: <)
}
}
//===----------------------------------------------------------------------===//
// starts(with:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are equivalent to the elements in another sequence, using
/// the given predicate as the equivalence test.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - possiblePrefix: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if the initial elements of the sequence are equivalent
/// to the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix,
by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> Bool {
var possiblePrefixIterator = possiblePrefix.makeIterator()
for e0 in self {
if let e1 = possiblePrefixIterator.next() {
if try !areEquivalent(e0, e1) {
return false
}
}
else {
return true
}
}
return possiblePrefixIterator.next() == nil
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are the same as the elements in another sequence.
///
/// This example tests whether one countable range begins with the elements
/// of another countable range.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(b.starts(with: a))
/// // Prints "true"
///
/// Passing a sequence with no elements or an empty collection as
/// `possiblePrefix` always results in `true`.
///
/// print(b.starts(with: []))
/// // Prints "true"
///
/// - Parameter possiblePrefix: A sequence to compare to this sequence.
/// - Returns: `true` if the initial elements of the sequence are the same as
/// the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix
) -> Bool where PossiblePrefix.Element == Element {
return self.starts(with: possiblePrefix, by: ==)
}
}
//===----------------------------------------------------------------------===//
// elementsEqual()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain equivalent elements in the same order, using the given
/// predicate as the equivalence test.
///
/// At least one of the sequences must be finite.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if this sequence and `other` contain equivalent items,
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence,
by areEquivalent: (Element, OtherSequence.Element) throws -> Bool
) rethrows -> Bool {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
switch (iter1.next(), iter2.next()) {
case let (e1?, e2?):
if try !areEquivalent(e1, e2) {
return false
}
case (_?, nil), (nil, _?): return false
case (nil, nil): return true
}
}
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain the same elements in the same order.
///
/// At least one of the sequences must be finite.
///
/// This example tests whether one countable range shares the same elements
/// as another countable range and an array.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(a.elementsEqual(b))
/// // Prints "false"
/// print(a.elementsEqual([1, 2, 3]))
/// // Prints "true"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence and `other` contain the same elements
/// in the same order.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.elementsEqual(other, by: ==)
}
}
//===----------------------------------------------------------------------===//
// lexicographicallyPrecedes()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the given
/// predicate to compare elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areInIncreasingOrder: A predicate that returns `true` if its first
/// argument should be ordered before its second argument; otherwise,
/// `false`.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that perform
/// localized comparison instead.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool
where OtherSequence.Element == Element {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
if let e1 = iter1.next() {
if let e2 = iter2.next() {
if try areInIncreasingOrder(e1, e2) {
return true
}
if try areInIncreasingOrder(e2, e1) {
return false
}
continue // Equivalent
}
return false
}
return iter2.next() != nil
}
}
}
extension Sequence where Element: Comparable {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the
/// less-than operator (`<`) to compare elements.
///
/// This example uses the `lexicographicallyPrecedes` method to test which
/// array of integers comes first in a lexicographical ordering.
///
/// let a = [1, 2, 2, 2]
/// let b = [1, 2, 3, 4]
///
/// print(a.lexicographicallyPrecedes(b))
/// // Prints "true"
/// print(b.lexicographicallyPrecedes(b))
/// // Prints "false"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that
/// perform localized comparison.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.lexicographicallyPrecedes(other, by: <)
}
}
//===----------------------------------------------------------------------===//
// contains()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence contains an
/// element that satisfies the given predicate.
///
/// You can use the predicate to check for an element of a type that
/// doesn't conform to the `Equatable` protocol, such as the
/// `HTTPResponse` enumeration in this example.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
/// let hadError = lastThreeResponses.contains { element in
/// if case .error = element {
/// return true
/// } else {
/// return false
/// }
/// }
/// // 'hadError' == true
///
/// Alternatively, a predicate can be satisfied by a range of `Equatable`
/// elements or a general condition. This example shows how you can check an
/// array for an expense greater than $100.
///
/// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
/// let hasBigPurchase = expenses.contains { $0 > 100 }
/// // 'hasBigPurchase' == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element represents a match.
/// - Returns: `true` if the sequence contains an element that satisfies
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(
where predicate: (Element) throws -> Bool
) rethrows -> Bool {
for e in self {
if try predicate(e) {
return true
}
}
return false
}
/// Returns a Boolean value indicating whether every element of a sequence
/// satisfies a given predicate.
///
/// The following code uses this method to test whether all the names in an
/// array have at least five characters:
///
/// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
/// // allHaveAtLeastFive == true
///
/// If the sequence is empty, this method returns `true`.
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element satisfies a condition.
/// - Returns: `true` if the sequence contains only elements that satisfy
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func allSatisfy(
_ predicate: (Element) throws -> Bool
) rethrows -> Bool {
return try !contains { try !predicate($0) }
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether the sequence contains the
/// given element.
///
/// This example checks to see whether a favorite actor is in an array
/// storing a movie's cast.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// print(cast.contains("Marlon"))
/// // Prints "true"
/// print(cast.contains("James"))
/// // Prints "false"
///
/// - Parameter element: The element to find in the sequence.
/// - Returns: `true` if the element was found in the sequence; otherwise,
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(_ element: Element) -> Bool {
if let result = _customContainsEquatableElement(element) {
return result
} else {
return self.contains { $0 == element }
}
}
}
//===----------------------------------------------------------------------===//
// reduce()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(_:_:)` method to produce a single value from the elements
/// of an entire sequence. For example, you can use this method on an array
/// of numbers to find their sum or product.
///
/// The `nextPartialResult` closure is called sequentially with an
/// accumulating value initialized to `initialResult` and each element of
/// the sequence. This example shows how to find the sum of an array of
/// numbers.
///
/// let numbers = [1, 2, 3, 4]
/// let numberSum = numbers.reduce(0, { x, y in
/// x + y
/// })
/// // numberSum == 10
///
/// When `numbers.reduce(_:_:)` is called, the following steps occur:
///
/// 1. The `nextPartialResult` closure is called with `initialResult`---`0`
/// in this case---and the first element of `numbers`, returning the sum:
/// `1`.
/// 2. The closure is called again repeatedly with the previous call's return
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the last value returned from the
/// closure is returned to the caller.
///
/// If the sequence has no elements, `nextPartialResult` is never executed
/// and `initialResult` is the result of the call to `reduce(_:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// `initialResult` is passed to `nextPartialResult` the first time the
/// closure is executed.
/// - nextPartialResult: A closure that combines an accumulating value and
/// an element of the sequence into a new accumulating value, to be used
/// in the next call of the `nextPartialResult` closure or returned to
/// the caller.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult:
(_ partialResult: Result, Element) throws -> Result
) rethrows -> Result {
var accumulator = initialResult
for element in self {
accumulator = try nextPartialResult(accumulator, element)
}
return accumulator
}
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(into:_:)` method to produce a single value from the
/// elements of an entire sequence. For example, you can use this method on an
/// array of integers to filter adjacent equal entries or count frequencies.
///
/// This method is preferred over `reduce(_:_:)` for efficiency when the
/// result is a copy-on-write type, for example an Array or a Dictionary.
///
/// The `updateAccumulatingResult` closure is called sequentially with a
/// mutable accumulating value initialized to `initialResult` and each element
/// of the sequence. This example shows how to build a dictionary of letter
/// frequencies of a string.
///
/// let letters = "abracadabra"
/// let letterCount = letters.reduce(into: [:]) { counts, letter in
/// counts[letter, default: 0] += 1
/// }
/// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]
///
/// When `letters.reduce(into:_:)` is called, the following steps occur:
///
/// 1. The `updateAccumulatingResult` closure is called with the initial
/// accumulating value---`[:]` in this case---and the first character of
/// `letters`, modifying the accumulating value by setting `1` for the key
/// `"a"`.
/// 2. The closure is called again repeatedly with the updated accumulating
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the accumulating value is returned to
/// the caller.
///
/// If the sequence has no elements, `updateAccumulatingResult` is never
/// executed and `initialResult` is the result of the call to
/// `reduce(into:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - updateAccumulatingResult: A closure that updates the accumulating
/// value with an element of the sequence.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
into initialResult: __owned Result,
_ updateAccumulatingResult:
(_ partialResult: inout Result, Element) throws -> ()
) rethrows -> Result {
var accumulator = initialResult
for element in self {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
}
//===----------------------------------------------------------------------===//
// reversed()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the elements of this sequence in reverse
/// order.
///
/// The sequence must be finite.
///
/// - Returns: An array containing the elements of this sequence in
/// reverse order.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func reversed() -> [Element] {
// FIXME(performance): optimize to 1 pass? But Array(self) can be
// optimized to a memcpy() sometimes. Those cases are usually collections,
// though.
var result = Array(self)
let count = result.count
for i in 0..<count/2 {
result.swapAt(i, count - ((i + 1) as Int))
}
return result
}
}
//===----------------------------------------------------------------------===//
// flatMap()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the concatenated results of calling the
/// given transformation with each element of this sequence.
///
/// Use this method to receive a single-level collection when your
/// transformation produces a sequence or collection for each element.
///
/// In this example, note the difference in the result of using `map` and
/// `flatMap` with a transformation that returns an array.
///
/// let numbers = [1, 2, 3, 4]
///
/// let mapped = numbers.map { Array(repeating: $0, count: $0) }
/// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
///
/// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
/// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
///
/// In fact, `s.flatMap(transform)` is equivalent to
/// `Array(s.map(transform).joined())`.
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns a sequence or collection.
/// - Returns: The resulting flattened array.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable
public func flatMap<SegmentOfResult: Sequence>(
_ transform: (Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] {
var result: [SegmentOfResult.Element] = []
for element in self {
result.append(contentsOf: try transform(element))
}
return result
}
}
extension Sequence {
/// Returns an array containing the non-`nil` results of calling the given
/// transformation with each element of this sequence.
///
/// Use this method to receive an array of non-optional values when your
/// transformation produces an optional value.
///
/// In this example, note the difference in the result of using `map` and
/// `compactMap` with a transformation that returns an optional `Int` value.
///
/// let possibleNumbers = ["1", "2", "three", "///4///", "5"]
///
/// let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
/// // [1, 2, nil, nil, 5]
///
/// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
/// // [1, 2, 5]
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns an optional value.
/// - Returns: An array of the non-`nil` results of calling `transform`
/// with each element of the sequence.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable // protocol-only
public func compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try _compactMap(transform)
}
// The implementation of compactMap accepting a closure with an optional result.
// Factored out into a separate function in order to be used in multiple
// overloads.
@inlinable // protocol-only
@inline(__always)
public func _compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
for element in self {
if let newElement = try transform(element) {
result.append(newElement)
}
}
return result
}
}
|
apache-2.0
|
d16c754bc08377023cf2b1da2935d388
| 37.993865 | 83 | 0.602958 | 4.356408 | false | false | false | false |
SomnusLee1988/Azure
|
Azure/ViewController.swift
|
1
|
12453
|
//
// ViewController.swift
// Azure
//
// Created by Somnus on 16/7/5.
// Copyright © 2016年 Somnus. All rights reserved.
//
import UIKit
import AFNetworking
import MBProgressHUD
import AVFoundation
import AVKit
import Alamofire
import MJRefresh
import SLAlertController
let URL_SUFFIX = "(format=m3u8-aapl)"
private var azureContext = 0
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var liveCollectionView: UICollectionView!
@IBOutlet var videoCollectionView: UICollectionView!
@IBOutlet var segmentBar: UIView!
@IBOutlet var liveButton: UIButton!
@IBOutlet var videoButton: UIButton!
@IBOutlet var liveBtnBackgroundView: UIView!
@IBOutlet var videoBtnBackgroundView: UIView!
@IBOutlet var contentWidthConstraint: NSLayoutConstraint!
@IBOutlet var segmentBarLeadingConstraint: NSLayoutConstraint!
var videoArray:[AnyObject] = []
var liveArray:[AnyObject] = []
var segmentBarConstraints = [NSLayoutConstraint]()
var selectedSegmentIndex = -1 {
didSet {
self.segmentIndexChanged()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.addObserver(self, forKeyPath: "selectedSegmentIndex", options: .New, context: &azureContext)
selectedSegmentIndex = 0
self.liveCollectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
self.queryVideoData()
})
self.videoCollectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
self.queryVideoData()
})
self.queryVideoData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func updateViewConstraints() {
super.updateViewConstraints()
contentWidthConstraint.constant = view.frame.width * 2
NSLayoutConstraint.deactivateConstraints([segmentBarLeadingConstraint])
NSLayoutConstraint.deactivateConstraints(segmentBarConstraints)
segmentBarConstraints.removeAll()
if selectedSegmentIndex == 0 {
segmentBarConstraints.append(NSLayoutConstraint(item: segmentBar, attribute: .CenterX, relatedBy: .Equal, toItem: liveBtnBackgroundView, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
self.scrollView.contentOffset.x = 0
}
else {
segmentBarConstraints.append(NSLayoutConstraint(item: segmentBar, attribute: .CenterX, relatedBy: .Equal, toItem: videoBtnBackgroundView, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
self.scrollView.contentOffset.x = self.view.frame.width
}
NSLayoutConstraint.activateConstraints(segmentBarConstraints)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
self.videoCollectionView.collectionViewLayout.invalidateLayout()
self.liveCollectionView.collectionViewLayout.invalidateLayout()
// if selectedSegmentIndex == 0 {
// self.scrollView.contentOffset.x = 0
// }
// else {
// self.scrollView.contentOffset.x = size.width
// }
}
func queryVideoData() {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
videoArray.removeAll()
liveArray.removeAll()
Alamofire.request(.GET, "http://epush.huaweiapi.com/content").validate().responseJSON { (response) in
guard response.result.isSuccess else {
print("Error while fetching remote videos: \(response.result.error)")
return
}
guard let value = response.result.value as? [AnyObject] else {
print("Malformed data received from queryVideoData service")
return
}
for dict in value {
if let mode = dict["mode"] as? String where mode == "0" {
self.videoArray.append(dict)
}
else if let mode = dict["mode"] as? String where mode == "1" {
self.liveArray.append(dict)
}
}
dispatch_async(dispatch_get_main_queue(), {
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.liveCollectionView.mj_header.endRefreshing()
self.videoCollectionView.mj_header.endRefreshing()
self.liveCollectionView.reloadData()
self.videoCollectionView.reloadData()
})
}
}
//MARK: - UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == liveCollectionView
{
return liveArray.count
}
else if collectionView == videoCollectionView
{
return videoArray.count
}
return 0
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if collectionView == liveCollectionView
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellID1", forIndexPath: indexPath) as! AzureCollectionViewCell
let data = liveArray[indexPath.row]
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if let imageUrl = data["poster"] as? String
{
if let imageData = NSData(contentsOfURL: NSURL(string: imageUrl)!)
{
dispatch_async(dispatch_get_main_queue(), {
cell.imageView.image = UIImage(data: imageData)
})
}
}
})
if let name = data["name"] as? String {
cell.titleLabel.text = name
}
if let desc = data["desc"] as? String {
cell.descriptionLabel.text = desc
}
if let hlsUrl = data["hlsUrl"] as? String {
cell.playButton.addHandler({
let videoURL = NSURL(string: hlsUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
let player = AVPlayer(URL: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
})
}
else {
cell.playButton.addHandler({
let alert = SLAlertController(title: "Something wrong may happen with this video", message: nil, image: nil, cancelButtonTitle: "OK", otherButtonTitle: nil, delay: nil, withAnimation: SLAlertAnimation.Fade)
alert.alertTintColor = UIColor.RGB(255, 58, 47)
alert.show(self, animated: true, completion: nil)
})
}
return cell
}
else if collectionView == videoCollectionView
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellID2", forIndexPath: indexPath) as! AzureCollectionViewCell
let data = videoArray[indexPath.row]
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if let imageUrl = data["poster"] as? String
{
if let imageData = NSData(contentsOfURL: NSURL(string: imageUrl)!)
{
dispatch_async(dispatch_get_main_queue(), {
cell.imageView.image = UIImage(data: imageData)
})
}
}
})
if let name = data["name"] as? String {
cell.titleLabel.text = name
}
if let desc = data["desc"] as? String {
cell.descriptionLabel.text = desc
}
if let hlsUrl = data["hlsUrl"] as? String {
cell.playButton.addHandler({
let videoURL = NSURL(string: hlsUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
let player = AVPlayer(URL: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
})
}
else {
cell.playButton.addHandler({
let alert = SLAlertController(title: "Something wrong may happen with this video", message: nil, image: nil, cancelButtonTitle: "OK", otherButtonTitle: nil, delay: nil, withAnimation: SLAlertAnimation.Fade)
alert.alertTintColor = UIColor.RGB(255, 58, 47)
alert.show(self, animated: true, completion: nil)
})
}
return cell
}
return UICollectionViewCell()
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == self.scrollView {
let offsetRatio = scrollView.contentOffset.x / self.view.frame.width
var frame = self.segmentBar.frame
frame.origin.x = self.view.frame.width / 4.0 - segmentBar.frame.width / 2.0 + offsetRatio * (self.view.frame.width / 2.0)
segmentBar.frame = frame
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView == self.scrollView {
if self.scrollView.contentOffset.x == 0 {
selectedSegmentIndex = 0
}
else if self.scrollView.contentOffset.x == self.view.frame.width {
selectedSegmentIndex = 1
}
}
}
// MARK: -
func segmentIndexChanged() {
if selectedSegmentIndex == 0 {
self.liveButton.setTitleColor(UIColor.RGB(47, 160, 251), forState: .Normal)
self.videoButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
else if selectedSegmentIndex == 1 {
self.liveButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
self.videoButton.setTitleColor(UIColor.RGB(47, 160, 251), forState: .Normal)
}
}
@IBAction func liveButtonClicked(sender: AnyObject) {
selectedSegmentIndex = 0
self.scrollView.scrollRectToVisible(self.liveCollectionView.frame, animated: true)
}
@IBAction func videoButtonClicked(sender: AnyObject) {
selectedSegmentIndex = 1
self.scrollView.scrollRectToVisible(self.videoCollectionView.frame, animated: true)
}
}
|
mit
|
d2b8a98236304146c93174bc2eb82100
| 37.307692 | 226 | 0.585301 | 5.774583 | false | false | false | false |
idapgroup/IDPDesign
|
Tests/iOS/Pods/Nimble/Sources/Nimble/Utils/Stringers.swift
|
8
|
7160
|
import Foundation
internal func identityAsString(_ value: Any?) -> String {
let anyObject: AnyObject?
#if os(Linux)
#if swift(>=4.0)
#if !swift(>=4.1.50)
anyObject = value as? AnyObject
#else
anyObject = value as AnyObject?
#endif
#else
#if !swift(>=3.4)
anyObject = value as? AnyObject
#else
anyObject = value as AnyObject?
#endif
#endif
#else
anyObject = value as AnyObject?
#endif
if let value = anyObject {
return NSString(format: "<%p>", unsafeBitCast(value, to: Int.self)).description
} else {
return "nil"
}
}
internal func arrayAsString<T>(_ items: [T], joiner: String = ", ") -> String {
return items.reduce("") { accum, item in
let prefix = (accum.isEmpty ? "" : joiner)
return accum + prefix + "\(stringify(item))"
}
}
/// A type with a customized test output text representation.
///
/// This textual representation is produced when values will be
/// printed in test runs, and may be useful when producing
/// error messages in custom matchers.
///
/// - SeeAlso: `CustomDebugStringConvertible`
public protocol TestOutputStringConvertible {
var testDescription: String { get }
}
extension Double: TestOutputStringConvertible {
public var testDescription: String {
return NSNumber(value: self).testDescription
}
}
extension Float: TestOutputStringConvertible {
public var testDescription: String {
return NSNumber(value: self).testDescription
}
}
extension NSNumber: TestOutputStringConvertible {
// This is using `NSString(format:)` instead of
// `String(format:)` because the latter somehow breaks
// the travis CI build on linux.
public var testDescription: String {
let description = self.description
if description.contains(".") {
// Travis linux swiftpm build doesn't like casting String to NSString,
// which is why this annoying nested initializer thing is here.
// Maybe this will change in a future snapshot.
let decimalPlaces = NSString(string: NSString(string: description)
.components(separatedBy: ".")[1])
// SeeAlso: https://bugs.swift.org/browse/SR-1464
switch decimalPlaces.length {
case 1:
return NSString(format: "%0.1f", self.doubleValue).description
case 2:
return NSString(format: "%0.2f", self.doubleValue).description
case 3:
return NSString(format: "%0.3f", self.doubleValue).description
default:
return NSString(format: "%0.4f", self.doubleValue).description
}
}
return self.description
}
}
extension Array: TestOutputStringConvertible {
public var testDescription: String {
let list = self.map(Nimble.stringify).joined(separator: ", ")
return "[\(list)]"
}
}
extension AnySequence: TestOutputStringConvertible {
public var testDescription: String {
let generator = self.makeIterator()
var strings = [String]()
var value: AnySequence.Iterator.Element?
repeat {
value = generator.next()
if let value = value {
strings.append(stringify(value))
}
} while value != nil
let list = strings.joined(separator: ", ")
return "[\(list)]"
}
}
extension NSArray: TestOutputStringConvertible {
public var testDescription: String {
let list = Array(self).map(Nimble.stringify).joined(separator: ", ")
return "(\(list))"
}
}
extension NSIndexSet: TestOutputStringConvertible {
public var testDescription: String {
let list = Array(self).map(Nimble.stringify).joined(separator: ", ")
return "(\(list))"
}
}
extension String: TestOutputStringConvertible {
public var testDescription: String {
return self
}
}
extension Data: TestOutputStringConvertible {
public var testDescription: String {
#if os(Linux)
// FIXME: Swift on Linux triggers a segfault when calling NSData's hash() (last checked on 03-11-16)
return "Data<length=\(count)>"
#else
return "Data<hash=\((self as NSData).hash),length=\(count)>"
#endif
}
}
///
/// Returns a string appropriate for displaying in test output
/// from the provided value.
///
/// - parameter value: A value that will show up in a test's output.
///
/// - returns: The string that is returned can be
/// customized per type by conforming a type to the `TestOutputStringConvertible`
/// protocol. When stringifying a non-`TestOutputStringConvertible` type, this
/// function will return the value's debug description and then its
/// normal description if available and in that order. Otherwise it
/// will return the result of constructing a string from the value.
///
/// - SeeAlso: `TestOutputStringConvertible`
public func stringify<T>(_ value: T?) -> String {
guard let value = value else { return "nil" }
if let value = value as? TestOutputStringConvertible {
return value.testDescription
}
if let value = value as? CustomDebugStringConvertible {
return value.debugDescription
}
return String(describing: value)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@objc public class NMBStringer: NSObject {
@objc public class func stringify(_ obj: Any?) -> String {
return Nimble.stringify(obj)
}
}
#endif
// MARK: Collection Type Stringers
/// Attempts to generate a pretty type string for a given value. If the value is of a Objective-C
/// collection type, or a subclass thereof, (e.g. `NSArray`, `NSDictionary`, etc.).
/// This function will return the type name of the root class of the class cluster for better
/// readability (e.g. `NSArray` instead of `__NSArrayI`).
///
/// For values that don't have a type of an Objective-C collection, this function returns the
/// default type description.
///
/// - parameter value: A value that will be used to determine a type name.
///
/// - returns: The name of the class cluster root class for Objective-C collection types, or the
/// the `dynamicType` of the value for values of any other type.
public func prettyCollectionType<T>(_ value: T) -> String {
switch value {
case is NSArray:
return String(describing: NSArray.self)
case is NSDictionary:
return String(describing: NSDictionary.self)
case is NSSet:
return String(describing: NSSet.self)
case is NSIndexSet:
return String(describing: NSIndexSet.self)
default:
return String(describing: value)
}
}
/// Returns the type name for a given collection type. This overload is used by Swift
/// collection types.
///
/// - parameter collection: A Swift `CollectionType` value.
///
/// - returns: A string representing the `dynamicType` of the value.
public func prettyCollectionType<T: Collection>(_ collection: T) -> String {
return String(describing: type(of: collection))
}
|
bsd-3-clause
|
2f8725dbb46cdac00f7b0cc33af3f421
| 31.844037 | 112 | 0.647905 | 4.586803 | false | true | false | false |
banxi1988/Staff
|
Staff/ClockStatusView.swift
|
1
|
6279
|
//
// ClockStatusView.swift
// Staff
//
// Created by Haizhen Lee on 16/3/1.
// Copyright © 2016年 banxi1988. All rights reserved.
//
import Foundation
// Build for target uimodel
import UIKit
import BXModel
import SwiftyJSON
import BXiOSUtils
import BXForm
//-ClockStatusView:
//clock[hor0,t0]:v
//worked_time[x,bl8@clock](f15,cpt)
//need_time[l0@worked_time,bl8@worked_time](f15,cpt)
//off_time[l0@worked_time,bl8@need_time](f15,cpt)
class ClockStatusView : UIView ,BXBindable {
let clockView = ArtClockView(frame:CGRectZero)
let worked_timeLabel = UILabel(frame:CGRectZero)
let worked_timeText = UILabel(frame:CGRectZero)
let need_timeLabel = UILabel(frame:CGRectZero)
let need_timeText = UILabel(frame:CGRectZero)
let off_timeLabel = UILabel(frame:CGRectZero)
let off_timeText = UILabel(frame:CGRectZero)
let statusLabel = UILabel(frame: CGRectZero)
var isFirstShow = true
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func bind(item:ClockStatus){
worked_timeLabel.text = item.worked_time_label
worked_timeText.text = item.worked_time_text
need_timeLabel.text = item.need_time_label
need_timeText.text = item.need_time_text
off_timeLabel.text = item.off_time_label
off_timeText.text = item.off_time_text
if (isWorking && timerInterval > 10) || isFirstShow || isClockEvent {
clockView.bind(CGFloat(item.progress))
isFirstShow = false
isClockEvent = false
}
}
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var allOutlets :[UIView]{
return [clockView,worked_timeLabel,worked_timeText, need_timeLabel,need_timeText,off_timeLabel,off_timeText,statusLabel]
}
var allUILabelOutlets :[UILabel]{
return [worked_timeLabel,worked_timeText, need_timeLabel,need_timeText,off_timeLabel,off_timeText]
}
var allUIViewOutlets :[UIView]{
return [clockView]
}
func commonInit(){
for childView in allOutlets{
addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
autobind()
NSNotificationCenter.defaultCenter().addObserverForName(AppEvents.WorkDurationChanged, object: nil, queue: nil) { [weak self] (notif) -> Void in
self?.isClockEvent = true
self?.autobind()
}
NSNotificationCenter.defaultCenter().addObserverForName(AppEvents.ClockDataSetChanged, object: nil, queue: nil) { [weak self] (notif) -> Void in
self?.isClockEvent = true
self?.autobind()
}
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func installConstaints(){
statusLabel.pa_top.eq(sdp2dp(16)).install()
statusLabel.pa_centerX.install()
clockView.pac_horizontal(0)
clockView.pa_below(statusLabel, offset: sdp2dp(15)).install()
worked_timeLabel.pa_below(clockView,offset:-16).install()
worked_timeLabel.pa_centerX.install()
worked_timeText.pa_below(worked_timeLabel, offset: 4).install()
worked_timeText.pa_centerX.install()
need_timeLabel.pa_below(worked_timeText,offset:sdp2dp(15)).install()
need_timeLabel.pa_trailing.equalTo(.CenterX, ofView: self).offset(-50).install()
need_timeText.pa_trailing.eqTo(need_timeLabel).install()
need_timeText.pa_below(need_timeLabel, offset: 4).install()
off_timeLabel.pa_top.eqTo(need_timeLabel).install()
off_timeLabel.pa_leading.equalTo(.CenterX, ofView: self).offset(50).install()
off_timeText.pa_leading.eqTo(off_timeLabel).install()
off_timeText.pa_bottom.eqTo(need_timeText).install()
}
func setupAttrs(){
for label in allUILabelOutlets{
label.textColor = AppColors.primaryTextColor
label.font = UIFont.systemFontOfSize(13)
}
statusLabel.textColor = AppColors.primaryTextColor
let statusFontSize = sdp2dp(36)
if #available(iOS 8.2, *) {
statusLabel.font = UIFont.systemFontOfSize(statusFontSize, weight: UIFontWeightMedium)
} else {
statusLabel.font = UIFont.systemFontOfSize(statusFontSize)
}
worked_timeText.font = UIFont.boldSystemFontOfSize(sdp2dp(40))
worked_timeText.textColor = AppColors.accentColor
need_timeLabel.textAlignment = .Right
need_timeText.textAlignment = .Right
off_timeLabel.textAlignment = .Left
off_timeText.textAlignment = .Left
clockView.punchButton.addTarget(self, action: "onClockButtonPressed:", forControlEvents: .TouchUpInside)
}
override static func requiresConstraintBasedLayout() -> Bool{
return true
}
var isWorking :Bool = false
var timerInterval :NSTimeInterval = 1
func autobind(){
isWorking = (ClockRecordService.sharedService.lastRecordInToday()?.recordType == ClockRecordType.On) ?? false
let status = ClockRecordHelper.currentClockStatus()
let bestTimerInterval:NSTimeInterval = status.worked_seconds > 60 ? 60: 1
if bestTimerInterval != timerInterval{
timerInterval = bestTimerInterval
startTimer()
}
statusLabel.text = isWorking ? "工作中" : "休息中"
bind(status)
if isWorking && timerInterval > 0 {
AppNotifications.notifyWorkedTimeExceed(status.need_time_seconds)
}
}
var isClockEvent = false
func onClockButtonPressed(sender:AnyObject){
ClockRecordHelper.clock()
isClockEvent = true
autobind()
}
var clockButton:UIView{
return clockView.punchButton
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let cpoint = clockButton.convertPoint(point, fromView: self)
if clockButton.pointInside(cpoint, withEvent: event){
return clockButton
}
let view = super.hitTest(point, withEvent: event)
return view
}
func onTimerCallback(){
autobind()
}
var timer:NSTimer?
func startTimer(){
stopTimer()
timer = NSTimer.scheduledTimerWithTimeInterval(timerInterval, target: self, selector: "onTimerCallback", userInfo: nil, repeats: true)
autobind()
}
func stopTimer(){
timer?.invalidate()
timer = nil
}
}
|
mit
|
bb3a270aea76c1a254984267d3b29538
| 27.733945 | 148 | 0.698595 | 3.957044 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClientIntegrationTests/Spec/Comment/CommentsResponseHandlerSpec.swift
|
1
|
4824
|
//
// CommentsResponseHandlerSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class CommentsResponseHandlerSpec: QuickSpec {
override func spec() {
describe("Comment response handler") {
it("Should return comments for Creation") {
guard let creationId = TestConfiguration.testCreationIdentifier
else { return }
let request = CommentsRequest(creationId: creationId, page: nil, perPage: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:CommentsResponseHandler {
(comments, pageInfo, error) -> (Void) in
expect(error).to(beNil())
expect(comments).notTo(beNil())
expect(pageInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return comments for Gallery") {
guard let galleryId = TestConfiguration.testGalleryIdentifier
else { return }
let request = CommentsRequest(galleryId: galleryId, page: nil, perPage: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:CommentsResponseHandler {
(comments, pageInfo, error) -> (Void) in
expect(error).to(beNil())
expect(comments).notTo(beNil())
expect(pageInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return comments for Profile") {
guard let userId = TestConfiguration.testUserIdentifier
else { return }
let request = CommentsRequest(userId: userId, page: nil, perPage: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:CommentsResponseHandler {
(comments, pData, error) -> (Void) in
expect(error).to(beNil())
expect(comments).notTo(beNil())
expect(pData).notTo(beNil())
sender.logout()
done()
})
}
}
}
}
}
}
|
mit
|
bf2ef899474fe99153a2a9736edbeea0
| 44.509434 | 100 | 0.540216 | 5.729216 | false | true | false | false |
bhargavg/Request
|
Tests/RequestTests/HTTPBinResponse.swift
|
1
|
919
|
import Foundation
struct HTTPBinResponse {
let args: [String: String]
let headers: [String: String]
let data: String?
let origin: String
let url: String
init?(data: Data) {
guard let mayBeDict = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let dict = mayBeDict else {
return nil
}
guard let args = dict["args"] as? [String: String] else {
return nil
}
guard let headers = dict["headers"] as? [String: String] else {
return nil
}
guard let origin = dict["origin"] as? String else {
return nil
}
guard let url = dict["url"] as? String else {
return nil
}
self.args = args
self.headers = headers
self.origin = origin
self.url = url
self.data = dict["data"] as? String
}
}
|
mit
|
82f1ca50ae26888252708b5edc472563
| 22.564103 | 94 | 0.5321 | 4.314554 | false | false | false | false |
LiulietLee/BilibiliCD
|
BCD/waifu2x/UIImage+Alpha.swift
|
1
|
844
|
//
// UIImage+Alpha.swift
// waifu2x
//
// Created by 谢宜 on 2017/12/29.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
func alpha() -> [UInt8] {
let width = Int(size.width)
let height = Int(size.height)
let data = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height)
let alphaOnly = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width, space: CGColorSpace.init(name: CGColorSpace.linearGray)!, bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)
alphaOnly?.draw(cgImage!, in: CGRect(x: 0, y: 0, width: width, height: height))
var result: [UInt8] = []
for i in 0 ..< width * height {
result.append(data[i])
}
return result
}
}
|
gpl-3.0
|
f6d4a50ea88bea3142ee16afcd9105fa
| 30 | 223 | 0.630824 | 3.72 | false | false | false | false |
huyouare/Emoji-Search-Keyboard
|
Keyboard/Catboard.swift
|
1
|
5092
|
//
// Catboard.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 9/24/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
/*
This is the demo keyboard. If you're implementing your own keyboard, simply follow the example here and then
set the name of your KeyboardViewController subclass in the Info.plist file.
*/
let kCatTypeEnabled = "kCatTypeEnabled"
class Catboard: KeyboardViewController {
let takeDebugScreenshot: Bool = false
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
NSUserDefaults.standardUserDefaults().registerDefaults([kCatTypeEnabled: true])
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func keyPressed(key: Key) {
if let textDocumentProxy = self.textDocumentProxy as? UITextDocumentProxy {
let keyOutput = key.outputForCase(self.shiftState.uppercase())
if !NSUserDefaults.standardUserDefaults().boolForKey(kCatTypeEnabled) {
textDocumentProxy.insertText(keyOutput)
return
}
if key.type == .Character || key.type == .SpecialCharacter {
let context = textDocumentProxy.documentContextBeforeInput
if context != nil {
if countElements(context) < 2 {
textDocumentProxy.insertText(keyOutput)
return
}
var index = context!.endIndex
index = index.predecessor()
if context[index] != " " {
textDocumentProxy.insertText(keyOutput)
return
}
index = index.predecessor()
if context[index] == " " {
textDocumentProxy.insertText(keyOutput)
return
}
textDocumentProxy.insertText("\(randomCat())")
textDocumentProxy.insertText(" ")
textDocumentProxy.insertText(keyOutput)
return
}
else {
textDocumentProxy.insertText(keyOutput)
return
}
}
else {
textDocumentProxy.insertText(keyOutput)
return
}
}
}
override func setupKeys() {
super.setupKeys()
if takeDebugScreenshot {
if self.layout == nil {
return
}
for page in keyboard.pages {
for rowKeys in page.rows {
for key in rowKeys {
if let keyView = self.layout!.viewForKey(key) {
keyView.addTarget(self, action: "takeScreenshotDelay", forControlEvents: .TouchDown)
}
}
}
}
}
}
override func createBanner() -> ExtraView? {
return CatboardBanner(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
}
func takeScreenshotDelay() {
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("takeScreenshot"), userInfo: nil, repeats: false)
}
func takeScreenshot() {
if !CGRectIsEmpty(self.view.bounds) {
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
let oldViewColor = self.view.backgroundColor
self.view.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.86, alpha: 1)
var rect = self.view.bounds
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
var context = UIGraphicsGetCurrentContext()
self.view.drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true)
var capturedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let name = (self.interfaceOrientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape")
var imagePath = "/Users/archagon/Documents/Programming/OSX/RussianPhoneticKeyboard/External/tasty-imitation-keyboard/\(name).png"
UIImagePNGRepresentation(capturedImage).writeToFile(imagePath, atomically: true)
self.view.backgroundColor = oldViewColor
}
}
}
func randomCat() -> String {
let cats = "🐱😺😸😹😽😻😿😾😼🙀"
let numCats = countElements(cats)
let randomCat = arc4random() % UInt32(numCats)
let index = advance(cats.startIndex, Int(randomCat))
let character = cats[index]
return String(character)
}
|
bsd-3-clause
|
d80f15f8cb29275420184645e0763bce
| 35.417266 | 146 | 0.564599 | 5.636971 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
Pods/HXPHPicker/Sources/HXPHPicker/Core/Util/PhotoTools+File.swift
|
1
|
7928
|
//
// PhotoTools+File.swift
// HXPHPicker
//
// Created by Slience on 2021/6/1.
//
import UIKit
public extension PhotoTools {
/// 获取文件大小
/// - Parameter path: 文件路径
/// - Returns: 文件大小
static func fileSize(atPath path: String) -> Int {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: path) {
let fileSize = try? fileManager.attributesOfItem(atPath: path)[.size]
if let size = fileSize as? Int {
return size
}
}
return 0
}
/// 获取文件夹里的所有文件大小
/// - Parameter path: 文件夹路径
/// - Returns: 文件夹大小
static func folderSize(atPath path: String) -> Int {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) { return 0 }
let childFiles = fileManager.subpaths(atPath: path)
var folderSize = 0
childFiles?.forEach({ (fileName) in
let fileAbsolutePath = path + "/" + fileName
folderSize += fileSize(atPath: fileAbsolutePath)
})
return folderSize
}
/// 获取系统缓存文件夹路径
static func getSystemCacheFolderPath() -> String {
return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
}
/// 获取图片缓存文件夹路径
static func getImageCacheFolderPath() -> String {
var cachePath = getSystemCacheFolderPath()
cachePath.append(contentsOf: "/com.silence.HXPHPicker/imageCache")
folderExists(atPath: cachePath)
return cachePath
}
/// 获取视频缓存文件夹路径
static func getVideoCacheFolderPath() -> String {
var cachePath = getSystemCacheFolderPath()
cachePath.append(contentsOf: "/com.silence.HXPHPicker/videoCache")
folderExists(atPath: cachePath)
return cachePath
}
static func getAudioTmpFolderPath() -> String {
var tmpPath = NSTemporaryDirectory()
tmpPath.append(contentsOf: "com.silence.HXPHPicker/audioCache")
folderExists(atPath: tmpPath)
return tmpPath
}
static func getLivePhotoImageCacheFolderPath() -> String {
var cachePath = getImageCacheFolderPath()
cachePath.append(contentsOf: "/LivePhoto")
folderExists(atPath: cachePath)
return cachePath
}
static func getLivePhotoVideoCacheFolderPath() -> String {
var cachePath = getVideoCacheFolderPath()
cachePath.append(contentsOf: "/LivePhoto")
folderExists(atPath: cachePath)
return cachePath
}
/// 删除缓存
static func removeCache() {
removeVideoCache()
removeImageCache()
removeAudioCache()
}
/// 删除视频缓存
@discardableResult
static func removeVideoCache() -> Bool {
return removeFile(filePath: getVideoCacheFolderPath())
}
/// 删除图片缓存
@discardableResult
static func removeImageCache() -> Bool {
return removeFile(filePath: getImageCacheFolderPath())
}
/// 删除音频临时缓存
@discardableResult
static func removeAudioCache() -> Bool {
return removeFile(filePath: getAudioTmpFolderPath())
}
/// 获取视频缓存文件大小
@discardableResult
static func getVideoCacheFileSize() -> Int {
return folderSize(atPath: getVideoCacheFolderPath())
}
/// 获取视频缓存文件地址
/// - Parameter key: 生成文件的key
@discardableResult
static func getVideoCacheURL(for key: String) -> URL {
var cachePath = getVideoCacheFolderPath()
cachePath.append(contentsOf: "/" + key.md5 + ".mp4")
return URL.init(fileURLWithPath: cachePath)
}
@discardableResult
static func getAudioTmpURL(for key: String) -> URL {
var cachePath = getAudioTmpFolderPath()
cachePath.append(contentsOf: "/" + key.md5 + ".mp3")
return URL.init(fileURLWithPath: cachePath)
}
/// 视频是否有缓存
/// - Parameter key: 对应视频的key
@discardableResult
static func isCached(forVideo key: String) -> Bool {
let fileManager = FileManager.default
let filePath = getVideoCacheURL(for: key).path
return fileManager.fileExists(atPath: filePath)
}
@discardableResult
static func isCached(forAudio key: String) -> Bool {
let fileManager = FileManager.default
let filePath = getAudioTmpURL(for: key).path
return fileManager.fileExists(atPath: filePath)
}
/// 获取对应后缀的临时路径
@discardableResult
static func getTmpURL(for suffix: String) -> URL {
var tmpPath = NSTemporaryDirectory()
tmpPath.append(contentsOf: String.fileName(suffix: suffix))
let tmpURL = URL.init(fileURLWithPath: tmpPath)
return tmpURL
}
/// 获取图片临时路径
@discardableResult
static func getImageTmpURL(_ imageContentType: ImageContentType = .jpg) -> URL {
var suffix: String
switch imageContentType {
case .jpg:
suffix = "jpeg"
case .png:
suffix = "png"
case .gif:
suffix = "gif"
default:
suffix = "jpeg"
}
return getTmpURL(for: suffix)
}
/// 获取视频临时路径
@discardableResult
static func getVideoTmpURL() -> URL {
return getTmpURL(for: "mp4")
}
/// 将UIImage转换成Data
@discardableResult
static func getImageData(for image: UIImage?) -> Data? {
if let pngData = image?.pngData() {
return pngData
}else if let jpegData = image?.jpegData(compressionQuality: 1) {
return jpegData
}
return nil
}
@discardableResult
static func write(
toFile fileURL: URL? = nil,
image: UIImage?) -> URL? {
if let imageData = getImageData(for: image) {
return write(toFile: fileURL, imageData: imageData)
}
return nil
}
@discardableResult
static func write(
toFile fileURL: URL? = nil,
imageData: Data) -> URL? {
let imageURL = fileURL == nil ? getImageTmpURL(imageData.isGif ? .gif : .png) : fileURL!
do {
if FileManager.default.fileExists(atPath: imageURL.path) {
try FileManager.default.removeItem(at: imageURL)
}
try imageData.write(to: imageURL)
return imageURL
} catch {
return nil
}
}
@discardableResult
static func copyFile(at srcURL: URL, to dstURL: URL) -> Bool {
if srcURL.path == dstURL.path {
return true
}
do {
if FileManager.default.fileExists(atPath: dstURL.path) {
try FileManager.default.removeItem(at: dstURL)
}
try FileManager.default.copyItem(at: srcURL, to: dstURL)
return true
} catch {
return false
}
}
@discardableResult
static func removeFile(fileURL: URL) -> Bool {
removeFile(filePath: fileURL.path)
}
@discardableResult
static func removeFile(filePath: String) -> Bool {
do {
if FileManager.default.fileExists(atPath: filePath) {
try FileManager.default.removeItem(atPath: filePath)
}
return true
} catch {
return false
}
}
static func folderExists(atPath path: String) {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) {
try? fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
}
}
|
mit
|
10f501b06447594170d00d6402bf4653
| 29.294821 | 110 | 0.602578 | 4.824873 | false | false | false | false |
Vadim-Yelagin/DataSourceExample
|
DataSourceExample/Catalog/CatalogViewController.swift
|
1
|
2101
|
//
// CatalogViewController.swift
// DataSourceExample
//
// Created by Vadim Yelagin on 15/06/15.
// Copyright (c) 2015 Fueled. All rights reserved.
//
import UIKit
import DataSource
class CatalogViewController: UIViewController {
@IBOutlet var tableView: UITableView?
let tableDataSource = TableViewDataSource()
override func awakeFromNib() {
super.awakeFromNib()
let items: [Any] = [
CatalogItem(title: "Static (items)") { StaticItemsViewModel() },
CatalogItem(title: "Static (sections)") { StaticSectionsViewModel() },
CatalogItem(title: "Proxy") { ProxyViewModel() },
CatalogItem(title: "Auto Diff") { AutoDiffViewModel() },
CatalogItem(title: "Auto Diff Sections") { AutoDiffSectionsViewModel() },
CatalogItem(title: "Composite") { CompositeViewModel() },
CatalogItem(title: "Mutable") { MutableViewModel() },
CatalogStaticItem(reuseIdentifier: "Editing"),
CatalogStaticItem(reuseIdentifier: "InputForm")
]
self.tableDataSource.dataSource.innerDataSource.value = StaticDataSource(items: items)
self.tableDataSource.reuseIdentifierForItem = {
_, item in
if let item = item as? CatalogStaticItem {
return item.reuseIdentifier
} else {
return "DefaultCell"
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let tableView = self.tableView {
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableView.automaticDimension
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.dataSource = self.tableDataSource
self.tableDataSource.tableView = tableView
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView?.deselectAllRows(animated)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nc = segue.destination as? UINavigationController,
let vc = nc.topViewController as? ExampleViewController,
let cell = sender as? CatalogCell,
let cellModel = cell.cellModel.value as? CatalogItem,
segue.identifier == "ShowExampleSegue"
{
vc.viewModel = cellModel.viewModel()
}
}
}
|
mit
|
f9151b77924275ee0b241b58dbca03ac
| 29.449275 | 88 | 0.734888 | 3.971645 | false | false | false | false |
dn-m/Collections
|
Collections/Sequence+Algebra.swift
|
1
|
1710
|
//
// Sequence+Monoid.swift
// Collections
//
// Created by James Bean on 7/19/17.
//
//
import Algebra
extension Sequence where Iterator.Element: Monoid {
/// - Returns: The values contained herein, reduced from the `.identity` value of the `Monoid`,
/// composing with the `<>` operation of the `Monoid`.
public var reduced: Iterator.Element {
return reduce(.identity, <>)
}
}
extension Sequence where Iterator.Element: MonoidView {
/// - Returns: The values contained herein, reduced from the `.identity` value of the `Monoid`,
/// composing with the `<>` operation of the `Monoid`.
public var reduced: Iterator.Element.Value {
return reduce(.identity, <>).value
}
}
extension Sequence where Iterator.Element: Multiplicative {
/// - Returns: Product of all values contained herein.
public var product: Iterator.Element {
return map { $0.product }.reduced
}
}
extension Sequence where Iterator.Element: Additive {
/// - Returns: Sum of all values contained herein.
public var sum: Iterator.Element {
return map { $0.sum }.reduced
}
}
extension Collection where
Iterator.Element: AdditiveSemigroup,
SubSequence.Iterator.Element == Iterator.Element
{
public var nonEmptySum: Iterator.Element? {
guard let (head,tail) = destructured else { return nil }
return tail.reduce(head, +)
}
}
extension Collection where
Iterator.Element: MultiplicativeSemigroup,
SubSequence.Iterator.Element == Iterator.Element
{
public var nonEmptyProduct: Iterator.Element? {
guard let (head,tail) = destructured else { return nil }
return tail.reduce(head, *)
}
}
|
mit
|
a6a4c6a6ebc464be633c471f5a0f5e81
| 25.307692 | 99 | 0.672515 | 4.275 | false | false | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Services/RDSDataService/RDSDataService_Error.swift
|
1
|
2831
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for RDSDataService
public struct RDSDataServiceErrorType: AWSErrorType {
enum Code: String {
case badRequestException = "BadRequestException"
case forbiddenException = "ForbiddenException"
case internalServerErrorException = "InternalServerErrorException"
case notFoundException = "NotFoundException"
case serviceUnavailableError = "ServiceUnavailableError"
case statementTimeoutException = "StatementTimeoutException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize RDSDataService
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// There is an error in the call or in a SQL statement.
public static var badRequestException: Self { .init(.badRequestException) }
/// There are insufficient privileges to make the call.
public static var forbiddenException: Self { .init(.forbiddenException) }
/// An internal error occurred.
public static var internalServerErrorException: Self { .init(.internalServerErrorException) }
/// The resourceArn, secretArn, or transactionId value can't be found.
public static var notFoundException: Self { .init(.notFoundException) }
/// The service specified by the resourceArn parameter is not available.
public static var serviceUnavailableError: Self { .init(.serviceUnavailableError) }
/// The execution of the SQL statement timed out.
public static var statementTimeoutException: Self { .init(.statementTimeoutException) }
}
extension RDSDataServiceErrorType: Equatable {
public static func == (lhs: RDSDataServiceErrorType, rhs: RDSDataServiceErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension RDSDataServiceErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
|
apache-2.0
|
8e47f628579c96446ba06752fcca58a8
| 38.319444 | 117 | 0.677146 | 5.073477 | false | false | false | false |
hikelee/cinema
|
Sources/App/Extensions/StringExtensions.swift
|
1
|
10063
|
import Foundation
public extension String {
/// Return string decoded from base64.
public var base64Decoded: String? {
guard let decodedData = Data(base64Encoded: self) else {
return nil
}
return String(data: decodedData, encoding: .utf8)
}
/// Return string encoded in base64.
public var base64Encoded: String? {
let plainData = self.data(using: .utf8)
return plainData?.base64EncodedString()
}
/// Returns CamelCase of string.
public var camelCased: String {
let source = lowercased()
if source.characters.contains(" ") {
let first = source.substring(to: source.index(after: source.startIndex))
let camel = source.capitalized.replace(" ", with: "").replace("\n", with: "")
let rest = String(camel.characters.dropFirst())
return "\(first)\(rest)"
} else {
let first = source.lowercased().substring(to: source.index(after: source.startIndex))
let rest = String(source.characters.dropFirst())
return "\(first)\(rest)"
}
}
/// Converts string format to CamelCase.
public mutating func camelize() {
self = camelCased
}
/// Return true if string contains one or more instance of substring.
public func contain(_ string: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return range(of: string, options: .caseInsensitive) != nil
}
return range(of: string) != nil
}
/// Return true if string contains one or more emojis.
public var containEmoji: Bool {
for scalar in unicodeScalars {
switch scalar.value {
case 0x3030, 0x00AE, 0x00A9, // Special Characters
0x1D000...0x1F77F, // Emoticons
0x2100...0x27BF, // Misc symbols and Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs
return true
default:
continue
}
}
return false
}
/// Return count of substring in string.
public func count(of string: String, caseSensitive: Bool = true) -> Int {
if !caseSensitive {
return lowercased().components(separatedBy: string).count - 1
}
return components(separatedBy: string).count - 1
}
/// Return true if string ends with substring.
public func end(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
/// Return first character of string.
public var firstCharacter: String? {
return Array(characters).map({String($0)}).first
}
/// Return first index of substring in string.
public func firstIndex(of string: String) -> Int? {
return Array(self.characters).map({String($0)}).index(of: string)
}
/// Return true if string contains one or more letters.
public var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
/// Return true if string contains one or more numbers.
public var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
}
/// Return true if string contains only letters.
public var isAlphabetic: Bool {
return hasLetters && !hasNumbers
}
/// Return true if string contains at least one letter and one number.
public var isAlphaNumeric: Bool {
return components(separatedBy: CharacterSet.alphanumerics)
.joined(separator: "").characters.count == 0 && hasLetters && hasNumbers
}
/// Return true if string is https URL.
public var isHttpsUrl: Bool {
guard start(with: "https://".lowercased()) else {
return false
}
return URL(string: self) != nil
}
/// Return true if string is http URL.
public var isHttpUrl: Bool {
guard start(with: "http://".lowercased()) else {
return false
}
return URL(string: self) != nil
}
/// Return true if string contains only numbers.
public var isNumeric: Bool {
return !hasLetters && hasNumbers
}
/// Return last character of string.
public var lastCharacter: String? {
return Array(characters).map({String($0)}).last
}
/// Latinize string.
public mutating func latinize() {
self = latinized
}
/// Return latinized string.
public var latinized: String {
return folding(options: .diacriticInsensitive, locale: Locale.current)
}
/// Returns array of strings separated by new lines.
public var lines: [String] {
var result:[String] = []
enumerateLines { (line, stop) -> () in
result.append(line)
}
return result
}
/// Return most common character in string.
public var mostCommonCharacter: String {
var mostCommon = ""
let charSet = Set(withoutSpacesAndNewLines.characters.map{String($0)})
var count = 0
for string in charSet {
if self.count(of: string) > count {
count = self.count(of: string)
mostCommon = string
}
}
return mostCommon
}
/// Replace part of string with another string.
public func replace(_ substring: String, with: String) -> String {
return replacingOccurrences(of: substring, with: with)
}
/// Reverse string.
public mutating func reverse() {
self = String(characters.reversed())
}
/// Return reversed string.
public var reversed: String {
return String(characters.reversed())
}
/// Return an array of strings separated by given string.
public func split(by separator: Character) -> [String] {
return characters.split{$0 == separator}.map(String.init)
}
/// Return true if string starts with substring.
public func start(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
}
/// Return string repeated n times.
public func * (left: String, right: Int) -> String {
var newString = ""
for _ in 0 ..< right {
newString += left
}
return newString
}
public extension String {
/// Return Bool value from string (if applicable.)
public var toBool: Bool? {
let selfLowercased = self.trimmed.lowercased()
if selfLowercased == "true" || selfLowercased == "1" {
return true
} else if selfLowercased == "false" || selfLowercased == "0" {
return false
} else {
return nil
}
}
// Return date object from "yyyy-MM-dd" formatted string
public var toDate: Date? {
let selfLowercased = self.trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: selfLowercased)
}
// Return date object from "yyyy-MM-dd HH:mm:ss" formatted string.
public var toDateTime: Date? {
let selfLowercased = self.trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.date(from: selfLowercased)
}
/// Return URL from string (if applicable.)
public var toURL: URL? {
return URL(string: self)
}
/// Return Date value from string of date format (if applicable.)
public func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
/// Removes spaces and new lines in beginning and end of string.
public mutating func trim() {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// Return string with no spaces or new lines in beginning and end.
public var trimmed: String {
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// Truncate string (cut it to a given number of characters).
public mutating func truncate(toLength: Int, trailing: String? = "...") {
if self.characters.count > toLength {
self = self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
}
/// Return truncated string (limited to a given number of characters).
public func truncated(toLength: Int, trailing: String? = "...") -> String {
guard self.characters.count > toLength else {
return self
}
return self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
/// Return an array with unicodes for all characters in a string.
public var unicodeArray: [Int] {
return unicodeScalars.map({$0.hashValue})
}
/// Return readable string from URL string.
public mutating func urlDecode() {
self = removingPercentEncoding ?? self
}
/// Convert URL string into readable string.
public var urlDecoded: String {
return removingPercentEncoding ?? self
}
/// Return URL-escaped string.
public mutating func urlEncode() {
self = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self
}
/// Escape string.
public var urlEncoded: String {
return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self
}
/// Return string without spaces and new lines.
public var withoutSpacesAndNewLines: String {
return replace(" ", with: "").replace("\n", with: "")
}
}
|
mit
|
3ebc0dcc5c0c0f64ae2b8cc9a7a3ea42
| 31.672078 | 100 | 0.613237 | 4.769194 | false | false | false | false |
KrauseFx/fastlane
|
snapshot/lib/assets/SnapshotHelper.swift
|
10
|
11690
|
//
// SnapshotHelper.swift
// Example
//
// Created by Felix Krause on 10/8/15.
//
// -----------------------------------------------------
// IMPORTANT: When modifying this file, make sure to
// increment the version number at the very
// bottom of the file to notify users about
// the new SnapshotHelper.swift
// -----------------------------------------------------
import Foundation
import XCTest
var deviceLanguage = ""
var locale = ""
func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) {
Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations)
}
func snapshot(_ name: String, waitForLoadingIndicator: Bool) {
if waitForLoadingIndicator {
Snapshot.snapshot(name)
} else {
Snapshot.snapshot(name, timeWaitingForIdle: 0)
}
}
/// - Parameters:
/// - name: The name of the snapshot
/// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait.
func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {
Snapshot.snapshot(name, timeWaitingForIdle: timeout)
}
enum SnapshotError: Error, CustomDebugStringConvertible {
case cannotFindSimulatorHomeDirectory
case cannotRunOnPhysicalDevice
var debugDescription: String {
switch self {
case .cannotFindSimulatorHomeDirectory:
return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable."
case .cannotRunOnPhysicalDevice:
return "Can't use Snapshot on a physical device."
}
}
}
@objcMembers
open class Snapshot: NSObject {
static var app: XCUIApplication?
static var waitForAnimations = true
static var cacheDirectory: URL?
static var screenshotsDirectory: URL? {
return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true)
}
open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) {
Snapshot.app = app
Snapshot.waitForAnimations = waitForAnimations
do {
let cacheDir = try getCacheDirectory()
Snapshot.cacheDirectory = cacheDir
setLanguage(app)
setLocale(app)
setLaunchArguments(app)
} catch let error {
NSLog(error.localizedDescription)
}
}
class func setLanguage(_ app: XCUIApplication) {
guard let cacheDirectory = self.cacheDirectory else {
NSLog("CacheDirectory is not set - probably running on a physical device?")
return
}
let path = cacheDirectory.appendingPathComponent("language.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"]
} catch {
NSLog("Couldn't detect/set language...")
}
}
class func setLocale(_ app: XCUIApplication) {
guard let cacheDirectory = self.cacheDirectory else {
NSLog("CacheDirectory is not set - probably running on a physical device?")
return
}
let path = cacheDirectory.appendingPathComponent("locale.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
} catch {
NSLog("Couldn't detect/set locale...")
}
if locale.isEmpty && !deviceLanguage.isEmpty {
locale = Locale(identifier: deviceLanguage).identifier
}
if !locale.isEmpty {
app.launchArguments += ["-AppleLocale", "\"\(locale)\""]
}
}
class func setLaunchArguments(_ app: XCUIApplication) {
guard let cacheDirectory = self.cacheDirectory else {
NSLog("CacheDirectory is not set - probably running on a physical device?")
return
}
let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt")
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"]
do {
let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8)
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substring(with: result.range)
}
app.launchArguments += results
} catch {
NSLog("Couldn't detect/set launch_arguments...")
}
}
open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {
if timeout > 0 {
waitForLoadingIndicatorToDisappear(within: timeout)
}
NSLog("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work
if Snapshot.waitForAnimations {
sleep(1) // Waiting for the animation to be finished (kind of)
}
#if os(OSX)
guard let app = self.app else {
NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
return
}
app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: [])
#else
guard self.app != nil else {
NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
return
}
let screenshot = XCUIScreen.main.screenshot()
#if os(iOS) && !targetEnvironment(macCatalyst)
let image = XCUIDevice.shared.orientation.isLandscape ? fixLandscapeOrientation(image: screenshot.image) : screenshot.image
#else
let image = screenshot.image
#endif
guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return }
do {
// The simulator name contains "Clone X of " inside the screenshot file when running parallelized UI Tests on concurrent devices
let regex = try NSRegularExpression(pattern: "Clone [0-9]+ of ")
let range = NSRange(location: 0, length: simulator.count)
simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "")
let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png")
#if swift(<5.0)
UIImagePNGRepresentation(image)?.write(to: path, options: .atomic)
#else
try image.pngData()?.write(to: path, options: .atomic)
#endif
} catch let error {
NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png")
NSLog(error.localizedDescription)
}
#endif
}
class func fixLandscapeOrientation(image: UIImage) -> UIImage {
#if os(watchOS)
return image
#else
if #available(iOS 10.0, *) {
let format = UIGraphicsImageRendererFormat()
format.scale = image.scale
let renderer = UIGraphicsImageRenderer(size: image.size, format: format)
return renderer.image { context in
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
}
} else {
return image
}
#endif
}
class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) {
#if os(tvOS)
return
#endif
guard let app = self.app else {
NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
return
}
let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element
let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator)
_ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout)
}
class func getCacheDirectory() throws -> URL {
let cachePath = "Library/Caches/tools.fastlane"
// on OSX config is stored in /Users/<username>/Library
// and on iOS/tvOS/WatchOS it's in simulator's home dir
#if os(OSX)
let homeDir = URL(fileURLWithPath: NSHomeDirectory())
return homeDir.appendingPathComponent(cachePath)
#elseif arch(i386) || arch(x86_64) || arch(arm64)
guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
throw SnapshotError.cannotFindSimulatorHomeDirectory
}
let homeDir = URL(fileURLWithPath: simulatorHostHome)
return homeDir.appendingPathComponent(cachePath)
#else
throw SnapshotError.cannotRunOnPhysicalDevice
#endif
}
}
private extension XCUIElementAttributes {
var isNetworkLoadingIndicator: Bool {
if hasAllowListedIdentifier { return false }
let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20)
let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3)
return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize
}
var hasAllowListedIdentifier: Bool {
let allowListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]
return allowListedIdentifiers.contains(identifier)
}
func isStatusBar(_ deviceWidth: CGFloat) -> Bool {
if elementType == .statusBar { return true }
guard frame.origin == .zero else { return false }
let oldStatusBarSize = CGSize(width: deviceWidth, height: 20)
let newStatusBarSize = CGSize(width: deviceWidth, height: 44)
return [oldStatusBarSize, newStatusBarSize].contains(frame.size)
}
}
private extension XCUIElementQuery {
var networkLoadingIndicators: XCUIElementQuery {
let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in
guard let element = evaluatedObject as? XCUIElementAttributes else { return false }
return element.isNetworkLoadingIndicator
}
return self.containing(isNetworkLoadingIndicator)
}
var deviceStatusBars: XCUIElementQuery {
guard let app = Snapshot.app else {
fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
}
let deviceWidth = app.windows.firstMatch.frame.width
let isStatusBar = NSPredicate { (evaluatedObject, _) in
guard let element = evaluatedObject as? XCUIElementAttributes else { return false }
return element.isStatusBar(deviceWidth)
}
return self.containing(isStatusBar)
}
}
private extension CGFloat {
func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool {
return numberA...numberB ~= self
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [1.28]
|
mit
|
522963b1b6380626d349a6977803cc5f
| 36.831715 | 158 | 0.631223 | 5.404531 | false | false | false | false |
Sharelink/Bahamut
|
Bahamut/BahamutUIKit/PaddingLabel.swift
|
1
|
728
|
//
// PaddingLabel.swift
// aivigi
//
// Created by Alex Chow on 2017/5/13.
// Copyright © 2017年 Bahamut. All rights reserved.
//
import Foundation
import UIKit
class PaddingLabel: UILabel {
var padding:UIEdgeInsets!
override func drawText(in rect: CGRect) {
if let pd = padding{
let newRect = rect.inset(by: pd)
super.drawText(in: newRect)
}else{
super.drawText(in: rect)
}
}
override var intrinsicContentSize: CGSize{
var size = super.intrinsicContentSize
if let pd = self.padding{
size.height += pd.top + pd.bottom
size.width += pd.left + pd.right
}
return size
}
}
|
mit
|
38c66808a9f5564cfd29aa2be370383a
| 21.65625 | 51 | 0.573793 | 4.050279 | false | false | false | false |
wenghengcong/Coderpursue
|
BeeFun/BeeFun/ToolKit/JSToolKit/JSUIKit/UIView+Draw.swift
|
1
|
9856
|
//
// UIView+Draw.swift
// LoveYou
//
// Created by WengHengcong on 2017/3/8.
// Copyright © 2017年 JungleSong. All rights reserved.
//
import UIKit
// MARK: - Position
extension UIView {
var width: CGFloat {
get {
return self.frame.size.width
}
set {
self.frame.size.width = newValue
}
}
var height: CGFloat {
get {
return self.frame.size.height
}
set {
self.frame.size.height = newValue
}
}
var size: CGSize {
get {
return self.frame.size
}
set {
self.frame.size = newValue
}
}
var origin: CGPoint {
get {
return self.frame.origin
}
set {
self.frame.origin = newValue
}
}
var x: CGFloat {
get {
return self.frame.origin.x
}
set {
self.frame.origin = CGPoint(x: newValue, y: self.frame.origin.y)
}
}
var y: CGFloat {
get {
return self.frame.origin.y
}
set {
self.frame.origin = CGPoint(x: self.frame.origin.x, y: newValue)
}
}
var centerX: CGFloat {
get {
return self.center.x
}
set {
self.center = CGPoint(x: newValue, y: self.center.y)
}
}
var centerY: CGFloat {
get {
return self.center.y
}
set {
self.center = CGPoint(x: self.center.x, y: newValue)
}
}
var left: CGFloat {
get {
return self.frame.origin.x
}
set {
self.frame.origin.x = newValue
}
}
var right: CGFloat {
get {
return self.frame.origin.x + self.frame.size.width
}
set {
self.frame.origin.x = newValue - self.frame.size.width
}
}
var top: CGFloat {
get {
return self.frame.origin.y
}
set {
self.frame.origin.y = newValue
}
}
var bottom: CGFloat {
get {
return self.frame.origin.y + self.frame.size.height
}
set {
self.frame.origin.y = newValue - self.frame.size.height
}
}
}
// MARK: - Calculator poisiton
extension UIView {
/// 计算控件相对于屏幕的左边距
///
/// - Parameter width: 控件宽度
/// - Returns: 控件距离屏幕左边距
class func xSpace(width: CGFloat) -> CGFloat {
return self.xSpace(width: width, relative: ScreenSize.width)
}
/// 计算控件相对于父视图的左边距
///
/// - Parameters:
/// - width: 控件宽度
/// - full: 父视图的整体宽度
/// - Returns: 控件相对于父视图的左边距
class func xSpace(width: CGFloat, relative full: CGFloat) -> CGFloat {
let leftX = (full-width)/2.0
return leftX
}
/// 计算控件相对于屏幕的上边距
///
/// - Parameter height: 控件高度
/// - Returns: 控件距离屏幕上边距
class func ySpace(height: CGFloat) -> CGFloat {
return self.ySpace(height: height, relative: ScreenSize.height)
}
/// 计算控件相对于父视图的上边距
///
/// - Parameters:
/// - height: 控件高度
/// - full: 控件父视图的整体高度
/// - Returns: 控件相对于父视图的上边距
class func ySpace(height: CGFloat, relative full: CGFloat) -> CGFloat {
let topY = (full-height)/2.0
return topY
}
}
// MARK: - Draw Layout
extension UIView {
/// 设置圆角
var radius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
self.layer.masksToBounds = true
}
}
/// 设置边框颜色
var borderColor: UIColor {
get {
if let color = self.layer.borderColor {
return UIColor(cgColor: color)
}
return UIColor.white
}
set {
self.layer.borderColor = newValue.cgColor
}
}
/// 设置边框颜色
var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
/// 边框类型
///
/// - none: 不添加
/// - one: 添加单边
/// - all: 添加四边
enum BorderType {
case none
case one
case all
}
/// 视图Border类型
///
/// - left: 左边框
/// - right: 右边框
/// - top: 上边框
/// - bottom: 下边框
enum ViewBorder: String {
case left = "borderLeft"
case right = "borderRight"
case top = "borderTop"
case bottom = "borderBottom"
}
/// 默认边框颜色
var defaultBorderColor: UIColor {
get {
return UIColor.bfLineBackgroundColor
}
set {
self.defaultBorderColor = newValue
}
}
/// 添加边框(颜色:默认,圆角:0,宽度:1px)
///
/// - Parameters:
/// - type: 边框类型
/// - at: 指定哪条边添加边框
func addBorder(type: BorderType, at: ViewBorder) {
let width = 1.0 / (UIScreen.main.scale)
addBorder(type: type, color: defaultBorderColor, radius: 0, width: width, at: at)
}
/// 添加边框(颜色:默认,宽度:1px)
func addBorder(type: BorderType, radius: CGFloat, at: ViewBorder) {
let width = 1.0 / (UIScreen.main.scale)
addBorder(type: type, color: defaultBorderColor, radius: radius, width: width, at: at)
}
/// 添加边框(宽度:1px)
func addBorder(type: BorderType, color: UIColor, radius: CGFloat, at: ViewBorder) {
let width = 1.0 / (UIScreen.main.scale)
addBorder(type: type, color: color, radius: radius, width: width, at: at)
}
/// 添加边框
///
/// - Parameters:
/// - type: 边框类型
/// - color: 颜色
/// - radius: 圆角
/// - width: 宽度
/// - at: 指点哪条边
func addBorder(type: BorderType, color: UIColor, radius: CGFloat, width: CGFloat, at: ViewBorder) {
switch type {
case .none:
break
case .one:
addBorderSingle(color, width: width, at: at)
case .all:
addBorderAround(color, radius: radius, width: width)
}
}
/**
添加四周边框
*/
func addBorderAroundInOnePixel() {
self.addBorderAroundInOnePixel(defaultBorderColor, radius: 0)
}
/// 添加1像素四周边框
///
/// - Parameter color: 边框颜色
func addBorderAroundInOnePixel(_ color: UIColor) {
self.addBorderAroundInOnePixel(color, radius: 0)
}
/// 添加1像素的四周边框
///
/// - Parameters:
/// - color: 边框颜色
/// - radius: 边框圆角
func addBorderAroundInOnePixel(_ color: UIColor, radius: CGFloat) {
let retinaPixelSize = 1.0 / (UIScreen.main.scale)
self.addBorderAround(color, radius: radius, width: retinaPixelSize)
}
/// 添加四周边框
///
/// - Parameters:
/// - color: 边框颜色
/// - radius: 边框圆角
/// - width: 边框宽度
func addBorderAround(_ color: UIColor, radius: CGFloat, width: CGFloat) {
self.layer.borderWidth = width
self.layer.borderColor = color.cgColor
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
/// 添加单边边框(颜色:默认,宽度:1px)
func addBorderSingle(at: ViewBorder) {
let retinaPixelSize = 1.0 / (UIScreen.main.scale)
addBorderSingle(defaultBorderColor, width: retinaPixelSize, at: at)
}
/// 添加单边边框(宽度:1px)
func addBorderSingle(_ color: UIColor, at: ViewBorder) {
let retinaPixelSize = 1.0 / (UIScreen.main.scale)
addBorderSingle(color, width: retinaPixelSize, at: at)
}
/// 添加单边边框
///
/// - Parameters:
/// - color: 牙呢
/// - width: 宽度
/// - at: 指定哪条边
func addBorderSingle(_ color: UIColor, width: CGFloat, at: ViewBorder) {
let retinaPixelSize = 1.0 / (UIScreen.main.scale)
let maxLinewidth = max(retinaPixelSize, width)
let border = CALayer()
border.borderColor = color.cgColor
border.borderWidth = maxLinewidth
border.name = at.rawValue
switch at {
case .top:
border.frame = CGRect(x: 0, y: 0, width: self.width, height: width)
break
case .left:
border.frame = CGRect(x: 0, y: 0, width: width, height: self.height)
break
case .right:
border.frame = CGRect(x: self.width-width, y: 0, width: width, height: self.height)
break
case .bottom:
border.frame = CGRect(x: 0, y: self.height-width, width: self.width, height: width)
break
}
removeBorder(at)
self.layer.addSublayer(border)
}
func removeBorder(_ at: ViewBorder) {
var layerForRemove: CALayer?
if let sublayers = self.layer.sublayers {
for layer in sublayers where layer.name == at.rawValue {
layerForRemove = layer
}
if let layer = layerForRemove {
layer.removeFromSuperlayer()
}
}
}
func removeAllBorders() {
removeBorder(.top)
removeBorder(.left)
removeBorder(.bottom)
removeBorder(.right)
}
}
|
mit
|
7511d0a573a7af1886fc7eca1b00cc87
| 22.329082 | 103 | 0.523127 | 3.921527 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer
|
TimerViewsGear/ActivityView.swift
|
2
|
2505
|
import UIKit
final public class ActivityView: UIView {
enum Parity {
case even
case odd
}
// If there is no change in the activity value, and fadeoutWithoutActivity is
// true, then animate this view to transparent.
public var fadeoutWithoutActivity = true
public var fadeoutDelay = TimeInterval(1)
public var fadeoutDuration = TimeInterval(1)
fileprivate var timer = Timer()
public var activity = CGFloat(0) {
didSet(oldActivity) {
resetFadeAnimation()
let angle = CGFloat(Double.pi*2) * activityPercentage
switch activityParity {
case .even:
pieLayer.startAngle = 0
pieLayer.endAngle = angle
case .odd:
pieLayer.startAngle = angle
pieLayer.endAngle = CGFloat(Double.pi*2)
}
}
}
public var fillColor: UIColor {
get {
return pieLayer.fillColor
}
set(newColor) {
pieLayer.fillColor = newColor
}
}
// MARK:
// MARK: Init
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
isOpaque = false
pieLayer.polarity = .negative
}
// MARK:
fileprivate var activityPercentage: CGFloat {
return percentageFromActivity(activity)
}
fileprivate func percentageFromActivity(_ activity: CGFloat) -> CGFloat {
let rounded = floor(activity)
return activity - rounded
}
fileprivate var activityParity: Parity {
let parity: Parity
if Int(activity) % 2 == 0 {
parity = .even
} else {
parity = .odd
}
return parity
}
func resetFadeAnimation() {
layer.removeAllAnimations()
alpha = 1.0
timer.invalidate()
timer = Timer.scheduledTimer( timeInterval: fadeoutDelay,
target: self,
selector: #selector(ActivityView.fadeAnimation),
userInfo: nil,
repeats: false)
timer.tolerance = fadeoutDelay / 2
}
@objc func fadeAnimation() {
UIView.animate(withDuration: fadeoutDuration, animations: {
self.alpha = 0
})
}
public override class var layerClass : AnyClass {
return PieLayer.self
}
fileprivate var pieLayer: PieLayer {
return self.layer as! PieLayer
}
}
|
mit
|
eb8b00478df2d3420ff6198437c5a25e
| 20.973684 | 90 | 0.597206 | 4.587912 | false | false | false | false |
richeterre/jumu-nordost-ios
|
JumuNordost/Application/PerformanceViewController.swift
|
1
|
1727
|
//
// PerformanceViewController.swift
// JumuNordost
//
// Created by Martin Richter on 21/02/16.
// Copyright © 2016 Martin Richter. All rights reserved.
//
import ReactiveCocoa
import Cartography
class PerformanceViewController: UIViewController {
private let mediator: PerformanceMediator
private let scrollView = UIScrollView()
private let performanceView: PerformanceView
// MARK: - Lifecycle
init(mediator: PerformanceMediator) {
self.mediator = mediator
performanceView = PerformanceView(performance: mediator.formattedPerformance)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
scrollView.layoutMargins = UIEdgeInsets(top: 16, left: 8, bottom: 16, right: 8)
scrollView.addSubview(performanceView)
view.addSubview(scrollView)
makeConstraints()
makeBindings()
}
// MARK: - Layout
private func makeConstraints() {
constrain(view, scrollView, performanceView) { superview, scrollView, performanceView in
scrollView.edges == superview.edges
performanceView.top == scrollView.topMargin
performanceView.left == superview.leftMargin
performanceView.right == superview.rightMargin
performanceView.bottom == scrollView.bottomMargin
}
}
// MARK: - Bindings
private func makeBindings() {
self.title = mediator.title
mediator.active <~ isActive()
}
}
|
mit
|
b8d168d666f05b4023fb579a730b024a
| 24.761194 | 96 | 0.66686 | 5.03207 | false | false | false | false |
xuanyi0627/jetstream-ios
|
Jetstream/SessionCreateMessage.swift
|
1
|
2563
|
//
// SessionCreateMessage.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class SessionCreateMessage: NetworkMessage {
class var messageType: String {
return "SessionCreate"
}
override var type: String {
return SessionCreateMessage.messageType
}
let params: [String: AnyObject]
let version: String
init(params: [String: AnyObject], version: String) {
self.params = params
self.version = version
super.init(index: 0)
}
convenience init() {
self.init(params: [String: AnyObject]())
}
convenience init(params: [String: AnyObject]) {
self.init(params: params, version: clientVersion)
}
override func serialize() -> [String: AnyObject] {
var dictionary = super.serialize()
dictionary["params"] = params
dictionary["version"] = version
return dictionary
}
class func unserialize(dictionary: [String: AnyObject]) -> NetworkMessage? {
var params = dictionary["params"] as? [String: AnyObject]
var version = dictionary["version"] as? String
if params != nil && version != nil {
return SessionCreateMessage(params: params!, version: version!)
} else if params != nil {
return SessionCreateMessage(params: params!)
} else {
return SessionCreateMessage()
}
}
}
|
mit
|
d4db36acbcc4bf2c2d471842d3a3d3eb
| 34.597222 | 81 | 0.668748 | 4.59319 | false | false | false | false |
Roommate-App/roomy
|
roomy/Pods/IBAnimatable/Sources/Animators/Common/PresentationPresenterManager.swift
|
5
|
1083
|
//
// Created by Tom Baranes on 16/07/16.
// Copyright © 2016 Jake Lin. All rights reserved.
//
import Foundation
public class PresentationPresenterManager {
// MARK: - Singleton
public static let shared = PresentationPresenterManager()
private init() {}
// MARK: - Private
private var cache = [PresentationAnimationType: PresentationPresenter]()
// MARK: Internal Interface
public func retrievePresenter(presentationAnimationType: PresentationAnimationType,
transitionDuration: Duration = defaultPresentationDuration,
interactiveGestureType: InteractiveGestureType? = nil) -> PresentationPresenter {
let presenter = cache[presentationAnimationType]
if let presenter = presenter {
presenter.transitionDuration = transitionDuration
return presenter
}
let newPresenter = PresentationPresenter(presentationAnimationType: presentationAnimationType, transitionDuration: transitionDuration)
cache[presentationAnimationType] = newPresenter
return newPresenter
}
}
|
mit
|
70d2ecc566fdde8a1cf6b9f32e2d63f8
| 32.8125 | 138 | 0.730129 | 5.848649 | false | false | false | false |
ypresto/SwiftLintXcode
|
SwiftLintXcode/Formatter.swift
|
1
|
5763
|
//
// Formatter.swift
// SwiftLintXcode
//
// Created by yuya.tanaka on 2016/04/04.
// Copyright (c) 2016 Yuya Tanaka. All rights reserved.
//
import Foundation
import Cocoa
final class Formatter {
static var sharedInstance = Formatter()
private static let pathExtension = "SwiftLintXcode"
private let fileManager = FileManager.default
private struct CursorPosition {
let line: Int
let column: Int
}
class func isFormattableDocument(_ document: NSDocument) -> Bool {
return document.fileURL?.pathExtension.lowercased() == "swift"
}
func tryFormatDocument(_ document: IDESourceCodeDocument) -> Bool {
do {
try formatDocument(document)
return true
} catch let error as NSError {
NSAlert(error: error).runModal()
} catch {
NSAlert(error: errorWithMessage("Unknown error occured: \(error)")).runModal()
}
return false
}
func formatDocument(_ document: IDESourceCodeDocument) throws {
let textStorage: DVTSourceTextStorage = document.textStorage()
let originalString = textStorage.string
let formattedString = try formatString(originalString)
if formattedString == originalString { return }
let selectedRange = SwiftLintXcodeTRVSXcode.textView().selectedRange()
let cursorPosition = cursorPositionForSelectedRange(selectedRange, textStorage: textStorage)
textStorage.beginEditing()
textStorage.replaceCharacters(in: NSRange(location: 0, length: textStorage.length), with: formattedString, withUndoManager: document.undoManager())
textStorage.endEditing()
let newLocation = locationForCursorPosition(cursorPosition, textStorage: textStorage)
SwiftLintXcodeTRVSXcode.textView().setSelectedRange(NSRange(location: newLocation, length: 0))
}
private func cursorPositionForSelectedRange(_ selectedRange: NSRange, textStorage: DVTSourceTextStorage) -> CursorPosition {
let line = textStorage.lineRange(forCharacterRange: selectedRange).location
let column = selectedRange.location - startLocationOfLine(line, textStorage: textStorage)
return CursorPosition(line: line, column: column)
}
private func locationForCursorPosition(_ cursorPosition: CursorPosition, textStorage: DVTSourceTextStorage) -> Int {
let startOfLine = startLocationOfLine(cursorPosition.line, textStorage: textStorage)
let locationOfNextLine = textStorage.characterRange(forLineRange: NSRange(location: cursorPosition.line + 1, length: 0)).location
// XXX: Can reach EOF..? Cursor position may be trimmed one charactor when cursor is on EOF.
return min(startOfLine + cursorPosition.column, locationOfNextLine - 1)
}
private func startLocationOfLine(_ line: Int, textStorage: DVTSourceTextStorage) -> Int {
return textStorage.characterRange(forLineRange: NSRange(location: line, length: 0)).location
}
private func formatString(_ string: String) throws -> String {
guard let workspaceRootDirectory = SwiftLintXcodeIDEHelper.currentWorkspaceURL()?.deletingLastPathComponent().path else {
throw errorWithMessage("Cannot determine project directory.")
}
return try withTempporaryFile { (filePath) in
try string.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8)
let swiftlintPath = try self.getExecutableOnPath(name: "swiftlint", workingDirectory: workspaceRootDirectory)
let task = Process()
task.launchPath = swiftlintPath
task.arguments = ["autocorrect", "--path", filePath]
task.currentDirectoryPath = workspaceRootDirectory
task.launch()
task.waitUntilExit()
if task.terminationStatus != 0 {
throw errorWithMessage("Executing swiftlint exited with non-zero status.")
}
return try String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
}
}
private func getExecutableOnPath(name: String, workingDirectory: String) throws -> String {
let pipe = Pipe()
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = [
"-l", "-c", "which \(name)"
]
task.currentDirectoryPath = workingDirectory
task.standardOutput = pipe
task.launch()
task.waitUntilExit()
if task.terminationStatus != 0 {
throw errorWithMessage("Executing `which swiftlint` exited with non-zero status.")
}
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let pathString = String(data: data, encoding: String.Encoding.utf8) else {
throw errorWithMessage("Cannot read result of `which swiftlint`.")
}
let path = pathString.trimmingCharacters(in: CharacterSet.newlines)
if !fileManager.isExecutableFile(atPath: path) {
throw errorWithMessage("swiftlint at \(path) is not executable.")
}
return path
}
private func withTempporaryFile<T>(_ callback: (_ filePath: String) throws -> T) throws -> T {
let filePath = createTemporaryPath()
if fileManager.fileExists(atPath: filePath) {
throw errorWithMessage("Cannot write to \(filePath), file already exists.")
}
defer { _ = try? fileManager.removeItem(atPath: filePath) }
return try callback(filePath)
}
private func createTemporaryPath() -> String {
return URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent("SwiftLintXcode_\(UUID().uuidString).swift").path
}
}
|
mit
|
cbcb108c659c1736ea385f69f884c9d4
| 42.330827 | 155 | 0.67864 | 5.154741 | false | false | false | false |
dsmelov/simsim
|
SimSim/Constants.swift
|
1
|
1703
|
import Foundation
import Cocoa
//============================================================================
class Constants: NSObject
{
static let iconSize = 16
static let maxRecentSimulators = 5
static let githubUrl = "https://github.com/dsmelov/simsim"
struct Paths
{
static let finderApp = "/System/Library/CoreServices/Finder.app"
static let terminalApp = "/Applications/Utilities/Terminal.app"
static let iTermApp = "/Applications/iTerm.app"
static let commanderOneApp = "/Applications/Commander One.app"
static let commanderOneProApp = "/Applications/Commander One PRO.app"
static let realmApp = "/Applications/Realm Studio.app"
}
struct Actions
{
static let finder = "Finder"
static let terminal = "Terminal"
static let iTerm = "iTerm"
static let commanderOne = "Commander One"
static let clipboard = "Copy path to Clipboard"
static let reset = "Reset application data"
static let login = "Start at Login"
static let quit = "Quit"
}
struct Realm
{
static let appName = "Realm Studio"
static let appUrl = "https://realm.io/products/realm-studio/"
static let dbPaths: Array = ["Documents", "Library/Caches", nil]
}
struct Other
{
static let commanderOnePlist = "Library/Preferences/com.eltima.cmd1.plist"
static let dsStore = ".DS_Store"
static let iTermBundle = "com.googlecode.iterm2"
}
struct Simulator
{
static let deviceProperties = "device.plist"
static let rootPath = "Library/Developer/CoreSimulator/Devices"
}
}
|
mit
|
d19887182d420cac62440d75dbcc58a3
| 31.132075 | 82 | 0.6101 | 4.481579 | false | false | false | false |
SusanDoggie/Doggie
|
Sources/DoggieGraphics/ImageCodec/Algorithm/TIFF/TIFFCompression/TIFFLZWCompression.swift
|
1
|
7529
|
//
// TIFFLZWCompression.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
private struct TIFFLZWBitsWriter {
var buffer = Data()
var byte: UInt8 = 0
var bitsize: UInt = 0
mutating func write(_ bits: UInt, _ size: UInt) {
var bits = bits & ((1 << size) - 1)
var remain = size
while remain != 0 {
let _size = min(8 - bitsize, remain)
remain -= _size
byte = (byte << _size) | UInt8(bits >> remain)
bits &= (1 << remain) - 1
bitsize += _size
if bitsize == 8 {
buffer.append(byte)
byte = 0
bitsize = 0
}
}
}
mutating func finalize() {
if bitsize != 0 {
buffer.append(byte << (8 - bitsize))
}
}
}
public class TIFFLZWEncoder: CompressionCodec {
public enum Error: Swift.Error {
case endOfStream
}
private let maxBitsWidth: Int
private var tableLimit: Int {
return 1 << maxBitsWidth
}
private var table: [Data] = []
private var writer: TIFFLZWBitsWriter = {
var writer = TIFFLZWBitsWriter()
writer.write(256, 9)
return writer
}()
public private(set) var isEndOfStream: Bool = false
public init(maxBitsWidth: Int = 12) {
self.maxBitsWidth = max(9, maxBitsWidth)
self.table.reserveCapacity(tableLimit - 258)
}
public func update(_ source: UnsafeBufferPointer<UInt8>, _ callback: (UnsafeBufferPointer<UInt8>) throws -> Void) throws {
guard !isEndOfStream else { throw Error.endOfStream }
var source = source
while let char = source.first {
let bit_count = log2(UInt(table.count + 258)) + 1
var max_length = 0
var index: Int?
for (i, sequence) in table.enumerated() where max_length < sequence.count && source.starts(with: sequence) {
max_length = sequence.count
index = i
}
if let index = index {
writer.write(UInt(index + 258), bit_count)
} else {
writer.write(UInt(char), bit_count)
max_length = 1
}
let sequence = source.prefix(max_length + 1)
source = UnsafeBufferPointer(rebasing: source.dropFirst(max_length))
if table.count + 259 < tableLimit {
table.append(Data(sequence))
} else {
writer.write(256, bit_count)
table.removeAll(keepingCapacity: true)
}
if writer.buffer.count > 4095 {
try writer.buffer.withUnsafeBufferPointer(callback)
writer.buffer.removeAll(keepingCapacity: true)
}
}
}
public func finalize(_ callback: (UnsafeBufferPointer<UInt8>) throws -> Void) throws {
guard !isEndOfStream else { throw Error.endOfStream }
writer.write(257, log2(UInt(table.count + 258)) + 1)
writer.finalize()
try writer.buffer.withUnsafeBufferPointer(callback)
isEndOfStream = true
}
}
public struct TIFFLZWDecoder: TIFFCompressionDecoder {
public enum Error: Swift.Error {
case invalidInputData
}
public static func decode(_ input: inout Data) throws -> Data {
var table: [Data] = []
table.reserveCapacity(0xEFE)
var bits: UInt = 0
var bitsize: UInt = 0
var last_code_size: UInt?
func next_code() -> UInt? {
while let byte = input.popFirst() {
bits = (bits << 8) | UInt(byte)
bitsize += 8
if let code_size = last_code_size, bitsize >= code_size {
let remain = bitsize - code_size
let code = bits >> remain
if code == 256 {
bits &= (1 << remain) - 1
bitsize = remain
last_code_size = nil
return code
}
}
let code_size = log2(UInt(table.count + 258)) + 1
guard bitsize >= code_size else { continue }
let remain = bitsize - code_size
let code = bits >> remain
bits &= (1 << remain) - 1
bitsize = remain
last_code_size = code_size
return code
}
return nil
}
var output = Data()
while let code = next_code() {
guard code != 257 else { break }
if code == 256 {
table.removeAll(keepingCapacity: true)
} else if 0...255 ~= code {
if var last_sequence = table.last {
last_sequence.append(UInt8(code))
table[table.count - 1] = last_sequence
}
output.append(UInt8(code))
table.append(output.suffix(1))
} else {
let index = Int(code - 258)
guard index < table.count else { throw Error.invalidInputData }
if var last_sequence = table.last {
last_sequence.append(table[index].first!)
table[table.count - 1] = last_sequence
}
let sequence = table[index]
output.append(sequence)
table.append(sequence)
}
}
return output
}
}
|
mit
|
6dbeb54eb55c012815e7399a418346b6
| 29.605691 | 126 | 0.483464 | 5.070034 | false | false | false | false |
fluidsonic/JetPack
|
Sources/Extensions/Foundation/NSDateFormatter.swift
|
1
|
866
|
import Foundation
public extension DateFormatter {
@nonobjc
private static let iso8601Formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale.englishUnitedStatesComputer
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}()
@nonobjc
private static let iso8601FormatterWithFractionalSeconds: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale.englishUnitedStatesComputer
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
return formatter
}()
@nonobjc
static func iso8601Formatter(withFractionalSeconds: Bool = false) -> DateFormatter {
if withFractionalSeconds {
return iso8601FormatterWithFractionalSeconds
}
return iso8601Formatter
}
}
|
mit
|
1e027b1c25cf6af5dd3ce487001e7153
| 23.055556 | 85 | 0.773672 | 3.990783 | false | false | false | false |
Qmerce/ios-sdk
|
Sources/Helpers/UserAgent.swift
|
1
|
1497
|
//
// UserAgent.swift
// ApesterKit
//
// Created by Hasan Sawaed Tabash on 9/28/19.
// Copyright © 2019 Apester. All rights reserved.
//
import Foundation
import UIKit
class UserAgent {
//eg. Darwin/16.3.0
private static var darwinVersion: String {
var sysinfo = utsname()
uname(&sysinfo)
let dv = String(bytes: Data(bytes: &sysinfo.release, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters)
return "Darwin/\(dv)"
}
//eg. CFNetwork/808.3
private static var CFNetworkVersion: String {
let dictionary = Bundle(identifier: "com.apple.CFNetwork")?.infoDictionary ?? [:]
let version = dictionary[ "CFBundleShortVersionString"] as? String ?? ""
return "CFNetwork/\(version)"
}
//eg. iOS/10_1
private static var deviceVersion: String {
let currentDevice = UIDevice.current
return "\(currentDevice.systemName)/\(currentDevice.systemVersion)"
}
//eg. iPhone5,2
private static var deviceName: String {
var sysinfo = utsname()
uname(&sysinfo)
return String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters)
}
static func customized(with dictionary: [String : String]) -> String {
return " WebViewApp \(BundleInfo.appNameAndVersion(from: dictionary)) \(deviceName) \(deviceVersion) \(CFNetworkVersion) \(darwinVersion)"
}
}
|
mit
|
95aeb15cec5ce512cb7ae83b010ffcec
| 34.619048 | 149 | 0.661765 | 4.144044 | false | false | false | false |
panadaW/MyNews
|
MyWb完善首页数据/MyWb/Class/Controllers/Mine/MineTableViewController.swift
|
2
|
3416
|
//
// MineTableViewController.swift
// MyWb
//
// Created by 王明申 on 15/10/8.
// Copyright © 2015年 晨曦的Mac. All rights reserved.
//
import UIKit
class MineTableViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
visitorview?.changViewInfo(false, imagename: "visitordiscover_image_profile", message: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
// 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 numberOfSectionsInTableView(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, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
ecd429ddeea34d57e28361cc17c2c03e
| 34.210526 | 157 | 0.690882 | 5.377814 | false | false | false | false |
abeschneider/stem
|
Sources/Op/AddOp.swift
|
1
|
2482
|
//
// add.swift
// stem
//
// Created by Schneider, Abraham R. on 11/12/16.
// Copyright © 2016 none. All rights reserved.
//
import Foundation
import Tensor
open class AddOp<S:Storage>: Op<S> where S.ElementType:FloatNumericType {
open var inOps:[Op<S>] {
let inputs:[Source<S>] = self.inputs[0]
return inputs.map { $0.op! }
}
public init(_ ops:Op<S>...) {
super.init(inputs: ["input"], outputs: ["output"])
connect(from: ops, "output", to: self, "input")
outputs["output"] = [Tensor<S>](repeating: zeros(ops[0].output.shape), count: ops.count)
}
required public init(op: Op<S>, shared: Bool) {
fatalError("init(op:shared:) has not been implemented")
}
open override func apply() {
if output.shape != inOps[0].output.shape {
output.resize(inOps[0].output.shape)
}
copy(from: inOps[0].output, to: output)
for op in inOps[1..<inOps.count] {
iadd(output, op.output)
}
}
}
open class AddOpGrad<S:Storage>: Op<S>, Gradient where S.ElementType:FloatNumericType {
open var _add:Tensor<S> { return inputs[0].output }
open var _input:[Tensor<S>] {
let _in:[Source<S>] = inputs[1]
return _in.map { $0.output }
}
open var _gradOutput:Tensor<S> { return inputs[2].output }
public required init(op:AddOp<S>) {
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
let opInputs:[Source<S>] = op.inputs[0]
connect(from: op, "output", to: self, "op")
connect(from: opInputs.map { $0.op! }, "output", to: self, "input")
outputs["output"] = [Tensor<S>](repeating: Tensor<S>(_input[0].shape), count: _input.count)
}
required public init(op: Op<S>, shared: Bool) {
fatalError("init(op:shared:) has not been implemented")
}
open override func apply() {
if outputs["output"]!.count != _input.count {
outputs["output"] = [Tensor<S>](repeating: Tensor<S>(_input[0].shape), count: _input.count)
}
for out in outputs["output"]! {
copy(from: _gradOutput, to: out)
}
}
open override func reset() {
for out in outputs["output"]! {
fill(out, value: 0)
}
}
}
extension AddOp: Differentiable {
public func gradient() -> GradientType {
return AddOpGrad<S>(op: self)
}
}
|
mit
|
a7140a77dd2e85696cb5502cbd965fa5
| 29.256098 | 103 | 0.562273 | 3.529161 | false | false | false | false |
HabitRPG/habitrpg-ios
|
HabitRPG/TableviewCells/SubscriptionOptionView.swift
|
1
|
3253
|
//
// SubscriptionOptionView.swift
// Habitica
//
// Created by Phillip Thelen on 07/02/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
class SubscriptionOptionView: UITableViewCell {
//swiftlint:disable private_outlet
@IBOutlet weak var wrapperView: UIView!
@IBOutlet weak var selectionView: UIImageView!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var gemCapLabel: PaddedLabel!
@IBOutlet weak var mysticHourglassLabel: PaddedLabel!
@IBOutlet weak var flagView: FlagView!
//swiftlint:enable private_outlet
private var isAlreadySelected = false
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
let animDuration = 0.3
let theme = ThemeService.shared.theme
if selected {
UIView.animate(withDuration: animDuration, animations: {[weak self] () in
self?.wrapperView.borderWidth = 2
self?.selectionView.image = Asset.circleSelected.image
if theme.isDark {
self?.titleLabel?.textColor = UIColor.white
self?.priceLabel?.textColor = UIColor.white
} else {
self?.titleLabel?.textColor = UIColor.purple300
self?.priceLabel?.textColor = UIColor.purple300
}
self?.gemCapLabel.textColor = UIColor.white
self?.gemCapLabel.backgroundColor = UIColor.purple400
self?.mysticHourglassLabel.textColor = UIColor.white
self?.mysticHourglassLabel.backgroundColor = UIColor.purple400
})
} else {
UIView.animate(withDuration: animDuration, animations: {[weak self] () in
self?.wrapperView.borderWidth = 0
self?.selectionView.image = Asset.circleUnselected.image
self?.titleLabel?.textColor = theme.ternaryTextColor
self?.priceLabel?.textColor = theme.ternaryTextColor
self?.gemCapLabel.textColor = theme.secondaryTextColor
self?.gemCapLabel.backgroundColor = theme.offsetBackgroundColor
self?.mysticHourglassLabel.textColor = theme.secondaryTextColor
self?.mysticHourglassLabel.backgroundColor = theme.offsetBackgroundColor
})
}
wrapperView.backgroundColor = ThemeService.shared.theme.windowBackgroundColor
}
func setMonthCount(_ count: Int) {
switch count {
case 1:
setGemCap(25)
setHourglassCount(0)
case 3:
setGemCap(30)
setHourglassCount(1)
case 6:
setGemCap(35)
setHourglassCount(2)
case 12:
setGemCap(45)
setHourglassCount(4)
default: break
}
}
func setGemCap(_ count: Int) {
gemCapLabel.text = L10n.gemCap(count)
}
func setHourglassCount(_ count: Int) {
// swiftlint:disable:next empty_count
mysticHourglassLabel.isHidden = count == 0
mysticHourglassLabel.text = L10n.hourglassCount(count)
}
}
|
gpl-3.0
|
55f4e7f166081a70aa6dfbe63ed65305
| 36.37931 | 88 | 0.619619 | 4.93475 | false | false | false | false |
CrowdShelf/ios
|
CrowdShelf/CrowdShelf/Models/SerializableObject.swift
|
1
|
2972
|
//
// SerializableObject.swift
// CrowdShelf
//
// Created by Øyvind Grimnes on 21/09/15.
// Copyright © 2015 Øyvind Grimnes. All rights reserved.
//
/**
JSON: a hierarchical dictionary containing valid JSON data types.
SQLite: a flat dictionary containing Cocoa classes
*/
public enum SerializationMode {
case JSON, SQLite
}
public class SerializableObject: NSObject {
/**
Serialize the object
- returns: A dictionary containing the data from the object
*/
public func serialize() -> [String: AnyObject] {
var dictionary: [String: AnyObject] = [:]
let mirror = Mirror(reflecting: self)
for (key, child) in mirror.children {
if key == nil || (mirror.subjectType as! SerializableObject.Type).ignoreProperties().contains(key!) {
continue
}
var propertyValue: AnyObject? = SerializableObject.serializedValueForProperty(key!)
if propertyValue == nil {
if let value = self.unwrap(child) as? AnyObject {
propertyValue = value
/* Convert data to string and dates to timestamps for JSON */
if let serializableValue = value as? SerializableObject {
propertyValue = serializableValue.serialize()
} else if let arrayValue = value as? [SerializableObject] {
propertyValue = arrayValue.map {$0.serialize()}
} else if let dataValue = value as? NSData {
propertyValue = dataValue.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
} else if let dateValue = value as? NSDate {
propertyValue = dateValue.timeIntervalSince1970
}
}
}
dictionary[key!] = propertyValue ?? NSNull()
}
return dictionary
}
/**
Unwraps any optional values
- parameter value: The value to unwrap
*/
private func unwrap(value: Any) -> Any? {
let mi = Mirror(reflecting: value)
if mi.displayStyle != .Optional {
return value
}
if mi.children.count == 0 {
return nil
}
let (_, some) = mi.children.first!
return some
}
/**
Used to customize the serialization of an objects properties. Can be overridden in subclasses
- parameter property: The name of a property
- returns: An optional custom serialized object
*/
class func serializedValueForProperty(property: String) -> AnyObject? {
return nil
}
class public func ignoreProperties() -> Set<String> {
return []
}
}
|
mit
|
1a1cebf648eab604664991307fb20fb3
| 28.7 | 139 | 0.55069 | 5.612476 | false | false | false | false |
Antidote-for-Tox/Antidote
|
Antidote/ActiveSessionCoordinator.swift
|
1
|
23987
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
protocol ActiveSessionCoordinatorDelegate: class {
func activeSessionCoordinatorDidLogout(_ coordinator: ActiveSessionCoordinator, importToxProfileFromURL: URL?)
func activeSessionCoordinatorDeleteProfile(_ coordinator: ActiveSessionCoordinator)
func activeSessionCoordinatorRecreateCoordinatorsStack(_ coordinator: ActiveSessionCoordinator, options: CoordinatorOptions)
func activeSessionCoordinatorDidStartCall(_ coordinator: ActiveSessionCoordinator)
func activeSessionCoordinatorDidFinishCall(_ coordinator: ActiveSessionCoordinator)
}
private struct Options {
static let ToShowKey = "ToShowKey"
static let StoredOptions = "StoredOptions"
enum Coordinator {
case none
case settings
}
}
private struct IpadObjects {
let splitController: UISplitViewController
let primaryController: PrimaryIpadController
let keyboardObserver = KeyboardObserver()
}
private struct IphoneObjects {
enum TabCoordinator: Int {
case friends = 0
case chats = 1
case settings = 2
case profile = 3
static func allValues() -> [TabCoordinator]{
return [friends, chats, settings, profile]
}
}
let chatsCoordinator: ChatsTabCoordinator
let tabBarController: TabBarController
let friendsTabBarItem: TabBarBadgeItem
let chatsTabBarItem: TabBarBadgeItem
let profileTabBarItem: TabBarProfileItem
}
class ActiveSessionCoordinator: NSObject {
weak var delegate: ActiveSessionCoordinatorDelegate?
fileprivate let theme: Theme
fileprivate let window: UIWindow
// Tox manager is stored here
fileprivate var toxManager: OCTManager!
fileprivate let friendsCoordinator: FriendsTabCoordinator
fileprivate let settingsCoordinator: SettingsTabCoordinator
fileprivate let profileCoordinator: ProfileTabCoordinator
fileprivate let notificationCoordinator: NotificationCoordinator
fileprivate let automationCoordinator: AutomationCoordinator
fileprivate var callCoordinator: CallCoordinator!
/**
One of following properties will be non-empty, depending on running device.
*/
fileprivate var iPhone: IphoneObjects!
fileprivate var iPad: IpadObjects!
init(theme: Theme, window: UIWindow, toxManager: OCTManager) {
self.theme = theme
self.window = window
self.toxManager = toxManager
self.friendsCoordinator = FriendsTabCoordinator(theme: theme, toxManager: toxManager)
self.settingsCoordinator = SettingsTabCoordinator(theme: theme)
self.profileCoordinator = ProfileTabCoordinator(theme: theme, toxManager: toxManager)
self.notificationCoordinator = NotificationCoordinator(theme: theme, submanagerObjects: toxManager.objects)
self.automationCoordinator = AutomationCoordinator(submanagerObjects: toxManager.objects, submanagerFiles: toxManager.files)
super.init()
// order matters
createDeviceSpecificObjects()
createCallCoordinator()
toxManager.user.delegate = self
friendsCoordinator.delegate = self
settingsCoordinator.delegate = self
profileCoordinator.delegate = self
notificationCoordinator.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(ActiveSessionCoordinator.applicationWillTerminate), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func applicationWillTerminate() {
toxManager = nil
// Giving tox some time to close all connections.
let until = Date(timeIntervalSinceNow:1.0)
RunLoop.current.run(until: until)
}
}
extension ActiveSessionCoordinator: TopCoordinatorProtocol {
func startWithOptions(_ options: CoordinatorOptions?) {
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.tabBarController.selectedIndex = IphoneObjects.TabCoordinator.chats.rawValue
iPhone.chatsCoordinator.startWithOptions(nil)
window.rootViewController = iPhone.tabBarController
case .iPad:
primaryIpadControllerShowFriends(iPad.primaryController)
window.rootViewController = iPad.splitController
}
var settingsOptions: CoordinatorOptions?
let toShow = options?[Options.ToShowKey] as? Options.Coordinator ?? .none
switch toShow {
case .none:
break
case .settings:
settingsOptions = options?[Options.StoredOptions] as? CoordinatorOptions
}
friendsCoordinator.startWithOptions(nil)
settingsCoordinator.startWithOptions(settingsOptions)
profileCoordinator.startWithOptions(nil)
notificationCoordinator.startWithOptions(nil)
automationCoordinator.startWithOptions(nil)
callCoordinator.startWithOptions(nil)
toxManager.bootstrap.addPredefinedNodes()
toxManager.bootstrap.bootstrap()
updateUserAvatar()
updateUserName()
switch toShow {
case .none:
break
case .settings:
showSettings()
}
}
func handleLocalNotification(_ notification: UILocalNotification) {
notificationCoordinator.handleLocalNotification(notification)
}
func handleInboxURL(_ url: URL) {
let fileName = url.lastPathComponent
let filePath = url.path
let isToxFile = url.isToxURL()
let style: UIAlertControllerStyle
switch InterfaceIdiom.current() {
case .iPhone:
style = .actionSheet
case .iPad:
style = .alert
}
let alert = UIAlertController(title: nil, message: fileName, preferredStyle: style)
if isToxFile {
alert.addAction(UIAlertAction(title: String(localized: "create_profile"), style: .default) { [unowned self] _ -> Void in
self.logout(importToxProfileFromURL: url)
})
}
alert.addAction(UIAlertAction(title: String(localized: "file_send_to_contact"), style: .default) { [unowned self] _ -> Void in
self.sendFileToChats(filePath, fileName: fileName)
})
alert.addAction(UIAlertAction(title: String(localized: "alert_cancel"), style: .cancel, handler: nil))
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.tabBarController.present(alert, animated: true, completion: nil)
case .iPad:
iPad.splitController.present(alert, animated: true, completion: nil)
}
}
}
extension ActiveSessionCoordinator: OCTSubmanagerUserDelegate {
func submanagerUser(_ submanager: OCTSubmanagerUser, connectionStatusUpdate connectionStatus: OCTToxConnectionStatus) {
updateUserStatusView()
let show = (connectionStatus == .none)
notificationCoordinator.toggleConnectingView(show: show, animated: true)
}
}
extension ActiveSessionCoordinator: NotificationCoordinatorDelegate {
func notificationCoordinator(_ coordinator: NotificationCoordinator, showChat chat: OCTChat) {
showChat(chat)
}
func notificationCoordinatorShowFriendRequest(_ coordinator: NotificationCoordinator, showRequest request: OCTFriendRequest) {
showFriendRequest(request)
}
func notificationCoordinatorAnswerIncomingCall(_ coordinator: NotificationCoordinator, userInfo: String) {
callCoordinator.answerIncomingCallWithUserInfo(userInfo)
}
func notificationCoordinator(_ coordinator: NotificationCoordinator, updateFriendsBadge badge: Int) {
let text: String? = (badge > 0) ? "\(badge)" : nil
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.friendsTabBarItem.badgeText = text
case .iPad:
iPad.primaryController.friendsBadgeText = text
break
}
}
func notificationCoordinator(_ coordinator: NotificationCoordinator, updateChatsBadge badge: Int) {
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.chatsTabBarItem.badgeText = (badge > 0) ? "\(badge)" : nil
case .iPad:
// none
break
}
}
}
extension ActiveSessionCoordinator: CallCoordinatorDelegate {
func callCoordinator(_ coordinator: CallCoordinator, notifyAboutBackgroundCallFrom caller: String, userInfo: String) {
notificationCoordinator.showCallNotificationWithCaller(caller, userInfo: userInfo)
}
func callCoordinatorDidStartCall(_ coordinator: CallCoordinator) {
delegate?.activeSessionCoordinatorDidStartCall(self)
}
func callCoordinatorDidFinishCall(_ coordinator: CallCoordinator) {
delegate?.activeSessionCoordinatorDidFinishCall(self)
}
}
extension ActiveSessionCoordinator: FriendsTabCoordinatorDelegate {
func friendsTabCoordinatorOpenChat(_ coordinator: FriendsTabCoordinator, forFriend friend: OCTFriend) {
let chat = toxManager.chats.getOrCreateChat(with: friend)
showChat(chat!)
}
func friendsTabCoordinatorCall(_ coordinator: FriendsTabCoordinator, toFriend friend: OCTFriend) {
let chat = toxManager.chats.getOrCreateChat(with: friend)!
callCoordinator.callToChat(chat, enableVideo: false)
}
func friendsTabCoordinatorVideoCall(_ coordinator: FriendsTabCoordinator, toFriend friend: OCTFriend) {
let chat = toxManager.chats.getOrCreateChat(with: friend)!
callCoordinator.callToChat(chat, enableVideo: true)
}
}
extension ActiveSessionCoordinator: ChatsTabCoordinatorDelegate {
func chatsTabCoordinator(_ coordinator: ChatsTabCoordinator, chatWillAppear chat: OCTChat) {
notificationCoordinator.banNotificationsForChat(chat)
}
func chatsTabCoordinator(_ coordinator: ChatsTabCoordinator, chatWillDisapper chat: OCTChat) {
notificationCoordinator.unbanNotificationsForChat(chat)
}
func chatsTabCoordinator(_ coordinator: ChatsTabCoordinator, callToChat chat: OCTChat, enableVideo: Bool) {
callCoordinator.callToChat(chat, enableVideo: enableVideo)
}
}
extension ActiveSessionCoordinator: SettingsTabCoordinatorDelegate {
func settingsTabCoordinatorRecreateCoordinatorsStack(_ coordinator: SettingsTabCoordinator, options settingsOptions: CoordinatorOptions) {
delegate?.activeSessionCoordinatorRecreateCoordinatorsStack(self, options: [
Options.ToShowKey: Options.Coordinator.settings,
Options.StoredOptions: settingsOptions,
])
}
}
extension ActiveSessionCoordinator: ProfileTabCoordinatorDelegate {
func profileTabCoordinatorDelegateLogout(_ coordinator: ProfileTabCoordinator) {
logout()
}
func profileTabCoordinatorDelegateDeleteProfile(_ coordinator: ProfileTabCoordinator) {
delegate?.activeSessionCoordinatorDeleteProfile(self)
}
func profileTabCoordinatorDelegateDidChangeUserStatus(_ coordinator: ProfileTabCoordinator) {
updateUserStatusView()
}
func profileTabCoordinatorDelegateDidChangeAvatar(_ coordinator: ProfileTabCoordinator) {
updateUserAvatar()
}
func profileTabCoordinatorDelegateDidChangeUserName(_ coordinator: ProfileTabCoordinator) {
updateUserName()
}
}
extension ActiveSessionCoordinator: PrimaryIpadControllerDelegate {
func primaryIpadController(_ controller: PrimaryIpadController, didSelectChat chat: OCTChat) {
showChat(chat)
}
func primaryIpadControllerShowFriends(_ controller: PrimaryIpadController) {
iPad.splitController.showDetailViewController(friendsCoordinator.navigationController, sender: nil)
}
func primaryIpadControllerShowSettings(_ controller: PrimaryIpadController) {
iPad.splitController.showDetailViewController(settingsCoordinator.navigationController, sender: nil)
}
func primaryIpadControllerShowProfile(_ controller: PrimaryIpadController) {
iPad.splitController.showDetailViewController(profileCoordinator.navigationController, sender: nil)
}
}
extension ActiveSessionCoordinator: ChatPrivateControllerDelegate {
func chatPrivateControllerWillAppear(_ controller: ChatPrivateController) {
notificationCoordinator.banNotificationsForChat(controller.chat)
}
func chatPrivateControllerWillDisappear(_ controller: ChatPrivateController) {
notificationCoordinator.unbanNotificationsForChat(controller.chat)
}
func chatPrivateControllerCallToChat(_ controller: ChatPrivateController, enableVideo: Bool) {
callCoordinator.callToChat(controller.chat, enableVideo: enableVideo)
}
func chatPrivateControllerShowQuickLookController(
_ controller: ChatPrivateController,
dataSource: QuickLookPreviewControllerDataSource,
selectedIndex: Int)
{
let controller = QuickLookPreviewController()
controller.dataSource = dataSource
controller.dataSourceStorage = dataSource
controller.currentPreviewItemIndex = selectedIndex
iPad.splitController.present(controller, animated: true, completion: nil)
}
}
extension ActiveSessionCoordinator: FriendSelectControllerDelegate {
func friendSelectController(_ controller: FriendSelectController, didSelectFriend friend: OCTFriend) {
rootViewController().dismiss(animated: true) { [unowned self] in
guard let filePath = controller.userInfo as? String else {
return
}
let chat = self.toxManager.chats.getOrCreateChat(with: friend)
self.sendFile(filePath, toChat: chat!)
}
}
func friendSelectControllerCancel(_ controller: FriendSelectController) {
rootViewController().dismiss(animated: true, completion: nil)
guard let filePath = controller.userInfo as? String else {
return
}
_ = try? FileManager.default.removeItem(atPath: filePath)
}
}
private extension ActiveSessionCoordinator {
func createDeviceSpecificObjects() {
switch InterfaceIdiom.current() {
case .iPhone:
let chatsCoordinator = ChatsTabCoordinator(theme: theme, submanagerObjects: toxManager.objects, submanagerChats: toxManager.chats, submanagerFiles: toxManager.files)
chatsCoordinator.delegate = self
let tabBarControllers = IphoneObjects.TabCoordinator.allValues().map { object -> UINavigationController in
switch object {
case .friends:
return friendsCoordinator.navigationController
case .chats:
return chatsCoordinator.navigationController
case .settings:
return settingsCoordinator.navigationController
case .profile:
return profileCoordinator.navigationController
}
}
let tabBarItems = createTabBarItems()
let friendsTabBarItem = tabBarItems[IphoneObjects.TabCoordinator.friends.rawValue] as! TabBarBadgeItem
let chatsTabBarItem = tabBarItems[IphoneObjects.TabCoordinator.chats.rawValue] as! TabBarBadgeItem
let profileTabBarItem = tabBarItems[IphoneObjects.TabCoordinator.profile.rawValue] as! TabBarProfileItem
let tabBarController = TabBarController(theme: theme, controllers: tabBarControllers, tabBarItems: tabBarItems)
iPhone = IphoneObjects(
chatsCoordinator: chatsCoordinator,
tabBarController: tabBarController,
friendsTabBarItem: friendsTabBarItem,
chatsTabBarItem: chatsTabBarItem,
profileTabBarItem: profileTabBarItem)
case .iPad:
let splitController = UISplitViewController()
splitController.preferredDisplayMode = .allVisible
let primaryController = PrimaryIpadController(theme: theme, submanagerChats: toxManager.chats, submanagerObjects: toxManager.objects)
primaryController.delegate = self
splitController.viewControllers = [UINavigationController(rootViewController: primaryController)]
iPad = IpadObjects(splitController: splitController, primaryController: primaryController)
}
}
func createCallCoordinator() {
let presentingController: UIViewController
switch InterfaceIdiom.current() {
case .iPhone:
presentingController = iPhone.tabBarController
case .iPad:
presentingController = iPad.splitController
}
self.callCoordinator = CallCoordinator(
theme: theme,
presentingController: presentingController,
submanagerCalls: toxManager.calls,
submanagerObjects: toxManager.objects)
callCoordinator.delegate = self
}
func createTabBarItems() -> [TabBarAbstractItem] {
return IphoneObjects.TabCoordinator.allValues().map {
switch $0 {
case .friends:
let item = TabBarBadgeItem(theme: theme)
item.image = UIImage(named: "tab-bar-friends")
item.text = String(localized: "contacts_title")
item.badgeAccessibilityEnding = String(localized: "contact_requests_section")
return item
case .chats:
let item = TabBarBadgeItem(theme: theme)
item.image = UIImage(named: "tab-bar-chats")
item.text = String(localized: "chats_title")
item.badgeAccessibilityEnding = String(localized: "accessibility_chats_ending")
return item
case .settings:
let item = TabBarBadgeItem(theme: theme)
item.image = UIImage(named: "tab-bar-settings")
item.text = String(localized: "settings_title")
return item
case .profile:
return TabBarProfileItem(theme: theme)
}
}
}
func showFriendRequest(_ request: OCTFriendRequest) {
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.tabBarController.selectedIndex = IphoneObjects.TabCoordinator.friends.rawValue
case .iPad:
primaryIpadControllerShowFriends(iPad.primaryController)
}
friendsCoordinator.showRequest(request, animated: false)
}
/**
Returns active chat controller if it is visible, nil otherwise.
*/
func activeChatController() -> ChatPrivateController? {
switch InterfaceIdiom.current() {
case .iPhone:
if iPhone.tabBarController.selectedIndex != IphoneObjects.TabCoordinator.chats.rawValue {
return nil
}
return iPhone.chatsCoordinator.activeChatController()
case .iPad:
return iPadDetailController() as? ChatPrivateController
}
}
func showChat(_ chat: OCTChat) {
switch InterfaceIdiom.current() {
case .iPhone:
if iPhone.tabBarController.selectedIndex != IphoneObjects.TabCoordinator.chats.rawValue {
iPhone.tabBarController.selectedIndex = IphoneObjects.TabCoordinator.chats.rawValue
}
iPhone.chatsCoordinator.showChat(chat, animated: false)
case .iPad:
if let chatVC = iPadDetailController() as? ChatPrivateController {
if chatVC.chat == chat {
// controller is already visible
return
}
}
let controller = ChatPrivateController(
theme: theme,
chat: chat,
submanagerChats: toxManager.chats,
submanagerObjects: toxManager.objects,
submanagerFiles: toxManager.files,
delegate: self,
showKeyboardOnAppear: iPad.keyboardObserver.keyboardVisible)
let navigation = UINavigationController(rootViewController: controller)
iPad.splitController.showDetailViewController(navigation, sender: nil)
}
}
func showSettings() {
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.tabBarController.selectedIndex = IphoneObjects.TabCoordinator.settings.rawValue
case .iPad:
primaryIpadControllerShowFriends(iPad.primaryController)
}
}
func updateUserStatusView() {
let status = UserStatus(connectionStatus: toxManager.user.connectionStatus, userStatus: toxManager.user.userStatus)
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.profileTabBarItem.userStatus = status
case .iPad:
iPad.primaryController.userStatus = status
}
}
func updateUserAvatar() {
var avatar: UIImage?
if let avatarData = toxManager.user.userAvatar() {
avatar = UIImage(data: avatarData)
}
switch InterfaceIdiom.current() {
case .iPhone:
iPhone.profileTabBarItem.userImage = avatar
case .iPad:
iPad.primaryController.userAvatar = avatar
}
}
func updateUserName() {
switch InterfaceIdiom.current() {
case .iPhone:
// nop
break
case .iPad:
iPad.primaryController.userName = toxManager.user.userName()
}
}
func iPadDetailController() -> UIViewController? {
guard iPad.splitController.viewControllers.count == 2 else {
return nil
}
let controller = iPad.splitController.viewControllers[1]
if let navigation = controller as? UINavigationController {
return navigation.topViewController
}
return controller
}
func logout(importToxProfileFromURL profileURL: URL? = nil) {
delegate?.activeSessionCoordinatorDidLogout(self, importToxProfileFromURL: profileURL)
}
func rootViewController() -> UIViewController {
switch InterfaceIdiom.current() {
case .iPhone:
return iPhone.tabBarController
case .iPad:
return iPad.splitController
}
}
func sendFileToChats(_ filePath: String, fileName: String) {
let controller = FriendSelectController(theme: theme, submanagerObjects: toxManager.objects)
controller.delegate = self
controller.title = String(localized: "file_send_to_contact")
controller.userInfo = filePath as AnyObject?
let navigation = UINavigationController(rootViewController: controller)
rootViewController().present(navigation, animated: true, completion: nil)
}
func sendFile(_ filePath: String, toChat chat: OCTChat) {
showChat(chat)
toxManager.files.sendFile(atPath: filePath, moveToUploads: true, to: chat, failureBlock: { (error: Error) in
handleErrorWithType(.sendFileToFriend, error: error as NSError)
})
}
}
|
mpl-2.0
|
13a356babb48f47c2f2e74b3a158e6e7
| 36.894155 | 191 | 0.667487 | 5.546127 | false | false | false | false |
asurinsaka/swift_examples_2.1
|
Regions/Regions/RegionViewController.swift
|
1
|
9668
|
//
// ViewController.swift
// Regions
//
// Created by doudou on 8/26/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class RegionViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource
{
enum EventState
{
case Enter
case Exit
}
struct RegionMonitorEvent
{
let region:CLCircularRegion
let timestamp:NSDate
let state:EventState
}
let LAT_SPAN:CLLocationDistance = 500.0
let LON_SPAN:CLLocationDistance = 500.0
let MONITOR_RADIUS:CLLocationDistance = 50.0
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet var insertButton: UIBarButtonItem!
@IBOutlet var searchButton: UIBarButtonItem!
private var locationManager:CLLocationManager!
private var location:CLLocation!
private var deviceAnnotation:DeviceAnnotation!
private var isUpdated:Bool!
private var placemark:CLPlacemark!
private var heading:CLHeading!
private var monitorEvents:[RegionMonitorEvent]!
private var dateFormatter:NSDateFormatter!
private var geocoder:CLGeocoder!
private var geotime:NSDate!
override func viewDidLoad()
{
super.viewDidLoad()
monitorEvents = []
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
geocoder = CLGeocoder()
tableView.alpha = 0.0
tableView.hidden = true
map.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: 22.55, longitude: 113.94), LAT_SPAN, LON_SPAN)
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.startUpdatingLocation()
if CLLocationManager.headingAvailable()
{
locationManager.headingFilter = 1.0
locationManager.startUpdatingHeading()
}
for region in locationManager.monitoredRegions
{
locationManager.stopMonitoringForRegion(region as CLRegion)
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool)
{
isUpdated = false
}
//MARK: 滚动列表展示
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("RegionEventCell") as UITableViewCell!
var text = ""
var event = monitorEvents[indexPath.row]
switch event.state
{
case .Enter:
text += "进入"
case .Exit:
text += "走出"
}
text += " \(dateFormatter.stringFromDate(event.timestamp))"
cell.textLabel?.text = text
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return monitorEvents.count
}
//MARK: 页签组件切换
@IBAction func segementChanged(sender: UISegmentedControl)
{
let duration:NSTimeInterval = 0.4
if sender.selectedSegmentIndex == 0
{
navigationItem.setLeftBarButtonItem(searchButton, animated: true)
navigationItem.setRightBarButtonItem(insertButton, animated: true)
map.hidden = false
UIView.animateWithDuration(duration,
animations:
{
self.map.alpha = 1.0
self.tableView.alpha = 0.0
},
completion:
{
(flag) in
self.tableView.hidden = true
})
}
else
{
navigationItem.setLeftBarButtonItem(nil, animated: true)
navigationItem.setRightBarButtonItem(nil, animated: true)
tableView.reloadData()
tableView.hidden = false
UIView.animateWithDuration(duration / 2.0, animations:
{
self.map.alpha = 0.0
self.tableView.alpha = 1.0
},
completion:
{
(flag) in
self.map.hidden = true
})
}
UIView.commitAnimations()
}
//MARK: 按钮交互
@IBAction func showDeviceLocation(sender: UIBarButtonItem)
{
if map.userLocation != nil
{
map.setRegion(MKCoordinateRegionMakeWithDistance(map.userLocation.coordinate, LAT_SPAN, LON_SPAN), animated: true)
}
}
@IBAction func inertMonitorRegion(sender: UIBarButtonItem)
{
if (location == nil || map.userLocation == nil)
{
return
}
var lat = map.userLocation.coordinate.latitude - location.coordinate.latitude
var lon = map.userLocation.coordinate.longitude - location.coordinate.longitude
var region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: map.centerCoordinate.latitude - lat, longitude: map.centerCoordinate.longitude - lon),
radius: MONITOR_RADIUS,
identifier: String(format:"%.8f-%.8f", map.centerCoordinate.latitude, map.centerCoordinate.longitude))
var annotation = RegionAnnotation(coordinate: map.centerCoordinate, region: region)
map.addAnnotation(annotation)
map.addOverlay(MKCircle(centerCoordinate: annotation.coordinate, radius: MONITOR_RADIUS))
if CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion)
{
locationManager.startMonitoringForRegion(region)
}
}
//MARK: 地图相关
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!
{
if annotation.isKindOfClass(DeviceAnnotation)
{
let identifier = "DeviceAnnotationView"
var anView = map.dequeueReusableAnnotationViewWithIdentifier(identifier) as MKPinAnnotationView!
if anView == nil
{
anView = MKPinAnnotationView(annotation: deviceAnnotation, reuseIdentifier: identifier)
anView.canShowCallout = true
anView.pinColor = MKPinAnnotationColor.Purple
}
else
{
anView.annotation = annotation
}
if placemark != nil
{
var button = UIButton.buttonWithType(.DetailDisclosure) as UIButton
button.addTarget(self, action: "displayPlacemarkInfo", forControlEvents: UIControlEvents.TouchUpInside)
anView.rightCalloutAccessoryView = button
}
else
{
anView.rightCalloutAccessoryView = nil
}
return anView
}
else
if annotation.isKindOfClass(RegionAnnotation)
{
let identifier = "RegionAnnotationView"
var anView = map.dequeueReusableAnnotationViewWithIdentifier(identifier) as MKPinAnnotationView!
if anView == nil
{
anView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
anView.canShowCallout = true
anView.pinColor = MKPinAnnotationColor.Green
}
else
{
anView.annotation = annotation
}
return anView
}
return nil
}
func displayPlacemarkInfo()
{
var locationCtrl = PlacemarkViewController(nibName: "PlacemarkInfoView", bundle: nil)
locationCtrl.placemark = placemark
navigationController?.pushViewController(locationCtrl, animated: true)
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!
{
if overlay.isKindOfClass(MKCircle)
{
var render = MKCircleRenderer(overlay: overlay)
render.strokeColor = UIColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 0.5)
render.fillColor = UIColor(red: 1.0, green: 0.0, blue: 1.0, alpha: 0.2)
render.lineWidth = 1.0
return render
}
return nil
}
//MARK: 方向定位
func locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!)
{
heading = newHeading
}
//MARK: 定位相关
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)
{
location = newLocation
var chinaloc = ChinaGPS.encrypt(newLocation)
if deviceAnnotation == nil
{
deviceAnnotation = DeviceAnnotation(coordinate: chinaloc.coordinate)
map.addAnnotation(deviceAnnotation)
}
else
{
deviceAnnotation.coordinate = chinaloc.coordinate
}
deviceAnnotation.update(location:chinaloc)
if geotime == nil || fabs(geotime.timeIntervalSinceNow) > 10.0
{
geotime = NSDate()
println("geocode", geotime.description)
geocoder.reverseGeocodeLocation(chinaloc,
completionHandler:
{
(placemarks, error) in
if error == nil
{
self.processPlacemark(placemarks as [CLPlacemark])
}
else
{
println(error)
}
});
}
map.selectAnnotation(deviceAnnotation, animated: false)
}
func processPlacemark(placemarks:[CLPlacemark])
{
var initialized = !(self.placemark == nil)
placemark = placemarks.first!
if placemark != nil && !initialized
{
map.removeAnnotation(deviceAnnotation)
map.addAnnotation(deviceAnnotation)
map.selectAnnotation(deviceAnnotation, animated: true)
}
if placemark != nil
{
deviceAnnotation.update(placemark: placemark)
}
}
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!)
{
var event = RegionMonitorEvent(region: region as CLCircularRegion, timestamp: NSDate(), state: .Enter)
monitorEvents.append(event)
if !tableView.hidden
{
tableView.reloadData()
}
}
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!)
{
var event = RegionMonitorEvent(region: region as CLCircularRegion, timestamp: NSDate(), state: .Exit)
monitorEvents.append(event)
if !tableView.hidden
{
tableView.reloadData()
}
}
func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!)
{
UIAlertView(title: "区域监听失败", message: error?.description, delegate: nil, cancelButtonTitle: "我知道了").show()
}
//MARK: 地图相关
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!)
{
if !isUpdated
{
map.setCenterCoordinate(userLocation.coordinate, animated: true)
isUpdated = true
}
}
}
|
mit
|
bb630f9e48ee57df43c0a0f3f00710cf
| 24.202632 | 159 | 0.731621 | 3.968504 | false | false | false | false |
frtlupsvn/Vietnam-To-Go
|
Pods/Former/Former/RowFormers/StepperRowFormer.swift
|
1
|
3052
|
//
// StepperRowFormer.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/30/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public protocol StepperFormableRow: FormableRow {
func formStepper() -> UIStepper
func formTitleLabel() -> UILabel?
func formDisplayLabel() -> UILabel?
}
public final class StepperRowFormer<T: UITableViewCell where T: StepperFormableRow>
: BaseRowFormer<T>, Formable {
// MARK: Public
public var value: Double = 0
public var titleDisabledColor: UIColor? = .lightGrayColor()
public var displayDisabledColor: UIColor? = .lightGrayColor()
public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: (T -> Void)? = nil) {
super.init(instantiateType: instantiateType, cellSetup: cellSetup)
}
public final func onValueChanged(handler: (Double -> Void)) -> Self {
onValueChanged = handler
return self
}
public final func displayTextFromValue(handler: (Double -> String?)) -> Self {
displayTextFromValue = handler
return self
}
public override func cellInitialized(cell: T) {
super.cellInitialized(cell)
cell.formStepper().addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
}
public override func update() {
super.update()
cell.selectionStyle = .None
let titleLabel = cell.formTitleLabel()
let displayLabel = cell.formDisplayLabel()
let stepper = cell.formStepper()
stepper.value = value
stepper.enabled = enabled
displayLabel?.text = displayTextFromValue?(value) ?? "\(value)"
if enabled {
_ = titleColor.map { titleLabel?.textColor = $0 }
_ = displayColor.map { displayLabel?.textColor = $0 }
_ = stepperTintColor.map { stepper.tintColor = $0 }
titleColor = nil
displayColor = nil
stepperTintColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() }
if displayColor == nil { displayColor = displayLabel?.textColor ?? .blackColor() }
if stepperTintColor == nil { stepperTintColor = stepper.tintColor }
titleLabel?.textColor = titleDisabledColor
displayLabel?.textColor = displayDisabledColor
stepper.tintColor = stepperTintColor?.colorWithAlphaComponent(0.5)
}
}
// MARK: Private
private final var onValueChanged: (Double -> Void)?
private final var displayTextFromValue: (Double -> String?)?
private final var titleColor: UIColor?
private final var displayColor: UIColor?
private final var stepperTintColor: UIColor?
private dynamic func valueChanged(stepper: UIStepper) {
let value = stepper.value
self.value = value
cell.formDisplayLabel()?.text = displayTextFromValue?(value) ?? "\(value)"
onValueChanged?(value)
}
}
|
mit
|
621444ad25a2d6853ce2aa5fba092aa1
| 33.681818 | 107 | 0.638151 | 5.145025 | false | false | false | false |
apple/swift-format
|
Tests/SwiftFormatPrettyPrintTests/TernaryExprTests.swift
|
1
|
6343
|
final class TernaryExprTests: PrettyPrintTestCase {
func testTernaryExprs() {
let input =
"""
let x = a ? b : c
let y = a ?b:c
let z = a ? b: c
let reallyLongName = a ? longTruePart : longFalsePart
let reallyLongName = reallyLongCondition ? reallyLongTruePart : reallyLongFalsePart
let reallyLongName = reallyLongCondition ? reallyReallyReallyLongTruePart : reallyLongFalsePart
let reallyLongName = someCondition ? firstFunc(foo: arg) : secondFunc(bar: arg)
"""
let expected =
"""
let x = a ? b : c
let y = a ? b : c
let z = a ? b : c
let reallyLongName =
a ? longTruePart : longFalsePart
let reallyLongName =
reallyLongCondition
? reallyLongTruePart : reallyLongFalsePart
let reallyLongName =
reallyLongCondition
? reallyReallyReallyLongTruePart
: reallyLongFalsePart
let reallyLongName =
someCondition
? firstFunc(foo: arg)
: secondFunc(bar: arg)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
}
func testTernaryExprsWithMultiplePartChoices() {
let input =
"""
let someLocalizedText =
shouldUseTheFirstOption ? stringFunc(name: "Name1", comment: "short comment") :
stringFunc(name: "Name2", comment: "Some very, extremely long comment", details: "Another comment")
"""
let expected =
"""
let someLocalizedText =
shouldUseTheFirstOption
? stringFunc(name: "Name1", comment: "short comment")
: stringFunc(
name: "Name2", comment: "Some very, extremely long comment",
details: "Another comment")
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 80)
}
func testTernaryWithWrappingExpressions() {
let input =
"""
foo = firstTerm + secondTerm + thirdTerm ? firstTerm + secondTerm + thirdTerm : firstTerm + secondTerm + thirdTerm
let foo = firstTerm + secondTerm + thirdTerm ? firstTerm + secondTerm + thirdTerm : firstTerm + secondTerm + thirdTerm
foo = firstTerm || secondTerm && thirdTerm ? firstTerm + secondTerm + thirdTerm : firstTerm + secondTerm + thirdTerm
let foo = firstTerm || secondTerm && thirdTerm ? firstTerm + secondTerm + thirdTerm : firstTerm + secondTerm + thirdTerm
"""
let expected =
"""
foo =
firstTerm
+ secondTerm
+ thirdTerm
? firstTerm
+ secondTerm
+ thirdTerm
: firstTerm
+ secondTerm
+ thirdTerm
let foo =
firstTerm
+ secondTerm
+ thirdTerm
? firstTerm
+ secondTerm
+ thirdTerm
: firstTerm
+ secondTerm
+ thirdTerm
foo =
firstTerm
|| secondTerm
&& thirdTerm
? firstTerm
+ secondTerm
+ thirdTerm
: firstTerm
+ secondTerm
+ thirdTerm
let foo =
firstTerm
|| secondTerm
&& thirdTerm
? firstTerm
+ secondTerm
+ thirdTerm
: firstTerm
+ secondTerm
+ thirdTerm
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 15)
}
func testNestedTernaries() {
let input =
"""
a = b ? c : d ? e : f
let a = b ? c : d ? e : f
a = b ? c0 + c1 : d ? e : f
let a = b ? c0 + c1 : d ? e : f
a = b ? c0 + c1 + c2 + c3 : d ? e : f
let a = b ? c0 + c1 + c2 + c3 : d ? e : f
foo = testA ? testB ? testC : testD : testE ? testF : testG
let foo = testA ? testB ? testC : testD : testE ? testF : testG
"""
let expected =
"""
a =
b
? c
: d ? e : f
let a =
b
? c
: d ? e : f
a =
b
? c0 + c1
: d ? e : f
let a =
b
? c0 + c1
: d ? e : f
a =
b
? c0 + c1
+ c2 + c3
: d ? e : f
let a =
b
? c0 + c1
+ c2 + c3
: d ? e : f
foo =
testA
? testB
? testC
: testD
: testE
? testF
: testG
let foo =
testA
? testB
? testC
: testD
: testE
? testF
: testG
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 15)
}
func testExpressionStartsWithTernary() {
// When the ternary itself doesn't already start on a continuation line, we don't have a way
// to indent the continuation of the condition differently from the first and second choices,
// because we don't want to double-indent the condition's continuation lines, and we don't want
// to keep put the choices at the same indentation level as the condition (because that would
// be the start of the statement). Neither of these choices is really ideal, unfortunately.
let input =
"""
condition ? callSomething() : callSomethingElse()
condition && otherCondition ? callSomething() : callSomethingElse()
(condition && otherCondition) ? callSomething() : callSomethingElse()
"""
let expected =
"""
condition
? callSomething()
: callSomethingElse()
condition
&& otherCondition
? callSomething()
: callSomethingElse()
(condition
&& otherCondition)
? callSomething()
: callSomethingElse()
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 25)
}
func testParenthesizedTernary() {
let input =
"""
let a = (
foo ?
bar : baz
)
a = (
foo ?
bar : baz
)
b = foo ? (
bar
) : (
baz
)
c = foo ?
(
foo2 ? nestedBar : nestedBaz
) : (baz)
"""
let expected =
"""
let a = (foo ? bar : baz)
a = (foo ? bar : baz)
b = foo ? (bar) : (baz)
c = foo ? (foo2 ? nestedBar : nestedBaz) : (baz)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 50)
}
}
|
apache-2.0
|
be5cb1352663f616e5b4bdad4c202113
| 24.995902 | 126 | 0.529718 | 4.326739 | false | true | false | false |
SomeSimpleSolutions/MemorizeItForever
|
MemorizeItForever/MemorizeItForever/DataSource/Depot/TemporaryPhraseListDataSource.swift
|
1
|
4191
|
//
// TemporaryPhraseListDataSource.swift
// MemorizeItForever
//
// Created by Hadi Zamani on 11/2/19.
// Copyright © 2019 SomeSimpleSolutions. All rights reserved.
//
import UIKit
import MemorizeItForeverCore
final class TemporaryPhraseListDataSource: NSObject, DepotTableDataSourceProtocol{
// MARK: Private variables
private var temporaryPhraseModelList = [TemporaryPhraseModel]()
// MARK: MemorizeItTableDataSourceProtocol
var rowActionHandler: MITypealiasHelper.RowActionClosure?
func setModels(_ models: [MemorizeItModelProtocol]) {
guard let models = models as? [TemporaryPhraseModel] else {
return
}
temporaryPhraseModelList = models
}
// MARK: UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return temporaryPhraseModelList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(.temporaryListTableIdentifier, forIndexPath: indexPath)
let tmp = temporaryPhraseModelList[(indexPath as NSIndexPath).row]
cell.textLabel?.text = tmp.phrase
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return [deleteAction(tableView), editAction(), addAction(tableView)]
}
// MARK: Private Methods
private func editAction() -> UITableViewRowAction {
let editTitle = NSLocalizedString("Edit", comment: "Edit")
let edit = UITableViewRowAction(style: .default, title: editTitle) {[weak self] (action, index) in
if let strongSelf = self{
strongSelf.editTempPhrase(indexPath: index)
}
}
if #available(iOS 11.0, *) {
edit.backgroundColor = UIColor(named: "editTableRow")
} else {
edit.backgroundColor = UIColor.yellow
}
return edit
}
private func deleteAction(_ tableView: UITableView) -> UITableViewRowAction {
let deleteTitle = NSLocalizedString("Delete", comment: "Delete")
let delete = UITableViewRowAction(style: .default, title: deleteTitle) {[weak self] (action, index) in
if let strongSelf = self{
strongSelf.deleteTempPhrase(indexPath: index, tableView: tableView)
}
}
if #available(iOS 11.0, *) {
delete.backgroundColor = UIColor(named: "deleteTableRow")
} else {
delete.backgroundColor = UIColor.red
}
return delete
}
private func addAction(_ tableView: UITableView) -> UITableViewRowAction {
let addTitle = NSLocalizedString("Add", comment: "Add")
let add = UITableViewRowAction(style: .default, title: addTitle) {[weak self] (action, index) in
if let strongSelf = self{
strongSelf.addTempPhrase(indexPath: index, tableView: tableView)
}
}
if #available(iOS 11.0, *) {
add.backgroundColor = UIColor(named: "addTableRow")
} else {
add.backgroundColor = UIColor.green
}
return add
}
private func deleteTempPhrase(indexPath: IndexPath, tableView: UITableView){
let model = temporaryPhraseModelList.remove(at: (indexPath as NSIndexPath).row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
rowActionHandler?(model, .delete)
}
private func editTempPhrase(indexPath: IndexPath){
let row = (indexPath as NSIndexPath).row
let model = temporaryPhraseModelList[row]
rowActionHandler?(model, .edit)
}
private func addTempPhrase(indexPath: IndexPath, tableView: UITableView){
let model = temporaryPhraseModelList.remove(at: (indexPath as NSIndexPath).row)
rowActionHandler?(model, .add)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
|
mit
|
087118e1ecc5f6c5ba450be6302588d2
| 36.747748 | 118 | 0.650835 | 5.198511 | false | false | false | false |
jovito-royeca/ManaKit
|
Sources/Classes/ManaKit+Imaging.swift
|
1
|
3359
|
//
// ManaKit+Imaging.swift
// Pods
//
// Created by Vito Royeca on 11/27/19.
//
import Foundation
import PromiseKit
import SDWebImage
import UIKit
extension ManaKit {
public func imageFromFramework(imageName: ImageName) -> UIImage? {
let bundle = Bundle(for: ManaKit.self)
guard let bundleURL = bundle.resourceURL?.appendingPathComponent("ManaKit.bundle"),
let resourceBundle = Bundle(url: bundleURL) else {
return nil
}
return UIImage(named: imageName.rawValue, in: resourceBundle, compatibleWith: nil)
}
public func symbolImage(name: String) -> UIImage? {
let bundle = Bundle(for: ManaKit.self)
guard let bundleURL = bundle.resourceURL?.appendingPathComponent("ManaKit.bundle"),
let resourceBundle = Bundle(url: bundleURL) else {
return nil
}
return UIImage(named: name, in: resourceBundle, compatibleWith: nil)
}
public func downloadImage(ofCard card: MGCard, type: CardImageType, faceOrder: Int) -> Promise<Void> {
guard let url = card.imageURL(type: type,
faceOrder: faceOrder) else {
return Promise { seal in
let error = NSError(domain: NSURLErrorDomain,
code: 404,
userInfo: [NSLocalizedDescriptionKey: "No valid URL for image"])
seal.reject(error)
}
}
let roundCornered = type != .artCrop
if let _ = card.image(type: type,
faceOrder: faceOrder,
roundCornered: roundCornered) {
return Promise { seal in
seal.fulfill(())
}
} else {
return downloadImage(url: url)
}
}
public func downloadImage(url: URL) -> Promise<Void> {
return Promise { seal in
let cacheKey = url.absoluteString
let completion = { (image: UIImage?, data: Data?, error: Error?, finished: Bool) in
if let error = error {
seal.reject(error)
} else {
if let image = image {
let imageCache = SDImageCache.init()
let imageCacheCompletion = {
seal.fulfill(())
}
imageCache.store(image,
forKey: cacheKey,
toDisk: true,
completion: imageCacheCompletion)
} else {
let error = NSError(domain: NSURLErrorDomain,
code: 404,
userInfo: [NSLocalizedDescriptionKey: "Image not found: \(url)"])
seal.reject(error)
}
}
}
SDWebImageDownloader.shared.downloadImage(with: url,
options: .lowPriority,
progress: nil,
completed: completion)
}
}
}
|
mit
|
da292d58aaf6a15cc5444151cc7d6621
| 35.51087 | 109 | 0.470378 | 5.771478 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.