Datasets:
repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kumabook/StickyNotesiOS | refs/heads/master | StickyNotes/WebViewController+NewPage.swift | mit | 1 | //
// WebViewController+NewPage.swift
// StickyNotes
//
// Created by Hiroki Kumamoto on 2017/04/28.
// Copyright © 2017 kumabook. All rights reserved.
//
import Foundation
import UIKit
import RealmSwift
extension WebViewController: UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {
func enterViewMode() {
navigationController?.navigationBar.topItem?.title = ""
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "search"), style: .plain, target: self, action: #selector(WebViewController.enterNewPageMode))
navigationItem.titleView = nil
navigationItem.title = page?.title ?? ""
collectionView?.removeFromSuperview()
}
func enterNewPageMode() {
searchController = UISearchController(searchResultsController: nil)
searchController?.searchBar.placeholder = "Search or enter address"
searchController?.searchBar.returnKeyType = UIReturnKeyType.go
searchController?.searchResultsUpdater = self
searchController?.delegate = self
searchController?.searchBar.delegate = self
searchController?.hidesNavigationBarDuringPresentation = false
searchController?.dimsBackgroundDuringPresentation = true
navigationItem.titleView = searchController?.searchBar
navigationItem.rightBarButtonItem = nil
definesPresentationContext = true
searchController?.searchBar.becomeFirstResponder()
collectionView = createCollectionView()
view.addSubview(collectionView!)
}
public func updateSearchResults(for searchController: UISearchController) {
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let text = searchBar.text else { return }
if let url = URL(string: text), let schema = url.scheme, schema == "http" || schema == "https" {
loadURL(url)
} else {
let q = text.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed) ?? text
loadURL(URL(string: "http://google.com/search?q=\(q)")!)
}
searchController?.isActive = false
mode = .view
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
if page != nil {
mode = .view
}
}
}
extension WebViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var sites: [Site] {
return Site.defaultSites
}
func createCollectionView() -> UICollectionView {
let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - toolbarHeight)
let collectionView = UICollectionView(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.contentInset = UIEdgeInsets(top: topLayoutGuide.length, left: 0, bottom: 0, right: 0)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(SiteCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.autoresizesSubviews = true
collectionView.autoresizingMask = [UIViewAutoresizing.flexibleWidth,
UIViewAutoresizing.flexibleHeight,
UIViewAutoresizing.flexibleBottomMargin,
UIViewAutoresizing.flexibleLeftMargin,
UIViewAutoresizing.flexibleRightMargin,
UIViewAutoresizing.flexibleTopMargin,
UIViewAutoresizing.flexibleBottomMargin]
collectionView.alwaysBounceVertical = true
return collectionView
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sites.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! SiteCollectionViewCell
let site = sites[indexPath.row]
cell.titleLabel.text = site.title
cell.imageView.sd_setImage(with: site.imageURL, placeholderImage: UIImage(named: "no_image"))
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize: CGFloat = view.frame.size.width / 3
return CGSize(width: cellSize, height: cellSize)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let site = sites[indexPath.row]
loadURL(site.url)
}
}
| 3eea232541e5e1afdb4137c6d39e1484 | 44.806723 | 176 | 0.686846 | false | false | false | false |
Inquisitor0/LSB2 | refs/heads/master | Cocoapods/Pods/PKHUD/PKHUD/FrameView.swift | apache-2.0 | 9 | //
// HUDView.swift
// PKHUD
//
// Created by Philip Kluz on 6/16/14.
// Copyright (c) 2016 NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import UIKit
/// Provides the general look and feel of the PKHUD, into which the eventual content is inserted.
internal class FrameView: UIVisualEffectView {
internal init() {
super.init(effect: UIBlurEffect(style: .light))
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
backgroundColor = UIColor(white: 0.8, alpha: 0.36)
layer.cornerRadius = 9.0
layer.masksToBounds = true
contentView.addSubview(self.content)
let offset = 20.0
let motionEffectsX = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
motionEffectsX.maximumRelativeValue = offset
motionEffectsX.minimumRelativeValue = -offset
let motionEffectsY = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
motionEffectsY.maximumRelativeValue = offset
motionEffectsY.minimumRelativeValue = -offset
let group = UIMotionEffectGroup()
group.motionEffects = [motionEffectsX, motionEffectsY]
addMotionEffect(group)
}
fileprivate var _content = UIView()
internal var content: UIView {
get {
return _content
}
set {
_content.removeFromSuperview()
_content = newValue
_content.alpha = 0.85
_content.clipsToBounds = true
_content.contentMode = .center
frame.size = _content.bounds.size
addSubview(_content)
}
}
}
| 26410e1005d73926bf8de243a14cf91f | 27.492063 | 109 | 0.639554 | false | false | false | false |
TheSafo/Sinkr | refs/heads/master | ios stuff/Sinkr/Views/CupView.swift | gpl-3.0 | 1 | //
// CupView.swift
// Sinkr
//
// Created by Jake Saferstein on 6/18/16.
// Copyright © 2016 Jake Saferstein. All rights reserved.
//
import Foundation
import UIKit
protocol CupViewDelegate {
func cupViewTapped(cupVw: CupView)
}
class CupView : UIView {
static var cupWidthHeight: CGFloat {
get {
let cupWidth = (RackView.rackWidth - cupPadding*3)/4
return cupWidth
}
}
var index: Index
var status: CupStatus {
didSet {
self.updateCupForCurrentStatus()
}
}
var delegate: CupViewDelegate? = nil
init(index: Index, status: CupStatus) {
self.index = index
self.status = status
super.init(frame: CGRectZero)
let tapGr = UITapGestureRecognizer(target: self, action: #selector(self.cupTapped(_:)))
tapGr.numberOfTapsRequired = 1
tapGr.numberOfTouchesRequired = 1
self.addGestureRecognizer(tapGr)
self.layer.cornerRadius = CupView.cupWidthHeight/2
self.layer.borderWidth = 2
self.updateCupForCurrentStatus()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateCupForCurrentStatus() {
switch status {
case .DNE:
self.hidden = true
case .Full:
self.backgroundColor = UIColor.redColor()
case .Hit:
self.backgroundColor = UIColor.greenColor()
}
}
//MARK: Button handling
func cupTapped(tapGR : UITapGestureRecognizer) {
// self.delegate?.cupViewTapped(self)
}
}
| 9dd273532175037b1ca978bac1f93a54 | 21.866667 | 95 | 0.58484 | false | false | false | false |
LeonClover/DouYu | refs/heads/master | DouYuZB/DouYuZB/Classes/Tools/Common.swift | mit | 1 | //
// Common.swift
// DouYuZB
//
// Created by Leon on 2017/6/7.
// Copyright © 2017年 pingan. All rights reserved.
//
import UIKit
let kStatusBarH: CGFloat = 20
let kNavigationBarH: CGFloat = 44
let kTabbarH: CGFloat = 49
let kScreenW: CGFloat = UIScreen.main.bounds.width
let kScreenH: CGFloat = UIScreen.main.bounds.height
| a0ba1ecab819e92c58def7275c2536ce | 15.9 | 51 | 0.710059 | false | false | false | false |
scotlandyard/expocity | refs/heads/master | expocity/View/Chat/Display/VChatDisplayMarks.swift | mit | 1 | import UIKit
class VChatDisplayMarks:UIView
{
weak var controller:CChat!
weak var button:UIButton?
private let kItemSize:CGFloat = 50
private let itemSize_2:CGFloat
init(controller:CChat)
{
itemSize_2 = kItemSize / 2.0
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
}
required init?(coder:NSCoder)
{
fatalError()
}
//MARK: actions
func actionButton(sender button:UIButton)
{
controller.displayDetail()
}
//MARK: public
func addItems()
{
self.button?.removeFromSuperview()
let imageWidth:CGFloat = bounds.maxX
let imageHeight:CGFloat = bounds.maxY
let button:UIButton = UIButton()
button.backgroundColor = UIColor.clear
button.translatesAutoresizingMaskIntoConstraints = false
button.clipsToBounds = true
button.addTarget(
self,
action:#selector(actionButton(sender:)),
for:UIControlEvents.touchUpInside)
self.button = button
addSubview(button)
let views:[String:UIView] = [
"button":button]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[button]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[button]-0-|",
options:[],
metrics:metrics,
views:views))
for modelItem:MChatDisplayAnnotationsItem in controller.model.annotations.items
{
let viewItem:VChatDisplayMarksItem = VChatDisplayMarksItem(controller:controller, model:modelItem)
button.addSubview(viewItem)
let percentX:CGFloat = modelItem.xPercent * imageWidth
let percentY:CGFloat = modelItem.yPercent * imageHeight
let itemLeft:CGFloat = percentX - itemSize_2
let itemTop:CGFloat = percentY - itemSize_2
let itemViews:[String:UIView] = [
"viewItem":viewItem]
let itemMetrics:[String:CGFloat] = [
"itemSize":kItemSize,
"itemLeft":itemLeft,
"itemTop":itemTop]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-(itemLeft)-[viewItem(itemSize)]",
options:[],
metrics:itemMetrics,
views:itemViews))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-(itemTop)-[viewItem(itemSize)]",
options:[],
metrics:itemMetrics,
views:itemViews))
}
}
}
| de0db101fab2de8a4e10a8179967d1dc | 29.79798 | 110 | 0.567727 | false | false | false | false |
notbenoit/tvOS-Twitch | refs/heads/develop | Code/tvOS/Controllers/Streams/StreamsViewController.swift | bsd-3-clause | 1 | // Copyright (c) 2015 Benoit Layer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import AVKit
import ReactiveSwift
import ReactiveCocoa
import DataSource
import Result
final class StreamsViewController: UIViewController {
let streamCellWidth: CGFloat = 308.0
let horizontalSpacing: CGFloat = 50.0
let verticalSpacing: CGFloat = 100.0
let presentStream: Action<(stream: Stream, controller: UIViewController), AVPlayerViewController, AnyError> = Action(execute: controllerProducerForStream)
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var loadingView: LoadingStateView!
@IBOutlet var noItemsLabel: UILabel!
@IBOutlet var loadingStreamView: UIView!
@IBOutlet var loadingMessage: UILabel!
let viewModel = MutableProperty<StreamList.ViewModelType?>(nil)
let collectionDataSource = CollectionViewDataSource()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.twitchDark
collectionDataSource.reuseIdentifierForItem = { _, item in
if let item = item as? ReuseIdentifierProvider {
return item.reuseIdentifier
}
fatalError()
}
loadingStreamView.reactive.isHidden <~ presentStream.isExecuting.producer.map(!)
loadingMessage.reactive.text <~ presentStream.isExecuting.producer
.filter { $0 }
.map { _ in LoadingMessages.randomMessage }
collectionDataSource.dataSource.innerDataSource <~ viewModel.producer.map { $0?.dataSource ?? EmptyDataSource() }
collectionDataSource.collectionView = collectionView
collectionView.dataSource = collectionDataSource
noItemsLabel.text = NSLocalizedString("No game selected yet. Pick a game in the upper list.", comment: "")
noItemsLabel.reactive.isHidden <~ viewModel.producer.map { $0 != nil }
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: streamCellWidth, height: 250.0)
layout.sectionInset = UIEdgeInsets(top: 60, left: 90, bottom: 60, right: 90)
layout.minimumInteritemSpacing = horizontalSpacing
layout.minimumLineSpacing = verticalSpacing
collectionView.register(StreamCell.nib, forCellWithReuseIdentifier: StreamCell.identifier)
collectionView.register(LoadMoreCell.nib, forCellWithReuseIdentifier: LoadMoreCell.identifier)
collectionView.collectionViewLayout = layout
collectionView.delegate = self
collectionView.remembersLastFocusedIndexPath = true
loadingView.reactive.loadingState <~ viewModel.producer.skipNil().chain { $0.paginator.loadingState }
loadingView.reactive.isEmpty <~ viewModel.producer.skipNil().chain { $0.viewModels }.map { $0.isEmpty }
loadingView.retry = { [weak self] in self?.viewModel.value?.paginator.loadFirst() }
presentStream.values
.observe(on: UIScheduler())
.observeValues { [weak self] in self?.present($0, animated: true, completion: nil) }
}
}
extension StreamsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let item = collectionDataSource.dataSource.item(at: indexPath) as? StreamViewModel {
presentStream.apply((item.stream, self)).start()
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffsetY = scrollView.contentOffset.y + scrollView.bounds.size.height
let wholeHeight = scrollView.contentSize.height
let remainingDistanceToBottom = wholeHeight - contentOffsetY
if remainingDistanceToBottom <= 600 {
viewModel.value?.loadMore()
}
}
}
private func controllerProducerForStream(_ stream: Stream, inController: UIViewController) -> SignalProducer<AVPlayerViewController, AnyError> {
return TwitchAPIClient.sharedInstance.m3u8URLForChannel(stream.channel.channelName)
.on(started: { UIApplication.shared.beginIgnoringInteractionEvents() })
.map { $0.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) }
.map { $0.flatMap { URL(string: $0) } }
.skipNil()
.map { (url: URL) -> AVPlayerViewController in
let playerController = AVPlayerViewController()
playerController.view.frame = UIScreen.main.bounds
let avPlayer = AVPlayer(url: url)
playerController.player = avPlayer
return playerController
}
.on() { _ in UIApplication.shared.endIgnoringInteractionEvents() }
.on(terminated: { UIApplication.shared.endIgnoringInteractionEvents() })
.observe(on: UIScheduler())
.on() { $0.player?.play() }
}
| 8ca19c6b1a1df2bb725c6da36477e776 | 40.761538 | 155 | 0.774544 | false | false | false | false |
thebinaryarchitect/list | refs/heads/master | Today/TodayViewController.swift | mit | 1 | //
// TodayViewController.swift
// Today
//
// Copyright (C) 2015 Xiao Yao. All Rights Reserved.
// See LICENSE.txt for more information.
//
import UIKit
import NotificationCenter
import ListKit
class TodayViewController: UITableViewController, NCWidgetProviding {
var list: List
override init(style: UITableViewStyle) {
if let list = NSUserDefaults.groupUserDefaults().loadList() {
self.list = list
} else {
self.list = List.init(title: "")
}
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.preferredContentSize = CGSizeMake(0.0, CGFloat(self.list.items.count) * 44.0)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self))
self.tableView.separatorStyle = .None
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let list = NSUserDefaults.groupUserDefaults().loadList() {
self.list = list
} else {
self.list = List.init(title: "")
}
self.tableView.reloadData()
}
// MARK: NCWidgetProviding
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NewData)
}
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(UITableViewCell.self), forIndexPath: indexPath)
let item = self.list.items[indexPath.row]
cell.textLabel?.text = item.title
cell.accessoryType = item.completed ? .Checkmark : .None
cell.textLabel?.textColor = UIColor.whiteColor()
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
self.list.items.removeAtIndex(indexPath.row)
self.list.save()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
if sourceIndexPath.row != destinationIndexPath.row {
let item = self.list.items[sourceIndexPath.row]
self.list.items.removeAtIndex(sourceIndexPath.row)
self.list.items.insert(item, atIndex: destinationIndexPath.row)
self.list.save()
}
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let item = self.list.items[indexPath.row]
item.completed = !item.completed
self.list.save()
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.accessoryType = item.completed ? .Checkmark : .None
}
}
| 49958d2c5b25f56a02aca6db8978ca0d | 35.547826 | 157 | 0.670711 | false | false | false | false |
amraboelela/swift | refs/heads/master | test/SILGen/reabstract-tuple.swift | apache-2.0 | 12 |
// RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s
// SR-3090:
class Box<T> {
public let value: T
public init(_ value: T) {
self.value = value
}
}
// CHECK: sil [ossa] @$s4main7testBoxyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: // function_ref closure #1 in testBox()
// CHECK: [[CLOSURE:%.*]] = function_ref @$s4main7testBoxyyFyycfU_ : $@convention(thin) () -> ()
// CHECK: [[THICK:%.*]] = thin_to_thick_function [[CLOSURE]] : $@convention(thin) () -> () to $@callee_guaranteed () -> ()
// CHECK: [[TUPLEA:%.*]] = tuple (%{{.*}} : $Int, [[THICK]] : $@callee_guaranteed () -> ())
// CHECK: ([[ELTA_0:%.*]], [[ELTA_1:%.*]]) = destructure_tuple [[TUPLEA]] : $(Int, @callee_guaranteed () -> ())
// CHECK: [[THUNK1:%.*]] = function_ref @$sIeg_ytIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[THUNK1]]([[ELTA_1]]) : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out ()
// CHECK: [[TUPLEB:%.*]] = tuple ([[ELTA_0]] : $Int, [[PA]] : $@callee_guaranteed () -> @out ())
// CHECK: ([[TUPLEB_0:%.*]], [[TUPLEB_1:%.*]]) = destructure_tuple [[TUPLEB]]
// CHECK: // function_ref Box.__allocating_init(_:)
// CHECK: [[INIT_F:%.*]] = function_ref @$s4main3BoxCyACyxGxcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thick Box<τ_0_0>.Type) -> @owned Box<τ_0_0>
// CHECK: [[CALL:%.*]] = apply [[INIT_F]]<(Int, () -> ())>(%{{.*}}, %{{.*}}) : $@convention(method) <τ_0_0> (@in τ_0_0, @thick Box<τ_0_0>.Type) -> @owned Box<τ_0_0>
// CHECK: [[BORROW_CALL:%.*]] = begin_borrow [[CALL]] : $Box<(Int, () -> ())>
// CHECK: [[REF:%.*]] = ref_element_addr [[BORROW_CALL]] : $Box<(Int, () -> ())>, #Box.value
// CHECK: [[TUPLEC:%.*]] = load [copy] [[REF]] : $*(Int, @callee_guaranteed () -> @out ())
// CHECK: ([[TUPLEC_0:%.*]], [[TUPLEC_1:%.*]]) = destructure_tuple [[TUPLEC]]
// CHECK: [[THUNK2:%.*]] = function_ref @$sytIegr_Ieg_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out ()) -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [[THUNK2]]([[TUPLEC_1]]) : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out ()) -> ()
// CHECK: destroy_value [[PA2]] : $@callee_guaranteed () -> ()
// CHECK: end_borrow [[BORROW_CALL]] : $Box<(Int, () -> ())>
// CHECK-LABEL: } // end sil function '$s4main7testBoxyyF'
public func testBox() {
let box = Box((22, { () in }))
let foo = box.value.0
print(foo)
}
// Another crash -- re-abstracting function type inside optional in tuple
// in-place
func g<T>() -> (Int, T)? { }
func f<T>(t: T) {
let _: (Int, ((T) -> (), T))? = g()
}
| e4c97a910eaf1eac09f449fd387abbdc | 52.058824 | 166 | 0.533999 | false | true | false | false |
resmio/TastyTomato | refs/heads/main | TastyTomato/Code/Types/CustomViews/ZoomView/ZoomView.swift | mit | 1 | //
// ZoomView.swift
// TastyTomato
//
// Created by Jan Nash on 11/29/16.
// Copyright © 2016 resmio. All rights reserved.
//
import Foundation
import SignificantSpices
// MARK: // Public
// MARK: -
public protocol ZoomViewDelegate: AnyObject {
func zoomed(to scale: CGFloat, in zoomView: ZoomView)
}
// MARK: -
// MARK: Interface
public extension ZoomView {
// Setters
func setDelegate(_ delegate: ZoomViewDelegate?) {
self._delegate = delegate
}
func setScrollEnabled(_ enabled: Bool) {
self._scrollView.isScrollEnabled = enabled
}
func setZoomThreshold(_ threshold: CGFloat) {
self._zoomThreshold = threshold
}
func setMaximumScale(_ scale: CGFloat) {
self._setMaximumZoomScale(scale)
}
func setShowsHorizontalScrollIndicator(_ shows: Bool) {
self._scrollView.showsHorizontalScrollIndicator = shows
}
func setShowsVerticalScrollIndicator(_ shows: Bool) {
self._scrollView.showsVerticalScrollIndicator = shows
}
func setDecelerationRate(_ rate: UIScrollView.DecelerationRate) {
self._scrollView.decelerationRate = rate
}
func setBounces(_ bounces: Bool) {
self._scrollView.bounces = bounces
}
func setBouncesZoom(_ bounces: Bool) {
self._scrollView.bouncesZoom = bounces
}
func setDoubleTapEnabled(_ enabled: Bool) {
self._setDoubleTapEnabled(enabled)
}
func setZoomOutTapEnabled(_ enabled: Bool) {
self._setZoomOutTapEnabled(enabled)
}
func setCenterHorizontally(_ center: Bool) {
self._setCenterHorizontally(center)
}
func setCenterVertically(_ center: Bool) {
self._setCenterVertically(center)
}
func setContentInset(_ inset: UIEdgeInsets) {
self._scrollView.contentInset = inset
}
// Functions
func zoomOut(animated: Bool = true) {
self._zoomOut(animated: animated)
}
// Call this when you changed the size of the
// contentView to ensure that the minimum and
// maximum zoomScale as well as the scrollView-
// contentSize are updated accordingly
func contentViewSizeChanged() {
self._contentViewSizeChanged()
}
}
// MARK: Class Declaration
public class ZoomView: UIView {
// Required Init
required public init?(coder aDecoder: NSCoder) {
fatalError("ZoomView does not support NSCoding")
}
// Privatized Inits
private init() { fatalError() }
private override init(frame: CGRect) { fatalError() }
// Convenience Init
public convenience init(contentView: UIView) {
self.init(frame: contentView.bounds, contentView: contentView)
}
// Designated Init
fileprivate init(frame: CGRect, contentView: UIView) {
self._contentView = contentView
super.init(frame: frame)
self.addSubview(self._scrollView)
self.setDoubleTapEnabled(true)
self.setZoomOutTapEnabled(true)
}
// Private Weak Variables
private weak var _delegate: ZoomViewDelegate?
// Private Lazy Variables
private lazy var _scrollView: ZoomToPointScrollView = self._createScrollView()
// ALOs
private lazy var _doubleTapRecognizer: ALO<UITapGestureRecognizer> = ALO({ [unowned self] in self._createDoubleTapRecognizer() })
private lazy var _zoomOutTapRecognizer: ALO<UITapGestureRecognizer> = ALO({ [unowned self] in self._createZoomOutTapRecognizer() })
// Private Variables
private var _contentView: UIView
private var _zoomThreshold: CGFloat = 0.2
private var _centerHorizontally: Bool = true
private var _centerVertically: Bool = true
private var __maximumZoomScale: CGFloat = 1
private var _doubleTapNextScale: CGFloat?
// Frame / Size Overrides
override public var frame: CGRect {
get { return self._frame }
set { self._frame = newValue }
}
override public var size: CGSize {
get { return self._size }
set { self._size = newValue }
}
override public var width: CGFloat {
get { return self._width }
set { self._width = newValue }
}
override public var height: CGFloat {
get { return self._height }
set { self._height = newValue }
}
}
// MARK: Protocol Conformances
// MARK: UIScrollViewDelegate
extension ZoomView: UIScrollViewDelegate {
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self._contentView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
self._didZoom(in: scrollView)
}
public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self._didZoom(in: scrollView)
}
}
// MARK: // Private
// MARK: Lazy Variable Creation
private extension ZoomView {
func _createScrollView() -> ZoomToPointScrollView {
let contentView: UIView = self._contentView
let scrollView: ZoomToPointScrollView = ZoomToPointScrollView(frame: self.bounds)
scrollView.clipsToBounds = false
scrollView.delegate = self
scrollView.addSubview(contentView)
scrollView.contentSize = contentView.size
return scrollView
}
func _createDoubleTapRecognizer() -> UITapGestureRecognizer {
let recognizer: UITapGestureRecognizer = UITapGestureRecognizer()
recognizer.numberOfTapsRequired = 2
recognizer.addTarget(self, action: #selector(self._handleDoubleTap))
return recognizer
}
func _createZoomOutTapRecognizer() -> UITapGestureRecognizer {
let recognizer: UITapGestureRecognizer = UITapGestureRecognizer()
recognizer.numberOfTapsRequired = 2
recognizer.numberOfTouchesRequired = 2
recognizer.addTarget(self, action: #selector(self._handleZoomOutTap))
return recognizer
}
}
// MARK: Setter Implementations
private extension ZoomView {
func _setMaximumZoomScale(_ scale: CGFloat) {
let scrollView: UIScrollView = self._scrollView
scrollView.maximumZoomScale = scale
if scrollView.zoomScale > scale {
scrollView.zoomIn(animated: false)
}
}
func _setDoubleTapEnabled(_ enabled: Bool) {
guard enabled == (self._doubleTapRecognizer¿ == nil) else { return }
if enabled {
self._scrollView.addGestureRecognizer(self._doubleTapRecognizer¡)
} else {
guard let recognizer: UITapGestureRecognizer = self._doubleTapRecognizer¿ else { return }
self._scrollView.removeGestureRecognizer(recognizer)
self._doubleTapRecognizer.clear()
}
}
func _setZoomOutTapEnabled(_ enabled: Bool) {
guard enabled == (self._zoomOutTapRecognizer¿ == nil) else { return }
if enabled {
self._scrollView.addGestureRecognizer(self._zoomOutTapRecognizer¡)
} else {
guard let recognizer: UITapGestureRecognizer = self._zoomOutTapRecognizer¿ else { return }
self._scrollView.removeGestureRecognizer(recognizer)
self._zoomOutTapRecognizer.clear()
}
}
func _setCenterHorizontally(_ center: Bool) {
self._centerHorizontally = center
self._adjustScrollViewContentInsets()
}
func _setCenterVertically(_ center: Bool) {
self._centerVertically = center
self._adjustScrollViewContentInsets()
}
}
// MARK: Frame / Size Override Implementations
private extension ZoomView {
var _frame: CGRect {
get { return super.frame }
set(newFrame) {
super.frame = newFrame
self._scrollView.size = newFrame.size
self._updateZoomScalesAndAdjustScrollViewContentInsets()
}
}
var _size: CGSize {
get { return super.size }
set(newSize) {
super.size = newSize
self._scrollView.size = newSize
self._updateZoomScalesAndAdjustScrollViewContentInsets()
}
}
var _width: CGFloat {
get { return super.width }
set(newWidth) {
super.width = newWidth
self._scrollView.width = newWidth
self._updateZoomScalesAndAdjustScrollViewContentInsets()
}
}
var _height: CGFloat {
get { return super.height }
set(newHeight) {
super.height = newHeight
self._scrollView.height = newHeight
self._updateZoomScalesAndAdjustScrollViewContentInsets()
}
}
}
// MARK: Protocol Conformance Implementations
// MARK: UIScrollViewDelegate
private extension ZoomView/*: UIScrollViewDelegate*/ {
func _didZoom(in scrollView: UIScrollView) {
self._adjustScrollViewContentInsets()
self._delegate?.zoomed(to: scrollView.zoomScale, in: self)
}
}
// MARK: Target Selectors
private extension ZoomView {
@objc func _handleDoubleTap(_ recognizer: UITapGestureRecognizer) {
let scrollView: ZoomToPointScrollView = self._scrollView
let minScale: CGFloat = scrollView.minimumZoomScale
let maxScale: CGFloat = scrollView.maximumZoomScale
guard abs(minScale - maxScale) > self._zoomThreshold else {
return
}
let midScale: CGFloat = (maxScale + minScale) / 2
let currentScale: CGFloat = scrollView.zoomScale
var newScale: CGFloat = minScale
switch currentScale {
case let scale where abs(scale - midScale) < 0.01:
newScale = self._doubleTapNextScale ?? minScale
case let scale where abs(scale - maxScale) < 0.01:
newScale = midScale
self._doubleTapNextScale = minScale
case let scale where scale < midScale - 0.01:
newScale = midScale
self._doubleTapNextScale = maxScale
case let scale where scale < maxScale - 0.01:
newScale = maxScale
default:
newScale = minScale
}
let point: CGPoint = recognizer.location(ofTouch: 0, in: scrollView)
scrollView.zoom(to: point, with: newScale)
}
@objc func _handleZoomOutTap() {
self._zoomOut(animated: true)
}
}
// MARK: Interface Implementations
private extension ZoomView {
func _zoomOut(animated: Bool) {
let animationDuration: TimeInterval = animated ? 0.2 : 0
UIView.animate(withDuration: animationDuration) {
self._scrollView.zoomScale = self._scrollView.minimumZoomScale
self._adjustScrollViewContentInsets()
}
}
func _contentViewSizeChanged() {
let scrollView: UIScrollView = self._scrollView
let contentViewSize: CGSize = self._contentView.size
guard scrollView.contentSize != contentViewSize else {
return
}
scrollView.contentSize = contentViewSize
self._updateZoomScalesAndAdjustScrollViewContentInsets()
}
}
// MARK: Adjust Content Position / Update Zoom Scales
private extension ZoomView {
func _updateZoomScalesAndAdjustScrollViewContentInsets() {
self._updateZoomScales()
self._adjustScrollViewContentInsets()
}
func _adjustScrollViewContentInsets() {
let centerH: Bool = self._centerHorizontally
let centerV: Bool = self._centerVertically
guard centerH || centerV else {
return
}
let scrollView: UIScrollView = self._scrollView
let boundsSize: CGSize = scrollView.bounds.size
let contentSize: CGSize = scrollView.contentSize
if centerH {
let leftInset: CGFloat = (boundsSize.width - contentSize.width) / 2
scrollView.contentInset.left = max(0, leftInset)
}
if centerV {
let topInset: CGFloat = (boundsSize.height - contentSize.height) / 2
scrollView.contentInset.top = max(0, topInset)
}
}
func _updateZoomScales() {
let scrollView: UIScrollView = self._scrollView
let contentSize: CGSize = self._scrollView.contentSize
let widthRatio: CGFloat = scrollView.width / contentSize.width
let heightRatio: CGFloat = scrollView.height / contentSize.height
let currentZoomScale: CGFloat = scrollView.zoomScale
let minScale: CGFloat = min(widthRatio, heightRatio) * currentZoomScale
scrollView.minimumZoomScale = minScale
if currentZoomScale < minScale {
self._scrollView.zoomOut(animated: false)
} else {
self._delegate?.zoomed(to: currentZoomScale, in: self)
}
}
}
| 93de27194091e8bd6bdd6c0864aeee93 | 29.992771 | 135 | 0.639947 | false | false | false | false |
quen2404/absolute0 | refs/heads/develop | Sources/App/Models/Post.swift | mit | 1 | import Vapor
import Fluent
import Foundation
struct PostModel: Model {
static var entity = "posts"
var id: Node?
var content: String
var creationDate: Date?
var user: UserModel
var event: EventModel
var exists: Bool = false
}
extension PostModel: NodeConvertible {
init(node: Node, in context: Context) throws {
id = try node.extract("id")
content = try node.extract("content")
creationDate = try node.extract("creationDate")
user = try node.extract("user")
event = try node.extract("event")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"content": content,
"creationDate": creationDate,
"user": user,
"event": event
])
}
}
extension PostModel: Preparation {
static func prepare(_ database: Database) throws {
try database.create(entity) { teams in
teams.id()
teams.string("content", optional: false)
teams.double("creationDate", optional: true)
teams.parent(EventModel.self, optional: false)
teams.parent(UserModel.self, optional: false)
}
}
static func revert(_ database: Database) throws {
fatalError("unimplemented \(#function)")
}
}
| 4a79784b6863994e9294108a24e6339d | 24.849057 | 58 | 0.583942 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/EmptyComposeController.swift | gpl-2.0 | 1 | //
// EmptyComposeController.swift
// TelegramMac
//
// Created by keepcoder on 27/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
class ComposeState<T> {
let result:T
init(_ result:T) {
self.result = result
}
}
class EmptyComposeController<I,T,R>: TelegramGenericViewController<R> where R:NSView {
public let onChange:Promise<T> = Promise()
public let onComplete:Promise<T> = Promise()
public let onCancel:Promise<Void> = Promise()
public var previousResult:ComposeState<I>? = nil
func restart(with result:ComposeState<I>) {
self.previousResult = result
}
}
| 74ef8a55e7ab591a66dd3b8d8028d0c6 | 21.870968 | 86 | 0.692525 | false | false | false | false |
steelwheels/Coconut | refs/heads/master | CoconutData/Source/Value/CNMutableSegment.swift | lgpl-2.1 | 1 | /*
* @file CNMutableSegmentValue.swift
* @brief Define CNMutableSegmentValue class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
import Foundation
public class CNMutableValueSegment: CNMutableValue
{
private var mSegmentValue: CNValueSegment
private var mContext: CNMutableValue?
public init(value val: CNValueSegment, sourceDirectory srcdir: URL, cacheDirectory cachedir: URL){
mSegmentValue = val
mContext = nil
super.init(type: .segment, sourceDirectory: srcdir, cacheDirectory: cachedir)
}
public var context: CNMutableValue? { get { return mContext }}
public var sourceFile: URL { get {
return self.sourceDirectory.appendingPathComponent(mSegmentValue.filePath)
}}
public var cacheFile: URL { get {
return self.cacheDirectory.appendingPathComponent(mSegmentValue.filePath)
}}
public var description: String { get {
return self.toValue().description
}}
public override func _value(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> Result<CNMutableValue?, NSError> {
let result: Result<CNMutableValue?, NSError>
switch load() {
case .success(let mval):
result = mval._value(forPath: path, in: root)
case .failure(let err):
result = .failure(err)
}
return result
}
public override func _set(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? {
let result: NSError?
switch load() {
case .success(let mval):
result = mval._set(value: val, forPath: path, in: root)
case .failure(let err):
result = err
}
return result
}
public override func _append(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? {
let result: NSError?
switch load() {
case .success(let mval):
result = mval._append(value: val, forPath: path, in: root)
case .failure(let err):
result = err
}
return result
}
public override func _delete(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? {
let result: NSError?
switch load() {
case .success(let mval):
result = mval._delete(forPath: path, in: root)
case .failure(let err):
result = err
}
return result
}
public func load() -> Result<CNMutableValue, NSError> {
let result: Result<CNMutableValue, NSError>
if let ctxt = mContext {
result = .success(ctxt)
} else {
if let src = mSegmentValue.load(fromSourceDirectory: self.sourceDirectory, cacheDirectory: self.cacheDirectory) {
let ctxt = toMutableValue(from: src)
mContext = ctxt
result = .success(ctxt)
} else {
result = .failure(NSError.parseError(message: "Failed to load: source=\(self.sourceFile.path) cache=\(self.cacheFile.path)"))
}
}
return result
}
public override func _search(name nm: String, value val: String, in root: CNMutableValue) -> Result<Array<CNValuePath.Element>?, NSError> {
let result: Result<Array<CNValuePath.Element>?, NSError>
switch load() {
case .success(let mval):
result = mval._search(name: nm, value: val, in: root)
case .failure(let err):
result = .failure(err)
}
return result
}
public override func _makeLabelTable(property name: String, path pth: Array<CNValuePath.Element>) -> Dictionary<String, Array<CNValuePath.Element>> {
switch load() {
case .success(let mval):
return mval._makeLabelTable(property: name, path: pth)
case .failure(let err):
CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file)
return [:]
}
}
public override func clone() -> CNMutableValue {
return CNMutableValueSegment(value: mSegmentValue, sourceDirectory: self.sourceDirectory, cacheDirectory: self.cacheDirectory)
}
public override func toValue() -> CNValue {
return .dictionaryValue(mSegmentValue.toValue())
}
}
| 0bba933273f801feae96bdefeab90f30 | 30.130081 | 150 | 0.712196 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/SILGen/scalar_to_tuple_args.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {}
func inoutWithCallerSideDefaults(_ x: inout 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 @_T020scalar_to_tuple_args1xSiv : $*Int
// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args17inoutWithDefaultsySiz_Si1ySi1ztF
// 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 @_T020scalar_to_tuple_args27inoutWithCallerSideDefaultsySiz_Si1ytF
// 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 @_T020scalar_to_tuple_args0A12WithDefaultsySi_Si1ySi1ztF
// CHECK: [[X:%.*]] = load [trivial] [[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 @_T020scalar_to_tuple_args0A22WithCallerSideDefaultsySi_Si1ytF
// CHECK: [[X:%.*]] = load [trivial] [[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 @_T020scalar_to_tuple_args0C12WithDefaultsySi_Sit1x_Si1ySi1ztF
// CHECK: [[X1:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[X2:%.*]] = load [trivial] [[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 @_T020scalar_to_tuple_args13variadicFirstySaySiG_dtF
// 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 [trivial] [[X_ADDR]]
// CHECK: store [[X]] to [trivial] [[ADDR]]
// CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
variadicFirst(x)
// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_T020scalar_to_tuple_args14variadicSecondySi_SaySiGdtF
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
variadicSecond(x)
| aab1e78414d663d5408742fc1b970ffa | 52.123077 | 126 | 0.607588 | false | false | false | false |
nathantannar4/NTComponents | refs/heads/master | NTComponents/Extensions/UIColor.swift | mit | 1 | //
// UIColor.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 2/12/17.
//
public extension UIColor {
//**************************************/
// Convenience Initilizers
//**************************************/
/// Takes a 6 character HEX string and initializes a corresponding UIColor. Initializes as UIColor.white
/// any discrepancies are found. (A # character will be automatically removed if added)
///
/// - Parameter hex: 6 HEX color code
public convenience init(hex: String) {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
self.init(red: 0, green: 0, blue: 0, alpha: 1)
} else {
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
/// Initializes a UIColor for its corresponding rgba UInt
///
/// - Parameter rgba: UInt
public convenience init(rgba: UInt){
let sRgba = min(rgba,0xFFFFFFFF)
let red: CGFloat = CGFloat((sRgba & 0xFF000000) >> 24) / 255.0
let green: CGFloat = CGFloat((sRgba & 0x00FF0000) >> 16) / 255.0
let blue: CGFloat = CGFloat((sRgba & 0x0000FF00) >> 8) / 255.0
let alpha: CGFloat = CGFloat(sRgba & 0x000000FF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat){
self.init(red: r / 255, green: g / 255, blue: b / 255, alpha: 1)
}
//**************************************/
// Functions
//**************************************/
func lighter(by percentage: CGFloat = 30.0) -> UIColor {
return self.adjust(by: abs(percentage)) ?? .white
}
func darker(by percentage: CGFloat = 30.0) -> UIColor {
return self.adjust(by: -1 * abs(percentage)) ?? .black
}
/// Performs an equivalent to the .map({}) function, adjusting the current r, g, b value by the percentage
///
/// - Parameter percentage: CGFloat
/// - Returns: UIColor or nil if there was an error
func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var r:CGFloat=0, g:CGFloat=0, b:CGFloat=0, a:CGFloat=0;
if (self.getRed(&r, green: &g, blue: &b, alpha: &a)){
return UIColor(red: min(r + percentage/100, 1.0),
green: min(g + percentage/100, 1.0),
blue: min(b + percentage/100, 1.0),
alpha: a)
} else{
return nil
}
}
func withAlpha(_ alpha: CGFloat) -> UIColor {
return self.withAlphaComponent(alpha)
}
func isDarker(than color: UIColor) -> Bool {
return self.luminance < color.luminance
}
func isLighter(than color: UIColor) -> Bool {
return !self.isDarker(than: color)
}
//**************************************/
// Extended Variables
//**************************************/
var ciColor: CIColor {
return CIColor(color: self)
}
var RGBA: [CGFloat] {
return [ciColor.red, ciColor.green, ciColor.blue, ciColor.alpha]
}
var luminance: CGFloat {
let RGBA = self.RGBA
func lumHelper(c: CGFloat) -> CGFloat {
return (c < 0.03928) ? (c/12.92): pow((c+0.055)/1.055, 2.4)
}
return 0.2126 * lumHelper(c: RGBA[0]) + 0.7152 * lumHelper(c: RGBA[1]) + 0.0722 * lumHelper(c: RGBA[2])
}
var isDark: Bool {
return self.luminance < 0.5
}
var isLight: Bool {
return !self.isDark
}
var isBlackOrWhite: Bool {
let RGBA = self.RGBA
let isBlack = RGBA[0] < 0.09 && RGBA[1] < 0.09 && RGBA[2] < 0.09
let isWhite = RGBA[0] > 0.91 && RGBA[1] > 0.91 && RGBA[2] > 0.91
return isBlack || isWhite
}
/// Apples default tint color
static var lightBlue: UIColor {
get {
return UIColor(hex: "007AFF")
}
}
}
| 6a65d595c404f38d9fbb6f1dffc80e76 | 33.277108 | 111 | 0.555009 | false | false | false | false |
eliakorkmaz/iCard | refs/heads/master | iCard/iCreditCard.swift | mit | 1 | //
// iCreditCard.swift
// iCard
//
// Created by xcodewarrior on 14.08.2017.
// Copyright © 2017 EmrahKorkmaz. All rights reserved.
//
import UIKit
class iCreditCard: UIView {
lazy var contentView: UIView = {
let view:UIView = UIView()
view.backgroundColor = UIColor.clear
return view
}()
lazy var bankNameLabel: UILabel = {
let label:UILabel = UILabel()
label.font = UIFont.init(name: "Avenir-Black", size: 20)
label.text = "BANK NAME"
label.textAlignment = .left
label.textColor = UIColor.white
return label
}()
lazy var topSeparator: UIView = {
let view:UIView = UIView()
view.backgroundColor = UIColor.white
return view
}()
lazy var creditCardButton: UIButton = {
let button:UIButton = UIButton()
button.setImage(UIImage.init(named: "creditCardBackground"), for: .normal)
button.layer.cornerRadius = 8
button.isUserInteractionEnabled = false
button.showsTouchWhenHighlighted = false
return button
}()
lazy var backgroundImageView: UIImageView = {
let imageView:UIImageView = UIImageView()
imageView.contentMode = .scaleToFill
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = 8
return imageView
}()
lazy var chipIconImageView: UIImageView = {
let imageView:UIImageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = 5
imageView.image = UIImage.init(named: "chip1")
return imageView
}()
lazy var creditCardNumbers: UILabel = {
let label:UILabel = UILabel()
label.textAlignment = .left
label.textColor = UIColor.white
label.text = "4111 1111 1111 1111"
label.font = UIFont.init(name: "Halter", size: 16)
return label
}()
lazy var creditNumberTitleLabel: UILabel = {
let label:UILabel = UILabel()
label.text = "CARD NUMBER"
label.font = UIFont.init(name: "Avenir-Light", size: 8)
label.textColor = UIColor.white
label.textAlignment = .left
return label
}()
lazy var creditCardLastUsage: UILabel = {
let label:UILabel = UILabel()
label.text = "06/21"
label.textColor = UIColor.white
label.font = UIFont.init(name: "Halter", size: 14)
label.textAlignment = .center
return label
}()
lazy var lastUsageTitleLabel: UILabel = {
let label:UILabel = UILabel()
label.text = "MONTH/YEAR"
label.textColor = UIColor.white
label.font = UIFont.init(name: "Avenir-Light", size: 8)
return label
}()
lazy var validThruLabel: UILabel = {
let label:UILabel = UILabel()
label.text = "VALID THRU"
label.textAlignment = .center
label.textColor = UIColor.white
label.font = UIFont.init(name: "Avenir-Light", size: 8)
label.numberOfLines = 0
return label
}()
lazy var cardBrandName: UILabel = {
let label:UILabel = UILabel()
label.text = "BANK NAME"
label.font = UIFont.init(name: "Avenir-Black", size: 20)
label.textAlignment = .left
label.textColor = UIColor.white
return label
}()
lazy var cardBrandImageView: UIImageView = {
let imageView:UIImageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = 5
imageView.image = UIImage.init(named: "maestro2Icon")
return imageView
}()
lazy var cardBrandImageViewBottom: UIImageView = {
let imageView:UIImageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = 5
imageView.image = UIImage.init(named: "visaIcon")
return imageView
}()
lazy var cardholderLabel: UILabel = {
let label:UILabel = UILabel()
label.text = "CARDHOLDER"
label.font = UIFont.init(name: "Avenir-Black", size: 20)
label.textColor = UIColor.white
return label
}()
convenience init(){
self.init(cardStyleWithBackgroundColor: .withBothBankIcon, withCardColors: .yelloway, pinIcon: .chip1, creditIcons: .cirrusIcon)
}
convenience init(cardColors: cardColors){
self.init(cardStyleWithBackgroundColor: .withBothBankIcon, withCardColors: .yelloway, pinIcon: .chip2, creditIcons: .americanExpressIcon)
}
init(cardStyleWithBackgroundColor: cardStyle , withCardColors colors: cardColors , pinIcon: chipIcons , creditIcons: creditIcons){
super.init(frame: CGRect())
addItemsWithColors(cardStyleWithBackgroundColor, colors: colors, chipIcon: pinIcon, creditIcon: creditIcons)
settingForLayout(cardStyle: cardStyleWithBackgroundColor, cardVisual: cardVisual.withBackgroundColor, withSeparator: true)
}
init(cardStyleWithBackgroundImage: cardStyle , withCardImage: UIImage?, pinIcon: chipIcons , creditIcons: creditIcons){
super.init(frame: CGRect())
addItemsWithImage(image: withCardImage, cardStyleWithBackgroundImage, chipIcon: pinIcon, creditIcon: creditIcons)
settingForLayout(cardStyle: cardStyleWithBackgroundImage, cardVisual: cardVisual.withBackgroundImage, withSeparator: true)
}
fileprivate func addItemsWithImage(image backgroundImage: UIImage? , _ cardStyle: cardStyle, chipIcon: chipIcons , creditIcon: creditIcons){
self.addSubview(contentView)
self.addSubview(backgroundImageView)
self.addSubview(bankNameLabel)
self.addSubview(creditCardButton)
self.addSubview(chipIconImageView)
self.addSubview(creditCardNumbers)
self.addSubview(creditNumberTitleLabel)
self.addSubview(creditCardLastUsage)
self.addSubview(lastUsageTitleLabel)
self.addSubview(validThruLabel)
self.addSubview(cardBrandName)
self.addSubview(cardholderLabel)
if let image = backgroundImage{
self.backgroundImageView.image = image
}else{
fillWithColor(color: cardColors.yelloway)
}
if cardStyle == .withBothBankIcon{
self.addSubview(cardBrandImageView)
cardBrandImageView.image = creditIconImage(creditIcon: creditIcon)
self.addSubview(cardBrandImageViewBottom)
cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon)
}else if cardStyle == .withTopBankIcon{
self.addSubview(cardBrandImageView)
cardBrandImageView.image = creditIconImage(creditIcon: creditIcon)
}else if cardStyle == .withBottomBankIcon{
self.addSubview(cardBrandImageViewBottom)
cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon)
}else{
// nothing will be added
}
switch chipIcon{
case .chip1:
chipIconImageView.image = UIImage(named: "chip1")
case .chip2:
chipIconImageView.image = UIImage(named: "chip2")
case .chip3:
chipIconImageView.image = UIImage(named: "chip1")
}
self.addSubview(topSeparator)
}
fileprivate func addItemsWithColors(_ cardStyle: cardStyle , colors: cardColors , chipIcon: chipIcons , creditIcon: creditIcons){
self.addSubview(contentView)
self.addSubview(bankNameLabel)
self.addSubview(creditCardButton)
self.addSubview(chipIconImageView)
self.addSubview(creditCardNumbers)
self.addSubview(creditNumberTitleLabel)
self.addSubview(creditCardLastUsage)
self.addSubview(lastUsageTitleLabel)
self.addSubview(validThruLabel)
self.addSubview(cardBrandName)
self.addSubview(cardholderLabel)
if cardStyle == .withBothBankIcon{
self.addSubview(cardBrandImageView)
cardBrandImageView.image = creditIconImage(creditIcon: creditIcon)
self.addSubview(cardBrandImageViewBottom)
cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon)
}else if cardStyle == .withTopBankIcon{
self.addSubview(cardBrandImageView)
cardBrandImageView.image = creditIconImage(creditIcon: creditIcon)
}else if cardStyle == .withBottomBankIcon{
self.addSubview(cardBrandImageViewBottom)
cardBrandImageViewBottom.image = creditIconImage(creditIcon: creditIcon)
}else{
// nothing will be added
}
switch chipIcon{
case .chip1:
chipIconImageView.image = UIImage(named: "chip1")
case .chip2:
chipIconImageView.image = UIImage(named: "chip2")
case .chip3:
chipIconImageView.image = UIImage(named: "chip3")
}
self.addSubview(topSeparator)
fillWithColor(color: colors)
}
fileprivate func fillWithColor(color: cardColors){
switch color {
case .blueway:
self.backgroundColor = UIColor(r: 28, g: 91, b: 140, alpha: 1)
case .yelloway:
self.backgroundColor = UIColor(r: 182, g: 152, b: 65, alpha: 1)
case .greenway:
self.backgroundColor = UIColor(r: 46, g: 204, b: 113, alpha: 1)
}
}
fileprivate func settingForLayout(cardStyle style: cardStyle , cardVisual : cardVisual , withSeparator: Bool){
self.layer.cornerRadius = 8
if cardVisual == .withBackgroundImage {
backgroundImageView.snp.makeConstraints({ (make) in
make.left.equalTo(self.snp.left)
make.right.equalTo(self.snp.right)
make.top.equalTo(self.snp.top)
make.bottom.equalTo(self.snp.bottom)
})
}
contentView.snp.makeConstraints({ (make) in
make.left.equalTo(self.snp.left)
make.right.equalTo(self.snp.right)
make.top.equalTo(self.snp.top)
make.bottom.equalTo(self.snp.bottom)
})
chipIconImageView.snp.makeConstraints({ (make) in
make.height.equalTo(40)
make.width.equalTo(60)
make.left.equalTo(self.snp.left).offset(15)
make.bottom.equalTo(self.snp.centerY)
})
creditCardNumbers.snp.makeConstraints({ (make) in
make.left.equalTo(chipIconImageView.snp.left).offset(8)
make.right.equalTo(self.snp.right).offset(-15)
make.centerX.equalTo(self.snp.centerX)
make.top.equalTo(chipIconImageView.snp.bottom).offset(5)
})
creditNumberTitleLabel.snp.makeConstraints({ (make) in
make.left.equalTo(creditCardNumbers)
make.top.equalTo(creditCardNumbers.snp.bottom).offset(1)
})
lastUsageTitleLabel.snp.makeConstraints({ (make) in
make.centerX.equalTo(self.snp.centerX)
make.centerY.equalTo(creditNumberTitleLabel.snp.centerY)
})
creditCardLastUsage.snp.makeConstraints({ (make) in
make.centerX.equalTo(lastUsageTitleLabel.snp.centerX)
make.top.equalTo(lastUsageTitleLabel.snp.bottom).offset(1)
})
validThruLabel.snp.makeConstraints({ (make) in
make.centerY.equalTo(creditCardLastUsage)
make.right.equalTo(creditCardLastUsage.snp.left).offset(-1)
make.width.equalTo(30)
})
if style == .withDefaultTitles{
cardBrandName.snp.makeConstraints({ (make) in
make.top.equalTo(self.snp.top).offset(10)
make.left.equalTo(self.snp.left).offset(10)
})
topSeparator.snp.makeConstraints({ (make) in
make.left.equalTo(self.snp.left)
make.right.equalTo(self.snp.right)
make.height.equalTo(2)
make.top.equalTo(cardBrandName.snp.bottom).offset(1)
})
}else if style == .withBottomBankIcon{
cardBrandImageViewBottom.snp.makeConstraints({ (make) in
make.right.equalTo(self.snp.right).offset(-10)
make.bottom.equalTo(self.snp.bottom).offset(-10)
make.height.equalTo(30)
make.width.equalTo(40)
})
topSeparator.snp.makeConstraints({ (make) in
make.left.equalTo(self.snp.left)
make.right.equalTo(self.snp.right)
make.height.equalTo(2)
make.top.equalTo(self.snp.top).offset(41)
})
}else if style == .withTopBankIcon{
cardBrandImageView.snp.makeConstraints({ (make) in
make.top.equalTo(self.snp.top).offset(10)
make.right.equalTo(self.snp.right).offset(-10)
make.height.equalTo(30)
make.width.equalTo(40)
})
topSeparator.snp.makeConstraints({ (make) in
make.left.equalTo(self.snp.left)
make.right.equalTo(self.snp.right)
make.height.equalTo(2)
make.top.equalTo(cardBrandImageView.snp.bottom).offset(1)
})
}else{
cardBrandImageView.snp.makeConstraints({ (make) in
make.top.equalTo(self.snp.top).offset(10)
make.right.equalTo(self.snp.right).offset(-10)
make.height.equalTo(30)
make.width.equalTo(40)
})
cardBrandImageViewBottom.snp.makeConstraints({ (make) in
make.right.equalTo(self.snp.right).offset(-10)
make.bottom.equalTo(self.snp.bottom).offset(-10)
make.height.equalTo(30)
make.width.equalTo(40)
})
topSeparator.snp.makeConstraints({ (make) in
make.left.equalTo(self.snp.left)
make.right.equalTo(self.snp.right)
make.height.equalTo(2)
make.top.equalTo(cardBrandImageView.snp.bottom).offset(1)
})
}
cardholderLabel.snp.makeConstraints({ (make) in
make.left.equalTo(creditCardNumbers)
make.bottom.equalTo(self.snp.bottom).offset(-10)
})
}
override init(frame: CGRect){
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
public enum cardColors{
case blueway
case yelloway
case greenway
}
public enum cardVisual{
case withBackgroundColor
case withBackgroundImage
}
public enum cardStyle{
case withDefaultTitles
case withTopBankIcon
case withBottomBankIcon
case withBothBankIcon
}
public enum creditIcons{
case americanExpressIcon
case bitcoinIcon
case bluePayIcon
case cirrusIcon
case citiIcon
case clickBank
case cvsIcon
case googleWalletIcon
case hsbcIcon
case maestroIcon
case maestroIcon2
case masterCard
case masterCardMini
case masterCardDetail
case moneyGramIcon
case paypalIcon
case paypalIconSimple
case visaIcon
case visaIconBigger
case visaIconText
case wePayIcon
case westernUnionIcon
}
public enum chipIcons{
case chip1
case chip2
case chip3
}
extension UIColor{
convenience init(r: Float, g: Float , b: Float , alpha: Int) {
self.init(red: CGFloat(r/255), green: CGFloat(g/255), blue: CGFloat(b/255), alpha: CGFloat(alpha))
}
}
extension iCreditCard{
fileprivate func creditIconImage(creditIcon toImage: creditIcons) -> UIImage{
switch toImage {
case .americanExpressIcon:
return UIImage(named: "americanExpressIcon")!
case .bitcoinIcon:
return UIImage(named: "bitcoinIcon")!
case .bluePayIcon:
return UIImage(named: "bluePayIcon")!
case .cirrusIcon:
return UIImage(named: "cirrusIcon")!
case .citiIcon:
return UIImage(named: "citiIcon")!
case .clickBank:
return UIImage(named: "clickBank")!
case .cvsIcon:
return UIImage(named: "cvsIcon")!
case .googleWalletIcon:
return UIImage(named: "googleWalletIcon")!
case .hsbcIcon:
return UIImage(named: "hsbcIcon")!
case .maestroIcon:
return UIImage(named: "maestroIcon")!
case .maestroIcon2:
return UIImage(named: "maestro2Icon")!
case .masterCard:
return UIImage(named: "masterCard")!
case .masterCardMini:
return UIImage(named: "masterCardMini")!
case .masterCardDetail:
return UIImage(named: "masterCardDetail")!
case .moneyGramIcon:
return UIImage(named: "moneygramIcon")!
case .paypalIcon:
return UIImage(named: "paypal2Icon")!
case .paypalIconSimple:
return UIImage(named: "paypalIcon")!
case .visaIcon:
return UIImage(named: "visaIcon")!
case .visaIconBigger:
return UIImage(named: "visaIconBigger")!
case .visaIconText:
return UIImage(named: "visaIconText")!
case .wePayIcon:
return UIImage(named: "wepayIcon")!
case .westernUnionIcon:
return UIImage(named: "westernUnionIcon")!
}
}
}
| 371ad5ac29db6ffc021f9e3cb80470d0 | 34.461538 | 145 | 0.613938 | false | false | false | false |
timfuqua/Bourgeoisie | refs/heads/master | Bourgeoisie/Pods/Buckets/Source/Graph.swift | mit | 1 | //
// Graph.swift
// Buckets
//
// Created by Mauricio Santos on 2/19/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
//
import Foundation
/// A simple directed graph: that is, one with no loops (edges
/// connected at both ends to the same vertex) and no more than one edge
/// in the same direction between any two different vertices.
/// All vertices in the graph are unique.
/// The preferred way to insert vertices and edges is using subscript notation. Example:
/// `graph["NY", "Boston"] = distance`
///
/// Conforms to `SequenceType`.
public struct Graph<Vertex: Hashable, Edge> {
private typealias GraphNode = VertexNode<Vertex, Edge>
// MARK: Creating a Graph
/// Creates an empty graph.
public init() {}
// MARK: Querying a Graph
/// Number of vertices stored in the graph.
public var count: Int {
return nodes.count
}
/// Returns `true` if and only if `count == 0`.
public var isEmpty: Bool {
return count == 0
}
/// Returns `true` if every pair of distinct vertices is connected by a
/// unique edge (one in each direction).
public var isComplete: Bool {
return !nodes.values.contains { $0.adjacencyList.count != count - 1 }
}
/// Returns `true` if there's not a path starting and ending
/// at the same vertex.
public var isAcyclic: Bool {
var visited = Set<GraphNode>()
for sourceNode in nodes.values {
var path = [Vertex]()
for neighbor in sourceNode.successors {
if containsPathFrom(neighbor, to: sourceNode, visited: &visited, path: &path) {
return false
}
}
}
return true
}
/// Returns the vertices stored in the graph.
public var vertices: Set<Vertex> {
return Set(nodes.keys)
}
/// Returns the edges stored in the graph.
public var edges: [Edge] {
var edges = [Edge]()
for node in nodes.values {
edges += node.edges
}
return edges
}
/// Returns `true` if the graph contains the given vertex.
public func containsVertex(vertex: Vertex) -> Bool {
return nodes[vertex] != nil
}
/// Returns `true` if the graph contains an edge from `source` to `destination`.
/// Subscript notation is preferred.
public func containsEdgeFrom(source: Vertex, to destination: Vertex) -> Bool {
return edgeFrom(source, to: destination) != nil
}
/// Returns the edge connecting `source` to `destination` if it exists.
/// Subscript notation is preferred.
public func edgeFrom(source: Vertex, to destination: Vertex) -> Edge? {
if let sourceNode = nodes[source], destinationNode = nodes[destination] {
return sourceNode.edgeConnectingTo(destinationNode)
}
return nil
}
/// Returns the set of direct successors of the given vertex. An empty set
/// is returned if the vertex does not exist.
public func neighbors(source: Vertex) -> Set<Vertex> {
if let node = nodes[source] {
return Set(node.successors.map{$0.data})
}
return []
}
/// Returns an array of vertices representing a path from `source` to `destination`, if it exists.
///
/// - returns: An array containing at least two vertices (`source` and `destination`) or an empty array.
public func pathFrom(source: Vertex, to destination: Vertex) -> [Vertex] {
if let sourceNode = nodes[source], destinationNode = nodes[destination] {
var path = [Vertex]()
var visited = Set<GraphNode>()
for successor in sourceNode.successors {
if containsPathFrom(successor, to: destinationNode, visited: &visited, path: &path) {
return [source] + path
}
}
}
return []
}
/// Returns a generator iterating over the vertices in the specified order starting at the given vertex.
/// Valid options are .DepthFirst and .BreadthFirst.
///
/// The generator never returns the same vertex more than once.
public func generateAt(source: Vertex, order: GraphTraversalOrder) -> AnyGenerator<Vertex> {
if let sourceNode = nodes[source] {
let nextNode: () -> GraphNode?
let visitEventually: (GraphNode) -> Void
switch order {
case .DepthFirst:
var nextVertices = Stack<GraphNode>()
nextNode = {nextVertices.pop()}
visitEventually = {nextVertices.push($0)}
case .BreadthFirst:
var nextVertices = Queue<GraphNode>()
nextNode = {nextVertices.dequeue()}
visitEventually = {nextVertices.enqueue($0)}
}
return vertexGenerator(sourceNode, nextNode: nextNode, visitEventually: visitEventually)
}
return anyGenerator(EmptyGenerator())
}
// MARK: Adding and Removing Elements
// Gets, sets, or deletes an edge between vertices.
// The vertices are inserted if they don´t exist in the graph, except when removing.
public subscript(source: Vertex, destination: Vertex) -> Edge? {
get {
return edgeFrom(source, to: destination)
}
set {
if let newValue = newValue {
insertEdge(newValue, from: source, to: destination)
} else {
removeEdgeFrom(source, to: destination)
}
}
}
/// Inserts the given vertex to the graph if it doesn't exist.
public mutating func insertVertex(vertex: Vertex) {
if !containsVertex(vertex) {
copyMyself()
nodes[vertex] = GraphNode(vertex)
}
}
/// Removes and returns the given vertex from the graph if it was present.
public mutating func removeVertex(vertex : Vertex) -> Vertex? {
if containsVertex(vertex) {
copyMyself()
let value = nodes.removeValueForKey(vertex)?.data
for other in nodes.keys {
removeEdgeFrom(other, to: vertex)
}
return value
}
return nil
}
/// Connects two vertices with the given edge. If an edge already exists, it is replaced.
/// Subscript notation is preferred.
public mutating func insertEdge(edge: Edge, from source: Vertex, to destination: Vertex) {
if source == destination {
fatalError("Simple graphs can't have edges connected at both ends to the same vertex.")
}
copyMyself()
insertVertex(source)
insertVertex(destination)
removeEdgeFrom(source, to: destination)
nodes[source]?.connectTo(nodes[destination]!, withEdge: edge)
}
/// Removes and returns the edge connecting the given vertices if it exists.
public mutating func removeEdgeFrom(source: Vertex, to destination: Vertex) -> Edge? {
if containsVertex(source) && containsVertex(destination) {
copyMyself()
return nodes[source]!.removeConnectionTo(nodes[destination]!)
}
return nil
}
/// Removes all vertices and edges from the graph, and by default
/// clears the underlying storage buffer.
public mutating func removeAll(keepCapacity keep: Bool = true) {
nodes.removeAll(keepCapacity: keep)
}
// MARK: Private Properties and Helper Methods
/// Adjacency lists graph representation.
private var nodes = [Vertex: GraphNode]()
/// Unique identifier to perform copy-on-write.
private var tag = Tag()
/// Finds a path from `source` to `destination` recursively.
private func containsPathFrom(source: GraphNode, to destination: GraphNode, inout visited: Set<GraphNode> , inout path: [Vertex]) -> Bool {
if visited.contains(source) {
return false
}
visited.insert(source)
path.append(source.data)
if source == destination {
return true
}
for vertex in source.successors {
if containsPathFrom(vertex, to: destination, visited: &visited, path: &path) {
return true
}
}
path.removeLast()
return false
}
/// Returns a generator over the vertices starting at the given node.
/// The generator never returns the same vertex twice.
/// Using nextVertex and visitEventually allows you to specify the order of traversal.
///
/// - parameter source: The first node to visit.
/// - parameter nextNode: Returns the next node to visit.
/// - parameter visitEventually: Gives a neighbor of the vertex previously returned by nextNode().
private func vertexGenerator(source: GraphNode, nextNode:() -> GraphNode?, visitEventually: (GraphNode)->Void) -> AnyGenerator<Vertex> {
var visited = Set<GraphNode>()
visitEventually(source)
return anyGenerator {
if let next = nextNode() {
visited.insert(next)
for successor in next.successors {
if !visited.contains(successor) {
visitEventually(successor)
}
}
return next.data
}
return nil
}
}
/// Creates a new copy of the nodes in the graph if there´s
/// more than one strong reference pointing the graph's tag.
///
/// The Graph itself is a value type but a VertexNode is a reference type,
/// calling this method ensures copy-on-write behavior.
private mutating func copyMyself() {
if !isUniquelyReferencedNonObjC(&tag) {
tag = Tag()
var newNodes = [Vertex: GraphNode]()
for vertex in nodes.keys {
newNodes[vertex] = GraphNode(vertex)
}
for (vertex, oldNode) in nodes {
let newNode = newNodes[vertex]!
let edges = oldNode.edges
let successors = oldNode.successors.map{newNodes[$0.data]!}
for (index, successor) in successors.enumerate() {
newNode.connectTo(successor, withEdge: edges[index])
}
}
nodes = newNodes
}
}
}
extension Graph: SequenceType {
// MARK: SequenceType Protocol Conformance
/// Provides for-in loop functionality.
///
/// - returns: A generator over the vertices.
public func generate() -> AnyGenerator<Vertex> {
return anyGenerator(nodes.keys.generate())
}
}
// MARK: - Operators
// MARK: Graph Operators
/// Returns `true` if and only if the graphs contain the same vertices and edges per vertex.
/// The underlying edges must conform to the `Equatable` protocol.
public func ==<V, E: Equatable>(lhs: Graph<V,E>, rhs: Graph<V,E>) -> Bool {
if lhs.count != rhs.count {
return false
}
for (vertex, lNode) in lhs.nodes {
if rhs.nodes[vertex] == nil {
return false
}
let rNode = rhs.nodes[vertex]!
if lNode.adjacencyList.count != rNode.adjacencyList.count {
return false
}
let containsAllEdges = !lNode.successors.contains {
rNode.edgeConnectingTo($0) != lNode.edgeConnectingTo($0)
}
if !containsAllEdges {
return false
}
}
return true
}
public func !=<V, E: Equatable>(lhs: Graph<V,E>, rhs: Graph<V,E>) -> Bool {
return !(lhs == rhs)
}
// MARK: - GraphTraversalOrder
public enum GraphTraversalOrder {
case DepthFirst
case BreadthFirst
}
// MARK: - VertexNode
private class VertexNode<V: Hashable, E>: Hashable {
typealias Bridge = (destination: VertexNode<V,E>, edge: E)
let data : V
var adjacencyList = [Bridge]()
var successors: LazyCollection<[VertexNode<V, E>]> {
return LazyCollection(LazyCollection(adjacencyList).map{$0.destination})
}
var edges: LazyCollection<[E]> {
return LazyCollection(LazyCollection(adjacencyList).map{$0.edge})
}
var hashValue: Int {
return data.hashValue
}
init(_ vertex: V) {
self.data = vertex
}
func connectTo(vertex: VertexNode, withEdge edge: E) {
adjacencyList.append((vertex, edge))
}
func edgeConnectingTo(vertex: VertexNode) -> E? {
for neighbor in adjacencyList {
if neighbor.destination == vertex {
return neighbor.edge
}
}
return nil
}
func removeConnectionTo(vertex: VertexNode) -> E? {
for (index, neighbor) in adjacencyList.enumerate() {
if neighbor.destination == vertex {
return adjacencyList.removeAtIndex(index).edge
}
}
return nil
}
}
private func ==<V, E>(lhs: VertexNode<V, E>, rhs: VertexNode<V, E>) -> Bool {
return lhs.data == rhs.data
}
// MARK: - Tag
private class Tag {}
| 3514bc7a505c950ebed9497328bb65ed | 32.576142 | 143 | 0.593469 | false | false | false | false |
BOTDOTME/AZExpandableIconListView | refs/heads/master | Pod/Classes/AZExpandableIconListView.swift | mit | 1 | //
// AZExpandableIconListView.swift
// Pods
//
// Created by Chris Wu on 01/28/2016.
// Copyright (c) 2016 Chris Wu. All rights reserved.
//
import Foundation
open class AZExpandableIconListView: UIView {
fileprivate var icons: [(UILabel, UIImageView)] = []
fileprivate var scrollView: UIScrollView
fileprivate var contentView: UIView
fileprivate var isSetupFinished: Bool = false
open var isExpanded: Bool = false
fileprivate var middleItemSpacingConstraint: NSLayoutConstraint?
fileprivate var rightMiddleItemSpacingConstraint: NSLayoutConstraint?
fileprivate var leftMiddleItemSpacingConstraint: NSLayoutConstraint?
fileprivate var rightItemSpacingConstraints: [NSLayoutConstraint] = []
fileprivate var leftItemSpacingConstraints: [NSLayoutConstraint] = []
open var imageSpacing: CGFloat = 4.0
open var onExpanded: (()->())?
open var onCollapsed:(()->())?
/// Image width is set to be always 80% of container view's frame width
fileprivate var imageWidth: CGFloat { return scrollView.frame.height * 0.6 }
fileprivate var halfImageWidth: CGFloat { return imageWidth * 0.5 }
fileprivate var stretchedImageWidth: CGFloat { return (CGFloat(icons.count) * imageWidth) + (CGFloat(icons.count) * imageSpacing) }
fileprivate var contractedImageWidth: CGFloat { return imageWidth + 0.20*CGFloat(icons.count - 1)*imageWidth }
fileprivate var realContractedCenterOffset: CGFloat { return contractedImageWidth/2.0 - (imageWidth + 0.20*9.0*imageWidth)/2.0 }
fileprivate var needsToAdjust: Bool { return icons.count > 10 ? true : false }
/**
Initializer
- parameter frame: The frame
- parameter images: An array of images that are going to be displayed
- returns: an AZExpandableIconListView
*/
/////////////////////////////////////////////////////////////////////////////
public init(frame: CGRect, views: [(UILabel, UIImageView)], imageSpacing: CGFloat) {
let bounds = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
scrollView = UIScrollView(frame: bounds)
scrollView.isScrollEnabled = true
scrollView.bounces = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
contentView = UIView(frame: bounds)
super.init(frame: bounds)
self.imageSpacing = imageSpacing
self.clipsToBounds = true
let onTapView = UITapGestureRecognizer(target: self, action: #selector(AZExpandableIconListView.adjustView))
onTapView.numberOfTapsRequired = 2
scrollView.addGestureRecognizer(onTapView)
var tag = views.count - 1
// Add the participantViews
// Reverse the array of incoming participants so that the User is the last one added (is on top)
for (label, image) in views.reversed() {
image.frame = CGRect(x: 0, y: 0, width: imageWidth*0.5, height: imageWidth*0.5)
image.tag = tag
if tag > 9 { image.alpha = 0.0 } // if there are more than 10 participants, make the 11th - Nth participant invisible for now
self.icons.append((label, image))
contentView.addSubview(image)
tag -= 1
}
// Reverse again so that constraints match in the future
self.icons = self.icons.reversed()
self.addSubview(scrollView)
scrollView.addSubview(contentView)
// constraints for scrollView and contentView
self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0))
scrollView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: scrollView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
updateConstraints()
updateContentSize()
}
/////////////////////////////////////////////////////////////////////////////
public func adjustView(){
updateSpacingConstraints()
isExpanded = !isExpanded
displayNames()
updateContentSize()
UIView.animate(withDuration: 0.4,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.3,
options: UIViewAnimationOptions(),
animations: { [weak self] in self?.layoutIfNeeded() },
completion: { [weak self] finished in
if let weakself = self {
if weakself.isExpanded { weakself.onExpanded?() }
else { weakself.onCollapsed?() }
}
})
}
/////////////////////////////////////////////////////////////////////////////
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/////////////////////////////////////////////////////////////////////////////
open override func updateConstraints() {
super.updateConstraints()
if isSetupFinished == false {
setupInitialLayout()
}
}
/////////////////////////////////////////////////////////////////////////////
fileprivate func setupInitialLayout() {
var layoutConstraints:[NSLayoutConstraint] = []
let hasMiddle = icons.count % 2 == 0 ? false : true
let middleIndex = hasMiddle ? ((icons.count - 1) / 2) : (icons.count / 2)
let avatarYoffset = -(self.frame.height / 8)
var previousRightView = icons[middleIndex].1
var previousLeftView = hasMiddle ? icons[middleIndex].1 : icons[middleIndex - 1].1
// Add constraints for middle Avatar(s)
if hasMiddle {
let middleView = icons[middleIndex].1
layoutConstraints.append(NSLayoutConstraint(item: middleView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset))
layoutConstraints.append(NSLayoutConstraint(item: middleView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
layoutConstraints.append(NSLayoutConstraint(item: middleView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
self.middleItemSpacingConstraint = NSLayoutConstraint(item: middleView, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: needsToAdjust ? realContractedCenterOffset : 1)
layoutConstraints.append(self.middleItemSpacingConstraint!)
}
else {
let middleRightView = icons[middleIndex].1
let middleLeftView = icons[middleIndex - 1].1
layoutConstraints.append(NSLayoutConstraint(item: middleRightView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset))
layoutConstraints.append(NSLayoutConstraint(item: middleRightView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
layoutConstraints.append(NSLayoutConstraint(item: middleRightView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
self.rightMiddleItemSpacingConstraint = NSLayoutConstraint(item: middleRightView, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: needsToAdjust ? realContractedCenterOffset + (imageWidth / 10) : imageWidth / 10)
layoutConstraints.append(NSLayoutConstraint(item: middleLeftView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset))
layoutConstraints.append(NSLayoutConstraint(item: middleLeftView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
layoutConstraints.append(NSLayoutConstraint(item: middleLeftView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
self.leftMiddleItemSpacingConstraint = NSLayoutConstraint(item: middleLeftView, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: needsToAdjust ? realContractedCenterOffset - (imageWidth / 10) : -(imageWidth / 10))
layoutConstraints.append(self.rightMiddleItemSpacingConstraint!)
layoutConstraints.append(self.leftMiddleItemSpacingConstraint!)
}
// Add constraints iteratively for the non-middle Avatars
for index in (middleIndex + 1) ..< icons.count {
let distanceFromCenter = index - middleIndex
let rightView = icons[index].1
let leftView = hasMiddle ? icons[middleIndex - distanceFromCenter].1 : icons[(middleIndex - 1) - distanceFromCenter].1
// Proportion constraints
layoutConstraints.append(NSLayoutConstraint(item: rightView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset))
layoutConstraints.append(NSLayoutConstraint(item: rightView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
layoutConstraints.append(NSLayoutConstraint(item: rightView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
layoutConstraints.append(NSLayoutConstraint(item: leftView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: avatarYoffset))
layoutConstraints.append(NSLayoutConstraint(item: leftView, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
layoutConstraints.append(NSLayoutConstraint(item: leftView, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 0.6, constant: 0))
// Spacing constraints
self.rightItemSpacingConstraints.append(NSLayoutConstraint(item: rightView, attribute: .left, relatedBy: .equal, toItem: previousRightView, attribute: .right, multiplier: 1, constant: -imageWidth*0.8))
self.leftItemSpacingConstraints.append(NSLayoutConstraint(item: leftView, attribute: .right, relatedBy: .equal, toItem: previousLeftView, attribute: .left, multiplier: 1, constant: imageWidth*0.8))
previousRightView = rightView
previousLeftView = leftView
}
layoutConstraints.append(contentsOf: rightItemSpacingConstraints)
layoutConstraints.append(contentsOf: leftItemSpacingConstraints)
contentView.addConstraints(layoutConstraints)
isSetupFinished = true
}
/////////////////////////////////////////////////////////////////////////////
fileprivate func displayNames() {
if (isExpanded) {
var layoutConstraints: [NSLayoutConstraint] = []
for icon in self.icons {
let label = icon.0
let image = icon.1
image.addSubview(label)
layoutConstraints.append(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: image, attribute: .centerX, multiplier: 1, constant: 0))
layoutConstraints.append(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: image, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: imageWidth*0.75))
layoutConstraints.append(NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: image, attribute: .width, multiplier: 1.50, constant: 1))
layoutConstraints.append(NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: image, attribute: .height, multiplier: 0.25, constant: 1))
image.addConstraints(layoutConstraints)
layoutConstraints = []
}
}
else { for icon in self.icons { icon.0.removeFromSuperview() } }
}
/**
Update the contraints of image spacing based on whether the images are expanded or not.
Update content size of the containing UIScrollView.
*/
/////////////////////////////////////////////////////////////////////////////
fileprivate func updateSpacingConstraints() {
// Spacing constraints for expanding
if !isExpanded {
let width = stretchedImageWidth < scrollView.frame.width ? scrollView.frame.width : stretchedImageWidth
contentView.frame = CGRect(x: scrollView.frame.origin.x, y: scrollView.frame.origin.y, width: width, height: scrollView.frame.height)
scrollView.contentSize = CGSize(width: contentView.frame.width, height: scrollView.frame.height)
if let midConstraint = self.middleItemSpacingConstraint {
if needsToAdjust { midConstraint.constant = 1 }
}
for constraint in rightItemSpacingConstraints { constraint.constant = imageSpacing }
for constraint in leftItemSpacingConstraints { constraint.constant = -imageSpacing }
if let midRightConstraint = self.rightMiddleItemSpacingConstraint, let midLeftConstraint = self.leftMiddleItemSpacingConstraint {
midRightConstraint.constant = (0.1 * imageWidth) + imageSpacing
midLeftConstraint.constant = -((0.1 * imageWidth) + imageSpacing)
}
}
// Spacing constraints for contracting
else {
contentView.frame = CGRect(x: scrollView.frame.origin.x, y: scrollView.frame.origin.y, width: scrollView.frame.width, height: scrollView.frame.height)
scrollView.contentSize = CGSize(width: contentView.frame.width, height: scrollView.frame.height)
if let midConstraint = self.middleItemSpacingConstraint {
if needsToAdjust { midConstraint.constant = realContractedCenterOffset }
}
for constraint in rightItemSpacingConstraints { constraint.constant = -imageWidth*0.8 }
for constraint in leftItemSpacingConstraints { constraint.constant = imageWidth*0.8 }
if let midRightConstraint = self.rightMiddleItemSpacingConstraint, let midLeftConstraint = self.leftMiddleItemSpacingConstraint {
midRightConstraint.constant = needsToAdjust ? realContractedCenterOffset + (imageWidth / 10) : imageWidth / 10
midLeftConstraint.constant = needsToAdjust ? realContractedCenterOffset - (imageWidth / 10) : -(imageWidth / 10)
}
}
// Make participants visible / invisible appropriately
for (_, image) in self.icons { if image.tag > 9 { image.alpha = isExpanded ? 0.0 : 1.0 } }
}
/**
Update the content size of the containing UIScrollView based on whether the images are expanded or not.
*/
/////////////////////////////////////////////////////////////////////////////
fileprivate func updateContentSize() {
let width = isExpanded ? stretchedImageWidth : contractedImageWidth
scrollView.contentSize = CGSize(width: width, height: scrollView.frame.height)
}
/**
Convert the passed in UIImage to a round UIImageView, plus add a white border around it.
- parameter image: The icon
- parameter frame: The container's frame of the image
- returns: A circular UIImageView
*/
/////////////////////////////////////////////////////////////////////////////
fileprivate func buildCircularIconFrom(_ image:UIImage, containerFrame frame:CGRect) -> UIImageView {
let newframe = CGRect(x: 0, y: 0, width: imageWidth, height: imageWidth)
let imageView = UIImageView(frame:newframe)
imageView.image = image
let borderLayer = CALayer()
let borderFrame = CGRect(x: -1, y: -1, width: newframe.width + 2, height: newframe.height + 2)
borderLayer.backgroundColor = UIColor.clear.cgColor
borderLayer.frame = borderFrame
borderLayer.cornerRadius = newframe.width * 0.5
borderLayer.borderWidth = 2.0
borderLayer.borderColor = UIColor.clear.cgColor
borderLayer.masksToBounds = false
imageView.layer.addSublayer(borderLayer)
imageView.clipsToBounds = false
imageView.layer.cornerRadius = newframe.width * 0.5
return imageView
}
}
| c62ce7b2d7af484818c57a92014a3017 | 54.835962 | 300 | 0.641243 | false | false | false | false |
DianQK/LearnRxSwift | refs/heads/master | LearnRxSwift/Rx.playground/Pages/Transforming.xcplaygroundpage/Contents.swift | mit | 1 | //: [上一节](@previous) - [目录](Index)
import RxSwift
/*:
## 变换 Observables
下面的这些操作符可以变换一个序列发射的值。这样我们的序列功能就强大了许多,创建,然后进行变换。甚至这里就类似于一条生产线。先做出一个原型,然后再进行各种加工,最后出我们想要的成品。
*/
/*:
### `map`
map 就是用你指定的方法去**变换每一个值**,这里非常类似 Swift 中的 map ,特别是对 SequenceType 的操作,几乎就是一个道理。一个一个的改变里面的值,并返回一个新的 functor 。
![map](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/map.png)
*/
let disposeBag = DisposeBag()
let originalSequence = Observable.of(1, 2, 3)
originalSequence
.map { number in
number * 2
}
.subscribe { print($0) }
.addDisposableTo(disposeBag)
/*:
#### `mapWithIndex`
这是一个和 map 一起的操作,唯一的不同就是我们有了 **index** ,注意第一个是序列发射的值,第二个是 index 。
*/
originalSequence
.mapWithIndex { number, index in
number * index
}
.subscribe { print($0) }
.addDisposableTo(disposeBag)
/*:
### `flatMap`
将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。
![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png)
我们来看这个有趣的例子:
*/
let sequenceInt = Observable.of(1, 2, 3)
let sequenceString = Observable.of("A", "B", "C", "D", "E", "F", "--")
sequenceInt
.flatMap { (x:Int) -> Observable<String> in
print("from sequenceInt \(x)")
return sequenceString
}
.subscribe {
print($0)
}
.addDisposableTo(disposeBag)
/*:
可以看到每当 `sequenceInt` 发射一个值,最终订阅者都会依次收到 `A` `B` `C` `D` `E` `F` `--` ,但不会收到 Complete 。也就是说我们将三次转换的三个序列都压在了一起。只是这里的变换是每当发射一个整数,就发射一系列的字母和符号 `--` 。这很有意思,比简单的 map 强大很多。当你遇到数据异步变换或者更复杂的变换,记得尝试 `flatMap` 。比如像这样:
Observable.of(1, 2, 4)
.flatMap { fetch($0) }
.subscribe {
print($0)
}
.addDisposableTo(disposeBag)
*/
/*:
#### `flatMapFirst`
将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。
![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png)
*/
/*:
#### `flatMapLatest`
将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。
![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png)
*/
/*:
#### `flatMapIndex`
将一个序列发射的值**转换成序列**,然后将他们压平到一个序列。这也类似于 SequenceType 中的 `flatMap` 。
![flatMap](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png)
*/
/*:
### `scan`
应用一个 accumulator (累加) 的方法遍历一个序列,然后**返回累加的结果**。此外我们还需要一个初始的累加值。实时上这个操作就类似于 Swift 中的 `reduce` 。
![scan](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/scan.png)
*/
let sequenceToSum = Observable.of(0, 1, 2, 3, 4, 5)
sequenceToSum
.scan(0) { acum, elem in
acum + elem
}
.subscribe {
print($0)
}.addDisposableTo(disposeBag)
/*:
图片就对应了这段代码的意思,每接收到一个值,就和上一次的累加值加起来并发射。这是一个很有趣的功能,你可以参见一下官方的计算器 Demo ,很有意思。记得,这里的 `scan` 以及 `reduce` 可不仅仅是只能用来累加,这是一个遍历所有值得过程,所以你可以在这做任何你想做的操作。
*/
/*:
### `reduce`
和 `scan` 非常相似,唯一的不同是, `reduce` 会在序列结束时才发射最终的累加值。就是说,最终**只发射一个最终累加值**
*/
sequenceToSum
.reduce(0) { acum, elem in
acum + elem
}
.subscribe {
print($0)
}.addDisposableTo(disposeBag)
/*:
### `buffer`
在特定的线程,定期定量收集序列发射的值,然后发射这些的值的集合。
![buffer](http://reactivex.io/documentation/operators/images/Buffer.png)
*/
sequenceToSum
.buffer(timeSpan: 5, count: 2, scheduler: MainScheduler.instance)
.subscribe {
print($0)
}.addDisposableTo(disposeBag)
/*:
### `window`
window 和 buffer 非常类似。唯一的不同就是 window 发射的是序列, buffer 发射一系列值。
![window](http://reactivex.io/documentation/operators/images/window.C.png)
我想这里对比 buffer 的图解就很好理解 window 的行为了。
我们可以看 API 的不同:
/// buffer
public func buffer(timeSpan timeSpan: RxSwift.RxTimeInterval, count: Int, scheduler: SchedulerType) -> RxSwift.Observable<[Self.E]>
/// window
public func window(timeSpan timeSpan: RxSwift.RxTimeInterval, count: Int, scheduler: SchedulerType) -> RxSwift.Observable<RxSwift.Observable<Self.E>>
从返回结果可以看到 `buffer` 返回的序列发射的值是 `[Self.E]` ,而 `window` 是 `RxSwift.Observable<Self.E>` 。
*/
sequenceToSum
.window(timeSpan: 5, count: 2, scheduler: MainScheduler.instance)
.subscribe {
print($0)
}.addDisposableTo(disposeBag)
//: [目录](@Index) - [下一节 >>](@next)
| 33b1155ede832f3b4834be65c1c8e718 | 22.27933 | 205 | 0.695224 | false | false | false | false |
LYM-mg/DemoTest | refs/heads/master | 其他功能/SwiftyDemo/SwiftyDemo/Network/Tool + 普通封装/NetWorkTools+Extension.swift | mit | 1 | //
// NetWorkTools+Extension.swift
// SwiftyDemo
//
// Created by newunion on 2019/4/15.
// Copyright © 2019 firestonetmt. All rights reserved.
// 网络状态判断
import UIKit
import Alamofire
// MARK: -
// MARK: - 判断网络类型
//(与官方风格一致,推荐使用)
enum NetworkStatus {
case noNetWork // 没有网络
case viaWWAN
case viaWWAN2g // 2G
case viaWWAN3g // 3G
case viaWWAN4g // 4G
case wifi // WIFI
case other
}
extension NetWorkTools {
/// 获取网络状态
class func getNetworkStates() -> NetworkStatus? {
guard let object1 = UIApplication.shared.value(forKey: "statusBar") as? NSObject else { return nil }
guard let object2 = object1.value(forKey: "foregroundView") as? UIView else { return nil }
let subviews = object2.subviews
var status = NetworkStatus.noNetWork
for child in subviews {
if child.isKind(of: NSClassFromString("UIStatusBarDataNetworkItemView")!) {
// 获取到状态栏码
guard let networkType = child.value(forKey: "dataNetworkType") as? Int else { return nil }
switch (networkType) {
case 0: // 无网模式
status = NetworkStatus.noNetWork;
case 1: // 2G模式
status = NetworkStatus.viaWWAN2g;
case 2: // 3G模式
status = NetworkStatus.viaWWAN3g;
case 3: // 4G模式
status = NetworkStatus.viaWWAN4g;
case 5: // WIFI模式
status = NetworkStatus.wifi;
default:
break
}
}
}
// 返回网络类型
return status;
}
// MARK: - global function
///Alamofire监控网络,只能调用一次监听一次
func AlamofiremonitorNet(result: @escaping (NetworkStatus) -> Void) {
let manager = NetworkReachabilityManager(host: "www.apple.com")
manager?.listener = { status in
print("网络状态: \(status)")
if status == .reachable(.ethernetOrWiFi) { //WIFI
result(.wifi)
} else if status == .reachable(.wwan) { // 蜂窝网络
result(.viaWWAN)
} else if status == .notReachable { // 无网络
result(.noNetWork)
} else { // 其他
result(.other)
}
}
manager?.startListening()//开始监听网络
}
//Alamofire监控网络,只能调用一次监听一次
func NetWorkIsReachable() -> Bool {
let manager = NetworkReachabilityManager(host: "www.apple.com")
manager?.startListening()//开始监听网络
return manager?.isReachable ?? false;
}
}
| 4f84de87ce5819155924ff6d66dc1be7 | 30.309524 | 108 | 0.546008 | false | false | false | false |
DrGo/LearningSwift | refs/heads/master | PLAYGROUNDS/LSB_D003_NamedParameters.playground/section-2.swift | gpl-3.0 | 2 | import UIKit
/*
// Named Parameters
//
// Based on:
// https://skillsmatter.com/skillscasts/6142-swift-beauty-by-default
/===================================*/
/*------------------------------------/
// Functions: Unnamed
//
// Looks like C
/------------------------------------*/
func add(x: Int, y: Int) -> Int {
return x + y
}
add(1, 2)
/*------------------------------------/
// Methods: First is Unnamed,
// Rest Named
//
// Because of Objective-C
/------------------------------------*/
class Adder {
class func addX(x:Int, y:Int) -> Int {
return x + y
}
func addX(x: Int, y:Int) -> Int {
return x + y
}
}
Adder.addX(1, y: 2)
Adder().addX(1, y: 2)
/*------------------------------------/
// Initializer: Named
//
// Because of Objective-C
/------------------------------------*/
class Rect {
var x, y, width, height: Double
init(x: Double, y: Double, width: Double, height: Double) {
self.x = x
self.y = y
self.width = width
self.height = height
}
}
Rect(x: 0, y: 0, width: 100, height: 100)
/*-----------------------------------------/
// Parameters with default value: Named
//
// Makes optional parameter clearer
/-----------------------------------------*/
func greeting(name: String, yell: Bool = false) -> String {
let greet = "Hello, \(name)"
return yell ? greet.uppercaseString : greet
}
greeting("Jim")
greeting("Jim", yell: true)
| 97fccfc199d23b6aa6f685d01fcc503a | 18.066667 | 69 | 0.45035 | false | false | false | false |
wilfreddekok/Antidote | refs/heads/master | Antidote/HelperFunctions.swift | mpl-2.0 | 1 | // 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 Foundation
func isAddressString(string: String) -> Bool {
let nsstring = string as NSString
if nsstring.length != Int(kOCTToxAddressLength) {
return false
}
let validChars = NSCharacterSet(charactersInString: "1234567890abcdefABCDEF")
let components = nsstring.componentsSeparatedByCharactersInSet(validChars)
let leftChars = components.joinWithSeparator("")
return leftChars.isEmpty
}
| 68e8aca131aab1cb9c532c54727c6229 | 32.473684 | 81 | 0.735849 | false | false | false | false |
yakaolife/TrackLocations | refs/heads/master | Example/TrackLocations/ViewController.swift | mit | 1 | //
// ViewController.swift
// TrackLocations
//
// Created by yakaolife@gmail.com on 07/17/2017.
// Copyright (c) 2017 yakaolife@gmail.com. All rights reserved.
//
import UIKit
import TrackLocations
class ViewController: UIViewController {
var locations : [Location]?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Any call to Tracker will trigger asking user for location service permission
//Set up the callbacks, depend on applications
Tracker.enterRegionCallback = enterLocation(_:)
Tracker.trackRegionErrorCallback = onErrorTracking(_:_:)
print("Download a list of locations")
Tracker.load(requestURL: "https://mylocations-cc913.firebaseio.com/testing.json") { (success, locations, error) in
print("Success: \(success)")
self.locations = locations
}
}
func enterLocation(_ location: Location){
print("Enter \(location.name)!")
if UIApplication.shared.applicationState != .active{
//create notification
let note = UILocalNotification()
note.alertBody = "Entering \(location.name)"
UIApplication.shared.presentLocalNotificationNow(note)
}
}
func onErrorTracking(_ location: Location?,_ error: Error){
var name = "Unknown location"
if let location = location{
name = location.name
}
print("Tracking \(name) results in error: \(error)")
}
@IBAction func trackLocations(_ sender: UIButton) {
for loc in self.locations!{
print(loc)
let result = Tracker.track(location: loc)
switch(result){
case TrackLocationsError.NoError:
print("Successfully add \(loc.name) to track")
default:
print("Error: \(result)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 9a47d6d110042302eedf487cb13a1fe7 | 28.813333 | 122 | 0.586315 | false | false | false | false |
2briancox/ioscreator | refs/heads/master | IOS8SwiftScreenEdgePanGesturesTutorial/IOS8SwiftScreenEdgePanGesturesTutorial/ViewController.swift | mit | 40 | //
// ViewController.swift
// IOS8SwiftScreenEdgePanGesturesTutorial
//
// Created by Arthur Knopper on 13/01/15.
// Copyright (c) 2015 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
var screenEdgeRecognizer: UIScreenEdgePanGestureRecognizer!
var currentRadius:CGFloat = 0.0
func rotateBall(sender: UIScreenEdgePanGestureRecognizer) {
if sender.state == .Ended {
if self.currentRadius==360.0 {
self.currentRadius=0.0
}
UIView.animateWithDuration(1.0, animations: {
self.currentRadius += 90.0
self.imageView.transform = CGAffineTransformMakeRotation((self.currentRadius * CGFloat(M_PI)) / 180.0)
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
screenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self,
action: "rotateBall:")
screenEdgeRecognizer.edges = .Left
view.addGestureRecognizer(screenEdgeRecognizer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 9686ada2f9571b6c115def8d877915c2 | 25.704545 | 110 | 0.707234 | false | false | false | false |
steelwheels/KiwiComponents | refs/heads/master | Source/Compiler/KMLinkEdgePass.swift | lgpl-2.1 | 1 | /**
* @file KMLinkEdgePass.swift
* @brief Define KMLinkEdgePass class
* @par Copyright
* Copyright (C) 2017 Steel Wheels Project
*/
import KiwiControls
import KiwiEngine
import Canary
import JavaScriptCore
import Foundation
public class KMLinkEdgePass: KMPass
{
public func linkEdge(rootView root: KMStackView) -> Bool
{
linkEdge(component: root)
return errors.count == 0
}
private func linkEdge(component comp: KMComponentProtocol)
{
/* Check self notations */
for notation in comp.notations {
switch notation.value {
case .PrimitiveValue(_), .ClassValue(_, _), .EventMethodValue(_, _), .ConnectionValue(_, _):
break // Nothing have to do
case .ListenerMethodValue(let type, let exps, _):
let property = notation.identifier
linkEdge(component: comp, property: property, type: type, pathExpressions: exps)
}
}
/* Check sub components */
if let container = comp as? KMContainerProtocol {
for subcomp in container.subComponents {
linkEdge(component: subcomp)
}
}
}
private func linkEdge(component comp: KMComponentProtocol, property prop: String, type valtype: CNValueType, pathExpressions pathexps: Array<CNPathExpression>)
{
let dstptr = KMPointer(component: comp, propertyName: prop)
for exp in pathexps {
let (err0, ptr0) = KMPointer.make(component: comp, expression: exp)
switch err0 {
case .NoError:
linkEdges(fromPointer: ptr0!, toPointer: dstptr, type: valtype, pathExpression: exp)
default:
addError(error: err0)
}
}
}
private func linkEdges(fromPointer fromptr: KMPointer, toPointer toptr: KMPointer, type typ: CNValueType, pathExpression exp: CNPathExpression)
{
if checkExistentLink(fromPointer: fromptr, toPointer: toptr, pathExpression: exp) {
return
}
/* Allocate listener */
let fromdesc = fromptr.description
let todesc = toptr.description
console.print(string: "/* Add trigger edge: from \(fromdesc) to \(todesc) */\n")
let fromtable = fromptr.pointedPropertyTable
let fromname = fromptr.propertyName
let totable = toptr.pointedPropertyTable
let toname = toptr.propertyName
//let totrigger = totable.get(toname + "_callback")
//let tocomp = toptr.component
fromtable.addListener(property: fromname, listener: {
(Any) -> Void in
totable.set(toname + "_trigger", JSValue(bool: true, in: self.context))
})
}
private func checkExistentLink(fromPointer fromptr: KMPointer, toPointer toptr: KMPointer, pathExpression exp: CNPathExpression) -> Bool
{
let fromnode = fromptr.pointedNode
let tonode = toptr.pointedNode
let (isconnected, nodes) = CNGraph.isConnected(from: tonode, to: fromnode)
if isconnected {
let err = KMError.LoopDetectError(path: exp, nodes: nodes)
addError(error: err)
return true
} else {
/* Update graph by linking edge */
let newedge = graph.allocateEdge()
CNGraph.link(from: fromnode, to: tonode, by: newedge)
return false
}
}
}
| 6c8a8d103bca8746750641d5d0a2cbf6 | 29.474227 | 160 | 0.716847 | false | false | false | false |
leotumwattana/WWC-Animations | refs/heads/master | WWC-Animations/Circle.swift | bsd-3-clause | 1 | //
// Circle.swift
// WWC-Animations
//
// Created by Leo Tumwattana on 27/5/15.
// Copyright (c) 2015 Innovoso Ltd. All rights reserved.
//
import UIKit
@IBDesignable class Circle: UIView {
// ==================
// MARK: - Properties
// ==================
@IBInspectable var cornerRadius:CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
clipsToBounds = cornerRadius > 0
}
}
var tap:UITapGestureRecognizer!
var longPress:UILongPressGestureRecognizer!
// ============
// MARK: - Init
// ============
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
tap = UITapGestureRecognizer(target: self, action: "tapped:")
addGestureRecognizer(tap)
longPress = UILongPressGestureRecognizer(target: self, action: "longPressed:")
addGestureRecognizer(longPress)
}
// ======================
// MARK: - Event Handlers
// ======================
func tapped(tap:UITapGestureRecognizer) {
}
func longPressed(longPressed:UILongPressGestureRecognizer) {
}
}
| e52344974e4cadfed859f74ccb1ab35f | 21.508475 | 86 | 0.542922 | false | false | false | false |
Allow2CEO/browser-ios | refs/heads/master | Client/Frontend/Widgets/SnackBar.swift | mpl-2.0 | 1 | /* 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 Foundation
import SnapKit
import Shared
class SnackBarUX {
static var MaxWidth: CGFloat = 400
}
/**
* A specialized version of UIButton for use in SnackBars. These are displayed evenly
* spaced in the bottom of the bar. The main convenience of these is that you can pass
* in a callback in the constructor (although these also style themselves appropriately).
*
*``SnackButton(title: "OK", { _ in print("OK", terminator: "\n") })``
*/
class SnackButton : UIButton {
let callback: (_ bar: SnackBar) -> Void
fileprivate var bar: SnackBar!
/**
* An image to show as the background when a button is pressed. This is currently a 1x1 pixel blue color
*/
lazy var highlightImg: UIImage = {
let size = CGSize(width: 1, height: 1)
return UIImage.createWithColor(size, color: BraveUX.Blue.withAlphaComponent(0.2))
}()
init(title: String, accessibilityIdentifier: String, callback: @escaping (_ bar: SnackBar) -> Void) {
self.callback = callback
super.init(frame: CGRect.zero)
setTitle(title, for: .normal)
titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultStandardFontBold
setBackgroundImage(highlightImg, for: .highlighted)
setTitleColor(UIConstants.HighlightText, for: .highlighted)
addTarget(self, action: #selector(SnackButton.onClick), for: .touchUpInside)
self.accessibilityIdentifier = accessibilityIdentifier
}
override init(frame: CGRect) {
self.callback = { bar in }
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func onClick() {
callback(bar)
}
}
/**
* Presents some information to the user. Can optionally include some buttons and an image. Usage:
*
* ``let bar = SnackBar(text: "This is some text in the snackbar.",
* img: UIImage(named: "bookmark"),
* buttons: [
* SnackButton(title: "OK", { _ in print("OK", terminator: "\n") }),
* SnackButton(title: "Cancel", { _ in print("Cancel", terminator: "\n") }),
* SnackButton(title: "Maybe", { _ in print("Maybe", terminator: "\n") })
* ]
* )``
*/
class SnackBar: UIView {
let imageView: UIImageView
let textLabel: UILabel
let contentView: UIView
let backgroundView: UIView
let buttonsView: Toolbar
fileprivate var buttons = [SnackButton]()
// The Constraint for the bottom of this snackbar. We use this to transition it
var bottom: Constraint?
convenience init(text: String, img: UIImage?, buttons: [SnackButton]?) {
var attributes = [String: AnyObject]()
attributes[NSFontAttributeName] = DynamicFontHelper.defaultHelper.DefaultMediumFont
attributes[NSBackgroundColorAttributeName] = UIColor.clear
let attrText = NSAttributedString(string: text, attributes: attributes)
self.init(attrText: attrText, img: img, buttons: buttons)
}
init(attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) {
imageView = UIImageView()
textLabel = UILabel()
contentView = UIView()
buttonsView = Toolbar()
backgroundView = UIView()
backgroundView.backgroundColor = UIColor(rgb: 0xe8e8e8)
super.init(frame: CGRect.zero)
imageView.image = img
textLabel.attributedText = attrText
if let buttons = buttons {
for button in buttons {
addButton(button)
}
}
setup()
}
fileprivate override init(frame: CGRect) {
imageView = UIImageView()
textLabel = UILabel()
contentView = UIView()
buttonsView = Toolbar()
backgroundView = UIView()
backgroundView.backgroundColor = UIColor(rgb: 0xe8e8e8)
super.init(frame: frame)
}
fileprivate func setup() {
textLabel.backgroundColor = nil
addSubview(backgroundView)
addSubview(contentView)
contentView.addSubview(imageView)
contentView.addSubview(textLabel)
addSubview(buttonsView)
self.backgroundColor = UIColor.clear
buttonsView.drawTopBorder = true
buttonsView.drawBottomBorder = false
buttonsView.drawSeperators = false
imageView.contentMode = UIViewContentMode.left
textLabel.font = DynamicFontHelper.defaultHelper.DefaultStandardFont
textLabel.textAlignment = .center
textLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
textLabel.numberOfLines = 0
textLabel.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let imageWidth: CGFloat
if let img = imageView.image {
imageWidth = img.size.width + UIConstants.DefaultPadding * 2
} else {
imageWidth = 0
}
self.textLabel.preferredMaxLayoutWidth = contentView.frame.width - (imageWidth + UIConstants.DefaultPadding)
super.layoutSubviews()
}
/**
* Called to check if the snackbar should be removed or not. By default, Snackbars persist forever.
* Override this class or use a class like CountdownSnackbar if you want things expire
* - returns: true if the snackbar should be kept alive
*/
func shouldPersist(_ browser: Browser) -> Bool {
return true
}
override func updateConstraints() {
super.updateConstraints()
backgroundView.snp.remakeConstraints { make in
make.bottom.left.right.equalTo(self)
// Offset it by the width of the top border line so we can see the line from the super view
make.top.equalTo(self).offset(1)
}
contentView.snp.remakeConstraints { make in
make.top.left.right.equalTo(self).inset(UIEdgeInsetsMake(UIConstants.DefaultPadding, UIConstants.DefaultPadding, UIConstants.DefaultPadding, UIConstants.DefaultPadding))
}
if let img = imageView.image {
imageView.snp.remakeConstraints { make in
make.left.centerY.equalTo(contentView)
// To avoid doubling the padding, the textview doesn't have an inset on its left side.
// Instead, it relies on the imageView to tell it where its left side should be.
make.width.equalTo(img.size.width + UIConstants.DefaultPadding)
make.height.equalTo(img.size.height + UIConstants.DefaultPadding)
}
} else {
imageView.snp.remakeConstraints { make in
make.width.height.equalTo(0)
make.top.left.equalTo(self)
make.bottom.lessThanOrEqualTo(contentView.snp.bottom)
}
}
textLabel.snp.remakeConstraints { make in
make.top.equalTo(contentView)
make.left.equalTo(self.imageView.snp.right)
make.trailing.equalTo(contentView)
make.bottom.lessThanOrEqualTo(contentView.snp.bottom)
}
buttonsView.snp.remakeConstraints { make in
make.top.equalTo(contentView.snp.bottom).offset(UIConstants.DefaultPadding)
make.bottom.equalTo(self.snp.bottom)
make.left.right.equalTo(self)
if self.buttonsView.subviews.count > 0 {
make.height.equalTo(UIConstants.SnackbarButtonHeight)
} else {
make.height.equalTo(0)
}
}
}
var showing: Bool {
return alpha != 0 && self.superview != nil
}
/**
* Helper for animating the Snackbar showing on screen.
*/
func show() {
alpha = 1
bottom?.update(offset: 0)
}
/**
* Helper for animating the Snackbar leaving the screen.
*/
func hide() {
alpha = 0
var h = frame.height
if h == 0 {
h = UIConstants.ToolbarHeight
}
bottom?.update(offset: h)
}
fileprivate func addButton(_ snackButton: SnackButton) {
snackButton.bar = self
buttonsView.addButtons([snackButton])
buttonsView.setNeedsUpdateConstraints()
}
}
/**
* A special version of a snackbar that persists for at least a timeout. After that
* it will dismiss itself on the next page load where this tab isn't showing. As long as
* you stay on the current tab though, it will persist until you interact with it.
*/
class TimerSnackBar: SnackBar {
fileprivate var prevURL: URL? = nil
fileprivate var timer: Timer? = nil
fileprivate var timeout: TimeInterval
init(timeout: TimeInterval = 10, attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) {
self.timeout = timeout
super.init(attrText: attrText, img: img, buttons: buttons)
}
override init(frame: CGRect) {
self.timeout = 0
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func show() {
self.timer = Timer(timeInterval: timeout, target: self, selector: #selector(TimerSnackBar.SELTimerDone), userInfo: nil, repeats: false)
RunLoop.current.add(self.timer!, forMode: RunLoopMode.defaultRunLoopMode)
super.show()
}
@objc
func SELTimerDone() {
self.timer = nil
}
override func shouldPersist(_ browser: Browser) -> Bool {
if !showing {
return timer != nil
}
return super.shouldPersist(browser)
}
}
| aaa385c4106cca5ee984c62e46fceb2f | 32.859589 | 181 | 0.639527 | false | false | false | false |
TonnyTao/HowSwift | refs/heads/master | Funny Swift.playground/Pages/subscript_dic.xcplaygroundpage/Contents.swift | mit | 1 | import Foundation
extension Dictionary {
subscript(input: [Key]) -> [Value] {
get {
var result = [Value]()
result.reserveCapacity(input.count)
for key in input {
if let value = self[key] {
result.append(value)
}
}
return result
}
set {
assert(input.count == newValue.count, "not supported")
for (index, key) in input.enumerated() {
self[key] = newValue[index]
}
}
}
}
var dic = ["a": "1", "b":"2", "c": "3"]
dic[["a", "c"]]
dic[["a", "c"]] = ["0", "2"]
print(dic)
| 0ae10fad1dc85da182b69cb643fa45fd | 20.741935 | 66 | 0.4273 | false | false | false | false |
obdev/SocketWrapper | refs/heads/master | SocketWrapper/Extensions/String+UnsafeBufferPointer.swift | mit | 1 | //
// String+UnsafeBufferPointer.swift
// SocketWrapper
//
// Created by Christian Ludl on 2016-02-11.
// Copyright © 2016 Objective Development. All rights reserved.
//
import Foundation
extension String {
/// Initializes a `String` from a sequence of `NUL`-terminated `UTF8.CodeUnit` as a `WithUnsafeBufferPointerType`.
init?<T: WithUnsafeBufferPointerType where T.Element == UTF8.CodeUnit>(nulTerminatedUTF8: T) {
guard let string = nulTerminatedUTF8.withUnsafeBufferPointer({ String(UTF8String: UnsafePointer($0.baseAddress))}) else {
return nil
}
self = string
}
/// Initializes a `String` from a sequence of `UTF8.CodeUnit`s that conforms to `WithUnsafeBufferPointerType`. A `NUL`-terminator is not required.
init?<T: WithUnsafeBufferPointerType where T.Element == UTF8.CodeUnit>(UTF8CodeUnits: T) {
let string = UTF8CodeUnits.withUnsafeBufferPointer { NSString(bytes: $0.baseAddress, length: $0.count, encoding: NSUTF8StringEncoding) }
if let string = string as? String {
self = string
} else {
return nil
}
}
/// Initializes a `String` from any sequence of `UTF8.CodeUnit`s. A `NUL`-terminator is not required.
///
/// Note that this initializer may be slow because it must first convert the input sequence to an `Array`.
init?<T: SequenceType where T.Generator.Element == UTF8.CodeUnit>(UTF8CodeUnitSequence: T) {
self.init(UTF8CodeUnits: Array(UTF8CodeUnitSequence))
}
/// Initializes a `String` from a buffer of `UTF8.CodeUnit`. A `NUL`-terminator is not required.
init?(UTF8CodeUnits buffer: UnsafeBufferPointer<UTF8.CodeUnit>) {
if let string = NSString(bytes: buffer.baseAddress, length: buffer.count, encoding: NSUTF8StringEncoding) {
self = string as String
} else {
return nil
}
}
/// Initializes a `String` from a mutable buffer of `UTF8.CodeUnit`. A `NUL`-terminator is not required.
///
/// This is a convenience initializer for when a `UnsafeMutableBufferPointer` exists already. It does not modify the input.
init?(UTF8CodeUnits buffer: UnsafeMutableBufferPointer<UTF8.CodeUnit>) {
self.init(UTF8CodeUnits: UnsafeBufferPointer(start: buffer.baseAddress, count: buffer.count))
}
/// Calls the given closure with a `UnsafeBufferPointer<UTF8.CodeUnit>` to an optionally `NUL`-terminated UTF-8 representation of the `String`.
func withUTF8UnsafeBufferPointer<Result>(includeNulTerminator includeNulTerminator: Bool = true, @noescape f: UnsafeBufferPointer<UTF8.CodeUnit> throws -> Result) rethrows -> Result {
return try nulTerminatedUTF8.withUnsafeBufferPointer { codeUnitBuffer in
let cCharBufferCount = includeNulTerminator ? codeUnitBuffer.count : codeUnitBuffer.count - 1
let cCharBuffer = UnsafeBufferPointer<UTF8.CodeUnit>(start: UnsafePointer(codeUnitBuffer.baseAddress), count: cCharBufferCount)
return try f(cCharBuffer)
}
}
}
/// A common protocol of all array-like types that implement a `withUnsafeBufferPointer()` method.
protocol WithUnsafeBufferPointerType {
associatedtype Element
func withUnsafeBufferPointer<R>(@noescape body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R
}
extension Array: WithUnsafeBufferPointerType {
}
extension ArraySlice: WithUnsafeBufferPointerType {
}
extension ContiguousArray: WithUnsafeBufferPointerType {
}
| a843011d68d481dbc4814a14c3f015ba | 41.914634 | 187 | 0.710429 | false | false | false | false |
shnhrrsn/ImagePalette | refs/heads/master | src/ColorHistogram.swift | apache-2.0 | 1 | //
// ColorHistogram.swift
// ImagePalette
//
// Original created by Google/Android
// Ported to Swift/iOS by Shaun Harrison
//
import Foundation
import UIKit
/**
Class which provides a histogram for RGB values.
*/
public struct ColorHistogram {
/**
An array containing all of the distinct colors in the image.
*/
private(set) public var colors = [Int64]()
/**
An array containing the frequency of a distinct colors within the image.
*/
private(set) public var colorCounts = [Int64]()
/**
Number of distinct colors in the image.
*/
private(set) public var numberOfColors: Int
/**
A new ColorHistogram instance.
:param: Pixels array of image contents
*/
public init(pixels: [Int64]) {
// Sort the pixels to enable counting below
var pixels = pixels
pixels.sort()
// Count number of distinct colors
self.numberOfColors = type(of: self).countDistinctColors(pixels)
// Finally count the frequency of each color
self.countFrequencies(pixels)
}
private static func countDistinctColors(_ pixels: [Int64]) -> Int {
if pixels.count < 2 {
// If we have less than 2 pixels we can stop here
return pixels.count
}
// If we have at least 2 pixels, we have a minimum of 1 color...
var colorCount = 1
var currentColor = pixels[0]
// Now iterate from the second pixel to the end, counting distinct colors
for pixel in pixels {
// If we encounter a new color, increase the population
if pixel != currentColor {
currentColor = pixel
colorCount += 1
}
}
return colorCount
}
private mutating func countFrequencies(_ pixels: [Int64]) {
if pixels.count == 0 {
return
}
var currentColorIndex = 0
var currentColor = pixels[0]
self.colors.append(currentColor)
self.colorCounts.append(1)
if pixels.count == 1 {
// If we only have one pixel, we can stop here
return
}
// Now iterate from the second pixel to the end, population distinct colors
for pixel in pixels {
if pixel == currentColor {
// We’ve hit the same color as before, increase population
self.colorCounts[currentColorIndex] += 1
} else {
// We’ve hit a new color, increase index
currentColor = pixel
currentColorIndex += 1
self.colors.append(currentColor)
self.colorCounts.append(1)
}
}
}
}
| 7944147ce652c729239422d1330c4d81 | 21.300971 | 77 | 0.69003 | false | false | false | false |
fitpay/fitpay-ios-sdk | refs/heads/develop | FitpaySDK/Rest/RestClientCreditCard.swift | mit | 1 | import Foundation
import Alamofire
extension RestClient {
// MARK: - Completion Handlers
/**
Completion handler
- parameter result: Provides collection of credit cards, or nil if error occurs
- parameter error: Provides error object, or nil if no error occurs
*/
public typealias CreditCardsHandler = (_ result: ResultCollection<CreditCard>?, _ error: ErrorResponse?) -> Void
/**
Completion handler
- parameter creditCard: Provides credit card object, or nil if error occurs
- parameter error: Provides error object, or nil if no error occurs
*/
public typealias CreditCardHandler = (_ creditCard: CreditCard?, _ error: ErrorResponse?) -> Void
/**
Completion handler
- parameter pending: Provides pending flag, indicating that transition was accepted, but current status can be reviewed later. Note that CreditCard object is nil in this case
- parameter card?: Provides updated CreditCard object, or nil if pending (Bool) flag is true or if error occurs
- parameter error?: Provides error object, or nil if no error occurs
*/
public typealias CreditCardTransitionHandler = (_ pending: Bool, _ card: CreditCard?, _ error: ErrorResponse?) -> Void
/**
Completion handler
- parameter pending: Provides pending flag, indicating that transition was accepted, but current status can be reviewed later. Note that VerificationMethod object is nil in this case
- parameter verificationMethod: Provides VerificationMethod object, or nil if pending (Bool) flag is true or if error occurs
- parameter error: Provides error object, or nil if no error occurs
*/
public typealias VerifyHandler = (_ pending: Bool, _ verificationMethod: VerificationMethod?, _ error: ErrorResponse?) -> Void
/**
Completion handler
- parameter verificationMethods: Provides VerificationMethods objects, or nil if error occurs
- parameter error: Provides error object, or nil if no error occurs
*/
public typealias VerifyMethodsHandler = (_ verificationMethods: ResultCollection<VerificationMethod>?, _ error: ErrorResponse?) -> Void
/**
Completion handler
- parameter verificationMethod: Provides VerificationMethod object, or nil if error occurs
- parameter error: Provides error object, or nil if no error occurs
*/
public typealias VerifyMethodHandler = (_ verificationMethod: VerificationMethod?, _ error: ErrorResponse?) -> Void
// MARK: - Internal Functions
func createCreditCard(_ url: String, cardInfo: CardInfo, deviceId: String?, completion: @escaping CreditCardHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let strongSelf = self else { return }
guard let headers = headers else {
DispatchQueue.main.async { completion(nil, error) }
return
}
guard let cardJSON = cardInfo.toJSONString() else {
completion(nil, ErrorResponse(domain: RestClient.self, errorCode: nil, errorMessage: "Failed to parse JSON"))
return
}
let jweObject = JWE(.A256GCMKW, enc: .A256GCM, payload: cardJSON, keyId: headers[RestClient.fpKeyIdKey]!)
guard let encrypted = try? jweObject.encrypt(strongSelf.secret), let unwrappedEncrypted = encrypted else {
completion(nil, ErrorResponse(domain: RestClient.self, errorCode: nil, errorMessage: "Failed to encrypt object"))
return
}
var parameters: [String: String] = ["encryptedData": unwrappedEncrypted]
if let deviceId = deviceId {
parameters["deviceId"] = deviceId
}
self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in
guard let strongSelf = self else { return }
guard let resultValue = resultValue else {
completion(nil, error)
return
}
let card = try? CreditCard(resultValue)
card?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey])
card?.client = self
completion(card, error)
}
}
}
func creditCards(_ url: String, excludeState: [String], limit: Int, offset: Int, deviceId: String?, completion: @escaping CreditCardsHandler) {
var parameters: [String: Any] = ["excludeState": excludeState.joined(separator: ","), "limit": limit, "offset": offset]
if let deviceId = deviceId {
parameters["deviceId"] = deviceId
}
makeGetCall(url, parameters: parameters, completion: completion)
}
func getCreditCard(_ url: String, completion: @escaping CreditCardHandler) {
makeGetCall(url, parameters: nil, completion: completion)
}
func updateCreditCard(_ url: String, name: String?, address: Address, completion: @escaping CreditCardHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let strongSelf = self else { return }
guard let headers = headers else {
DispatchQueue.main.async { completion(nil, error) }
return
}
var operations: [[String: String]] = []
var parameters: [String: Any] = [:]
if let name = name {
operations.append(["op": "replace", "path": "/name", "value": name])
}
if let street1 = address.street1 {
operations.append(["op": "replace", "path": "/address/street1", "value": street1])
}
if let street2 = address.street2 {
operations.append(["op": "replace", "path": "/address/street2", "value": street2])
}
if let city = address.city {
operations.append(["op": "replace", "path": "/address/city", "value": city])
}
if let state = address.state {
operations.append(["op": "replace", "path": "/address/state", "value": state])
}
if let postalCode = address.postalCode {
operations.append(["op": "replace", "path": "/address/postalCode", "value": postalCode])
}
if let countryCode = address.countryCode {
operations.append(["op": "replace", "path": "/address/countryCode", "value": countryCode])
}
if let updateJSON = operations.JSONString {
let jweObject = JWE(JWTAlgorithm.A256GCMKW, enc: JWTEncryption.A256GCM, payload: updateJSON, keyId: headers[RestClient.fpKeyIdKey]!)
if let encrypted = try? jweObject.encrypt(strongSelf.secret)! {
parameters["encryptedData"] = encrypted
}
}
self?.makePatchCall(url, parameters: parameters, encoding: JSONEncoding.default, completion: completion)
}
}
func acceptCall(_ url: String, completion: @escaping CreditCardTransitionHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(false, nil, error) }
return
}
self?.restRequest.makeRequest(url: url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in
guard let resultValue = resultValue else {
self?.handleTransitionResponse(error, completion: completion)
return
}
let card = try? CreditCard(resultValue)
card?.client = self
completion(false, card, nil)
}
}
}
func selectVerificationType(_ url: String, completion: @escaping VerifyHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(false, nil, error) }
return
}
self?.restRequest.makeRequest(url: url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in
guard let resultValue = resultValue else {
self?.handleVerifyResponse(error, completion: completion)
return
}
let verificationMethod = try? VerificationMethod(resultValue)
verificationMethod?.client = self
completion(false, verificationMethod, error)
}
}
}
func verify(_ url: String, verificationCode: String, completion: @escaping VerifyHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(false, nil, error) }
return
}
let params = ["verificationCode": verificationCode]
self?.restRequest.makeRequest(url: url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in
guard let resultValue = resultValue else {
self?.handleVerifyResponse(error, completion: completion)
return
}
let verificationMethod = try? VerificationMethod(resultValue)
verificationMethod?.client = self
completion(false, verificationMethod, error)
}
}
}
func activationCall(_ url: String, causedBy: CreditCardInitiator, reason: String, completion: @escaping CreditCardTransitionHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(false, nil, error) }
return
}
let parameters = ["causedBy": causedBy.rawValue, "reason": reason]
self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in
guard let resultValue = resultValue else {
self?.handleTransitionResponse(error, completion: completion)
return
}
let card = try? CreditCard(resultValue)
card?.client = self
completion(false, card, error)
}
}
}
func makeCreditCardDefault(_ url: String, deviceId: String?, completion: @escaping CreditCardTransitionHandler) {
self.prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(false, nil, error) }
return
}
let parameters: [String: Any]? = deviceId != nil ? ["deviceId": deviceId!] : nil
self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: URLEncoding.queryString, headers: headers) { (resultValue, error) in
guard let resultValue = resultValue else {
self?.handleTransitionResponse(error, completion: completion)
return
}
let card = try? CreditCard(resultValue)
card?.client = self
completion(false, card, error)
}
}
}
// MARK: - Private Functions
private func handleVerifyResponse(_ response: ErrorResponse?, completion: @escaping VerifyHandler) {
guard let statusCode = response?.status else {
completion(false, nil, ErrorResponse.unhandledError(domain: RestClient.self))
return
}
switch statusCode {
case 202:
completion(true, nil, nil)
default:
completion(false, nil, response)
}
}
private func handleTransitionResponse(_ response: ErrorResponse?, completion: @escaping CreditCardTransitionHandler) {
guard let statusCode = response?.status else {
completion(false, nil, ErrorResponse.unhandledError(domain: RestClient.self))
return
}
switch statusCode {
case 202:
completion(true, nil, nil)
default:
completion(false, nil, response)
}
}
}
| 3863979d7747a66a5087e999cd552b3d | 44.051724 | 198 | 0.588902 | false | false | false | false |
jstn/IndependentRotation | refs/heads/master | IndependentRotationWithCamera/IndependentRotationWithCamera/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// IndependentRotationWithCamera
//
// Created by Justin Ouellette on 3/1/15.
// Copyright (c) 2015 Justin Ouellette. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var fixedWindow: UIWindow!
var rotatingWindow: UIWindow!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let screenBounds = UIScreen.mainScreen().bounds
let inset: CGFloat = fabs(screenBounds.width - screenBounds.height)
fixedWindow = UIWindow(frame: screenBounds)
fixedWindow.rootViewController = FixedViewController()
fixedWindow.backgroundColor = UIColor.blackColor()
fixedWindow.hidden = false
rotatingWindow = UIWindow(frame: CGRectInset(screenBounds, -inset, -inset))
rotatingWindow.rootViewController = RotatingViewController()
rotatingWindow.backgroundColor = UIColor.clearColor()
rotatingWindow.opaque = false
rotatingWindow.makeKeyAndVisible()
return true
}
}
| 7984b6bcb38293947bac076b3153cb7b | 33.030303 | 128 | 0.724844 | false | false | false | false |
saraheolson/360iDevMin-PokeMongo | refs/heads/master | PokeMongo/PokeMongo/Scenes/GameScene.swift | gpl-3.0 | 1 | //
// GameScene.swift
// PokeMongo
//
// Created by Floater on 8/21/16.
// Copyright © 2016 SarahEOlson. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
// So we can keep track of our monster!
var monster: SKSpriteNode?
// So we can keep track of our ball!
var ball: SKSpriteNode?
// Defines where user touched
var startTouchLocation: CGPoint = CGPoint.zero
var endTouchLocation: CGPoint = CGPoint.zero
override func sceneDidLoad() {
// If we don't already have a monster, create one.
if monster == nil {
createMonster()
}
// Add a ball to the scene
if ball == nil {
createBall()
}
}
// MARK: - Monster functions
func createMonster() {
// Create the monster from an atlas instead of an image
let textureAtlas = SKTextureAtlas(named: "PurpleMonster.atlas")
let spriteArray = [textureAtlas.textureNamed("PurpleMonster1"),
textureAtlas.textureNamed("PurpleMonster2")]
monster = SKSpriteNode(texture: spriteArray[0])
if let monster = self.monster {
monster.name = "monster"
monster.position = CGPoint(x: 0, y: frame.height/2)
monster.zPosition = 2
moveMonster()
// Animate our monster
let animateAction = SKAction.animate(with: spriteArray, timePerFrame: 0.2)
let repeatAnimation = SKAction.repeatForever(animateAction)
monster.run(repeatAnimation)
addChild(monster)
}
}
func moveMonster() {
guard let monster = self.monster else {
return
}
// Moves the monster to the right
let moveRight = SKAction.move(to: CGPoint(x: self.size.width/2,
y: self.size.height/2),
duration: 1.0)
// Moves the monster to the left
let moveLeft = SKAction.move(to: CGPoint(x: -(self.size.width/2),
y: self.size.height/2),
duration: 1.0)
// Groups the left and right actions together
let moveSequence = SKAction.sequence([moveLeft, moveRight])
// Repeats the group of actions forever
let repeatMovesForever = SKAction.repeatForever(moveSequence)
// Runs the repeated group of actions
monster.run(repeatMovesForever)
}
func monsterHit() {
guard let monster = self.monster else {
return
}
// Remove monster from scene
monster.removeAllActions()
monster.removeFromParent()
// Explode our monster
let spark: SKEmitterNode = SKEmitterNode(fileNamed: "SparkParticle")!
spark.position = monster.position
spark.particleColor = UIColor.purple
addChild(spark)
// Create a new monster
self.monster = nil
let waitAction = SKAction.wait(forDuration: 1)
spark.run(waitAction) {
// Display the monster
self.createMonster()
// Remove spark from scene
spark.removeFromParent()
}
}
// MARK: - Touch gesture methods
/**
* Called when a touch event is initiated.
*/
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Record the beginning of the touch event
startTouchLocation = touches.first!.location(in: self)
}
/**
* Called when a touch event moves.
*/
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// Move the ball along with the user's touch gesture
let currentTouchLocation = touches.first!.location(in: self)
if let ball = ball {
ball.position = currentTouchLocation
}
}
/**
* Called when a touch event is ended.
*/
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Record the end of the touch event
endTouchLocation = touches.first!.location(in: self)
// Continue the ball's movement along the same path as the touch gesture
let factor: CGFloat = 50
let vector = CGVector(dx: factor * (endTouchLocation.x - startTouchLocation.x), dy: factor * (endTouchLocation.y - startTouchLocation.y))
ball?.physicsBody?.applyImpulse(vector)
}
/**
* Called before each frame is rendered.
*/
override func update(_ currentTime: TimeInterval) {
guard let ball = self.ball else {
return
}
// Check to see if the ball node has left the scene bounds
if (ball.position.x > self.size.width/2 + ball.size.width/2 ||
ball.position.x < -(self.size.width/2 + ball.size.width/2) ||
ball.position.y > self.size.height + ball.size.height) {
// The ball is outside the bounds of the visible view
resetBall()
}
checkCollisions()
}
// MARK: - Ball functions
/**
* Create a ball node and add it to the scene.
*/
func createBall() {
// Create the ball node
ball = SKSpriteNode(imageNamed: "Ball")
if let ball = ball {
ball.name = "ball"
// Set position and scale
ball.position = CGPoint(x: 0, y: 100)
ball.zPosition = 2
ball.scale(to: CGSize(width: 50, height: 50))
// Add physics
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width/2)
ball.physicsBody?.isDynamic = true
ball.physicsBody?.affectedByGravity = false
ball.physicsBody?.allowsRotation = false
ball.physicsBody?.mass = 50
// Add to the scene
addChild(ball)
}
}
/**
* Reset the ball to the default position.
*/
func resetBall() {
// Remove the current ball from the scene
ball?.removeAllActions()
ball?.removeFromParent()
ball = nil
// Reset touch locations
startTouchLocation = CGPoint.zero
endTouchLocation = CGPoint.zero
// Create a new ball and add to the scene
createBall()
}
// MARK: - Collision detection
func checkCollisions() {
guard let ball = self.ball, let monster = self.monster else {
return
}
if ball.frame.insetBy(dx: 20, dy: 20).intersects(monster.frame) {
monsterHit()
}
}
}
| 7317d33dcd2f07aa59dfb45a89a328d8 | 28.325 | 145 | 0.543762 | false | false | false | false |
GitHub Swift Repositories
Dataset Description
Dataset Summary
This dataset comprises data extracted from GitHub repositories, specifically focusing on Swift code. It was extracted using Google BigQuery and contains detailed information such as the repository name, reference, path, and license.
Source Data
- Initial Data Collection and Normalization
The data was collected from GitHub repositories using Google BigQuery. The dataset includes data from over 2.8 million open-source repositories. The data extraction process focused specifically on Swift files, identifying them using the .swift
extension.
- Who are the source data producers?
Developers and contributors to open-source projects on GitHub.
Dataset Metadata
Data Curators: The data was curated using Google BigQuery.
Last Update: 22 Aug 2023
Dataset Creation Date: 20 May 2023
Licensing Information
Please note that this dataset is a collection of open-source repositories. Each repository or file might come with its own license. Always refer to the license field associated with each entry.
Feedback and Contributions
We welcome feedback and contributions. If you notice any issues with the dataset or would like your code remove, please raise an issue.
- Downloads last month
- 105