repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
adrian-kubala/MyPlaces | MyPlaces/CustomSearchBar.swift | 1 | 1859 | //
// CustomSearchBar.swift
// Places
//
// Created by Adrian on 29.09.2016.
// Copyright © 2016 Adrian Kubała. All rights reserved.
//
import UIKit
import CoreLocation
class CustomSearchBar: UISearchBar {
var textField: UITextField {
return value(forKey: "searchField") as! UITextField
}
func setupSearchBar() {
setupImages()
setupTextField()
}
fileprivate func setupImages() {
var image = UIImage(named: "loc-clear")
setImage(image, for: .clear, state: UIControlState())
image = UIImage(named: "loc-current")
setImage(image, for: .search, state: UIControlState())
}
fileprivate func setupTextField() {
setupTextFieldBackgroundColor()
setupClearButton()
autocapitalizationType = .none
text = " "
}
fileprivate func setupTextFieldBackgroundColor() {
textField.backgroundColor = barTintColor
}
fileprivate func setupClearButton() {
textField.clearButtonMode = .whileEditing
}
func changeSearchIcon() {
if isActive() {
setupSearchIcon()
} else {
setupCurrentLocationIcon()
}
}
func setupSearchIcon() {
let image = UIImage(named: "loc-search")!
setImage(image, for: .search, state: UIControlState())
}
func setupCurrentLocationIcon() {
let image = UIImage(named: "loc-current")!
setImage(image, for: .search, state: UIControlState())
}
func updateSearchText(with placemark: CLPlacemark) {
if let street = placemark.thoroughfare, let city = placemark.locality, let country = placemark.country {
let separator = ", "
let formattedAddress = street + separator + city + separator + country
text = formattedAddress
}
}
func updateSearchText(_ text: String) {
self.text = text
}
func isActive() -> Bool {
return isFirstResponder ? true : false
}
}
| mit | 1f794b1e97809edea24cdd8a59beb639 | 22.807692 | 108 | 0.665051 | 4.529268 | false | false | false | false |
AlwaysRightInstitute/SwiftyHTTP | SwiftSockets/SocketAddress.swift | 1 | 12163 | //
// SocketAddress.swift
// SwiftSockets
//
// Created by Helge Heß on 6/12/14.
// Copyright (c) 2014-2015 Always Right Institute. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
// import Darwin.POSIX.netinet.`in` - this doesn't seem to work
// import struct Darwin.POSIX.netinet.`in`.sockaddr_in - neither
let INADDR_ANY = in_addr(s_addr: 0)
/**
* in_addr represents an IPv4 address in Unix. We extend that a little bit
* to increase it's usability :-)
*/
public extension in_addr {
public init() {
s_addr = INADDR_ANY.s_addr
}
public init(string: String?) {
if let s = string {
if s.isEmpty {
s_addr = INADDR_ANY.s_addr
}
else {
var buf = INADDR_ANY // Swift wants some initialization
s.withCString { cs in inet_pton(AF_INET, cs, &buf) }
s_addr = buf.s_addr
}
}
else {
s_addr = INADDR_ANY.s_addr
}
}
public var asString: String {
if self == INADDR_ANY {
return "*.*.*.*"
}
let len = Int(INET_ADDRSTRLEN) + 2
var buf = [CChar](count: len, repeatedValue: 0)
var selfCopy = self // &self doesn't work, because it can be const?
let cs = inet_ntop(AF_INET, &selfCopy, &buf, socklen_t(len))
return String.fromCString(cs)!
}
}
public func ==(lhs: in_addr, rhs: in_addr) -> Bool {
return __uint32_t(lhs.s_addr) == __uint32_t(rhs.s_addr)
}
extension in_addr : Equatable, Hashable {
public var hashValue: Int {
// Knuth?
return Int(UInt32(s_addr) * 2654435761 % (2^32))
}
}
extension in_addr: StringLiteralConvertible {
// this allows you to do: let addr : in_addr = "192.168.0.1"
public init(stringLiteral value: StringLiteralType) {
self.init(string: value)
}
public init(extendedGraphemeClusterLiteral v: ExtendedGraphemeClusterType) {
self.init(string: v)
}
public init(unicodeScalarLiteral value: String) {
// FIXME: doesn't work with UnicodeScalarLiteralType?
self.init(string: value)
}
}
extension in_addr: CustomStringConvertible {
public var description: String {
return asString
}
}
public protocol SocketAddress {
static var domain: Int32 { get }
init() // create empty address, to be filled by eg getsockname()
var len: __uint8_t { get }
}
extension sockaddr_in: SocketAddress {
public static var domain = AF_INET // if you make this a let, swiftc segfaults
public static var size = __uint8_t(sizeof(sockaddr_in))
// how to refer to self?
public init() {
#if os(Linux) // no sin_len on Linux
#else
sin_len = sockaddr_in.size
#endif
sin_family = sa_family_t(sockaddr_in.domain)
sin_port = 0
sin_addr = INADDR_ANY
sin_zero = (0,0,0,0,0,0,0,0)
}
public init(address: in_addr = INADDR_ANY, port: Int?) {
self.init()
sin_port = port != nil ? in_port_t(htons(CUnsignedShort(port!))) : 0
sin_addr = address
}
public init(address: String?, port: Int?) {
let isWildcard = address != nil
? (address! == "*" || address! == "*.*.*.*")
: true;
let ipv4 = isWildcard ? INADDR_ANY : in_addr(string: address)
self.init(address: ipv4, port: port)
}
public init(string: String?) {
if let s = string {
if s.isEmpty {
self.init(address: INADDR_ANY, port: nil)
}
else {
// split string at colon
let components = s.characters.split(":", maxSplit: 1).map { String($0) }
if components.count == 2 {
self.init(address: components[0], port: Int(components[1]))
}
else {
assert(components.count == 1)
let c1 = components[0]
let isWildcard = (c1 == "*" || c1 == "*.*.*.*")
if isWildcard {
self.init(address: nil, port: nil)
}
else if let port = Int(c1) { // it's a number
self.init(address: nil, port: port)
}
else { // it's a host
self.init(address: c1, port: nil)
}
}
}
}
else {
self.init(address: INADDR_ANY, port: nil)
}
}
public var port: Int { // should we make that optional and use wildcard as nil
get {
return Int(ntohs(sin_port))
}
set {
sin_port = in_port_t(htons(CUnsignedShort(newValue)))
}
}
public var address: in_addr {
return sin_addr
}
public var isWildcardPort: Bool { return sin_port == 0 }
public var isWildcardAddress: Bool { return sin_addr == INADDR_ANY }
public var len: __uint8_t { return sockaddr_in.size }
public var asString: String {
let addr = address.asString
return isWildcardPort ? addr : "\(addr):\(port)"
}
}
public func == (lhs: sockaddr_in, rhs: sockaddr_in) -> Bool {
return (lhs.sin_addr.s_addr == rhs.sin_addr.s_addr)
&& (lhs.sin_port == rhs.sin_port)
}
extension sockaddr_in: Equatable, Hashable {
public var hashValue: Int {
return sin_addr.hashValue + sin_port.hashValue
}
}
/**
* This allows you to do: let addr : sockaddr_in = "192.168.0.1:80"
*
* Adding an IntLiteralConvertible seems a bit too weird and ambigiuous to me.
*
* Note: this does NOT work:
* let s : sockaddr_in = "*:\(port)"
* it requires:
* StringInterpolationConvertible
*/
extension sockaddr_in: StringLiteralConvertible {
public init(stringLiteral value: String) {
self.init(string: value)
}
public init(extendedGraphemeClusterLiteral v: ExtendedGraphemeClusterType) {
self.init(string: v)
}
public init(unicodeScalarLiteral v: String) {
// FIXME: doesn't work with UnicodeScalarLiteralType?
self.init(string: v)
}
}
extension sockaddr_in: CustomStringConvertible {
public var description: String {
return asString
}
}
extension sockaddr_in6: SocketAddress {
public static var domain = AF_INET6
public static var size = __uint8_t(sizeof(sockaddr_in6))
public init() {
#if os(Linux) // no sin_len on Linux
#else
sin6_len = sockaddr_in6.size
#endif
sin6_family = sa_family_t(sockaddr_in.domain)
sin6_port = 0
sin6_flowinfo = 0
sin6_addr = in6addr_any
sin6_scope_id = 0
}
public var port: Int {
get {
return Int(ntohs(sin6_port))
}
set {
sin6_port = in_port_t(htons(CUnsignedShort(newValue)))
}
}
public var isWildcardPort: Bool { return sin6_port == 0 }
public var len: __uint8_t { return sockaddr_in6.size }
}
extension sockaddr_un: SocketAddress {
// TBD: sockaddr_un would be interesting as the size of the structure is
// technically dynamic (embedded string)
public static var domain = AF_UNIX
public static var size = __uint8_t(sizeof(sockaddr_un)) // CAREFUL
public init() {
#if os(Linux) // no sin_len on Linux
#else // os(Darwin)
sun_len = sockaddr_un.size // CAREFUL - kinda wrong
#endif // os(Darwin)
sun_family = sa_family_t(sockaddr_un.domain)
// Autsch!
#if os(Linux)
sun_path = ( // 16 per block, 108 total
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
);
#else // os(Darwin)
sun_path = ( // 16 per block, 104 total
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
);
#endif
}
public var len: __uint8_t {
// FIXME?: this is wrong. It needs to be the base size + string length in
// the buffer
return sockaddr_un.size
}
}
/* DNS */
public extension addrinfo {
public init() {
ai_flags = 0 // AI_CANONNAME, AI_PASSIVE, AI_NUMERICHOST
ai_family = AF_UNSPEC // AF_INET or AF_INET6 or AF_UNSPEC
ai_socktype = sys_SOCK_STREAM
ai_protocol = 0 // or IPPROTO_xxx for IPv4
ai_addrlen = 0 // length of ai_addr below
ai_canonname = nil // UnsafePointer<Int8>
ai_addr = nil // UnsafePointer<sockaddr>
ai_next = nil // UnsafePointer<addrinfo>
}
public init(flags: Int32, family: Int32) {
self.init()
ai_flags = flags
ai_family = family
}
public var hasNext : Bool {
return ai_next != nil
}
public var next : addrinfo? {
return hasNext ? ai_next.memory : nil
}
public var canonicalName : String? {
guard ai_canonname != nil && ai_canonname[0] != 0 else { return nil }
return String.fromCString(ai_canonname)
}
public var hasAddress : Bool {
return ai_addr != nil
}
public var isIPv4 : Bool {
return hasAddress &&
(ai_addr.memory.sa_family == sa_family_t(sockaddr_in.domain))
}
public var addressIPv4 : sockaddr_in? { return address() }
/* Not working anymore in b4
public var addressIPv6 : sockaddr_in6? { return address() }
*/
public func address<T: SocketAddress>() -> T? {
guard ai_addr != nil else { return nil }
guard ai_addr.memory.sa_family == sa_family_t(T.domain) else { return nil }
let aiptr = UnsafePointer<T>(ai_addr) // cast
return aiptr.memory // copies the address to the return value
}
public var dynamicAddress : SocketAddress? {
guard hasAddress else { return nil }
if ai_addr.memory.sa_family == sa_family_t(sockaddr_in.domain) {
let aiptr = UnsafePointer<sockaddr_in>(ai_addr) // cast
return aiptr.memory // copies the address to the return value
}
if ai_addr.memory.sa_family == sa_family_t(sockaddr_in6.domain) {
let aiptr = UnsafePointer<sockaddr_in6>(ai_addr) // cast
return aiptr.memory // copies the address to the return value
}
return nil
}
}
extension addrinfo : CustomStringConvertible {
public var description : String {
var s = "<addrinfo"
if ai_flags != 0 {
var fs = [String]()
var f = ai_flags
if f & AI_CANONNAME != 0 {
fs.append("canonname")
f = f & ~AI_CANONNAME
}
if f & AI_PASSIVE != 0 {
fs.append("passive")
f = f & ~AI_PASSIVE
}
if f & AI_NUMERICHOST != 0 {
fs.append("numerichost")
f = f & ~AI_NUMERICHOST
}
if f != 0 {
fs.append("flags[\(f)]")
}
let fss = fs.joinWithSeparator(",")
s += " flags=" + fss
}
if ai_family != AF_UNSPEC { s += sa_family_t(ai_family).description }
switch ai_socktype {
case 0: break
case sys_SOCK_STREAM: s += " stream"
case sys_SOCK_DGRAM: s += " datagram"
default: s += " type[\(ai_socktype)]"
}
if let cn = canonicalName {
s += " " + cn
}
if hasAddress {
if let a = addressIPv4 {
s += " \(a)"
}
/* Not working anymore in b4
else if let a = addressIPv6 {
s += " \(a)"
}
*/
else {
s += " address[len=\(ai_addrlen)]"
}
}
s += (ai_next != nil ? " +" : "")
s += ">"
return s
}
}
extension addrinfo : SequenceType {
public func generate() -> AnyGenerator<addrinfo> {
var cursor : addrinfo? = self
return AnyGenerator {
guard let info = cursor else { return .None }
cursor = info.next
return info
}
}
}
public extension sa_family_t { // Swift 2 : CustomStringConvertible, already imp?!
// TBD: does Swift 2 still pick this up?
public var description : String {
switch Int32(self) {
case AF_UNSPEC: return ""
case AF_INET: return "IPv4"
case AF_INET6: return "IPv6"
case AF_LOCAL: return "local"
default: return "family[\(self)]"
}
}
}
| mit | 0e534668b0de2995b97867d1ca753e24 | 24.284823 | 82 | 0.57285 | 3.344884 | false | false | false | false |
gbammc/Morph | Morph/AnimationAnimator.swift | 1 | 3618 | //
// AnimationAnimator.swift
// Morph
//
// Created by Alvin on 09/01/2017.
// Copyright © 2017 Alvin. All rights reserved.
//
import UIKit
public typealias AnimationComplection = () -> Void
public typealias AnimationComplectionAction = (Animatable, KeyframeAnimation) -> Void
open class AnimationAnimator {
/// The view that apply the animations.
public let targetView: UIView?
/// The layer that apply the animations.
public let targetLayer: CALayer?
/// The array that contains all animation groups.
public var animations = [AnimationGroup]()
/// Indicate whether to print the infomation about the animation or not. Defaults is NO.
public var logEnable = false
/// Initializes a new `AnimationAnimator` object.
///
/// - Parameter view: The view that will apply the animations.
public init(view: UIView) {
targetView = view
targetLayer = nil
}
/// Initializes a new `AnimationAnimator` object.
///
/// - Parameter layer: The layer that will apply the animations.
public init(layer: CALayer) {
targetView = nil
targetLayer = layer
}
}
// MARK: API
public extension AnimationAnimator {
public func animate(completion: AnimationComplection? = nil) {
CATransaction.begin()
CATransaction.setDisableActions(true)
CATransaction.setCompletionBlock(completion)
for group in animations {
for animation in group.keyframeAnimations {
animation.calculate()
if logEnable {
log(animation)
}
targetView?.layer.add(animation, forKey: nil)
targetLayer?.add(animation, forKey: nil)
}
}
CATransaction.commit()
for group in animations {
for animation in group.keyframeAnimations {
execute(group.complectionAction, animation: animation)
}
}
}
}
fileprivate extension AnimationAnimator {
fileprivate func execute(_ action: AnimationComplectionAction?, animation: KeyframeAnimation) {
guard let action = action else {
return
}
let delay = max(animation.beginTime - CACurrentMediaTime(), 0)
if let targetView = targetView {
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { [unowned targetView] in
action(targetView, animation)
})
} else if let targetLayer = targetLayer {
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { [unowned targetLayer] in
CATransaction.begin()
CATransaction.setDisableActions(true)
action(targetLayer, animation)
CATransaction.commit()
})
}
}
fileprivate func log(_ animation: KeyframeAnimation) {
if let path = animation.toValue as? UIBezierPath {
dump("keyPath: \(animation.keyPath ?? ""), currentPoint: \(path.currentPoint), duration: \(animation.duration)")
} else if let fromValue = animation.fromValue, let toValue = animation.toValue {
dump("keyPath: \(animation.keyPath ?? ""), fromValue: \(fromValue), toValue: \(toValue), duration: \(animation.duration)")
} else {
dump("keyPath: \(animation.keyPath ?? ""), values: \(animation.values), keyTimes: \(animation.keyTimes)")
}
}
}
| mit | 53395207399e126cf52591bbc3a387f3 | 30.72807 | 134 | 0.593309 | 5.319118 | false | false | false | false |
Yeahming/YMWeiBo_swiftVersion | YMWeibo_swiftVersion/YMWeibo_swiftVersion/Classes/Message/MessageTableViewController.swift | 1 | 3261 | //
// MessageTableViewController.swift
// YMWeibo_swiftVersion
//
// Created by 樊彦明 on 15/9/27.
// Copyright © 2015年 developer_YM. All rights reserved.
//
import UIKit
class MessageTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | ac6a5a227ce5953e24b832842fd10674 | 33.231579 | 157 | 0.688499 | 5.549488 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/Shared/Collection View Cells/CoverCollectionViewCell.swift | 1 | 1785 |
import UIKit
import PopcornKit
class CoverCollectionViewCell: BaseCollectionViewCell {
@IBOutlet var watchedIndicator: UIImageView?
var watched = false {
didSet {
watchedIndicator?.isHidden = !watched
}
}
#if os(iOS)
override func layoutSubviews() {
super.layoutSubviews()
[highlightView, imageView].forEach {
$0?.layer.cornerRadius = self.bounds.width * 0.02
$0?.layer.masksToBounds = true
}
}
#elseif os(tvOS)
override func awakeFromNib() {
super.awakeFromNib()
if let watchedIndicator = watchedIndicator {
focusedConstraints.append(watchedIndicator.trailingAnchor.constraint(equalTo: imageView.focusedFrameGuide.trailingAnchor))
focusedConstraints.append(watchedIndicator.topAnchor.constraint(equalTo: imageView.focusedFrameGuide.topAnchor))
}
}
#endif
}
extension CoverCollectionViewCell: CellCustomizing {
func configureCellWith<T>(_ item: T) {
guard let media = item as? Media else { print(">>> initializing cell with invalid item"); return }
let placeholder = media is Movie ? "Movie Placeholder" : "Episode Placeholder"
self.titleLabel.text = media.title
self.watched = media.isWatched
#if os(tvOS)
self.hidesTitleLabelWhenUnfocused = true
#endif
if let image = media.smallCoverImage,
let url = URL(string: image) {
self.imageView.af_setImage(withURL: url, placeholderImage: UIImage(named: placeholder), imageTransition: .crossDissolve(.default))
} else {
self.imageView.image = UIImage(named: placeholder)
}
}
}
| gpl-3.0 | 4db0815614038959f674d2bc8df85976 | 26.890625 | 142 | 0.628571 | 5.1 | false | false | false | false |
adly-holler/Bond | Bond/iOS/Bond+UISlider.swift | 9 | 3692 | //
// Bond+UISlider.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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
@objc class SliderDynamicHelper
{
weak var control: UISlider?
var listener: (Float -> Void)?
init(control: UISlider) {
self.control = control
control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: .ValueChanged)
}
func valueChanged(slider: UISlider) {
self.listener?(slider.value)
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .ValueChanged)
}
}
class SliderDynamic<T>: InternalDynamic<Float>
{
let helper: SliderDynamicHelper
init(control: UISlider) {
self.helper = SliderDynamicHelper(control: control)
super.init(control.value)
self.helper.listener = { [unowned self] in
self.updatingFromSelf = true
self.value = $0
self.updatingFromSelf = false
}
}
}
private var designatedBondHandleUISlider: UInt8 = 0;
private var valueDynamicHandleUISlider: UInt8 = 0;
extension UISlider /*: Dynamical, Bondable */ {
public var dynValue: Dynamic<Float> {
if let d: AnyObject = objc_getAssociatedObject(self, &valueDynamicHandleUISlider) {
return (d as? Dynamic<Float>)!
} else {
let d = SliderDynamic<Float>(control: self)
let bond = Bond<Float>() { [weak self, weak d] v in
if let s = self, d = d where !d.updatingFromSelf {
s.value = v
}
}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &valueDynamicHandleUISlider, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedDynamic: Dynamic<Float> {
return self.dynValue
}
public var designatedBond: Bond<Float> {
return self.dynValue.valueBond
}
}
public func ->> (left: UISlider, right: Bond<Float>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == Float>(left: UISlider, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UISlider, right: UISlider) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<Float>, right: UISlider) {
left ->> right.designatedBond
}
public func <->> (left: UISlider, right: UISlider) {
left.designatedDynamic <->> right.designatedDynamic
}
public func <->> (left: Dynamic<Float>, right: UISlider) {
left <->> right.designatedDynamic
}
public func <->> (left: UISlider, right: Dynamic<Float>) {
left.designatedDynamic <->> right
}
| mit | bff0f0d058c15e7774824835a23763c5 | 29.262295 | 127 | 0.6961 | 4.097669 | false | false | false | false |
ivanfoong/IFCacheKit-Swift | Example/Tests/Book.swift | 3 | 888 | //
// Book.swift
// IFCacheKit
//
// Created by Ivan Foong on 7/9/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import Foundation
class Book : NSObject, NSCoding, Hashable, NSCopying {
var title:String?
init(title: String?) {
self.title = title
}
@objc func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.title, forKey: "title")
}
@objc required convenience init(coder aDecoder: NSCoder) {
let title = aDecoder.decodeObjectForKey("title") as? String
self.init(title: title)
}
func copyWithZone(zone: NSZone) -> AnyObject {
return Book(title: self.title)
}
override var hashValue: Int {
get {
return self.title?.hashValue ?? 0
}
}
}
func == (lhs: Book, rhs: Book) -> Bool {
return lhs.hashValue == rhs.hashValue
} | mit | 4284f96392dfaf511fdfb6df32b2b50b | 21.225 | 67 | 0.599099 | 3.964286 | false | false | false | false |
izotx/iTenWired-Swift | Conference App/AgendaController.swift | 1 | 3153 | // Copyright (c) 2016, Izotx
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Izotx nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// AgendaController.swift
// Agenda1
//
// Created by Felipe Neves Brito {[email protected]} on 4/5/16.
/// Agenda handler
class AgendaController{
/// An agenda containing the events
var agenda:Agenda = Agenda()
/// Agenda DataLoader to load the agenda
let dataLoader:AgendaDataLoader = AgendaDataLoader()
/**
Initializes the agenda controller and loads an agenda
*/
init(){
self.agenda = self.dataLoader.getAgenda()
}
func getAgenda() -> Agenda{
return self.agenda
}
/**
Returns an Event at the specified index.
Will crash if the index does not exist
- Parameter index: The index of the event requested.
- Returns: The event at the specific index
*/
func getEventAt(index:Int) ->Event{
self.agenda = self.dataLoader.getAgenda()
return self.agenda.events[index]
}
/**
Searches an event by its id
- Parameter id: The id of the requested event
- Returns: The event with the specific id.
*/
func getById(id:Int)->Event
{
var event : Event?
for tempEvents in self.agenda.events
{
if(tempEvents.id == id)
{
event = tempEvents
}
}
return event!
}
/**
Returns the amount of events stored in the agenda
- Returns: The event count
*/
func getEventsCount() -> Int{
return agenda.events.count
}
}
| bsd-2-clause | 335889cf6ed6fc90c29669cf302882c8 | 33.271739 | 82 | 0.657786 | 4.650442 | false | false | false | false |
barteljan/RocketChatAdapter | Pod/Classes/CommandHandler/LogonCommandHandler.swift | 1 | 2282 | //
// LogonCommandHandler.swift
// Pods
//
// Created by Jan Bartel on 12.03.16.
//
//
import Foundation
import SwiftDDP
import VISPER_CommandBus
public class LogonCommandHandler: CommandHandlerProtocol {
public func isResponsible(command: Any!) -> Bool {
return command is LogonCommandProtocol
}
public func process<T>(command: Any!, completion: ((result: T?, error: ErrorType?) -> Void)?) throws{
let myCommand = command as! LogonCommandProtocol
Meteor.loginWithPassword(myCommand.userNameOrEmail, password: myCommand.password) { (result, error) -> () in
if(error != nil){
completion?(result: nil,error: error!)
return
}
if(result != nil){
print(result)
if(result == nil){
completion?(result:nil,error: RocketChatAdapterError.RequiredResponseFieldWasEmpty(field: "result",fileName: __FILE__,function: __FUNCTION__,line: __LINE__,column: __COLUMN__))
return
}
let userId = result?["id"] as! String?
if(userId == nil){
completion?(result:nil,error: RocketChatAdapterError.RequiredResponseFieldWasEmpty(field: "id",fileName: __FILE__,function: __FUNCTION__,line: __LINE__,column: __COLUMN__))
return
}
let token = result?["token"] as! String?
if(token == nil){
completion?(result:nil,error: RocketChatAdapterError.RequiredResponseFieldWasEmpty(field: "token",fileName: __FILE__,function: __FUNCTION__,line: __LINE__,column: __COLUMN__))
return
}
let authorizationResult = AuthorizationResult(sessionToken: token!, userId: userId!)
completion?(result: (authorizationResult as! T),error: nil)
return
}
completion?(result: nil,error: RocketChatAdapterError.ServerDidResponseWithEmptyResult(fileName: __FILE__, function: __FUNCTION__, line: __LINE__, column: __COLUMN__))
}
}
}
| mit | b805ac9c104db46bb737c76f8033bf9f | 36.409836 | 196 | 0.542945 | 4.982533 | false | false | false | false |
doronkatz/firefox-ios | Extensions/NotificationService/NotificationService.swift | 1 | 4814 | /* 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 Shared
import Storage
import Sync
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
var display: SyncDataDisplay!
lazy var profile: ExtensionProfile = {
NSLog("APNS ExtensionProfile being created…")
let profile = ExtensionProfile(localName: "profile")
NSLog("APNS ExtensionProfile … now created")
return profile
}()
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
return
}
let userInfo = request.content.userInfo
NSLog("NotificationService APNS NOTIFICATION \(userInfo)")
let queue = self.profile.queue
self.display = SyncDataDisplay(content: content, contentHandler: contentHandler, tabQueue: queue)
self.profile.syncDelegate = display
let handler = FxAPushMessageHandler(with: profile)
handler.handle(userInfo: userInfo).upon {_ in
self.finished(cleanly: true)
}
}
func finished(cleanly: Bool) {
profile.shutdown()
// We cannot use tabqueue after the profile has shutdown;
// however, we can't use weak references, because TabQueue isn't a class.
// Rather than changing tabQueue, we manually nil it out here.
display.tabQueue = nil
display.displayNotification(cleanly)
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
finished(cleanly: false)
}
}
class SyncDataDisplay {
var contentHandler: ((UNNotificationContent) -> Void)
var notificationContent: UNMutableNotificationContent
var sentTabs: [SentTab]
var tabQueue: TabQueue?
init(content: UNMutableNotificationContent, contentHandler: @escaping (UNNotificationContent) -> Void, tabQueue: TabQueue) {
self.contentHandler = contentHandler
self.notificationContent = content
self.sentTabs = []
self.tabQueue = tabQueue
}
func displayNotification(_ didFinish: Bool) {
var userInfo = notificationContent.userInfo
// Add the tabs we've found to userInfo, so that the AppDelegate
// doesn't have to do it again.
let serializedTabs = sentTabs.flatMap { t -> NSDictionary? in
return [
"title": t.title,
"url": t.url.absoluteString,
] as NSDictionary
} as NSArray
userInfo["sentTabs"] = serializedTabs
userInfo["didFinish"] = didFinish
// Increment the badges. This may cause us to find bugs with multiple
// notifications in the future.
let badge = (notificationContent.badge?.intValue ?? 0) + sentTabs.count
notificationContent.badge = NSNumber(value: badge)
notificationContent.userInfo = userInfo
switch sentTabs.count {
case 0:
notificationContent.title = Strings.SentTab_NoTabArrivingNotification_title
notificationContent.body = Strings.SentTab_NoTabArrivingNotification_body
case 1:
let tab = sentTabs[0]
let title: String
if let deviceName = tab.deviceName {
title = String(format: Strings.SentTab_TabArrivingNotificationWithDevice_title, deviceName)
} else {
title = Strings.SentTab_TabArrivingNotificationNoDevice_title
}
notificationContent.title = title
notificationContent.body = tab.url.absoluteDisplayString
default:
notificationContent.title = Strings.SentTab_TabsArrivingNotification_title
notificationContent.body = String(format: Strings.SentTab_TabsArrivingNotification_title, sentTabs.count)
}
contentHandler(notificationContent)
}
}
extension SyncDataDisplay: SyncDelegate {
func displaySentTab(for url: URL, title: String, from deviceName: String?) {
if url.isWebPage() {
sentTabs.append(SentTab(url: url, title: title, deviceName: deviceName))
let item = ShareItem(url: url.absoluteString, title: title, favicon: nil)
_ = tabQueue?.addToQueue(item)
}
}
}
struct SentTab {
let url: URL
let title: String
let deviceName: String?
}
| mpl-2.0 | 7dcae2e52c0b0c5e4694920d4c23a8bc | 36.286822 | 142 | 0.665904 | 5.368304 | false | false | false | false |
AChildFromBUAA/PracticePlace | TestPractice/AccelerometerViewController.swift | 1 | 2278 | //
// AccelerometerViewController.swift
// TestPractice
//
// Created by kyz on 15/11/10.
// Copyright © 2015年 BUAA.Software. All rights reserved.
//
import UIKit
class AccelerometerViewController: UIViewController {
@IBOutlet weak var xLabel: NSLayoutConstraint!
@IBOutlet weak var yLabel: UILabel!
@IBOutlet weak var zLabel: UILabel!
@IBOutlet weak var xProgress: UIProgressView!
@IBOutlet weak var yProgress: UIProgressView!
@IBOutlet weak var zProgress: UIProgressView!
@IBOutlet weak var shakeLabel: UILabel!
let motionManger = AppDelegate.Motion.Manger
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
motionManger.accelerometerUpdateInterval = 0.1
if motionManger.accelerometerAvailable {
motionManger.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { (data, error) -> Void in
if error != nil {
self.motionManger.stopAccelerometerUpdates()
} else {
self.xProgress.progress = abs(Float((data?.acceleration.x)!))
self.yProgress.progress = abs(Float((data?.acceleration.y)!))
self.zProgress.progress = abs(Float((data?.acceleration.z)!))
}
}
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
motionManger.stopAccelerometerUpdates()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
motionManger.stopAccelerometerUpdates()
}
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
self.shakeLabel.text = "Shaking"
}
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
self.shakeLabel.text = "End Shake"
}
}
override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
self.shakeLabel.text = "Shake Cancelled"
}
}
}
| mit | 43def412b09b78f9a8de241a75d05226 | 29.743243 | 114 | 0.621538 | 5.254042 | false | false | false | false |
jaften/calendar-Swift-2.0- | CVCalendar Demo/CVCalendar Demo/ViewController.swift | 1 | 8637 | //
// ViewController.swift
// CVCalendar Demo
//
// Created by Мак-ПК on 1/3/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var calendarView: CVCalendarView!
@IBOutlet weak var menuView: CVCalendarMenuView!
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet weak var daysOutSwitch: UISwitch!
var shouldShowDaysOut = true
var animationFinished = true
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
monthLabel.text = CVDate(date: NSDate()).globalDescription
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calendarView.commitCalendarViewUpdate()
menuView.commitMenuViewUpdate()
}
}
// MARK: - CVCalendarViewDelegate & CVCalendarMenuViewDelegate
extension ViewController: CVCalendarViewDelegate, CVCalendarMenuViewDelegate {
/// Required method to implement!
func presentationMode() -> CalendarMode {
return .MonthView
}
/// Required method to implement!
func firstWeekday() -> Weekday {
return .Sunday
}
// MARK: Optional methods
func shouldShowWeekdaysOut() -> Bool {
return shouldShowDaysOut
}
func shouldAnimateResizing() -> Bool {
return true // Default value is true
}
func didSelectDayView(dayView: CVCalendarDayView) {
let _/*date*/ = dayView.date
print("\(calendarView.presentedDate.commonDescription) is selected!")
}
func presentedDateUpdated(date: CVDate) {
if monthLabel.text != date.globalDescription && self.animationFinished {
let updatedMonthLabel = UILabel()
updatedMonthLabel.textColor = monthLabel.textColor
updatedMonthLabel.font = monthLabel.font
updatedMonthLabel.textAlignment = .Center
updatedMonthLabel.text = date.globalDescription
updatedMonthLabel.sizeToFit()
updatedMonthLabel.alpha = 0
updatedMonthLabel.center = self.monthLabel.center
let offset = CGFloat(48)
updatedMonthLabel.transform = CGAffineTransformMakeTranslation(0, offset)
updatedMonthLabel.transform = CGAffineTransformMakeScale(1, 0.1)
UIView.animateWithDuration(0.35, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.animationFinished = false
self.monthLabel.transform = CGAffineTransformMakeTranslation(0, -offset)
self.monthLabel.transform = CGAffineTransformMakeScale(1, 0.1)
self.monthLabel.alpha = 0
updatedMonthLabel.alpha = 1
updatedMonthLabel.transform = CGAffineTransformIdentity
}) { _ in
self.animationFinished = true
self.monthLabel.frame = updatedMonthLabel.frame
self.monthLabel.text = updatedMonthLabel.text
self.monthLabel.transform = CGAffineTransformIdentity
self.monthLabel.alpha = 1
updatedMonthLabel.removeFromSuperview()
}
self.view.insertSubview(updatedMonthLabel, aboveSubview: self.monthLabel)
}
}
func topMarker(shouldDisplayOnDayView dayView: CVCalendarDayView) -> Bool {
return true
}
func dotMarker(shouldShowOnDayView dayView: CVCalendarDayView) -> Bool {
let day = dayView.date.day
let randomDay = Int(arc4random_uniform(31))
if day == randomDay {
return true
}
return false
}
func dotMarker(colorOnDayView dayView: CVCalendarDayView) -> [UIColor] {
let _/*day*/ = dayView.date.day
let red = CGFloat(arc4random_uniform(600) / 255)
let green = CGFloat(arc4random_uniform(600) / 255)
let blue = CGFloat(arc4random_uniform(600) / 255)
let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
let numberOfDots = Int(arc4random_uniform(3) + 1)
switch(numberOfDots) {
case 2:
return [color, color]
case 3:
return [color, color, color]
default:
return [color] // return 1 dot
}
}
func dotMarker(shouldMoveOnHighlightingOnDayView dayView: CVCalendarDayView) -> Bool {
return true
}
}
// MARK: - CVCalendarViewDelegate
extension ViewController/*: CVCalendarViewDelegate*/ {
func preliminaryView(viewOnDayView dayView: DayView) -> UIView {
let circleView = CVAuxiliaryView(dayView: dayView, rect: dayView.bounds, shape: CVShape.Circle)
circleView.fillColor = .colorFromCode(0xCCCCCC)
return circleView
}
func preliminaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
if (dayView.isCurrentDay) {
return true
}
return false
}
func supplementaryView(viewOnDayView dayView: DayView) -> UIView {
let π = M_PI
let ringSpacing: CGFloat = 3.0
let ringInsetWidth: CGFloat = 1.0
let ringVerticalOffset: CGFloat = 1.0
var ringLayer: CAShapeLayer!
let ringLineWidth: CGFloat = 4.0
let ringLineColour: UIColor = .blueColor()
let newView = UIView(frame: dayView.bounds)
let diameter: CGFloat = (newView.bounds.width) - ringSpacing
let radius: CGFloat = diameter / 2.0
let rect = CGRectMake(newView.frame.midX-radius, newView.frame.midY-radius-ringVerticalOffset, diameter, diameter)
ringLayer = CAShapeLayer()
newView.layer.addSublayer(ringLayer)
ringLayer.fillColor = nil
ringLayer.lineWidth = ringLineWidth
ringLayer.strokeColor = ringLineColour.CGColor
let ringLineWidthInset: CGFloat = CGFloat(ringLineWidth/2.0) + ringInsetWidth
let ringRect: CGRect = CGRectInset(rect, ringLineWidthInset, ringLineWidthInset)
let centrePoint: CGPoint = CGPointMake(ringRect.midX, ringRect.midY)
let startAngle: CGFloat = CGFloat(-π/2.0)
let endAngle: CGFloat = CGFloat(π * 2.0) + startAngle
let ringPath: UIBezierPath = UIBezierPath(arcCenter: centrePoint, radius: ringRect.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: true)
ringLayer.path = ringPath.CGPath
ringLayer.frame = newView.layer.bounds
return newView
}
func supplementaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
if (Int(arc4random_uniform(3)) == 1) {
return true
}
return false
}
}
// MARK: - CVCalendarViewAppearanceDelegate
extension ViewController: CVCalendarViewAppearanceDelegate {
func dayLabelPresentWeekdayInitallyBold() -> Bool {
return false
}
func spaceBetweenDayViews() -> CGFloat {
return 2
}
}
// MARK: - IB Actions
extension ViewController {
@IBAction func switchChanged(sender: UISwitch) {
if sender.on {
calendarView.changeDaysOutShowingState(false)
shouldShowDaysOut = true
} else {
calendarView.changeDaysOutShowingState(true)
shouldShowDaysOut = false
}
}
@IBAction func todayMonthView() {
calendarView.toggleCurrentDayView()
}
/// Switch to WeekView mode.
@IBAction func toWeekView(sender: AnyObject) {
calendarView.changeMode(.WeekView)
}
/// Switch to MonthView mode.
@IBAction func toMonthView(sender: AnyObject) {
calendarView.changeMode(.MonthView)
}
@IBAction func loadPrevious(sender: AnyObject) {
calendarView.loadPreviousView()
}
@IBAction func loadNext(sender: AnyObject) {
calendarView.loadNextView()
}
}
// MARK: - Convenience API Demo
extension ViewController {
func toggleMonthViewWithMonthOffset(offset: Int) {
let calendar = NSCalendar.currentCalendar()
let _/*calendarManager*/ = calendarView.manager
let components = Manager.componentsForDate(NSDate()) // from today
components.month += offset
let resultDate = calendar.dateFromComponents(components)!
self.calendarView.toggleViewWithDate(resultDate)
}
} | mit | 9dbbf2db73e47ae1122cfb064b06f7eb | 31.201493 | 162 | 0.627419 | 5.248783 | false | false | false | false |
4taras4/totp-auth | TOTP/ViperModules/AddItem/Module/Assembly/AddItemAssemblyContainer.swift | 1 | 1189 | //
// AddItemAddItemAssemblyContainer.swift
// TOTP
//
// Created by Tarik on 10/10/2020.
// Copyright © 2020 Taras Markevych. All rights reserved.
//
import Swinject
final class AddItemAssemblyContainer: Assembly {
func assemble(container: Container) {
container.register(AddItemInteractor.self) { (_, presenter: AddItemPresenter) in
let interactor = AddItemInteractor()
interactor.output = presenter
return interactor
}
container.register(AddItemRouter.self) { (_, viewController: AddItemViewController) in
let router = AddItemRouter()
router.transitionHandler = viewController
return router
}
container.register(AddItemPresenter.self) { (r, viewController: AddItemViewController) in
let presenter = AddItemPresenter()
presenter.view = viewController
presenter.interactor = r.resolve(AddItemInteractor.self, argument: presenter)
presenter.router = r.resolve(AddItemRouter.self, argument: viewController)
return presenter
}
container.storyboardInitCompleted(AddItemViewController.self) { r, viewController in
viewController.output = r.resolve(AddItemPresenter.self, argument: viewController)
}
}
}
| mit | c46318eedacc15678ee8c45cac89c3f6 | 27.285714 | 94 | 0.747475 | 4.335766 | false | false | false | false |
yellokrow/TileEditor | TileEditor/PaletteFactory.swift | 1 | 1581 | //
// PaletteFactory.swift
// TileEditor
//
// Created by iury bessa on 4/11/17.
// Copyright © 2017 yellokrow. All rights reserved.
//
import Foundation
public
class PaletteFactory: Factory {
public static func convert(array: [Int], type: PaletteType) -> Data? {
switch type {
case .nes:
// This is the number of bytes to save per 8 palettes. The bytesToSave should be 32
if array.count == 32 {
return Data(bytes: array as! [UInt8])
}
}
return nil
}
public static func generate(data: Data) -> [PaletteProtocol]? {
let paletteFactory = PaletteFactory()
if let paletteType = paletteFactory.paletteType(data: data) {
var paletteGenerated: [PaletteProtocol]? = nil
switch paletteType {
case .nes:
paletteGenerated = NESPalette.generateArrayOfPalettes(input: data)
}
guard let palette = paletteGenerated else {
return nil
}
return palette
}
return nil
}
public static func generate(type: PaletteType) -> [PaletteProtocol]? {
switch type {
case .nes:
return [NESPalette(),NESPalette(),NESPalette(),NESPalette(),NESPalette(),NESPalette(),NESPalette(),NESPalette()]
}
}
func paletteType(data: Data) -> PaletteType? {
// Check if Data is of type NES ( 32 bytes long )
if data.count == 32 {
return .nes
}
return nil
}
}
| mit | aac07e322b58d9561a2c720e2d4de1bd | 28.259259 | 124 | 0.562658 | 4.566474 | false | false | false | false |
diegorv/iOS-Swift-TableView-CoreData-Example | iOS-Swift-TableView-CoreData-Example/ViewController.swift | 1 | 6684 | //
// Item.swift
// iOS-Swift-TableView-CoreData-Example
//
// Created by Diego Rossini Vieira on 9/7/15.
// https://github.com/diegorv/iOS-Swift-TableView-CoreData-Example
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
// MARK: - Variables
/// CoreData connection variable
let coreDataDB = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
/// TableView array data
var items = [Item]()
// MARK: - Outlets
// TableView Outlet
@IBOutlet weak var tableView: UITableView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// NavigationController title
title = "My item list"
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
// Load CoreData data
items = Item.fetchAll(coreDataDB)
}
// MARK: - Actions
/// TableView add button
@IBAction func addButton(sender: UIBarButtonItem) {
let addFormAlert = UIAlertController(title: "New item", message: "Enter a name for the item", preferredStyle: .Alert)
let saveButton = UIAlertAction (title: "Save", style: .Default) { (action: UIAlertAction) -> Void in
let nameTextField = (addFormAlert.textFields![0] ).text
// Check if name is empty
if (nameTextField!.isEmpty) {
self.alertError("Unable to save", msg: "Item name can't be blank.")
}
// Check duplicate item name
else if (Item.checkDuplicate(nameTextField!, inManagedObjectContext: self.coreDataDB)) {
self.alertError("Unable to save", msg: "There is already an item with name: \(nameTextField).")
}
// Save data
else {
// Use class "Item" to create a new CoreData object
let newItem = Item(name: nameTextField!, inManagedObjectContext: self.coreDataDB)
// Add item to array
self.items.append(newItem)
// CoreData save
newItem.save(self.coreDataDB)
// Reload Coredata data
self.items = Item.fetchAll(self.coreDataDB)
// Reload TableView
self.tableView.reloadData()
}
}
// No action, no need handler
let cancelButton = UIAlertAction(title: "Cancel", style: .Destructive, handler: nil)
// Show textField in alert
addFormAlert.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = "Item name"
}
addFormAlert.addAction(saveButton)
addFormAlert.addAction(cancelButton)
presentViewController(addFormAlert, animated: true, completion: nil)
}
// MARK: - UITableViewDataSource
// TableView rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
// Show data in TableView row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = self.items[indexPath.row].name
return cell
}
// Allow edit cell in TableView
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
// Allow actions on cell swipe in TableView
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
// Actions on cell swipe in TableView
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
let editSwipeButton = UITableViewRowAction(style: .Default, title: "Edit") { (action, indexPath) in
let currentName = self.items[indexPath.row].name
let alertEdit = UIAlertController(title: "Editing item", message: "Change item name", preferredStyle: .Alert)
let saveButton = UIAlertAction(title: "Save", style: .Default) { (action) in
let newItemName = (alertEdit.textFields![0] ).text
// Check if name is empty
if (newItemName!.isEmpty) {
self.alertError("Unable to save", msg: "Item name can't be blank.")
}
// Current Name equal New Name
else if (currentName == newItemName) {
true // do nothing
}
// Check duplicate item name
else if (Item.checkDuplicate(newItemName!, inManagedObjectContext: self.coreDataDB)) {
self.alertError("Unable to save", msg: "There is already an item with name: \(newItemName).")
}
// Save CoreData
else {
// Update item name
let item = Item.search(currentName, inManagedObjectContext: self.coreDataDB)
item?.name = newItemName!
item?.save(self.coreDataDB)
// Reload Coredata data
self.items = Item.fetchAll(self.coreDataDB)
// Reload TableView
self.tableView.reloadData()
}
// Close cell buttons
self.tableView.setEditing(false, animated: false)
}
let cancelButton = UIAlertAction(title: "Cancel", style: .Destructive, handler: nil)
// Show textField in alert with current name value
alertEdit.addTextFieldWithConfigurationHandler { textField in
textField.text = currentName
}
alertEdit.addAction(cancelButton)
alertEdit.addAction(saveButton)
self.presentViewController(alertEdit, animated: true, completion: nil)
}
let deleteSwipteButton = UITableViewRowAction(style: .Normal, title: "Delete") { (action, indexPath) in
// Find item
let itemDelete = self.items[indexPath.row]
// Delete item in CoreData
itemDelete.destroy(self.coreDataDB)
// Save item
itemDelete.save(self.coreDataDB)
// Tableview always load data from "items" array.
// If you delete a item from CoreData you need reload array data.
self.items = Item.fetchAll(self.coreDataDB)
// Remove item from TableView
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
editSwipeButton.backgroundColor = UIColor.lightGrayColor()
deleteSwipteButton.backgroundColor = UIColor.redColor()
return [editSwipeButton, deleteSwipteButton]
}
// MARK: - Helpers
/// Show a alert error
///
/// - parameter title: Title
/// - parameter msg: Message
///
func alertError(title: String, msg: String) {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alert.addAction(okButton)
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit | a4885cb0d9c4328c6dafd8ff38ea0a61 | 31.604878 | 146 | 0.677738 | 4.750533 | false | false | false | false |
SteveBarnegren/SwiftChess | SwiftChess/Source/AIPlayer.swift | 1 | 10801 | //
// Piece.swift
// Pods
//
// Created by Steve Barnegren on 04/09/2016.
//
//
// swiftlint:disable for_where
import Foundation
public final class AIPlayer: Player {
let boardRaters: [BoardRater]!
public let configuration: AIConfiguration!
var openingMoves = [OpeningMove]()
public init(color: Color, configuration: AIConfiguration) {
self.configuration = configuration
self.boardRaters = [
BoardRaterCountPieces(configuration: configuration),
BoardRaterCenterOwnership(configuration: configuration),
BoardRaterBoardDominance(configuration: configuration),
BoardRaterCenterDominance(configuration: configuration),
BoardRaterThreatenedPieces(configuration: configuration),
BoardRaterPawnProgression(configuration: configuration),
BoardRaterKingSurroundingPossession(configuration: configuration),
BoardRaterCheckMateOpportunity(configuration: configuration),
BoardRaterCenterFourOccupation(configuration: configuration)
]
openingMoves = Opening.allOpeningMoves(for: color)
super.init()
self.color = color
}
public func makeMoveAsync() {
DispatchQueue.global(qos: .background).async {
self.makeMoveSync()
}
}
public func makeMoveSync() {
guard let game = self.game else { return }
// Check that the game is in progress
guard game.state == .inProgress else {
return
}
let board = game.board
var move: Move!
// Get an opening move
if let openingMove = openingMove(for: board) {
move = openingMove
}
// Or, get the Highest rated move
else {
move = highestRatedMove(on: board)
}
// Check that the game still exists
if self.game == nil { return }
// Make move
var operations = [BoardOperation]()
switch move.type {
case .singlePiece(let sourceLocation, let targetLocation):
operations = game.board.movePiece(from: sourceLocation, to: targetLocation)
case .castle(let color, let side):
operations = game.board.performCastle(color: color, side: side)
}
// Promote pawns
let pawnsToPromoteLocations = game.board.getLocationsOfPromotablePawns(color: color)
assert(pawnsToPromoteLocations.count < 2, "There should only ever be one pawn to promote at any time")
if pawnsToPromoteLocations.count > 0 {
game.board = promotePawns(on: game.board)
let location = pawnsToPromoteLocations.first!
let transformOperation = BoardOperation(type: .transformPiece,
piece: game.board.getPiece(at: location)!,
location: location)
operations.append(transformOperation)
}
let strongGame = self.game!
DispatchQueue.main.async {
strongGame.playerDidMakeMove(player: self, boardOperations: operations)
}
}
func openingMove(for board: Board) -> Move? {
let possibleMoves = openingMoves.filter {
$0.board == board
}
guard possibleMoves.count > 0 else {
return nil
}
let index = Int(arc4random_uniform(UInt32(possibleMoves.count)))
let openingMove = possibleMoves[index]
return Move(type: .singlePiece(from: openingMove.fromLocation,
to: openingMove.toLocation),
rating: 0)
}
func highestRatedMove(on board: Board) -> Move {
var possibleMoves = [Move]()
for sourceLocation in BoardLocation.all {
guard let piece = board.getPiece(at: sourceLocation) else {
continue
}
if piece.color != color {
continue
}
for targetLocation in BoardLocation.all {
guard canAIMovePiece(from: sourceLocation, to: targetLocation) else {
continue
}
// Make move
var resultBoard = board
resultBoard.movePiece(from: sourceLocation, to: targetLocation)
// Promote pawns
let pawnsToPromoteLocations = resultBoard.getLocationsOfPromotablePawns(color: color)
assert(pawnsToPromoteLocations.count < 2, "There should only ever be one pawn to promote at any time")
if pawnsToPromoteLocations.count > 0 {
resultBoard = promotePawns(on: resultBoard)
}
// Rate
var rating = ratingForBoard(resultBoard)
// reduce rating if suicide
if resultBoard.canColorMoveAnyPieceToLocation(color: color.opposite, location: targetLocation) {
rating -= (abs(rating) * configuration.suicideMultipler.value)
}
let move = Move(type: .singlePiece(from: sourceLocation, to: targetLocation),
rating: rating)
possibleMoves.append(move)
}
}
// Add castling moves
let castleSides: [CastleSide] = [.kingSide, .queenSide]
for side in castleSides {
guard game?.board.canColorCastle(color: color, side: side) ?? false else {
continue
}
// Perform the castling move
var resultBoard = board
resultBoard.performCastle(color: color, side: side)
// Rate
let rating = ratingForBoard(resultBoard)
let move = Move(type: .castle(color: color, side: side), rating: rating)
possibleMoves.append(move)
}
// If there are no possible moves, we must be in stale mate. This should never happen
if possibleMoves.count == 0 {
print("There are no possible moves!")
}
// Choose move with highest rating
var highestRating = possibleMoves.first!.rating
var highestRatedMove = possibleMoves.first!
for move in possibleMoves {
if move.rating > highestRating {
highestRating = move.rating
highestRatedMove = move
}
}
return highestRatedMove
}
func canAIMovePiece(from fromLocation: BoardLocation, to toLocation: BoardLocation) -> Bool {
// This is a stricter version of the canMove function, used by the AI, that returns false for errors
do {
return try canMovePiece(from: fromLocation, to: toLocation)
} catch {
return false
}
}
func ratingForBoard(_ board: Board) -> Double {
var rating: Double = 0
for boardRater in boardRaters {
let result = boardRater.ratingFor(board: board, color: color)
rating += result
}
// If opponent is in check mate, set the maximum rating
if board.isColorInCheckMate(color: color.opposite) {
rating = Double.greatestFiniteMagnitude
}
return rating
}
func promotePawns(on board: Board) -> Board {
let pawnsToPromoteLocations = board.getLocationsOfPromotablePawns(color: color)
guard pawnsToPromoteLocations.count > 0 else {
return board
}
assert(pawnsToPromoteLocations.count < 2, "There should only ever be one pawn to promote at any time")
let location = pawnsToPromoteLocations.first!
guard board.getPiece(at: location) != nil else {
return board
}
// Get the ratings
var highestRating = -Double.greatestFiniteMagnitude
var promotedBoard: Board!
for pieceType in Piece.PieceType.possiblePawnPromotionResultingTypes() {
var newBoard = board
guard newBoard.getPiece(at: location) != nil else {
return board
}
let newPiece = newBoard.getPiece(at: location)?.byChangingType(newType: pieceType)
newBoard.setPiece(newPiece!, at: location)
let rating = ratingForBoard(newBoard)
if rating > highestRating {
highestRating = rating
promotedBoard = newBoard
}
}
return promotedBoard
}
}
extension AIPlayer: Equatable {
public static func == (lhs: AIPlayer, rhs: AIPlayer) -> Bool {
return lhs.color == rhs.color && lhs.configuration == rhs.configuration
}
}
extension AIPlayer: DictionaryRepresentable {
struct Keys {
static let color = "color"
static let configuration = "configuration"
}
convenience init?(dictionary: [String: Any]) {
guard
let colorRaw = dictionary[Keys.color] as? String,
let color = Color(rawValue: colorRaw),
let configurationDict = dictionary[Keys.configuration] as? [String: Any],
let configuration = AIConfiguration(dictionary: configurationDict) else {
return nil
}
self.init(color: color, configuration: configuration)
}
var dictionaryRepresentation: [String: Any] {
var dictionary = [String: Any]()
dictionary[Keys.color] = color.rawValue
dictionary[Keys.configuration] = configuration.dictionaryRepresentation
return dictionary
}
}
struct Move {
enum MoveType {
case singlePiece(from: BoardLocation, to: BoardLocation)
case castle(color: Color, side: CastleSide)
}
let type: MoveType
let rating: Double
}
// MARK: - BoardRater
internal class BoardRater {
let configuration: AIConfiguration
init(configuration: AIConfiguration) {
self.configuration = configuration
}
func ratingFor(board: Board, color: Color) -> Double {
fatalError("Override ratingFor method in subclasses")
}
}
| mit | e89e228bb78d16f4d6e9f4382a639289 | 31.338323 | 118 | 0.558467 | 5.519162 | false | true | false | false |
darkbrow/iina | iina/MPVFilter.swift | 1 | 6250 | //
// MPVFilter.swift
// iina
//
// Created by lhc on 2/9/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
// See https://github.com/mpv-player/mpv/blob/master/options/m_option.c#L2955
// #define NAMECH "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
fileprivate let mpvAllowedCharacters = Set<Character>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")
fileprivate extension String {
var mpvQuotedFilterValue: String {
return self.allSatisfy({ mpvAllowedCharacters.contains($0) }) ? self : mpvFixedLengthQuoted
}
}
/**
Represents a mpv filter. It can be either created by user or loaded from mpv.
*/
class MPVFilter: NSObject {
enum FilterType: String {
case crop = "crop"
case expand = "expand"
case flip = "flip"
case mirror = "hflip"
case lavfi = "lavfi"
}
// MARK: - Static filters
static func crop(w: Int?, h: Int?, x: Int?, y: Int?) -> MPVFilter {
let f = MPVFilter(name: "crop", label: nil,
params: ["w": w?.description ?? "", "h": h?.description ?? "", "x": x?.description ?? "", "y": y?.description ?? ""])
return f
}
// FIXME: use lavfi vflip
static func flip() -> MPVFilter {
return MPVFilter(name: "flip", label: nil, params: nil)
}
// FIXME: use lavfi hflip
static func mirror() -> MPVFilter {
return MPVFilter(name: "hflip", label: nil, params: nil)
}
/**
A ffmpeg `unsharp` filter.
Args: l(uma)x, ly, la, c(hroma)x, xy, ca; default 5:5:0:5:5:0.
We only change la and ca here.
- parameter msize: Value for lx, ly, cx and cy. Should be an odd integer in [3, 23].
- parameter amount: Anount for la and ca. Should be in [-1.5, 1.5].
*/
static func unsharp(amount: Float, msize: Int = 5) -> MPVFilter {
let amoutStr = amount.description
let msizeStr = msize.description
return MPVFilter(lavfiName: "unsharp", label: nil, params: [msizeStr, msizeStr, amoutStr, msizeStr, msizeStr, amoutStr])
}
// MARK: - Members
var type: FilterType?
var name: String
var label: String?
var params: [String: String]?
var rawParamString: String?
/** Convert the filter to a valid mpv filter string. */
var stringFormat: String {
get {
var str = ""
// label
if let label = label { str += "@\(label):" }
// name
str += name
// params
if let rpstr = rawParamString {
// if is set by user
str += "="
str += rpstr
} else if params != nil && params!.count > 0 {
// if have format info, print using the format
if type != nil, let format = MPVFilter.formats[type!] {
str += "="
str += format.components(separatedBy: ":").map { params![$0] ?? "" }.joined(separator: ":")
// else print param names
} else {
str += "="
// special tweak for lavfi filters
if name == "lavfi" {
str += "[\(params!["graph"]!)]"
} else {
str += params!.map { "\($0)=\($1.mpvQuotedFilterValue)" } .joined(separator: ":")
}
}
}
return str
}
}
// MARK: - Initializers
init(name: String, label: String?, params: [String: String]?) {
self.type = FilterType(rawValue: name)
self.name = name
self.label = label
if let params = params, let type = type, let format = MPVFilter.formats[type]?.components(separatedBy: ":") {
var translated: [String: String] = [:]
for (key, value) in params {
if let number = Int(key.dropFirst()) {
translated[format[number]] = value
} else {
translated[key] = value
}
}
self.params = translated
} else {
self.params = params
}
}
init?(rawString: String) {
let splitted = rawString.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: true).map { String($0) }
guard splitted.count == 1 || splitted.count == 2 else { return nil }
self.name = splitted[0]
self.rawParamString = splitted[at: 1]
}
init(name: String, label: String?, paramString: String) {
self.name = name
self.type = FilterType(rawValue: name)
self.label = label
self.rawParamString = paramString
}
convenience init(lavfiName: String, label: String?, params: [String]) {
var ffmpegGraph = "[\(lavfiName)="
ffmpegGraph += params.joined(separator: ":")
ffmpegGraph += "]"
self.init(name: "lavfi", label: label, paramString: ffmpegGraph)
}
convenience init(lavfiName: String, label: String?, paramDict: [String: String]) {
var ffmpegGraph = "[\(lavfiName)="
ffmpegGraph += paramDict.map { "\($0)=\($1)" }.joined(separator: ":")
ffmpegGraph += "]"
self.init(name: "lavfi", label: label, paramString: ffmpegGraph)
}
convenience init(lavfiFilterFromPresetInstance instance: FilterPresetInstance) {
var dict: [String: String] = [:]
instance.params.forEach { (k, v) in
dict[k] = v.stringValue
}
self.init(lavfiName: instance.preset.name, label: nil, paramDict: dict)
}
convenience init(mpvFilterFromPresetInstance instance: FilterPresetInstance) {
var dict: [String: String] = [:]
instance.params.forEach { (k, v) in
dict[k] = v.stringValue
}
self.init(name: instance.preset.name, label: nil, params: dict)
}
// MARK: - Others
/** The parameter order when omitting their names. */
static let formats: [FilterType: String] = [
.crop: "w:h:x:y",
.expand: "w:h:x:y:aspect:round"
]
// MARK: - Param getter
func cropParams(videoSize: NSSize) -> [String: Double] {
guard type == .crop else {
Logger.fatal("Trying to get crop params from a non-crop filter!")
}
guard let params = params else { return [:] }
// w and h should always valid
let w = Double(params["w"]!)!
let h = Double(params["h"]!)!
let x: Double, y: Double
// check x and y
if let testx = Double(params["x"] ?? ""), let testy = Double(params["y"] ?? "") {
x = testx
y = testy
} else {
let cx = Double(videoSize.width) / 2
let cy = Double(videoSize.height) / 2
x = cx - w / 2
y = cy - h / 2
}
return ["x": x, "y": y, "w": w, "h": h]
}
}
| gpl-3.0 | 272ffeaca5055c22efe8e0705962c58a | 29.482927 | 139 | 0.599936 | 3.794171 | false | false | false | false |
renshu16/DouyuSwift | DouyuSwift/DouyuSwift/Classes/Home/Controller/AmuseController.swift | 1 | 1053 | //
// AmuseController.swift
// DouyuSwift
//
// Created by ToothBond on 16/12/1.
// Copyright © 2016年 ToothBond. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200
class AmuseController: BaseAnchorContorller {
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
override func setupUI() {
super.setupUI()
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsetsMake(kMenuViewH, 0, 0, 0)
}
override func loadData () {
baseVM = amuseVM
amuseVM.loadData {
self.collectionView.reloadData()
var tempArr = self.amuseVM.anchorGroups
tempArr.removeFirst()
self.menuView.groups = tempArr
}
}
}
| mit | 9cb619422abe8f869b9de7cf58f20b18 | 23.418605 | 90 | 0.619048 | 4.6875 | false | false | false | false |
stripe/stripe-ios | StripePayments/StripePayments/API Bindings/Models/STPConnectAccountIndividualParams.swift | 1 | 9715 | //
// STPConnectAccountIndividualParams.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 8/2/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
/// Information about the person represented by the account for use with `STPConnectAccountParams`.
/// - seealso: https://stripe.com/docs/api/tokens/create_account#create_account_token-account-individual
public class STPConnectAccountIndividualParams: NSObject {
/// The individual’s primary address.
@objc public var address: STPConnectAccountAddress?
/// The Kana variation of the the individual’s primary address (Japan only).
@objc public var kanaAddress: STPConnectAccountAddress?
/// The Kanji variation of the the individual’s primary address (Japan only).
@objc public var kanjiAddress: STPConnectAccountAddress?
/// The individual’s date of birth.
/// Must include `day`, `month`, and `year`, and only those fields are used.
@objc public var dateOfBirth: DateComponents?
/// The individual's email address.
@objc public var email: String?
/// The individual’s first name.
@objc public var firstName: String?
/// The Kana variation of the the individual’s first name (Japan only).
@objc public var kanaFirstName: String?
/// The Kanji variation of the individual’s first name (Japan only).
@objc public var kanjiFirstName: String?
/// The individual’s gender
/// International regulations require either “male” or “female”.
@objc public var gender: String?
/// The government-issued ID number of the individual, as appropriate for the representative’s country.
/// Examples are a Social Security Number in the U.S., or a Social Insurance Number in Canada.
/// Instead of the number itself, you can also provide a PII token (see https://stripe.com/docs/api/tokens/create_pii).
@objc public var idNumber: String?
/// The individual’s last name.
@objc public var lastName: String?
/// The Kana varation of the individual’s last name (Japan only).
@objc public var kanaLastName: String?
/// The Kanji varation of the individual’s last name (Japan only).
@objc public var kanjiLastName: String?
/// The individual’s maiden name.
@objc public var maidenName: String?
/// Set of key-value pairs that you can attach to an object.
/// This can be useful for storing additional information about the object in a structured format.
@objc public var metadata: [AnyHashable: Any]?
/// The individual’s phone number.
@objc public var phone: String?
/// The last four digits of the individual’s Social Security Number (U.S. only).
@objc public var ssnLast4: String?
/// The individual’s verification document information.
@objc public var verification: STPConnectAccountIndividualVerification?
/// :nodoc:
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
/// :nodoc:
@objc public override var description: String {
let props: [String] = [
// Object
String(
format: "%@: %p",
NSStringFromClass(STPConnectAccountIndividualParams.self),
self
),
// Properties
"address = \(address != nil ? "<redacted>" : "")",
"kanaAddress = \(kanaAddress != nil ? "<redacted>" : "")",
"kanjiAddress = \(kanjiAddress != nil ? "<redacted>" : "")",
"dateOfBirth = \(dateOfBirth != nil ? "<redacted>" : "")",
"email = \(email != nil ? "<redacted>" : "")",
"firstName = \(firstName != nil ? "<redacted>" : "")",
"kanaFirstName = \(kanaFirstName != nil ? "<redacted>" : "")",
"kanjiFirstName = \(kanjiFirstName != nil ? "<redacted>" : "")",
"gender = \(gender != nil ? "<redacted>" : "")",
"idNumber = \(idNumber != nil ? "<redacted>" : "")",
"lastName = \(lastName != nil ? "<redacted>" : "")",
"kanaLastName = \(kanaLastName != nil ? "<redacted>" : "")",
"kanjiLastNaame = \(kanjiLastName != nil ? "<redacted>" : "")",
"maidenName = \(maidenName != nil ? "<redacted>" : "")",
"metadata = \(metadata != nil ? "<redacted>" : "")",
"phone = \(phone != nil ? "<redacted>" : "")",
"ssnLast4 = \(ssnLast4 != nil ? "<redacted>" : "")",
"verification = \(String(describing: verification))",
]
return "<\(props.joined(separator: "; "))>"
}
@objc var _dateOfBirth: STPDateOfBirth? {
guard let dateOfBirth = dateOfBirth else {
return nil
}
let dob = STPDateOfBirth()
dob.day = dateOfBirth.day ?? 0
dob.month = dateOfBirth.month ?? 0
dob.year = dateOfBirth.year ?? 0
return dob
}
}
extension STPConnectAccountIndividualParams: STPFormEncodable {
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:address)): "address",
NSStringFromSelector(#selector(getter:kanaAddress)): "address_kana",
NSStringFromSelector(#selector(getter:kanjiAddress)): "address_kanji",
NSStringFromSelector(#selector(getter:_dateOfBirth)): "dob",
NSStringFromSelector(#selector(getter:email)): "email",
NSStringFromSelector(#selector(getter:firstName)): "first_name",
NSStringFromSelector(#selector(getter:kanaFirstName)): "first_name_kana",
NSStringFromSelector(#selector(getter:kanjiFirstName)): "first_name_kanji",
NSStringFromSelector(#selector(getter:gender)): "gender",
NSStringFromSelector(#selector(getter:idNumber)): "id_number",
NSStringFromSelector(#selector(getter:lastName)): "last_name",
NSStringFromSelector(#selector(getter:kanaLastName)): "last_name_kana",
NSStringFromSelector(#selector(getter:kanjiLastName)): "last_name_kanji",
NSStringFromSelector(#selector(getter:maidenName)): "maiden_name",
NSStringFromSelector(#selector(getter:metadata)): "metadata",
NSStringFromSelector(#selector(getter:phone)): "phone",
NSStringFromSelector(#selector(getter:ssnLast4)): "ssn_last_4",
NSStringFromSelector(#selector(getter:verification)): "verification",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
}
// MARK: -
/// The individual’s verification document information for use with `STPConnectAccountIndividualParams`.
public class STPConnectAccountIndividualVerification: NSObject {
/// An identifying document, either a passport or local ID card.
@objc public var document: STPConnectAccountVerificationDocument?
/// A document showing address, either a passport, local ID card, or utility bill from a well-known utility company.
@objc public var additionalDocument: STPConnectAccountVerificationDocument?
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
}
extension STPConnectAccountIndividualVerification: STPFormEncodable {
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:document)): "document",
NSStringFromSelector(#selector(getter:additionalDocument)): "additional_document",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
}
// MARK: -
/// An identifying document, either a passport or local ID card for use with `STPConnectAccountIndividualVerification`.
public class STPConnectAccountVerificationDocument: NSObject {
/// The back of an ID returned by a file upload with a `purpose` value of `identity_document`.
/// - seealso: https://stripe.com/docs/api/files/create for file uploads
@objc public var back: String?
/// The front of an ID returned by a file upload with a `purpose` value of `identity_document`.
/// - seealso: https://stripe.com/docs/api/files/create for file uploads
@objc public var front: String?
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
}
extension STPConnectAccountVerificationDocument: STPFormEncodable {
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:back)): "back",
NSStringFromSelector(#selector(getter:front)): "front",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
}
// MARK: - Date of Birth
/// An individual's date of birth.
/// See https://stripe.com/docs/api/tokens/create_account#create_account_token-account-individual-dob
public class STPDateOfBirth: NSObject {
/// The day of birth, between 1 and 31.
@objc public var day = 0
/// The month of birth, between 1 and 12.
@objc public var month = 0
/// The four-digit year of birth.
@objc public var year = 0
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
}
extension STPDateOfBirth: STPFormEncodable {
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:day)): "day",
NSStringFromSelector(#selector(getter:month)): "month",
NSStringFromSelector(#selector(getter:year)): "year",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
}
| mit | 3fb5ae6f1ff78abd1d3411d1c888be41 | 38.317073 | 123 | 0.649194 | 4.708861 | false | false | false | false |
hollance/swift-algorithm-club | K-Means/KMeans.swift | 3 | 2846 | import Foundation
class KMeans<Label: Hashable> {
let numCenters: Int
let labels: [Label]
private(set) var centroids = [Vector]()
init(labels: [Label]) {
assert(labels.count > 1, "Exception: KMeans with less than 2 centers.")
self.labels = labels
self.numCenters = labels.count
}
private func indexOfNearestCenter(_ x: Vector, centers: [Vector]) -> Int {
var nearestDist = Double.greatestFiniteMagnitude
var minIndex = 0
for (idx, center) in centers.enumerated() {
let dist = x.distanceTo(center)
if dist < nearestDist {
minIndex = idx
nearestDist = dist
}
}
return minIndex
}
func trainCenters(_ points: [Vector], convergeDistance: Double) {
let zeroVector = Vector([Double](repeating: 0, count: points[0].length))
// Randomly take k objects from the input data to make the initial centroids.
var centers = reservoirSample(points, k: numCenters)
var centerMoveDist = 0.0
repeat {
// This array keeps track of which data points belong to which centroids.
var classification: [[Vector]] = .init(repeating: [], count: numCenters)
// For each data point, find the centroid that it is closest to.
for p in points {
let classIndex = indexOfNearestCenter(p, centers: centers)
classification[classIndex].append(p)
}
// Take the average of all the data points that belong to each centroid.
// This moves the centroid to a new position.
let newCenters = classification.map { assignedPoints in
assignedPoints.reduce(zeroVector, +) / Double(assignedPoints.count)
}
// Find out how far each centroid moved since the last iteration. If it's
// only a small distance, then we're done.
centerMoveDist = 0.0
for idx in 0..<numCenters {
centerMoveDist += centers[idx].distanceTo(newCenters[idx])
}
centers = newCenters
} while centerMoveDist > convergeDistance
centroids = centers
}
func fit(_ point: Vector) -> Label {
assert(!centroids.isEmpty, "Exception: KMeans tried to fit on a non trained model.")
let centroidIndex = indexOfNearestCenter(point, centers: centroids)
return labels[centroidIndex]
}
func fit(_ points: [Vector]) -> [Label] {
assert(!centroids.isEmpty, "Exception: KMeans tried to fit on a non trained model.")
return points.map(fit)
}
}
// Pick k random elements from samples
func reservoirSample<T>(_ samples: [T], k: Int) -> [T] {
var result = [T]()
// Fill the result array with first k elements
for i in 0..<k {
result.append(samples[i])
}
// Randomly replace elements from remaining pool
for i in k..<samples.count {
let j = Int(arc4random_uniform(UInt32(i + 1)))
if j < k {
result[j] = samples[i]
}
}
return result
}
| mit | 5246522146fc7f291287e8167d3b8af9 | 28.957895 | 88 | 0.657063 | 4.042614 | false | false | false | false |
nsagora/ios-nsagora-3 | swift-app/swift-app/swift_app.playground/section-1.swift | 1 | 393 | // Playground - noun: a place where people can play
func fibonacci(n:Int)->Int {
return (n < 2) ? 1 : fibonacci(n-2) + fibonacci(n-1);
}
fibonacci(1)
0x100_000_000
-0x100_000_000
1.79769e+308
1.7976931348623157E+308
2.22507e-308
class x {
var x:Int!
var y:Int?
}
var z = x()
("\(z.x)")
("\(z.y)")
var h:Int = z.x
var g:Int = z.y!
z.x = 10
z.y = 20
("\(z.x)")
("\(z.y)")
| apache-2.0 | 5577ccb21e448ec24b20d7d5df427670 | 10.558824 | 57 | 0.562341 | 2.171271 | false | false | false | false |
threemonkee/VCLabs | VCLabs/UIKit Catalog/Source Code/SearchBarEmbeddedInNavigationBarViewController.swift | 1 | 1733 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to present a search controller's search bar within a navigation bar.
*/
import UIKit
class SearchBarEmbeddedInNavigationBarViewController: SearchControllerBaseViewController {
// MARK: Properties
// `searchController` is set in viewDidLoad(_:).
var searchController: UISearchController!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Create the search results view controller and use it for the `UISearchController`.
let searchResultsController = storyboard!.instantiateViewControllerWithIdentifier(SearchResultsViewController.StoryboardConstants.identifier) as! SearchResultsViewController
// Create the search controller and make it perform the results updating.
searchController = UISearchController(searchResultsController: searchResultsController)
searchController.searchResultsUpdater = searchResultsController
searchController.hidesNavigationBarDuringPresentation = false
/*
Configure the search controller's search bar. For more information on
how to configure search bars, see the "Search Bar" group under "Search".
*/
searchController.searchBar.searchBarStyle = .Minimal
searchController.searchBar.placeholder = NSLocalizedString("Search", comment: "")
// Include the search bar within the navigation bar.
navigationItem.titleView = searchController.searchBar
definesPresentationContext = true
}
}
| gpl-2.0 | 904c1e65822c6bf98785e72db443672a | 40.214286 | 181 | 0.720971 | 6.657692 | false | false | false | false |
GreenvilleCocoa/ChristmasDelivery | ChristmasDelivery/LoadedSleigh.swift | 1 | 6209 | //
// LoadedSleigh.swift
// ChristmasDelivery
//
// Created by Marcus Smith on 12/8/14.
// Copyright (c) 2014 GreenvilleCocoaheads. All rights reserved.
//
import SpriteKit
class LoadedSleigh: SKNode {
var sleighComponents: [SleighComponent] = []
var theSleigh: Sleigh {
get {
return sleighComponents[0] as! Sleigh
}
}
let santa: Santa
var presents: [Present] = []
var size: CGSize = CGSize.zeroSize
var spaceBetweenComponents: CGFloat {
get {
return theSleigh.size.width * 0.05
}
}
var climbingSpeed: CGFloat {
get {
return theSleigh.size.height * 4 * (CGFloat(sleighComponents.count) / 5.0)
}
}
var targetHeight: CGFloat = 0.0
override var position: CGPoint {
didSet {
self.targetHeight = position.y
}
}
init(size: CGSize) {
self.size = size
let santaSize = CGSize(width: size.width / 4.0, height: size.height * 1.5)
self.santa = Santa(size: santaSize)
super.init()
let aSleigh = Sleigh(size: size)
sleighComponents.append(aSleigh)
for _ in 0...3 {
self.addReindeer()
}
let presentSize = CGSize(width: size.width / 6.0, height: size.width / 6.0)
for _ in 0...9 {
let present = Present(size: presentSize)
self.presents.append(present)
}
for i in 0...9 {
self.addChild(self.presents[9 - i])
}
let startingPresentY: CGFloat = (size.height / 2.0)
let middlePresentX = size.width * -0.3
// let presentHeightOffset = (presentSize.height * presentBowPercentage)
self.presents[9].position = CGPoint(x: middlePresentX + (presentSize.width / 2.0), y: startingPresentY + (presentSize.height * 1.8))
self.presents[8].position = CGPoint(x: middlePresentX + presentSize.width, y: startingPresentY + (presentSize.height * 0.95))
self.presents[7].position = CGPoint(x: middlePresentX, y: startingPresentY + (presentSize.height * 1.20))
self.presents[6].position = CGPoint(x: middlePresentX + (presentSize.width * 1.5), y: startingPresentY + (presentSize.height * 0.1))
self.presents[5].position = CGPoint(x: middlePresentX + (presentSize.width / 2.0), y: startingPresentY + (presentSize.height * 0.35))
self.presents[4].position = CGPoint(x: middlePresentX - (presentSize.width / 2.0), y: startingPresentY + (presentSize.height * 0.6))
self.presents[3].position = CGPoint(x: middlePresentX + presentSize.width * 2, y: startingPresentY - presentSize.height * 0.75)
self.presents[2].position = CGPoint(x: middlePresentX + presentSize.width, y: startingPresentY - (presentSize.height / 2.0))
self.presents[1].position = CGPoint(x: middlePresentX, y: startingPresentY - (presentSize.height / 4.0))
self.presents[0].position = CGPoint(x: middlePresentX - presentSize.width, y: startingPresentY)
self.addChild(self.santa)
self.santa.position = CGPoint(x: santa.size.width / 2.0, y: santa.size.height * 0.45)
self.addChild(aSleigh)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented, stop calling it")
}
func addReindeer() {
let previousSleighComponent = sleighComponents.last!
let reindeerSize = CGSize(width: size.width / 2.0, height: size.height)
let reindeerPosition = CGPoint(x: previousSleighComponent.position.x + (previousSleighComponent.size.width / 2.0) + (reindeerSize.width / 2.0) + spaceBetweenComponents, y: previousSleighComponent.position.y)
let aReindeer: Reindeer = Reindeer(size: reindeerSize)
self.addChild(aReindeer)
aReindeer.position = reindeerPosition
//TODO: use joint to connect to previous sleigh component
sleighComponents.append(aReindeer)
}
func moveToHeight(height: CGFloat) {
let dY = height - targetHeight
targetHeight = height
let distance = fabs(dY)
let time: NSTimeInterval = NSTimeInterval(distance / climbingSpeed)
self.climbByHeight(dY, time: time)
}
func climbByHeight(dY: CGFloat, time: NSTimeInterval) {
let fallAction: SKAction = self.makeClimbAction(-dY, time: time, sleighComponentPosition: Int(sleighComponents.count - 1))
if sleighComponents.count > 1 {
for reindeerPosition in 0...(sleighComponents.count - 2) {
let reindeer: Reindeer = sleighComponents[(sleighComponents.count) - reindeerPosition - 1] as! Reindeer
let climbAction = self.makeClimbAction(dY, time: time, sleighComponentPosition: reindeerPosition)
reindeer.runAction(climbAction)
reindeer.runAction(fallAction)
}
}
let sleighClimbAction = self.makeClimbAction(dY, time: time, sleighComponentPosition: Int(sleighComponents.count - 1))
self.runAction(sleighClimbAction)
}
func makeClimbAction(dy: CGFloat, time: NSTimeInterval, sleighComponentPosition: Int) -> SKAction {
let numberOfSleighComponents = CGFloat(sleighComponents.count)
let climbTime = NSTimeInterval((numberOfSleighComponents - 1) * 0.2) * time
let waitTime = NSTimeInterval(CGFloat(sleighComponentPosition) * 0.2) * time
let waitAction = SKAction.waitForDuration(waitTime)
let climbAction = SKAction.moveByX(0, y: dy, duration: climbTime)
let sequenceAction = SKAction.sequence([waitAction, climbAction])
return sequenceAction
}
func dropPresent() {
if presents.count < 1 {
return
}
let present = presents.removeLast()
let santaPositionInScene = self.scene!.convertPoint(santa.position, fromNode: santa.parent!)
present.removeFromParent()
self.scene!.addChild(present)
present.physicsBody!.affectedByGravity = true
present.position = santaPositionInScene
}
}
| mit | ad488e6d32c2357dd0660e75b7867294 | 40.671141 | 215 | 0.63569 | 4.391089 | false | false | false | false |
Sumolari/OperationsKit | Source/AsynchronousOperation.swift | 1 | 14365 | //
// AsynchronousOperation.swift
// OperationsKit
//
// Created by Lluís Ulzurrun de Asanza Sàez on 10/12/16.
//
//
import Foundation
import PromiseKit
import ReactiveCocoa
import ReactiveSwift
import enum Result.Result
// MARK: - Protocols
public protocol WrappableError: Swift.Error {
/**
Wraps given error, returning an instance of this type if original error
was one or an `Unknown` error if it wasn't.
- parameter error: Error to be wrapped.
- returns: Proper instance of this type for given error.
*/
static func wrap(_ error: Swift.Error) -> Self
/**
Unwraps underlying error, returning a Swift error.
- returns: Underlyting error unwrapped.
*/
func unwrap() -> Swift.Error
}
/**
Common errors that may be throw by any kind of asynchronous operation.
*/
public protocol OperationError: WrappableError {
/// The operation was cancelled.
static var Cancelled: Self { get }
/**
Error to be returned when the operation failes with given unknown error.
- parameter error: Unknown error which made the operation fail.
- returns: Properly wrapped known error.
*/
static func Unknown(_ error: Swift.Error) -> Self
}
extension OperationError {
public static func wrap(_ error: Swift.Error) -> Self {
guard let knownError = error as? Self else { return Self.Unknown(error) }
return knownError
}
}
// MARK: - Base errors
/**
Common errors that may be throw by any kind of asynchronous operation.
- canceled: The operation was cancelled.
- unknown: The operation failed due to given unknown error.
*/
public enum BaseOperationError: OperationError {
public static var Cancelled: BaseOperationError { return .cancelled }
public static func Unknown(_ error: Swift.Error) -> BaseOperationError {
return .unknown(error)
}
case cancelled
case unknown(Swift.Error)
public func unwrap() -> Swift.Error {
switch self {
case .unknown(let error):
if let wrappableError = error as? WrappableError {
return wrappableError.unwrap()
} else {
return error
}
default:
return self
}
}
}
// MARK: - Status
/**
Possible states in which an operation can be.
- pending: Operation is waiting for some dependencies to finish before it can
be started.
- ready: Operation is ready to be executed but is not running yet.
- executing: Operation is currently being executed.
- cancelled: Operation was cancelled and it isn't running any more.
- finishing: Operation was executed successfully but children operations are
running and must finish before this operation can fulfill its promise.
- finished: Operation and its children finished.
*/
public enum OperationStatus {
case pending
case ready
case executing
case cancelled
case finishing
case finished
}
// MARK: - Base asynchronous operation
/**
An `AsynchronousOperation` is a subclass of `Operation` wrapping a promise
based asynchronous operation.
*/
open class AsynchronousOperation<ReturnType, ExecutionError>: Operation
where ExecutionError: OperationError {
// MARK: Attributes
/// Reactive lifetime.
open let lifetime: ReactiveSwift.Lifetime
/// Reactive lifetime token.
open let lifetimeToken: ReactiveSwift.Lifetime.Token
/// Progress of this operation.
open let progress: Progress
/// Promise wrapping underlying promise returned by block.
open let promise: Promise<ReturnType>
/// Block to `fulfill` public promise.
fileprivate let fulfillPromise: ((ReturnType) -> Void)
/// Block to `reject` public promise, used when cancelling the operation or
/// forwarding underlying promise errors.
fileprivate let rejectPromise: ((Error) -> Void)
/// Lock used to prevent race conditions when changing internal state
/// (`isExecuting`, `isFinished`).
fileprivate let stateLock = NSLock()
/// Return value of this operation. Will be `nil` until operation finishes
/// or when there's an error.
open fileprivate(set) var result: Result<ReturnType, ExecutionError>? = nil
/// Internal, thread-unsafe, start date.
fileprivate var _startDate: Date? = nil
/// Lock used to prevent race conditions when changing internal start date.
fileprivate let startDateLock = NSLock()
/// Date when this operation started. Thread-safe.
open fileprivate(set) var startDate: Date? {
get {
return self.startDateLock.withCriticalScope { self._startDate }
}
set {
self.startDateLock.withCriticalScope {
self._startDate = newValue
}
}
}
/// Internal, thread-unsafe, end date.
fileprivate var _endDate: Date? = nil
/// Lock used to prevent race conditions when changing internal end date.
fileprivate let endDateLock = NSLock()
/// Date when this operation ended. Thread-safe.
open fileprivate(set) var endDate: Date? {
get {
return self.endDateLock.withCriticalScope { self._endDate }
}
set {
self.endDateLock.withCriticalScope {
self._endDate = newValue
}
}
}
/// Time interval ellapsed to complete this operation.
open var executionDuration: TimeInterval? {
guard let start = self.startDate else { return nil }
return self.endDate?.timeIntervalSince(start)
}
/// Current status of this operation.
open var status: OperationStatus {
guard self.isReady else { return .pending }
guard self.isExecuting || self.isFinished else { return .ready }
if self.isExecuting { return .executing }
if self.isCancelled { return .cancelled }
if self.promise.isResolved { return .finished }
return .finishing
}
/**
Internal attribute used to store whether this operation is executing or
not.
- note: This attribute is **not** thread safe and should not be used
directly. Use `isExecuting` attribute instead.
*/
fileprivate var _executing: Bool = false
override fileprivate(set) open var isExecuting: Bool {
get {
return self.stateLock.withCriticalScope { self._executing }
}
set {
guard self.isExecuting != newValue else { return }
willChangeValue(forKey: "isExecuting")
self.stateLock.withCriticalScope {
self._executing = newValue
if newValue {
self.startDate = Date()
}
}
didChangeValue(forKey: "isExecuting")
}
}
/**
Internal attribute used to store whether this operation is finished or
not.
- note: This attribute is **not** thread safe and should not be used
directly. Use `isFinished` attribute instead.
*/
private var _finished: Bool = false
override fileprivate(set) open var isFinished: Bool {
get {
return self.stateLock.withCriticalScope { self._finished }
}
set {
guard self.isFinished != newValue else { return }
willChangeValue(forKey: "isFinished")
self.stateLock.withCriticalScope {
self._finished = newValue
if newValue {
self.endDate = Date()
}
}
didChangeValue(forKey: "isFinished")
}
}
open override var isConcurrent: Bool { return true }
open override var isAsynchronous: Bool { return true }
// MARK: Constructors
/**
Creates a new operation whose progress will be tracked by given progress.
- parameter progress: Progress tracking new operation's progress. If
`nil` operation's progress will remain the default one: a stalled progress
with a total count of 0 units.
*/
public init(progress: Progress? = nil) {
(
self.promise,
self.fulfillPromise,
self.rejectPromise
) = Promise<ReturnType>.pending()
self.progress = progress ?? Progress(totalUnitCount: 0)
(self.lifetime, self.lifetimeToken) = ReactiveSwift.Lifetime.make()
super.init()
}
// MARK: Status-change methods
/// Do not override this method. You must override `execute` method instead.
open override func main() {
guard !self.isCancelled else { return }
self.isExecuting = true
do {
try self.execute()
} catch let error {
self.finish(error: ExecutionError.wrap(error))
}
}
open override func cancel() {
guard !self.promise.isResolved else { return }
super.cancel()
self.isExecuting = false
self.isFinished = true
self._finish(error: ExecutionError.Cancelled)
}
/**
Changes internal state to reflect that this operation has finished its own
execution but does not resolve underlying promise, leaving the operation in
the `finishing` state.
- returns: `false` if operation was previously cancelled.
*/
fileprivate func moveToFinishing() -> Bool {
guard !self.isCancelled else { return false }
self.isExecuting = false
self.isFinished = true
return true
}
/**
Successfully finishes this operation regardless its cancellation state.
- warning: Will ignore `isCancelled` attribute, potentially fulfilling an
already rejected promise.
- parameter returnValue: Value to be used to fulfill promise.
*/
fileprivate func _finish(_ returnValue: ReturnType) {
self.progress.completedUnitCount = self.progress.totalUnitCount
self.result = .success(returnValue)
self.fulfillPromise(returnValue)
}
/**
You should call this method when your operation and its children operations
successfully.
- note: Moves this operation to `finished` status.
- note: Fulfills underlying promise, passing value to chained promises.
- parameter returnValue: Value to be used to fulfill promise.
*/
open func finish(_ returnValue: ReturnType) {
if self.moveToFinishing() {
self._finish(returnValue)
}
}
/**
Finishes this operation with given error, regardless its cancellation
state.
- warning: Will ignore `isCancelled` attribute, potentially rejecting an
already rejected promise.
- parameter error: Error to be thrown back.
*/
fileprivate func _finish(error: Swift.Error) {
self.progress.completedUnitCount = self.progress.totalUnitCount
let wrappedError = ExecutionError.wrap(error)
self.result = .failure(wrappedError)
self.rejectPromise(wrappedError)
}
/**
You should call this method when your operation or its children operations
finish with an error.
- note: Moves this operation to `finished` status.
- note: Rejects underlying promise, passing error to chained promises.
- parameter error: Error to be thrown back.
*/
open func finish(error: Swift.Error) {
if self.moveToFinishing() {
self._finish(error: error)
}
}
/**
Convenience method to finish this operation chaining the result of a
promise, useful to avoid boilerplate when dealing with children operations.
- warning: This method won't prevent deadlocks when enqueuing children
operations in the same queue used to enqueue parent. If you want to prevent
deadlocks you must use `finish(immediatelyForwarding:)` method.
- parameter promise: Promise whose result will be used to finish this
operation, successfully or not.
*/
open func finish(waitingAndForwarding promise: Promise<ReturnType>) {
promise
.then { self.finish($0) }
.catch { self.finish(error: $0) }
}
/**
Convenience method to finish this operation chaining the result of a
promise, useful to avoid boilerplate when dealing with children operations.
- note: This method will prevent deadlocks when enqueuing children
operations in the same queue used to enqueue parent as will move parent
operation to `finishing` status, dequeuing it from queue.
- warning: You must hold a strong reference to this operation or its promise
if you want to retrieve its result later on as the operation queue will
remove its reference.
- parameter promise: Promise whose result will be used to finish this
operation, successfully or not.
*/
open func finish(immediatelyForwarding promise: Promise<ReturnType>) {
if self.moveToFinishing() {
promise
.then { result -> Void in
guard !self.isCancelled else { return }
self._finish(result)
}
.catch { error in
guard !self.isCancelled else { return }
self._finish(error: error)
}
}
}
// MARK: Overridable methods
/**
Performs task.
- note: You must override this method in your subclasses.
- note: You must signal execution's end using `finish()` methods family.
- warning: Do not call `super.execute()`.
- throws: Any error throw will be catch and forwarded to `finish(error:)`.
*/
open func execute() throws {
fatalError("To be implemented by subclasses. You must not call `super.execute` method from a child class.")
}
}
| mit | c349bab2a587660d74970b8b85c10fb1 | 29.690171 | 115 | 0.61742 | 5.259246 | false | false | false | false |
DungntVccorp/mikrotik_router_manager | Sources/CORE/MikrotikConnection.swift | 1 | 39828 | //
// MikrotikConnection.swift
// mikrotik_router_manager
//
// Created by dung.nt on 8/21/17.
//
//
import Foundation
import Socket
import CryptoSwift
public enum ReturnType {
case NONE
case DONE
case TRAP
case HALT
case RE
}
public enum SentenceError : Error{
case NoData
case DataFailure
case DataInvalidFormat
}
public enum MikrotikConnectionError : Error{
case LOGIN
case API
case MISSING_PARAM
case UNKNOW
}
public enum ApiType {
case SET
case GET
case ADD
case DEL
}
public class Request{
var api : String!
var params : Dictionary<String,String>?
var apiType : ApiType? = .GET
var querys : Dictionary<String,String>?
var uid : String?
init(api : String,type : ApiType? = .GET,p : Dictionary<String,String>? = nil,q : Dictionary<String,String>? = nil,u : String? = nil ) {
self.api = api
self.apiType = type
self.params = p
self.querys = q
self.uid = u
}
}
public class Sentence{
var returnType : ReturnType = .NONE /// 0 = NONE
var SentenceData = Array<Dictionary<String,String>>()
var isDone : Bool = false
private var oldData : Data!
func ReadLength(data : Data) -> (Int,Int){ /// LEN - SIZE
if data.count < 1 {
return (-1,0)
}
let firstChar = data[0]
if (firstChar & 0xE0) == 0xE0 {
}else if (firstChar & 0xC0) == 0xC0 {
}else if (firstChar & 0x80) == 0x80 { // 2-byte encoded length
var c = Int(firstChar)
c = c & ~0xC0;
c = (c << 8) | Int(data[1])
return (c,2)
}else { // assume 1-byte encoded length...same on both LE and BE systems
return (Int(firstChar),1)
}
return (-1,0)
}
init(data : Data) throws {
guard data.count > 3 else {
throw SentenceError.NoData
}
let len = self.ReadLength(data: data)
guard len.0 > 0 else {
throw SentenceError.DataInvalidFormat
}
let typeData = data.subdata(in: len.1..<len.0+len.1)
let strType = String(data: typeData, encoding: String.Encoding.utf8)
guard strType != nil else {
throw SentenceError.DataInvalidFormat
}
if strType! == "!done" {
self.returnType = .DONE
isDone = true
self.unPackDone(data: data.subdata(in: len.0+len.1..<data.count))
}else if strType == "!trap"{
self.returnType = .TRAP
isDone = true
self.unPackTrap(data: data.subdata(in: len.0+len.1..<data.count))
}else if strType == "!re"{
self.returnType = .RE
SentenceData.append([:])
self.unPackRe(data: data.subdata(in: len.0+len.1..<data.count))
}
}
func updateData(data : Data){
if oldData != nil {
oldData.append(data)
self.unPackRe(data: oldData)
oldData = nil
}else{
self.unPackRe(data: data)
}
}
func unPackDone(data : Data){
let len = self.ReadLength(data: data)
if len.0 > 0 {
let contentData = data.subdata(in: len.1..<len.0+len.1)
if let strContent = String(data: contentData, encoding: String.Encoding.utf8){
let arr = strContent.components(separatedBy: "=")
if arr.count == 3 {
var dic = Dictionary<String,String>()
dic[arr[1]] = arr[2]
SentenceData.append(dic)
}
}
self.unPackDone(data: data.subdata(in: len.0+len.1..<data.count))
}
}
func unPackTrap(data : Data){
let len = self.ReadLength(data: data)
if len.0 > 0 {
let contentData = data.subdata(in: len.1..<len.0+len.1)
if let strContent = String(data: contentData, encoding: String.Encoding.ascii){
let arr = strContent.components(separatedBy: "=")
if arr.count == 3 {
var dic = Dictionary<String,String>()
dic[arr[1]] = arr[2]
SentenceData.append(dic)
}
}
self.unPackTrap(data: data.subdata(in: len.0+len.1..<data.count))
}
}
func unPackRe(data : Data){
let len = self.ReadLength(data: data)
if len.0 < 0 {
return
}
if data.count < len.1 || data.count < len.0 + len.1 {
oldData = data
return // dư data
}
let contentData = data.subdata(in: len.1..<len.0+len.1)
if let strContent = String(data: contentData, encoding: String.Encoding.utf8){
if strContent.isEmpty == false {
if strContent == "!re" {
SentenceData.append([:])
}else{
if strContent != "!done" {
let arr = strContent.components(separatedBy: "=")
if arr.count == 3 {
SentenceData[SentenceData.count - 1][arr[1]] = arr[2]
}
}
}
//SentenceData.append(strContent)
}
if strContent != "!done" {
self.unPackRe(data: data.subdata(in: len.0+len.1..<data.count))
}else{
isDone = true
}
}
}
}
class MikrotikConnection{
var userName : String!
var password : String!
var hostName : String!
var hostPort : Int = 0
var tcpSocket : Socket!
init(host : String,port : Int,userName : String,password : String) {
self.userName = userName
self.password = password
self.hostName = host
self.hostPort = port
}
func send(word : String,endsentence : Bool) -> Bool{
if word.isEmpty {
if endsentence {
do{
try self.tcpSocket.write(from: Data(bytes: [0x0]))
}catch{
return false
}
}
return true
}else{
if let data = word.data(using: String.Encoding.utf8){
var len = data.count
do{
if len < 0x80 {
var data = Data()
data.append([UInt8(len)], count: 1)
try self.tcpSocket.write(from: data)
}else if len < 0x4000 {
len = len | 0x8000;
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 8)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len)]))
}else if len < 0x20000 {
len = len | 0xC00000;
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 16)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 8)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len)]))
}
else if len < 0x10000000 {
len = len | 0xE0000000;
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 24)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 16)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 8)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len)]))
}else{
try self.tcpSocket.write(from: Data(bytes: [0xF0]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 24)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 16)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len >> 8)]))
try self.tcpSocket.write(from: Data(bytes: [UInt8(len)]))
}
try self.tcpSocket.write(from: data)
if endsentence {
try self.tcpSocket.write(from: Data(bytes: [0x0]))
}
return true
}catch{
return false
}
}
}
return false
}
func sendAPIs(requests : Array<Request>) -> (Bool,Error?,Array<Sentence>?){
do{
tcpSocket = try Socket.create()
tcpSocket.readBufferSize = 4096
try tcpSocket.connect(to: self.hostName, port: Int32(self.hostPort), timeout: 2000)
/// SEND GET TOKEN
var success : Bool = false
success = self.send(word: "/login", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// READ TOKEN
var data : Data = Data()
var lenRead = try tcpSocket.read(into: &data)
guard lenRead > 0 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// read type
let sentence = try Sentence(data: data)
guard sentence.returnType == .DONE else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// SEND LOGIN
success = self.send(word: "/login", endsentence: false)
guard success == true && self.userName != nil else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
success = self.send(word: "=name=\(self.userName!)",endsentence: false)
guard success == true && sentence.SentenceData.count == 1 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
var chal = self.hexStringToBytes("00")!
chal = chal + password.data(using: String.Encoding.ascii)!.bytes
chal = chal + self.hexStringToBytes(sentence.SentenceData[0]["ret"]!)!
chal = chal.md5()
success = self.send(word: "=response=00\(chal.toHexString())",endsentence: true)
guard success == true && sentence.SentenceData.count == 1 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
guard lenRead > 0 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
let sentenceLoginS2 = try Sentence(data: data)
guard sentenceLoginS2.returnType == .DONE else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// LOGIN SUCCESS
var result = Array<Sentence>()
for r in requests{
if r.apiType == .GET {
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
success = self.send(word: "=detail=", endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if r.querys != nil {
var i = 0
for p in r.querys! {
i = i + 1
success = self.send(word: "?\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
result.append(sentenceData)
}
else if r.apiType == .SET{
if r.params == nil{
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if r.uid != nil {
success = self.send(word: "=.id=\(r.uid!)", endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
if r.params != nil {
var i = 0
for p in r.params! {
i = i + 1
success = self.send(word: "=\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
result.append(sentenceData)
}
else if r.apiType == .ADD{
if r.params == nil {
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if r.params != nil {
var i = 0
for p in r.params! {
i = i + 1
success = self.send(word: "=\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
result.append(sentenceData)
}
else{ // DELETE
if r.uid == nil {
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
success = self.send(word: "=.id=\(r.uid!)", endsentence:true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
result.append(sentenceData)
}
}
tcpSocket.close()
return (true,nil,result)
}catch{
return (false,error,nil)
}
}
func sendAPI2(r : Request) -> (Bool,Error?,Sentence?){ // ISSUCCESS - ERROR - Sentence
do {
tcpSocket = try Socket.create()
tcpSocket.readBufferSize = 4096
try tcpSocket.connect(to: self.hostName, port: Int32(self.hostPort), timeout: 2000)
/// SEND GET TOKEN
var success : Bool = false
success = self.send(word: "/login", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// READ TOKEN
var data : Data = Data()
var lenRead = try tcpSocket.read(into: &data)
guard lenRead > 0 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// read type
let sentence = try Sentence(data: data)
guard sentence.returnType == .DONE else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// SEND LOGIN
success = self.send(word: "/login", endsentence: false)
guard success == true && self.userName != nil else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
success = self.send(word: "=name=\(self.userName!)",endsentence: false)
guard success == true && sentence.SentenceData.count == 1 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
var chal = self.hexStringToBytes("00")!
chal = chal + password.data(using: String.Encoding.ascii)!.bytes
chal = chal + self.hexStringToBytes(sentence.SentenceData[0]["ret"]!)!
chal = chal.md5()
success = self.send(word: "=response=00\(chal.toHexString())",endsentence: true)
guard success == true && sentence.SentenceData.count == 1 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
guard lenRead > 0 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
let sentenceLoginS2 = try Sentence(data: data)
guard sentenceLoginS2.returnType == .DONE else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// send abc
if r.apiType == .GET {
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
success = self.send(word: "=detail=", endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if r.querys != nil {
var i = 0
for p in r.querys! {
i = i + 1
success = self.send(word: "?\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
else if r.apiType == .SET{
if r.params == nil{
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if r.uid != nil {
success = self.send(word: "=.id=\(r.uid!)", endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
if r.params != nil {
var i = 0
for p in r.params! {
i = i + 1
success = self.send(word: "=\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
else if r.apiType == .ADD{
if r.params == nil {
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if r.params != nil {
var i = 0
for p in r.params! {
i = i + 1
success = self.send(word: "=\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
else{ // DELETE
if r.uid == nil {
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: r.api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
success = self.send(word: "=.id=\(r.uid!)", endsentence:true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
} catch {
return (false,error,nil)
}
}
func sendAPI(api : String , params : Dictionary<String,String>? = nil,apiType : ApiType = .GET,querys : Dictionary<String,String>? = nil,uid : String? = nil) -> (Bool,Error?,Sentence?){ // ISSUCCESS - ERROR - Sentence
do {
tcpSocket = try Socket.create()
tcpSocket.readBufferSize = 4096
try tcpSocket.connect(to: self.hostName, port: Int32(self.hostPort), timeout: 2000)
/// SEND GET TOKEN
var success : Bool = false
success = self.send(word: "/login", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// READ TOKEN
var data : Data = Data()
var lenRead = try tcpSocket.read(into: &data)
guard lenRead > 0 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// read type
let sentence = try Sentence(data: data)
guard sentence.returnType == .DONE else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// SEND LOGIN
success = self.send(word: "/login", endsentence: false)
guard success == true && self.userName != nil else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
success = self.send(word: "=name=\(self.userName!)",endsentence: false)
guard success == true && sentence.SentenceData.count == 1 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
var chal = self.hexStringToBytes("00")!
chal = chal + password.data(using: String.Encoding.ascii)!.bytes
chal = chal + self.hexStringToBytes(sentence.SentenceData[0]["ret"]!)!
chal = chal.md5()
success = self.send(word: "=response=00\(chal.toHexString())",endsentence: true)
guard success == true && sentence.SentenceData.count == 1 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
guard lenRead > 0 else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
let sentenceLoginS2 = try Sentence(data: data)
guard sentenceLoginS2.returnType == .DONE else {
tcpSocket.close()
return (false,MikrotikConnectionError.LOGIN,nil)
}
/// send abc
if apiType == .GET {
success = self.send(word: api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
success = self.send(word: "=detail=", endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if querys != nil {
var i = 0
for p in querys! {
i = i + 1
success = self.send(word: "?\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
else if apiType == .SET{
if params == nil || uid == nil {
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
success = self.send(word: "=.id=\(uid!)", endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if params != nil {
var i = 0
for p in params! {
i = i + 1
success = self.send(word: "=\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
else if apiType == .ADD{
if params == nil {
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
if params != nil {
var i = 0
for p in params! {
i = i + 1
success = self.send(word: "=\(p.key)=\(p.value)", endsentence: false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
}
}
success = self.send(word: "", endsentence: true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
else{ // DELETE
if uid == nil {
return (false,MikrotikConnectionError.MISSING_PARAM,nil)
}
success = self.send(word: api, endsentence:false)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
success = self.send(word: "=.id=\(uid!)", endsentence:true)
guard success == true else {
tcpSocket.close()
return (false,MikrotikConnectionError.API,nil)
}
var sentenceData : Sentence!
repeat{
data.removeAll()
lenRead = 0
lenRead = try tcpSocket.read(into: &data)
if sentenceData == nil {
sentenceData = try Sentence(data: data)
}
else{
sentenceData.updateData(data: data)
}
}while !sentenceData.isDone
tcpSocket.close()
return (true,nil,sentenceData)
}
} catch {
return (false,error,nil)
}
}
func hexStringToBytes(_ string: String) -> [UInt8]? {
let length = string.characters.count
if length & 1 != 0 {
return nil
}
var bytes = [UInt8]()
bytes.reserveCapacity(length/2)
var index = string.startIndex
for _ in 0..<length/2 {
let nextIndex = string.index(index, offsetBy: 2)
if let b = UInt8(string[index..<nextIndex], radix: 16) {
bytes.append(b)
} else {
return nil
}
index = nextIndex
}
return bytes
}
}
| apache-2.0 | afc896c76d542eb8c31dda3a20f80dcc | 37.893555 | 221 | 0.4278 | 5.618933 | false | false | false | false |
ben-ng/swift | stdlib/public/SDK/Dispatch/Private.swift | 1 | 15349 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Redeclarations of all SwiftPrivate functions with appropriate markup.
@available(*, unavailable, renamed:"DispatchQueue.init(label:qos:attributes:autoreleaseFrequency:target:)")
public func dispatch_queue_create(_ label: UnsafePointer<Int8>?, _ attr: __OS_dispatch_queue_attr?) -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.init(label:qos:attributes:autoreleaseFrequency:target:)")
public func dispatch_queue_create_with_target(_ label: UnsafePointer<Int8>?, _ attr: __OS_dispatch_queue_attr?, _ queue: DispatchQueue?) -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.init(type:fileDescriptor:queue:cleanupHandler:)")
public func dispatch_io_create(_ type: UInt, _ fd: Int32, _ queue: DispatchQueue, _ cleanup_handler: (Int32) -> Void) -> DispatchIO
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.init(type:path:oflag:mode:queue:cleanupHandler:)")
public func dispatch_io_create_with_path(_ type: UInt, _ path: UnsafePointer<Int8>, _ oflag: Int32, _ mode: mode_t, _ queue: DispatchQueue, _ cleanup_handler: (Int32) -> Void) -> DispatchIO
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.init(type:io:queue:cleanupHandler:)")
public func dispatch_io_create_with_io(_ type: UInt, _ io: DispatchIO, _ queue: DispatchQueue, _ cleanup_handler: (Int32) -> Void) -> DispatchIO
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.read(fileDescriptor:length:queue:handler:)")
public func dispatch_read(_ fd: Int32, _ length: Int, _ queue: DispatchQueue, _ handler: (__DispatchData, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.read(self:offset:length:queue:ioHandler:)")
func dispatch_io_read(_ channel: DispatchIO, _ offset: off_t, _ length: Int, _ queue: DispatchQueue, _ io_handler: (Bool, __DispatchData?, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.write(self:offset:data:queue:ioHandler:)")
func dispatch_io_write(_ channel: DispatchIO, _ offset: off_t, _ data: __DispatchData, _ queue: DispatchQueue, _ io_handler: (Bool, __DispatchData?, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.write(fileDescriptor:data:queue:handler:)")
func dispatch_write(_ fd: Int32, _ data: __DispatchData, _ queue: DispatchQueue, _ handler: (__DispatchData?, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.init(bytes:)")
public func dispatch_data_create(_ buffer: UnsafeRawPointer, _ size: Int, _ queue: DispatchQueue?, _ destructor: (() -> Void)?) -> __DispatchData
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchData.count(self:)")
public func dispatch_data_get_size(_ data: __DispatchData) -> Int
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.withUnsafeBytes(self:body:)")
public func dispatch_data_create_map(_ data: __DispatchData, _ buffer_ptr: UnsafeMutablePointer<UnsafeRawPointer?>?, _ size_ptr: UnsafeMutablePointer<Int>?) -> __DispatchData
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.append(self:_:)")
public func dispatch_data_create_concat(_ data1: __DispatchData, _ data2: __DispatchData) -> __DispatchData
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.subdata(self:in:)")
public func dispatch_data_create_subrange(_ data: __DispatchData, _ offset: Int, _ length: Int) -> __DispatchData
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.enumerateBytes(self:block:)")
public func dispatch_data_apply(_ data: __DispatchData, _ applier: (__DispatchData, Int, UnsafeRawPointer, Int) -> Bool) -> Bool
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.region(self:location:)")
public func dispatch_data_copy_region(_ data: __DispatchData, _ location: Int, _ offset_ptr: UnsafeMutablePointer<Int>) -> __DispatchData
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.asynchronously(self:group:qos:flags:execute:)")
public func dispatch_group_async(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed: "DispatchGroup.notify(self:qos:flags:queue:execute:)")
public func dispatch_group_notify(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchGroup.wait(self:timeout:)")
public func dispatch_group_wait(_ group: DispatchGroup, _ timeout: dispatch_time_t) -> Int
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.close(self:flags:)")
public func dispatch_io_close(_ channel: DispatchIO, _ flags: UInt)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.setInterval(self:interval:flags:)")
public func dispatch_io_set_interval(_ channel: DispatchIO, _ interval: UInt64, _ flags: UInt)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.apply(attributes:iterations:execute:)")
public func dispatch_apply(_ iterations: Int, _ queue: DispatchQueue, _ block: (Int) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.asynchronously(self:execute:)")
public func dispatch_async(_ queue: DispatchQueue, _ block: () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.global(attributes:)")
public func dispatch_get_global_queue(_ identifier: Int, _ flags: UInt) -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed: "getter:DispatchQueue.main()")
public func dispatch_get_main_queue() -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.Attributes.initiallyInactive")
public func dispatch_queue_attr_make_initially_inactive(_ attr: __OS_dispatch_queue_attr?) -> __OS_dispatch_queue_attr
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.AutoreleaseFrequency.workItem")
public func dispatch_queue_attr_make_with_autorelease_frequency(_ attr: __OS_dispatch_queue_attr?, _ frequency: __dispatch_autorelease_frequency_t) -> __OS_dispatch_queue_attr
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQoS")
public func dispatch_queue_attr_make_with_qos_class(_ attr: __OS_dispatch_queue_attr?, _ qos_class: qos_class_t, _ relative_priority: Int32) -> __OS_dispatch_queue_attr
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchQueue.label(self:)")
public func dispatch_queue_get_label(_ queue: DispatchQueue?) -> UnsafePointer<Int8>
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchQueue.qos(self:)")
public func dispatch_queue_get_qos_class(_ queue: DispatchQueue, _ relative_priority_ptr: UnsafeMutablePointer<Int32>?) -> qos_class_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.asyncAfter(self:deadline:qos:flags:execute:)")
public func dispatch_after(_ when: dispatch_time_t, _ queue: DispatchQueue, _ block: () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.async(self:group:qos:flags:execute:)")
public func dispatch_barrier_async(_ queue: DispatchQueue, _ block: () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.sync(self:flags:execute:)")
public func dispatch_barrier_sync(_ queue: DispatchQueue, _ block: () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.setSpecific(self:key:value:)")
public func dispatch_queue_set_specific(_ queue: DispatchQueue, _ key: UnsafeRawPointer, _ context: UnsafeMutableRawPointer?, _ destructor: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.getSpecific(self:key:)")
public func dispatch_queue_get_specific(_ queue: DispatchQueue, _ key: UnsafeRawPointer) -> UnsafeMutableRawPointer?
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.getSpecific(key:)")
public func dispatch_get_specific(_ key: UnsafeRawPointer) -> UnsafeMutableRawPointer?
{
fatalError()
}
@available(*, unavailable, renamed:"dispatchPrecondition(_:)")
public func dispatch_assert_queue(_ queue: DispatchQueue)
{
fatalError()
}
@available(*, unavailable, renamed:"dispatchPrecondition(_:)")
public func dispatch_assert_queue_barrier(_ queue: DispatchQueue)
{
fatalError()
}
@available(*, unavailable, renamed:"dispatchPrecondition(_:)")
public func dispatch_assert_queue_not(_ queue: DispatchQueue)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSemaphore.wait(self:timeout:)")
public func dispatch_semaphore_wait(_ dsema: DispatchSemaphore, _ timeout: dispatch_time_t) -> Int
{
fatalError()
}
@available(*, unavailable, renamed: "DispatchSemaphore.signal(self:)")
public func dispatch_semaphore_signal(_ dsema: DispatchSemaphore) -> Int
{
fatalError()
}
@available(*, unavailable, message:"Use DispatchSource class methods")
public func dispatch_source_create(_ type: __dispatch_source_type_t, _ handle: UInt, _ mask: UInt, _ queue: DispatchQueue?) -> DispatchSource
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.setEventHandler(self:handler:)")
public func dispatch_source_set_event_handler(_ source: DispatchSource, _ handler: (() -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.setCancelHandler(self:handler:)")
public func dispatch_source_set_cancel_handler(_ source: DispatchSource, _ handler: (() -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.cancel(self:)")
public func dispatch_source_cancel(_ source: DispatchSource)
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.isCancelled(self:)")
public func dispatch_source_testcancel(_ source: DispatchSource) -> Int
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.handle(self:)")
public func dispatch_source_get_handle(_ source: DispatchSource) -> UInt
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.mask(self:)")
public func dispatch_source_get_mask(_ source: DispatchSource) -> UInt
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.data(self:)")
public func dispatch_source_get_data(_ source: DispatchSource) -> UInt
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchUserDataAdd.mergeData(self:value:)")
public func dispatch_source_merge_data(_ source: DispatchSource, _ value: UInt)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchTimerSource.setTimer(self:start:interval:leeway:)")
public func dispatch_source_set_timer(_ source: DispatchSource, _ start: dispatch_time_t, _ interval: UInt64, _ leeway: UInt64)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.setRegistrationHandler(self:handler:)")
public func dispatch_source_set_registration_handler(_ source: DispatchSource, _ handler: (() -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchTime.now()")
public func dispatch_time(_ when: dispatch_time_t, _ delta: Int64) -> dispatch_time_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchWalltime.init(time:)")
public func dispatch_walltime(_ when: UnsafePointer<timespec>?, _ delta: Int64) -> dispatch_time_t
{
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.high")
public var DISPATCH_QUEUE_PRIORITY_HIGH: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.default")
public var DISPATCH_QUEUE_PRIORITY_DEFAULT: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.low")
public var DISPATCH_QUEUE_PRIORITY_LOW: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.background")
public var DISPATCH_QUEUE_PRIORITY_BACKGROUND: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.StreamType.stream")
public var DISPATCH_IO_STREAM: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.StreamType.random")
public var DISPATCH_IO_RANDOM: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.CloseFlags.stop")
public var DISPATCH_IO_STOP: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.IntervalFlags.strictInterval")
public var DISPATCH_IO_STRICT_INTERVAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MachSendEvent.dead")
public var DISPATCH_MACH_SEND_DEAD: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.normal")
public var DISPATCH_MEMORYPRESSURE_NORMAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.warning")
public var DISPATCH_MEMORYPRESSURE_WARN: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.critical")
public var DISPATCH_MEMORYPRESSURE_CRITICAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.exit")
public var DISPATCH_PROC_EXIT: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.fork")
public var DISPATCH_PROC_FORK: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.exec")
public var DISPATCH_PROC_EXEC: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.signal")
public var DISPATCH_PROC_SIGNAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.TimerFlags.strict")
public var DISPATCH_TIMER_STRICT: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.delete")
public var DISPATCH_VNODE_DELETE: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.write")
public var DISPATCH_VNODE_WRITE: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.extend")
public var DISPATCH_VNODE_EXTEND: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.attrib")
public var DISPATCH_VNODE_ATTRIB: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.link")
public var DISPATCH_VNODE_LINK: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.rename")
public var DISPATCH_VNODE_RENAME: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.revoke")
public var DISPATCH_VNODE_REVOKE: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.funlock")
public var DISPATCH_VNODE_FUNLOCK: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchTime.now()")
public var DISPATCH_TIME_NOW: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchTime.distantFuture")
public var DISPATCH_TIME_FOREVER: Int {
fatalError()
}
| apache-2.0 | 3e9a1348ba9e2dab632d72f752f5c3e0 | 31.519068 | 193 | 0.733663 | 3.948804 | false | false | false | false |
danthorpe/Examples | Operations/Permissions/Permissions/UserNotificationSettingsViewController.swift | 1 | 3124 | //
// UserNotificationSettingsViewController.swift
// Permissions
//
// Created by Daniel Thorpe on 04/08/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import UIKit
import Operations
enum UserNotificationSettings {
case Simple
var type: UIUserNotificationType {
switch self {
case .Simple:
return .Badge
}
}
var categories: Set<UIUserNotificationCategory>? {
return .None
}
var settings: UIUserNotificationSettings {
return UIUserNotificationSettings(forTypes: type, categories: categories)
}
}
class UserNotificationSettingsViewController: PermissionViewController {
var currentUserNotificationSettings: UIUserNotificationSettings {
return UserNotificationSettings.Simple.settings
}
var condition: UserNotificationCondition {
return UserNotificationCondition(settings: currentUserNotificationSettings, behavior: .Merge)
}
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("User Notifications", comment: "User Notifications")
permissionNotDetermined.informationLabel.text = "We haven't yet asked for permission to set the User Notification Settings."
permissionDenied.informationLabel.text = "Currently settings are not sufficient. 😞"
permissionGranted.instructionLabel.text = "We don't support any User Notification Operations"
permissionGranted.button.hidden = true
}
override func viewWillAppear(animated: Bool) {
determineAuthorizationStatus()
}
override func conditionsForState(state: State, silent: Bool) -> [Condition] {
return configureConditionsForState(state, silent: silent)(condition)
}
func determineAuthorizationStatus(silently silently: Bool = true) {
// Create a simple block operation to set the state.
let authorized = BlockOperation { (continueWithError: BlockOperation.ContinuationBlockType) in
self.state = .Authorized
continueWithError(error: nil)
}
authorized.name = "Authorized Access"
// Additionally, suppress the automatic request if not authorized.
authorized.addCondition(silently ? SilentCondition(condition) : condition)
// Attach an observer so that we can inspect any condition errors
// From here, we can determine the authorization status if not
// authorized.
authorized.addObserver(BlockObserver { (_, errors) in
if let error = errors.first as? UserNotificationCondition.Error {
switch error {
case let .SettingsNotSufficient(current: current, desired: _):
if let _ = current {
self.state = .Denied
}
else {
self.state = .Unknown
}
}
}
})
queue.addOperation(authorized)
}
override func requestPermission() {
determineAuthorizationStatus(silently: false)
}
}
| mit | 450986160c00f4ef7dcbe366879886a5 | 30.525253 | 132 | 0.655559 | 5.716117 | false | false | false | false |
CanBeMyQueen/DouYuZB | DouYu/DouYu/Classes/Home/View/AmuseMenuCollectionViewCell.swift | 1 | 1541 | //
// AmuseMenuCollectionViewCell.swift
// DouYu
//
// Created by 张萌 on 2018/1/23.
// Copyright © 2018年 JiaYin. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class AmuseMenuCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var groups : [AnchorGroupModel]? {
didSet {
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let itemW = collectionView.bounds.size.width / 4
let itemH = collectionView.bounds.size.height / 2
layout.itemSize = CGSize(width: itemW, height: itemH)
}
}
extension AmuseMenuCollectionViewCell : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! CollectionViewGameCell
cell.clipsToBounds = true
cell.group = groups?[indexPath.row]
return cell
}
}
| mit | 6e6895c1371c85f2f2615ccbb2ef1964 | 33.088889 | 130 | 0.711213 | 5.2 | false | false | false | false |
hyouuu/DateWeatherEmblemView | EmblemView.swift | 1 | 7471 | //
// EmblemView.swift
// Noter
//
// Created by hyouuu on 11/11/14.
//
import Foundation
@objc class EmblemView: UIView, CLLocationManagerDelegate {
let edgePad = 6.f
let weatherImageSide = 46.f
var timer: NSTimer!
// Fire every 45 seconds is good enough for the clock which only care about minute
let timerIntervalInSec = 45
var timerFireCount = 0
let weatherUpdateIntervalInMinute: Int = 30
var lastWeatherUpdateDate = NSDate()
var lastLocationUpdateDate = NSDate()
let timeLabel = UILabel()
let dateLabel = UILabel()
let weatherImageView = UIImageView()
let weatherLabel = UILabel()
let temperatureLabel = UILabel()
var isFahrenheit: Bool = isOption(kOptIsFahrenheit)
var isWeatherServiceDown = NO
let weatherAPI: OWMWeatherAPI
let locManager = CLLocationManager()
let activityIndicator: UIActivityIndicatorView!
func timeUp() {
let now = NSDate()
timeLabel.text = stringFromDate(now, format: timeFormat())
timeLabel.text = lowercaseTime(timeLabel.text)
dateLabel.text = stringFromDate(now, format: smartDateFormat(now))
timerFireCount++
if (timerIntervalInSec * timerFireCount > weatherUpdateIntervalInMinute * 60) {
timerFireCount = 0
updateWeather()
}
}
func setupClock() {
timer = NSTimer(timeInterval: timerIntervalInSec.t, target: self, selector: "timeUp", userInfo: nil, repeats: YES)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
timeUp()
}
func updateWeather() {
weatherAPI.setTemperatureFormat(isFahrenheit ? kOWMTempFahrenheit : kOWMTempCelcius)
lastWeatherUpdateDate = NSDate()
locManager.startUpdatingLocation()
}
func updateOrient() {
isLandscape()
let halfWidth = screenWidth() / 2
let halfWidthMinusPad = halfWidth - edgePad * 2
timeLabel.frame = CGRectMake(edgePad, 15, halfWidthMinusPad, 40)
dateLabel.frame = CGRectMake(edgePad, 40, halfWidthMinusPad, 40)
weatherImageView.frame = CGRectMake(
halfWidth * 1.5 - weatherImageSide / 2,
8,
weatherImageSide,
weatherImageSide)
weatherLabel.frame = CGRectMake(halfWidth + edgePad, 5, halfWidthMinusPad, 50)
activityIndicator.center = weatherLabel.center
temperatureLabel.frame = CGRectMake(halfWidth + edgePad, 51, halfWidthMinusPad, 20)
}
func constructWeatherLabel(coordinate: CLLocationCoordinate2D) {
weatherAPI.currentWeatherByCoordinate(coordinate, withCallback: {
[weak self]
(error: NSError!, result: [NSObject: AnyObject]!) in
if let s = self {
s.activityIndicator.stopAnimating()
if result == nil || error != nil {
return
}
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
var temp = "--"
var code = -1
var desc = ""
var icon = ""
if let mainResult = result["main"] as? NSDictionary {
if let newTemp = mainResult["temp"] as? Float {
temp = (NSString(format:"%.1f", newTemp) as String) + (s.isFahrenheit ? "℉" : "℃")
s.temperatureLabel.text = temp
}
}
if let newWeather: NSArray = result["weather"] as? NSArray {
if newWeather.count > 0 {
let weather = newWeather[0] as! NSDictionary
if let newCode = weather["id"] as? String {
if let intCode = Int(newCode) {
code = intCode
}
}
if let newDesc = weather["description"] as? String {
desc = newDesc
}
if let newIcon = weather["icon"] as? String {
icon = newIcon
}
// 900s contains extreme & special weather conditions
if code >= 900 {
if code >= 950 && code <= 956 {
icon = "windy"
} else {
// Extreme - show desc instead
icon = ""
s.weatherLabel.text = desc
}
} else if !icon.isEmpty {
let curHour = getCurDateComponents().hour
let isDaytime = curHour > 6 && curHour < 19
icon = icon.substringToIndex(icon.length - 1) + (isDaytime ? "d" : "n")
}
if icon.isEmpty {
s.isWeatherServiceDown = YES
} else {
s.weatherImageView.image = pendoImage("Weather/\(icon)")
s.isWeatherServiceDown = NO
}
}
}
}
})
}
func setupLocationManager() {
if #available(iOS 8.0, *) {
locManager.requestWhenInUseAuthorization()
}
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
updateWeather()
}
// CLLocationManagerDelegate
func locationManager(
manager: CLLocationManager!,
didChangeAuthorizationStatus
status: CLAuthorizationStatus)
{
if (CLLocationManager.authorizationStatus() == .Denied) {
weatherLabel.text = local("locationDenied")
activityIndicator.stopAnimating()
} else {
updateWeather()
}
}
func locationManager(
manager: CLLocationManager!,
didUpdateToLocation newLocation: CLLocation!,
fromLocation oldLocation: CLLocation!)
{
locManager.stopUpdatingLocation()
constructWeatherLabel(newLocation.coordinate)
}
override init(frame: CGRect) {
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
weatherAPI = OWMWeatherAPI(APIKey:"Your APIKey")
super.init(frame: frame)
timeLabel.textAlignment = .Center
timeLabel.textColor = UIColor.blackColor()
timeLabel.font = UIFont(name: "AppleSDGothicNeo-Light", size: 16)
timeLabel.adjustsFontSizeToFitWidth = YES
timeLabel.minimumScaleFactor = 0.1
addSubview(timeLabel)
dateLabel.textAlignment = .Center
dateLabel.textColor = UIColor.brownColor()
dateLabel.text = "Loading Date...";
dateLabel.font = UIFont(name: "Helvetica", size: 14)
dateLabel.adjustsFontSizeToFitWidth = YES;
dateLabel.minimumScaleFactor = 0.1;
addSubview(dateLabel)
weatherLabel.textAlignment = .Center
weatherLabel.textColor = UIColor.lightGrayColor()
weatherLabel.font = UIFont(name: "Helvetica", size: 12)
weatherLabel.lineBreakMode = .ByWordWrapping
weatherLabel.adjustsFontSizeToFitWidth = YES;
addSubview(weatherLabel)
addSubview(weatherImageView)
weatherAPI.setLangWithPreferedLanguage()
temperatureLabel.textAlignment = .Center
temperatureLabel.textColor = UIColor.lightGrayColor()
temperatureLabel.font = UIFont(name: "Helvetica", size:14)
temperatureLabel.adjustsFontSizeToFitWidth = YES
temperatureLabel.text = "--" + (isFahrenheit ? "℉" : "℃");
addSubview(temperatureLabel);
activityIndicator.center = CGPointMake(0, 0)
activityIndicator.hidesWhenStopped = YES
addSubview(activityIndicator)
activityIndicator.startAnimating()
observe(
self,
selector: "updateOrient",
name: UIApplicationDidChangeStatusBarOrientationNotification)
updateOrient()
setupClock()
setupLocationManager()
if (CLLocationManager.authorizationStatus() == .Denied) {
weatherLabel.text = local("locationDenied")
activityIndicator.stopAnimating()
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
unobserve(self)
}
}
| mit | 6d0de4946ff802f934a3f3c20a10eb60 | 30.357143 | 118 | 0.655366 | 4.814839 | false | false | false | false |
featherweightlabs/FeatherweightRouter | Demo/AppCoordinator.swift | 1 | 1044 | import UIKit
import FeatherweightRouter
typealias UIPresenter = Presenter<UIViewController>
func appCoordinator() -> UIViewController {
var router: Router<UIViewController, String>!
let store = AppStore() { _ = router.setRoute($0) }
router = createRouter(store)
store.setPath("welcome")
return router.presentable
}
func createRouter(_ store: AppStore) -> Router<UIViewController, String> {
return Router(tabBarPresenter()).junction([
Router(navigationPresenter("Welcome")).stack([
Router(welcomePresenter(store)).route(predicate: {$0 == "welcome"}, children: [
Router(registrationPresenter(store)).route(predicate: {$0 == "welcome/register"}, children: [
Router(step2Presenter(store)).route(predicate: {$0 == "welcome/register/step2"}),
]),
Router(loginPresenter(store)).route(predicate: {$0 == "welcome/login"}),
])
]),
Router(aboutPresenter(store)).route(predicate: {$0 == "about"}),
])
}
| apache-2.0 | 5ffe7d1e1ac959dba0d7424545948176 | 31.625 | 109 | 0.633142 | 4.53913 | false | false | false | false |
PiasMasumKhan/Swift | CoreLocation/CoreLocation/ViewController.swift | 18 | 6904 | //
// ViewController.swift
// CoreLocation
//
// Created by Carlos Butron on 19/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var myMap: MKMapView!
let locationManager: CLLocationManager = CLLocationManager()
var myLatitude: CLLocationDegrees!
var myLongitude: CLLocationDegrees!
var finalLatitude: CLLocationDegrees!
var finalLongitude: CLLocationDegrees!
var distance: CLLocationDistance!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let tap = UITapGestureRecognizer(target: self, action: "action:")
myMap.addGestureRecognizer(tap)
}
func action(gestureRecognizer:UIGestureRecognizer) {
var touchPoint = gestureRecognizer.locationInView(self.myMap)
var newCoord:CLLocationCoordinate2D = myMap.convertPoint(touchPoint, toCoordinateFromView: self.myMap)
var getLat: CLLocationDegrees = newCoord.latitude
var getLon: CLLocationDegrees = newCoord.longitude
//Convert to points to CLLocation. In this way we can measure distanceFromLocation
var newCoord2: CLLocation = CLLocation(latitude: getLat, longitude: getLon)
var newCoord3: CLLocation = CLLocation(latitude: myLatitude, longitude: myLongitude)
finalLatitude = newCoord2.coordinate.latitude
finalLongitude = newCoord2.coordinate.longitude
println("Original Latitude: \(myLatitude)")
println("Original Longitude: \(myLongitude)")
println("Final Latitude: \(finalLatitude)")
println("Final Longitude: \(finalLongitude)")
//distance between our position and the new point created
let distance = newCoord2.distanceFromLocation(newCoord3)
println("Distance between two points: \(distance)")
var newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = newCoord
newAnnotation.title = "My target"
newAnnotation.subtitle = ""
myMap.addAnnotation(newAnnotation)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
if placemarks.count > 0 {
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
} else {
println("Problem with the data received from geocoder")
}
})
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
//get data from placemark
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
myLongitude = (containsPlacemark.location.coordinate.longitude)
myLatitude = (containsPlacemark.location.coordinate.latitude)
// testing show data
println("Locality: \(locality)")
println("PostalCode: \(postalCode)")
println("Area: \(administrativeArea)")
println("Country: \(country)")
println(myLatitude)
println(myLongitude)
//update map with my location
let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.1 , 0.1)
let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: myLatitude, longitude: myLongitude)
let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location, theSpan)
myMap.setRegion(theRegion, animated: true)
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
//distance between two points
func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI }
func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {
let lat1 = degreesToRadians(point1.coordinate.latitude)
let lon1 = degreesToRadians(point1.coordinate.longitude)
let lat2 = degreesToRadians(point2.coordinate.latitude);
let lon2 = degreesToRadians(point2.coordinate.longitude);
println("Start latitude: \(point1.coordinate.latitude)")
println("Start longitude: \(point1.coordinate.longitude)")
println("Final latitude: \(point2.coordinate.latitude)")
println("Final longitude: \(point2.coordinate.longitude)")
let dLon = lon2 - lon1;
let y = sin(dLon) * cos(lat2);
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
let radiansBearing = atan2(y, x);
return radiansToDegrees(radiansBearing)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 3159fcf58afd6332ac7307d674f0953b | 38.227273 | 126 | 0.649768 | 5.554304 | false | false | false | false |
zom/Zom-iOS | Zom/Zom/Classes/UIImage+Zom.swift | 1 | 1201 | //
// UIImage+Zom.swift
// Zom
//
// Created by N-Pex on 2017-08-29.
//
//
import UIKit
extension UIImage
{
func tint(_ color: UIColor, blendMode: CGBlendMode) -> UIImage
{
let drawRect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context!.scaleBy(x: 1.0, y: -1.0)
context!.translateBy(x: 0.0, y: -self.size.height)
context!.clip(to: drawRect, mask: cgImage!)
color.setFill()
UIRectFill(drawRect)
draw(in: drawRect, blendMode: blendMode, alpha: 1.0)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage!
}
static func onePixelImage(_ color: UIColor) -> UIImage
{
let drawRect = CGRect(x: 0.0, y: 0.0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(CGSize(width:1,height:1), false, 1)
color.setFill()
UIRectFill(drawRect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| mpl-2.0 | 27388896a8fe61715b1aefc37750664c | 29.794872 | 85 | 0.638634 | 4.243816 | false | false | false | false |
e-government-ua/iMobile | iGov/Model/Service+CoreDataClass.swift | 1 | 2284 | //
// Service+CoreDataClass.swift
// iGov
//
// Created by Yurii Kolesnykov on 19.09.16.
// Copyright © 2016 iGov. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
@objc(Service)
public class Service: NSManagedObject {
class func create(_ context: NSManagedObjectContext, subcategory: Subcategory, nOpenedLimit:Int, sSubjectOperatorName: String, nID: Int, sName: String, nOrder: Int, nID_Status: Int, nStatus:Int) ->Service?
{
if let service = Service.mr_createEntity(in: context) {
service.nOpenedLimit = nOpenedLimit as NSNumber?
service.sSubjectOperatorName = sSubjectOperatorName
service.nID = nID as NSNumber?
service.sName = sName
service.nOrder = nOrder as NSNumber?
service.nID_Status = nID_Status as NSNumber?
service.nStatus = nStatus as NSNumber?
service.subcategory = subcategory
return service
}
else {
return nil
}
}
class func parse(_ context: NSManagedObjectContext, subcategory: Subcategory, jsonArray: [JSON]) -> [Service] {
var resultArray = [Service]()
for element in jsonArray {
if let serviceDict = element.dictionary {
guard
let nOpenedLimit = serviceDict["nOpenedLimit"]?.int,
let sSubjectOperatorName = serviceDict["sSubjectOperatorName"]?.string,
let nID = serviceDict["nID"]?.int,
let sName = serviceDict["sName"]?.string,
let nOrder = serviceDict["nOrder"]?.int,
let nID_Status = serviceDict["nID_Status"]?.int,
let nStatus = serviceDict["nStatus"]?.int
else {
continue
}
if let service = Service.create(context, subcategory: subcategory, nOpenedLimit: nOpenedLimit, sSubjectOperatorName: sSubjectOperatorName, nID: nID, sName: sName, nOrder: nOrder, nID_Status: nID_Status, nStatus: nStatus) {
resultArray.append(service)
}
}
}
return resultArray
}
}
| gpl-3.0 | 4b2b55f69f70f7ef5ef8567d7aea2439 | 37.05 | 278 | 0.574682 | 5.334112 | false | false | false | false |
skela/FileProvider | Sources/DropboxHelper.swift | 1 | 7407 | //
// DropboxHelper.swift
// FileProvider
//
// Created by Amir Abbas Mousavian.
// Copyright © 2016 Mousavian. Distributed under MIT license.
//
import Foundation
/// Error returned by Dropbox server when trying to access or do operations on a file or folder.
public struct FileProviderDropboxError: FileProviderHTTPError {
public let code: FileProviderHTTPErrorCode
public let path: String
public let serverDescription: String?
}
/// Containts path, url and attributes of a Dropbox file or resource.
public final class DropboxFileObject: FileObject {
internal convenience init? (jsonStr: String) {
guard let json = jsonStr.deserializeJSON() else { return nil }
self.init(json: json)
}
internal init? (json: [String: Any]) {
var json = json
if json["name"] == nil, let metadata = json["metadata"] as? [String: Any] {
json = metadata
}
guard let name = json["name"] as? String else { return nil }
guard let path = json["path_display"] as? String else { return nil }
super.init(url: nil, name: name, path: path)
self.size = (json["size"] as? NSNumber)?.int64Value ?? -1
self.serverTime = (json["server_modified"] as? String).flatMap(Date.init(rfcString:))
self.modifiedDate = (json["client_modified"] as? String).flatMap(Date.init(rfcString:))
self.type = (json[".tag"] as? String) == "folder" ? .directory : .regular
self.isReadOnly = ((json["sharing_info"] as? [String: Any])?["read_only"] as? NSNumber)?.boolValue ?? false
self.id = json["id"] as? String
self.rev = json["rev"] as? String
self.contentHash = json["content_hash"] as? String
}
/// The time contents of file has been modified on server, returns nil if not set
public internal(set) var serverTime: Date? {
get {
return allValues[.serverDateKey] as? Date
}
set {
allValues[.serverDateKey] = newValue
}
}
/// The document identifier is a value assigned by the Dropbox to a file.
/// This value is used to identify the document regardless of where it is moved on a volume.
public internal(set) var id: String? {
get {
return allValues[.fileResourceIdentifierKey] as? String
}
set {
allValues[.fileResourceIdentifierKey] = newValue
}
}
/// The document content hash generated by the Dropbox for a file.
open internal(set) var contentHash: String? {
get {
return allValues[.volumeUUIDStringKey] as? String // TODO: Find a key thats better for content hashes than volumeUUIDStringKey
}
set {
allValues[.volumeUUIDStringKey] = newValue // TODO: Find a key thats better for content hashes than volumeUUIDStringKey
}
}
/// The revision of file, which changes when a file contents are modified.
/// Changes to attributes or other file metadata do not change the identifier.
public internal(set) var rev: String? {
get {
return allValues[.generationIdentifierKey] as? String
}
set {
allValues[.generationIdentifierKey] = newValue
}
}
}
extension DropboxFileProvider {
func correctPath(_ path: String?) -> String? {
guard let path = path else { return nil }
if path.hasPrefix("id:") || path.hasPrefix("rev:") {
return path
}
var p = path.hasPrefix("/") ? path : "/" + path
if p.hasSuffix("/") {
p.remove(at: p.index(before:p.endIndex))
}
return p
}
func listRequest(path: String, queryStr: String? = nil, recursive: Bool = false) -> ((_ token: String?) -> URLRequest?) {
if let queryStr = queryStr {
return { [weak self] (token) -> URLRequest? in
guard let `self` = self else { return nil }
let url = URL(string: "files/search", relativeTo: self.apiURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: self.credential, with: .oAuth2)
request.setValue(contentType: .json)
var requestDictionary: [String: Any] = ["path": self.correctPath(path)!]
requestDictionary["query"] = queryStr
requestDictionary["start"] = NSNumber(value: (token.flatMap( { Int($0) } ) ?? 0))
request.httpBody = Data(jsonDictionary: requestDictionary)
return request
}
} else {
return { [weak self] (token) -> URLRequest? in
guard let `self` = self else { return nil }
var requestDictionary = [String: Any]()
let url: URL
if let token = token {
url = URL(string: "files/list_folder/continue", relativeTo: self.apiURL)!
requestDictionary["cursor"] = token
} else {
url = URL(string: "files/list_folder", relativeTo: self.apiURL)!
requestDictionary["path"] = self.correctPath(path)
requestDictionary["recursive"] = NSNumber(value: recursive)
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: self.credential, with: .oAuth2)
request.setValue(contentType: .json)
request.httpBody = Data(jsonDictionary: requestDictionary)
return request
}
}
}
}
internal extension DropboxFileProvider {
static let dateFormatter = DateFormatter()
static let decimalFormatter = NumberFormatter()
func mapMediaInfo(_ json: [String: Any]) -> (dictionary: [String: Any], keys: [String]) {
var dic = [String: Any]()
var keys = [String]()
if let dimensions = json["dimensions"] as? [String: Any], let height = dimensions["height"] as? UInt64, let width = dimensions["width"] as? UInt64 {
keys.append("Dimensions")
dic["Dimensions"] = "\(width)x\(height)"
}
if let location = json["location"] as? [String: Any], let latitude = location["latitude"] as? Double, let longitude = location["longitude"] as? Double {
DropboxFileProvider.decimalFormatter.numberStyle = .decimal
DropboxFileProvider.decimalFormatter.maximumFractionDigits = 5
keys.append("Location")
let latStr = DropboxFileProvider.decimalFormatter.string(from: NSNumber(value: latitude))!
let longStr = DropboxFileProvider.decimalFormatter.string(from: NSNumber(value: longitude))!
dic["Location"] = "\(latStr), \(longStr)"
}
if let timeTakenStr = json["time_taken"] as? String, let timeTaken = Date(rfcString: timeTakenStr) {
keys.append("Date taken")
DropboxFileProvider.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dic["Date taken"] = DropboxFileProvider.dateFormatter.string(from: timeTaken)
}
if let duration = json["duration"] as? UInt64 {
keys.append("Duration")
dic["Duration"] = TimeInterval(duration).formatshort
}
return (dic, keys)
}
}
| mit | eef4b868519c3596506f07ded1ae3255 | 42.822485 | 160 | 0.596273 | 4.669609 | false | false | false | false |
roadfire/Alamofire | Source/Alamofire.swift | 1 | 65942 | // Alamofire.swift
//
// Copyright (c) 2014 Alamofire (http://alamofire.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Alamofire errors
public let AlamofireErrorDomain = "com.alamofire.error"
public struct Alamofire {
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
}
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Alamofire.Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Alamofire.Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.query != nil ? URLComponents.query! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue)
}
}
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
*/
public protocol URLStringConvertible {
/// The URL string.
var URLString: String { get }
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString!
}
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL.URLString
}
}
// MARK: - URLRequestConvertible
/**
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
*/
public protocol URLRequestConvertible {
/// The URL request.
var URLRequest: NSURLRequest { get }
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSURLRequest {
return self
}
}
// MARK: -
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
*/
public class var sharedInstance: Manager {
struct Singleton {
static var configuration: NSURLSessionConfiguration = {
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = {
// Accept-Encoding HTTP Header; see http://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see http://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return join(",", components)
}()
// User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}()
return configuration
}()
static let instance = Manager(configuration: configuration)
}
return Singleton.instance
}
private let delegate: SessionDelegate
private let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
:param: configuration The configuration used to construct the managed session.
*/
required public init(configuration: NSURLSessionConfiguration? = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
}
deinit {
self.session.invalidateAndCancel()
}
// MARK: -
/**
Creates a request for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Alamofire.Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask?
dispatch_sync(queue) {
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
}
let request = Request(session: session, task: dataTask!)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) {
subdelegate = self.subdelegates[task.taskIdentifier]
}
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required override init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if sessionDidReceiveChallenge != nil {
completionHandler(sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
*/
public class Request {
private let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest { return task.originalRequest }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress? { return delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
/**
Associates an HTTP Basic credential with the request.
:param: user The user.
:param: password The password.
:returns: The request.
*/
public func authenticate(#user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
:param: credential The credential.
:returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
- For downloads, the progress closure returns the bytes read, total bytes read, and total bytes expected to write.
:param: closure The code to be executed periodically during the lifecycle of the request.
:returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
/**
A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
*/
public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public class func responseDataSerializer() -> Serializer {
return { (request, response, data) in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(Request.responseDataSerializer(), completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: serializer The closure responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(delegate.queue) {
let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
}
}
return self
}
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t
let progress: NSProgress
var data: NSData? { return nil }
private(set) var error: NSError?
var credential: NSURLCredential?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
return queue
}()
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if taskDidReceiveChallenge != nil {
(disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
// TODO: Incorporate Trust Evaluation & TLS Chain Validation
switch challenge.protectionSpace.authenticationMethod! {
case NSURLAuthenticationMethodServerTrust:
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
default:
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
}
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var bodyStream: NSInputStream?
if taskNeedNewBodyStream != nil {
bodyStream = taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if error != nil {
self.error = error
}
dispatch_resume(queue)
}
}
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData? {
return mutableData
}
private var expectedContentLength: Int64?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
dataTaskDidReceiveData?(session, dataTask, data)
mutableData.appendData(data)
if let expectedContentLength = dataTask?.response?.expectedContentLength {
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
}
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - Validation
extension Request {
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: validation A closure to validate the request.
:returns: The request.
*/
public func validate(validation: Validation) -> Self {
dispatch_async(delegate.queue) {
if self.response != nil && self.delegate.error == nil {
if !validation(self.request, self.response!) {
self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
}
}
}
return self
}
// MARK: Status Code
private class func response(response: NSHTTPURLResponse, hasAcceptableStatusCode statusCodes: [Int]) -> Bool {
return contains(statusCodes, response.statusCode)
}
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: range The range of acceptable status codes.
:returns: The request.
*/
public func validate(statusCode range: Range<Int>) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: range.map({$0}))
}
}
/**
Validates that the response has a status code in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: array The acceptable status codes.
:returns: The request.
*/
public func validate(statusCode array: [Int]) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: array)
}
}
// MARK: Content-Type
private struct MIMEType {
let type: String
let subtype: String
init(_ string: String) {
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
self.type = components.first!
self.subtype = components.last!
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case ("*", "*"), ("*", MIME.subtype), (MIME.type, "*"), (MIME.type, MIME.subtype):
return true
default:
return false
}
}
}
private class func response(response: NSHTTPURLResponse, hasAcceptableContentType contentTypes: [String]) -> Bool {
if response.MIMEType != nil {
let responseMIMEType = MIMEType(response.MIMEType!)
for acceptableMIMEType in contentTypes.map({MIMEType($0)}) {
if acceptableMIMEType.matches(responseMIMEType) {
return true
}
}
}
return false
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
:returns: The request.
*/
public func validate(contentType array: [String]) -> Self {
return validate {(_, response) in
return Request.response(response, hasAcceptableContentType: array)
}
}
// MARK: Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
:returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = self.request.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
// MARK: - Upload
extension Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Request {
var uploadTask: NSURLSessionUploadTask!
var stream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = session.uploadTaskWithStreamedRequest(request)
}
let request = Request(session: session, task: uploadTask)
if stream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return stream
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: File
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: file The file to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return upload(.File(URLRequest.URLRequest, file))
}
// MARK: Data
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: data The data to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return upload(.Data(URLRequest.URLRequest, data))
}
// MARK: Stream
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: stream The stream to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return upload(.Stream(URLRequest.URLRequest, stream))
}
}
extension Request {
class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if uploadProgress != nil {
uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
}
}
}
// MARK: - Download
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = session.downloadTaskWithResumeData(resumeData)
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if downloadTaskDidFinishDownloadingToURL != nil {
let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: - Printable
extension Request: Printable {
/// The textual representation used when written to an `OutputStreamType`, which includes the HTTP method and URL, as well as the response status code if a response has been received.
public var description: String {
var components: [String] = []
if request.HTTPMethod != nil {
components.append(request.HTTPMethod!)
}
components.append(request.URL.absoluteString!)
if response != nil {
components.append("(\(response!.statusCode))")
}
return join(" ", components)
}
}
extension Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = request.URL
if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
components.append("-X \(request.HTTPMethod!)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port?.integerValue ?? 0, `protocol`: URL.scheme!, realm: URL.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
for credential: NSURLCredential in (credentials as [NSURLCredential]) {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
if let cookieStorage = session.configuration.HTTPCookieStorage {
if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
if !cookies.isEmpty {
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
}
for (field, value) in request.allHTTPHeaderFields! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
for (field, value) in session.configuration.HTTPAdditionalHeaders! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
if let HTTPBody = request.HTTPBody {
if let escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") {
components.append("-d \"\(escapedBody)\"")
}
}
components.append("\"\(URL.absoluteString!)\"")
return join(" \\\n\t", components)
}
/// The textual representation used when written to an `OutputStreamType`, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:returns: A string response serializer.
*/
public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
return { (_, _, data) in
let string = NSString(data: data!, encoding: encoding)
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
return { (request, response, data) in
if data == nil {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responseJSON(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
return { (request, response, data) in
if data == nil {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience -
private func URLRequest(method: Alamofire.Method, URL: URLStringConvertible) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
return mutableURLRequest
}
// MARK: - Request
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Alamofire.Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
return Manager.sharedInstance.request(URLRequest.URLRequest)
}
// MARK: - Upload
// MARK: File
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
:param: method The HTTP method.
:param: URLString The URL string.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(method: Alamofire.Method, URLString: URLStringConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and file.
:param: URLRequest The URL request.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest, file: file)
}
// MARK: Data
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
:param: method The HTTP method.
:param: URLString The URL string.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(method: Alamofire.Method, URLString: URLStringConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and data.
:param: URLRequest The URL request.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest, data: data)
}
// MARK: Stream
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
:param: method The HTTP method.
:param: URLString The URL string.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(method: Alamofire.Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and stream.
:param: URLRequest The URL request.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest, stream: stream)
}
// MARK: - Download
// MARK: URL Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Alamofire.Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a download request using the shared manager instance for the specified URL request.
:param: URLRequest The URL request.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest, destination: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(data, destination: destination)
}
| mit | 7bee879ea8da47a93a9f36ac8936df53 | 39.983219 | 555 | 0.664478 | 5.71768 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/NSIndexPath.swift | 1 | 3569 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
public class NSIndexPath: NSObject, NSCopying, NSSecureCoding {
internal var _indexes : [Int]
override public init() {
_indexes = []
}
public init(indexes: UnsafePointer<Int>, length: Int) {
_indexes = Array(UnsafeBufferPointer(start: indexes, count: length))
}
private init(indexes: [Int]) {
_indexes = indexes
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject { NSUnimplemented() }
public convenience init(index: Int) {
self.init(indexes: [index])
}
public func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public static func supportsSecureCoding() -> Bool { return true }
public func adding(_ index: Int) -> IndexPath {
return IndexPath(indexes: _indexes + [index])
}
public func removingLastIndex() -> IndexPath {
if _indexes.count <= 1 {
return IndexPath(indexes: [])
} else {
return IndexPath(indexes: [Int](_indexes[0..<_indexes.count - 1]))
}
}
public func index(atPosition position: Int) -> Int {
return _indexes[position]
}
public var length: Int {
return _indexes.count
}
/*!
@abstract Copies the indexes stored in this index path from the positions specified by positionRange into indexes.
@param indexes Buffer of at least as many NSUIntegers as specified by the length of positionRange. On return, this memory will hold the index path's indexes.
@param positionRange A range of valid positions within this index path. If the location plus the length of positionRange is greater than the length of this index path, this method raises an NSRangeException.
@discussion
It is the developer’s responsibility to allocate the memory for the C array.
*/
public func getIndexes(_ indexes: UnsafeMutablePointer<Int>, range positionRange: NSRange) {
for (pos, idx) in _indexes[positionRange.location ..< NSMaxRange(positionRange)].enumerated() {
indexes.advanced(by: pos).pointee = idx
}
}
// comparison support
// sorting an array of indexPaths using this comparison results in an array representing nodes in depth-first traversal order
public func compare(_ otherObject: IndexPath) -> ComparisonResult {
let thisLength = length
let otherLength = otherObject.count
let minLength = thisLength >= otherLength ? otherLength : thisLength
for pos in 0..<minLength {
let otherValue = otherObject[pos]
let thisValue = index(atPosition: pos)
if thisValue < otherValue {
return .orderedAscending
} else if thisValue > otherValue {
return .orderedDescending
}
}
if thisLength > otherLength {
return .orderedDescending
} else if thisLength < otherLength {
return .orderedAscending
}
return .orderedSame
}
}
| apache-2.0 | 78247c3fef5d46802cb8edb7059d96ac | 35.773196 | 213 | 0.639473 | 5.009831 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/MarketOrdersInteractor.swift | 2 | 1620 | //
// MarketOrdersInteractor.swift
// Neocom
//
// Created by Artem Shimanski on 11/9/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import EVEAPI
class MarketOrdersInteractor: TreeInteractor {
typealias Presenter = MarketOrdersPresenter
typealias Content = ESI.Result<Value>
weak var presenter: Presenter?
required init(presenter: Presenter) {
self.presenter = presenter
}
struct Value {
var orders: [ESI.Market.CharacterOrder]
var locations: [Int64: EVELocation]?
}
var api = Services.api.current
func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
let api = self.api
let progress = Progress(totalUnitCount: 2)
return DispatchQueue.global(qos: .utility).async { () -> Content in
let orders = try progress.performAsCurrent(withPendingUnitCount: 1) {api.openOrders(cachePolicy: cachePolicy)}.get()
let locationIDs = orders.value.map{$0.locationID}
let locations = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.locations(with: Set(locationIDs))}.get()
return orders.map {Value(orders: $0, locations: locations)}
}
}
private var didChangeAccountObserver: NotificationObserver?
func configure() {
didChangeAccountObserver = NotificationCenter.default.addNotificationObserver(forName: .didChangeAccount, object: nil, queue: .main) { [weak self] _ in
self?.api = Services.api.current
_ = self?.presenter?.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { presentation in
self?.presenter?.view?.present(presentation, animated: true)
}
}
}
}
| lgpl-2.1 | 64e6b6f407cce9980a3469aa5b855fa7 | 31.38 | 153 | 0.744287 | 3.873206 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/StoredMessageFromSearchPeer.swift | 1 | 2961 | //
// StoredMessageFromSearchPeer.swift
// Telegram
//
// Created by Mikhail Filimonov on 19/01/2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Foundation
import Postbox
import TelegramCore
import SwiftSignalKit
func storedMessageFromSearchPeer(account: Account, peer: Peer) -> Signal<PeerId, NoError> {
return account.postbox.transaction { transaction -> PeerId in
if transaction.getPeer(peer.id) == nil {
updatePeers(transaction: transaction, peers: [peer], update: { previousPeer, updatedPeer in
return updatedPeer
})
}
if let group = transaction.getPeer(peer.id) as? TelegramGroup, let migrationReference = group.migrationReference {
return migrationReference.peerId
}
return peer.id
}
}
func storedMessageFromSearch(account: Account, message: Message) -> Signal<Void, NoError> {
return account.postbox.transaction { transaction -> Void in
if transaction.getMessage(message.id) == nil {
for (_, peer) in message.peers {
if transaction.getPeer(peer.id) == nil {
updatePeers(transaction: transaction, peers: [peer], update: { previousPeer, updatedPeer in
return updatedPeer
})
}
}
let storeMessage = StoreMessage(id: .Id(message.id), globallyUniqueId: message.globallyUniqueId, groupingKey: message.groupingKey, threadId: nil, timestamp: message.timestamp, flags: StoreMessageFlags(message.flags), tags: message.tags, globalTags: message.globalTags, localTags: message.localTags, forwardInfo: message.forwardInfo.flatMap(StoreMessageForwardInfo.init), authorId: message.author?.id, text: message.text, attributes: message.attributes, media: message.media)
let _ = transaction.addMessages([storeMessage], location: .Random)
}
}
}
func storeMessageFromSearch(transaction: Transaction, message: Message) {
if transaction.getMessage(message.id) == nil {
for (_, peer) in message.peers {
if transaction.getPeer(peer.id) == nil {
updatePeers(transaction: transaction, peers: [peer], update: { previousPeer, updatedPeer in
return updatedPeer
})
}
}
let storeMessage = StoreMessage(id: .Id(message.id), globallyUniqueId: message.globallyUniqueId, groupingKey: message.groupingKey, threadId: message.threadId, timestamp: message.timestamp, flags: StoreMessageFlags(message.flags), tags: message.tags, globalTags: message.globalTags, localTags: message.localTags, forwardInfo: message.forwardInfo.flatMap(StoreMessageForwardInfo.init), authorId: message.author?.id, text: message.text, attributes: message.attributes, media: message.media)
let _ = transaction.addMessages([storeMessage], location: .Random)
}
}
| gpl-2.0 | 1e95d792aebd947b8415c4483eb90c53 | 46.741935 | 495 | 0.669595 | 4.574961 | false | false | false | false |
allsome/LSYPaper | LSYPaper/NewsDetailLayout.swift | 1 | 2542 | //
// NewsDetailLayout.swift
// LSYPaper
//
// Created by 梁树元 on 1/9/16.
// Copyright © 2016 allsome.love. All rights reserved.
//
import UIKit
// A deprecated horizontal layout
private let sectionNumber = 0
class NewsDetailLayout: UICollectionViewLayout {
private var attributeArray:[UICollectionViewLayoutAttributes] = []
private var cellWidth:CGFloat = 0
private var cellHeight:CGFloat = 0
private var cellGap:CGFloat = 0
init(cellWidth:CGFloat,cellHeight:CGFloat,cellGap:CGFloat) {
super.init()
self.cellWidth = cellWidth
self.cellHeight = cellHeight
self.cellGap = cellGap
}
required init?(coder aDecoder: NSCoder) {
super.init()
}
func invalidateLayoutwith(_ newCellWidth:CGFloat,newCellHeight:CGFloat,newCellGap:CGFloat) {
cellWidth = newCellWidth
cellHeight = newCellHeight
cellGap = newCellGap
attributeArray.removeAll()
invalidateLayout()
}
override func prepare() {
if attributeArray.isEmpty {
let itemCount:Int = (collectionView?.numberOfItems(inSection: sectionNumber))!
for index in 0 ..< itemCount {
let attribute = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: index, section: sectionNumber))
attribute.size = CGSize(width: cellWidth, height: cellHeight)
let pointX:CGFloat = cellGap + cellWidth / 2 + CGFloat(index) * (cellWidth + cellGap)
attribute.center = CGPoint(x: pointX, y: CELL_NORMAL_HEIGHT - cellHeight / 2)
attributeArray.append(attribute)
}
}
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override var collectionViewContentSize: CGSize {
return CGSize(width: (cellWidth + cellGap) * CGFloat(attributeArray.count) + cellGap, height: cellHeight)
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return attributeArray[(indexPath as NSIndexPath).item]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attribute in attributeArray {
if attribute.frame.intersects(rect ) {
layoutAttributes.append(attribute)
}
}
return layoutAttributes
}
}
| mit | 00d1de2b24b36411bd1430704c95dcee | 32.8 | 125 | 0.658383 | 5.32563 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/Search.swift | 1 | 1610 | //
// Search.swift
// LeetCode
//
// Created by 黄伯驹 on 2020/3/28.
// Copyright © 2020 伯驹 黄. All rights reserved.
//
import Foundation
// nums = [4,5,6,7,0,1,2], target = 0
func search(_ nums: [Int], _ target: Int) -> Int {
if nums.isEmpty { return -1 }
var start = 0
var end = nums.count - 1
while start <= end {
let mid = start + (end - start) / 2
if nums[mid] == target { return mid }
if nums[start] <= nums[mid] {
if target >= nums[start] && target < nums[mid] {
end = mid - 1
} else {
start = mid + 1
}
} else {
if target > nums[mid] && target <= nums[end] {
start = mid + 1
} else {
end = mid - 1
}
}
}
return -1
}
func _search(_ nums: [Int], target: Int) -> Int {
if nums.isEmpty { return -1 }
var start = 0
var end = nums.count - 1
var mid = 0
while start <= end {
mid = start + (end - start) / 2
if nums[mid] == target { return mid }
if nums[start] <= target {
if nums[start] == target { return start }
if target > nums[start] && target < nums[mid] {
end = mid - 1
} else {
start = mid + 1
}
} else {
if nums[end] == target { return start }
if target > nums[mid] && target < nums[end] {
start = mid + 1
} else {
end = mid - 1
}
}
}
return -1
}
| mit | ab96c29df30b742e87464eb7cc25a3d4 | 24.349206 | 60 | 0.425798 | 3.740047 | false | false | false | false |
kemalenver/SwiftHackerRank | Algorithms/Strings.playground/Pages/Strings - Making Anagrams.xcplaygroundpage/Contents.swift | 1 | 996 |
import Foundation
var inputs = ["cde", "abc"] // 4
func readLine() -> String? {
let next = inputs.first
inputs.removeFirst()
return next
}
func calculateNumberOfChanges(a: String, b: String) -> Int {
// As usual we are going ascii. 97 is the letter a. We get an index between 0 and 25
var frequencyA = [Int](repeating: 0, count: 26)
var frequencyB = [Int](repeating: 0, count: 26)
let sA = a.utf8
let sB = b.utf8
for character in sA {
let idx = Int(character - 97)
frequencyA[idx] += 1
}
for character in sB {
let idx = Int(character - 97)
frequencyB[idx] += 1
}
var count = 0
for i in 0..<26 {
let difference = abs(frequencyA[i] - frequencyB[i])
count += difference
}
return count
}
let a = readLine()!
let b = readLine()!
let numberOfChanges = calculateNumberOfChanges(a: a, b: b)
print(numberOfChanges)
| mit | 5ba09a9cc9742b72b94b8f733315b609 | 17.792453 | 90 | 0.561245 | 3.730337 | false | false | false | false |
Paladinfeng/leetcode | leetcode/Palindrome Number/main.swift | 1 | 812 | //
// main.swift
// Palindrome Number
//
// Created by xuezhaofeng on 2017/8/4.
// Copyright © 2017年 paladinfeng. All rights reserved.
//
import Foundation
class Solution {
func isPalindrome(_ x: Int) -> Bool {
if x < 0 {
return false
}
var digitalArray: [Int] = [Int]();
var temp = x;
while temp != 0 {
// print(temp % 10)
digitalArray.append(temp % 10)
temp = temp / 10
}
for i in 0..<digitalArray.count/2 {
// print(i)
if digitalArray[i] != digitalArray[digitalArray.count - 1 - i] {
return false
}
}
// print(digitalArray)
return true
}
}
let result = Solution().isPalindrome(-2147447412);
print(result)
| mit | dd30ad0c374bbd053558444867491ecf | 21.472222 | 76 | 0.509271 | 3.798122 | false | false | false | false |
btanner/Eureka | Source/Rows/Controllers/SelectorViewController.swift | 2 | 9017 | // SelectorViewController.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/**
* Responsible for the options passed to a selector view controller
*/
public protocol OptionsProviderRow: TypedRowType {
associatedtype OptionsProviderType: OptionsProviderConformance
var optionsProvider: OptionsProviderType? { get set }
var cachedOptionsData: [OptionsProviderType.Option]? { get set }
}
extension OptionsProviderRow where Self: BaseRow {
public var options: [OptionsProviderType.Option]? {
set (newValue){
let optProvider = OptionsProviderType.init(array: newValue)
optionsProvider = optProvider
}
get {
return self.cachedOptionsData ?? optionsProvider?.optionsArray
}
}
public var cachedOptionsData: [OptionsProviderType.Option]? {
get {
return self._cachedOptionsData as? [OptionsProviderType.Option]
}
set {
self._cachedOptionsData = newValue
}
}
}
public protocol OptionsProviderConformance: ExpressibleByArrayLiteral {
associatedtype Option: Equatable
init(array: [Option]?)
func options(for selectorViewController: FormViewController, completion: @escaping ([Option]?) -> Void)
var optionsArray: [Option]? { get }
}
/// Provider of selectable options.
public enum OptionsProvider<T: Equatable>: OptionsProviderConformance {
/// Synchronous provider that provides array of options it was initialized with
case array([T]?)
/// Provider that uses closure it was initialized with to provide options. Can be synchronous or asynchronous.
case lazy((FormViewController, @escaping ([T]?) -> Void) -> Void)
public init(array: [T]?) {
self = .array(array)
}
public init(arrayLiteral elements: T...) {
self = .array(elements)
}
public func options(for selectorViewController: FormViewController, completion: @escaping ([T]?) -> Void) {
switch self {
case let .array(array):
completion(array)
case let .lazy(fetch):
fetch(selectorViewController, completion)
}
}
public var optionsArray: [T]?{
switch self {
case let .array(arrayData):
return arrayData
default:
return nil
}
}
}
open class _SelectorViewController<Row: SelectableRowType, OptionsRow: OptionsProviderRow>: FormViewController, TypedRowControllerType where Row: BaseRow, Row.Cell.Value == OptionsRow.OptionsProviderType.Option {
/// The row that pushed or presented this controller
public var row: RowOf<Row.Cell.Value>!
public var enableDeselection = true
public var dismissOnSelection = true
public var dismissOnChange = true
public var selectableRowSetup: ((_ row: Row) -> Void)?
public var selectableRowCellUpdate: ((_ cell: Row.Cell, _ row: Row) -> Void)?
public var selectableRowCellSetup: ((_ cell: Row.Cell, _ row: Row) -> Void)?
/// A closure to be called when the controller disappears.
public var onDismissCallback: ((UIViewController) -> Void)?
/// A closure that should return key for particular row value.
/// This key is later used to break options by sections.
public var sectionKeyForValue: ((Row.Cell.Value) -> (String))?
/// A closure that returns header title for a section for particular key.
/// By default returns the key itself.
public var sectionHeaderTitleForKey: ((String) -> String?)? = { $0 }
/// A closure that returns footer title for a section for particular key.
public var sectionFooterTitleForKey: ((String) -> String?)?
public var optionsProviderRow: OptionsRow {
return row as! OptionsRow
}
override public init(style: UITableView.Style) {
super.init(style: style)
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience public init(_ callback: ((UIViewController) -> Void)?) {
self.init(nibName: nil, bundle: nil)
onDismissCallback = callback
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func viewDidLoad() {
super.viewDidLoad()
setupForm()
}
open func setupForm() {
let optProvider = optionsProviderRow.optionsProvider
optProvider?.options(for: self) { [weak self] (options: [Row.Cell.Value]?) in
guard let strongSelf = self, let options = options else { return }
strongSelf.optionsProviderRow.cachedOptionsData = options
strongSelf.setupForm(with: options)
}
}
open func setupForm(with options: [Row.Cell.Value]) {
if let optionsBySections = optionsBySections(with: options) {
for (sectionKey, options) in optionsBySections {
form +++ section(with: options,
header: sectionHeaderTitleForKey?(sectionKey),
footer: sectionFooterTitleForKey?(sectionKey))
}
} else {
form +++ section(with: options, header: nil, footer: nil)
}
}
func optionsBySections(with options: [Row.Cell.Value]) -> [(String, [Row.Cell.Value])]? {
guard let sectionKeyForValue = sectionKeyForValue else { return nil }
let sections = options.reduce([:]) { (reduced, option) -> [String: [Row.Cell.Value]] in
var reduced = reduced
let key = sectionKeyForValue(option)
reduced[key] = (reduced[key] ?? []) + [option]
return reduced
}
return sections.sorted(by: { (lhs, rhs) in lhs.0 < rhs.0 })
}
func section(with options: [Row.Cell.Value], header: String?, footer: String?) -> SelectableSection<Row> {
let section = SelectableSection<Row>(header: header, footer: footer, selectionType: .singleSelection(enableDeselection: enableDeselection)) { section in
section.onSelectSelectableRow = { [weak self] _, row in
let changed = self?.row.value != row.value
self?.row.value = row.value
if let form = row.section?.form {
for section in form where section !== row.section && section is SelectableSection<Row> {
let section = section as Any as! SelectableSection<Row>
if let selectedRow = section.selectedRow(), selectedRow !== row {
selectedRow.value = nil
selectedRow.updateCell()
}
}
}
if self?.dismissOnSelection == true || (changed && self?.dismissOnChange == true) {
self?.onDismissCallback?(self!)
}
}
}
for option in options {
section <<< Row.init(String(describing: option)) { lrow in
lrow.title = self.row.displayValueFor?(option)
lrow.selectableValue = option
lrow.value = self.row.value == option ? option : nil
self.selectableRowSetup?(lrow)
}.cellSetup { [weak self] cell, row in
self?.selectableRowCellSetup?(cell, row)
}.cellUpdate { [weak self] cell, row in
self?.selectableRowCellUpdate?(cell, row)
}
}
return section
}
}
/// Selector Controller (used to select one option among a list)
open class SelectorViewController<OptionsRow: OptionsProviderRow>: _SelectorViewController<ListCheckRow<OptionsRow.OptionsProviderType.Option>, OptionsRow> {
}
| mit | 8078185029c74fde856e1bc5b31c739e | 37.866379 | 212 | 0.636686 | 4.995568 | false | false | false | false |
RuiAAPeres/TeamGen | TeamGen/Sources/Screens/GroupsScreen/GroupsScreenViewController.swift | 1 | 1689 | import UIKit
import TeamGenFoundation
import TinyConstraints
final class GroupsScreenViewController: UIViewController {
private var viewModel: GroupsViewModelProtocol!
private var tableView = UITableView(frame: .zero, style: .plain).configure { tableView in
tableView.tableFooterView = UIView()
}
private var tableViewManager: TableViewManager<GroupCellViewModel>
public init(viewModel: GroupsViewModelProtocol) {
GroupsScreen.registerCells(tableView: tableView)
self.viewModel = viewModel
self.tableViewManager = TableViewManager<GroupCellViewModel>(
tableView: tableView,
dataSource: viewModel.state.map(GroupsScreen.toViewState),
generator: GroupsScreen.generator)
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
let view = UIView(frame: UIScreen.main.bounds)
view.addSubview(tableView)
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel.viewLifecycle.value = .didLoad
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.edgesToSuperview(usingSafeArea: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewModel.viewLifecycle.value = .didAppear
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
viewModel.viewLifecycle.value = .didDisappear
}
}
| mit | d378469edd334e87e66725dfaac36800 | 30.277778 | 93 | 0.683837 | 5.430868 | false | false | false | false |
codestergit/swift | test/IDE/local_types.swift | 3 | 4210 | // Tests lookup and mangling of local types
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swiftc_driver -v -emit-module -module-name LocalTypes -o %t/LocalTypes.swiftmodule %s
// RUN: %target-swift-ide-test -print-local-types -I %t -module-to-print LocalTypes -source-filename %s | %FileCheck %s
public func singleFunc() {
// CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD6StructL_V
struct SingleFuncStruct {
let sfsi: Int
}
// CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD5ClassL_C
class SingleFuncClass {
let sfcs: String
init(s: String) {
self.sfcs = s
}
}
// CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD4EnumL_O
enum SingleFuncEnum {
case SFEI(Int)
}
}
public func singleFuncWithDuplicates(_ fake: Bool) {
if fake {
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL_V
struct SingleFuncStruct {
let sfsi: Int
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL_C
class SingleFuncClass {
let sfcs: String
init(s: String) {
self.sfcs = s
}
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL_O
enum SingleFuncEnum {
case SFEI(Int)
}
} else {
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL0_V
struct SingleFuncStruct {
let sfsi: Int
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL0_C
class SingleFuncClass {
let sfcs: String
init(s: String) {
self.sfcs = s
}
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL0_O
enum SingleFuncEnum {
case SFEI(Int)
}
}
}
public let singleClosure: () -> () = {
// CHECK-DAG: 10LocalTypesyycfU_19SingleClosureStructL_V
struct SingleClosureStruct {
let scsi: Int
}
// CHECK-DAG: 10LocalTypesyycfU_18SingleClosureClassL_C
class SingleClosureClass {
let sccs: String
init(s: String) {
self.sccs = s
}
}
// CHECK-DAG: 10LocalTypesyycfU_17SingleClosureEnumL_O
enum SingleClosureEnum {
case SCEI(Int)
}
}
public var singlePattern: Int {
// CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD6StructL_V
struct SinglePatternStruct {
let spsi: Int
}
// CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD5ClassL_C
class SinglePatternClass {
let spcs: String
init(s: String) {
self.spcs = s
}
}
// CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD4EnumL_O
enum SinglePatternEnum {
case SPEI(Int)
}
return 2
}
public func singleDefaultArgument(i: Int = {
//CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE6StructL_V
struct SingleDefaultArgumentStruct {
let sdasi: Int
}
// CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE5ClassL_C
class SingleDefaultArgumentClass {
let sdacs: String
init(s: String) {
self.sdacs = s
}
}
// CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE4EnumL_O
enum SingleDefaultArgumentEnum {
case SDAEI(Int)
}
return 2
}()){
print(i)
}
public func doubleFunc() {
func innerFunc() {
// CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD6StructL_V
struct DoubleFuncStruct {
let dfsi: Int
}
// CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD5ClassL_C
class DoubleFuncClass {
let dfcs: String
init(s: String) {
self.dfcs = s
}
}
// CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD4EnumL_O
enum DoubleFuncEnum {
case DFEI(Int)
}
}
innerFunc()
}
public let doubleClosure: () -> () = {
let singleClosure: () -> () = {
// CHECK-DAG: 10LocalTypesyycfU0_yycfU_19DoubleClosureStructL_V
struct DoubleClosureStruct {
let dcsi: Int
}
// CHECK-DAG: 10LocalTypesyycfU0_yycfU_18DoubleClosureClassL_C
class DoubleClosureClass {
let dccs: String
init(s: String) {
self.dccs = s
}
}
// CHECK-DAG: 10LocalTypesyycfU0_yycfU_17DoubleClosureEnumL_O
enum DoubleClosureEnum {
case DCEI(Int)
}
}
singleClosure()
}
| apache-2.0 | bd283337d2a7a9b84a22e01417fb400a | 25.149068 | 119 | 0.690261 | 3.582979 | false | false | false | false |
StormXX/STTableBoard | STTableBoardDemo/CheckBoxView.swift | 1 | 691 | //
// CheckBoxView.swift
// STTableBoardDemo
//
// Created by DangGu on 15/12/23.
// Copyright © 2015年 StormXX. All rights reserved.
//
import UIKit
class CheckBoxView: UIImageView{
fileprivate let uncheckedImageName = "checkbox"
fileprivate let checkedImageName = "checkbox"
var checked: Bool = false {
didSet {
self.image = checked ? UIImage(named: checkedImageName) : UIImage(named: uncheckedImageName)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
checked = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| cc0-1.0 | ee4af96ec16d6220cca92d18dd642911 | 21.933333 | 104 | 0.633721 | 4.144578 | false | false | false | false |
balazs630/Bad-Jokes | BadJokes/Storage/Services/AppUpdateService.swift | 1 | 3388 | //
// AppUpdateService.swift
// BadJokes
//
// Created by Horváth Balázs on 2018. 06. 06..
// Copyright © 2018. Horváth Balázs. All rights reserved.
//
import Foundation
class AppUpdateService {
// MARK: Properties
public static var currentAppVersion: String {
guard let currentVersion = Bundle.main.infoDictionary?[Constant.shortVersionString] as? String else {
return "1.1"
}
return currentVersion
}
private static var lastAppVersion: String {
guard let lastVersion = UserDefaults.standard.string(forKey: UserDefaults.Key.appVersion) else {
return "1.1"
}
return lastVersion
}
// MARK: Routines for app updates
static func checkUpdates() {
guard isAppVersionChangedSinceLastLaunch() else { return }
runDatabaseMigration()
runApplicationUpdateStatements()
syncCurrentAppVersion()
}
static func readFile(named fileName: String) -> String? {
guard let file = Bundle.main.path(forResource: fileName, ofType: nil) else { return nil }
return try? String(contentsOfFile: file, encoding: .utf8)
}
}
// MARK: Utility methods
extension AppUpdateService {
private static func isAppVersionChangedSinceLastLaunch() -> Bool {
return currentAppVersion != lastAppVersion
}
private static func runDatabaseMigration() {
[
"1.2": "v1.2.sql",
"1.3": "v1.3.sql",
"1.4": "v1.4.sql",
"1.5": "v1.5.sql",
"1.6": "v1.6.sql",
"1.7": "v1.7.sql"
]
.filter { $0.key.isGreater(than: lastAppVersion) }
.forEach { DBService.shared.executeSQLFile(named: $0.value) }
}
private static func runApplicationUpdateStatements() {
if "1.2".isGreater(than: lastAppVersion) {
renameUserDefaultsKey(from: "sldIT", to: "sldGeek")
}
if "1.3".isGreater(than: lastAppVersion) {
renameUserDefaultsKey(from: "sldMoriczka", to: "sldMoricka")
}
if "1.3.1".isGreater(than: lastAppVersion) {
let isActive = true
UserDefaults.standard.set(isActive, forKey: UserDefaults.Key.StoreReviewTrigger.newUser)
UserDefaults.standard.set(isActive, forKey: UserDefaults.Key.StoreReviewTrigger.oldUser)
UserDefaults.standard.set(isActive, forKey: UserDefaults.Key.StoreReviewTrigger.copyJoke)
}
if "1.5".isGreater(than: lastAppVersion) {
regenerateJokeSchedules()
}
if "1.6".isGreater(than: lastAppVersion) {
regenerateJokeSchedules()
}
if "1.7".isGreater(than: lastAppVersion) {
regenerateJokeSchedules()
}
}
private static func syncCurrentAppVersion() {
UserDefaults.standard.set(currentAppVersion, forKey: UserDefaults.Key.appVersion)
}
private static func renameUserDefaultsKey(from oldKey: String, to newKey: String) {
let oldValue = UserDefaults.standard.double(forKey: oldKey)
UserDefaults.standard.set(oldValue, forKey: newKey)
UserDefaults.standard.removeObject(forKey: oldKey)
}
private static func regenerateJokeSchedules() {
let jokeNotificationService = JokeNotificationService()
jokeNotificationService.setNewRepeatingNotifications()
}
}
| apache-2.0 | 05dfc5a5df153a394fea9e3bbc81879f | 30.324074 | 109 | 0.639078 | 4.439633 | false | false | false | false |
FuckBoilerplate/RxCache | watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift | 6 | 3225 | //
// CombineLatest.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
protocol CombineLatestProtocol : class {
func next(_ index: Int)
func fail(_ error: Swift.Error)
func done(_ index: Int)
}
class CombineLatestSink<O: ObserverType>
: Sink<O>
, CombineLatestProtocol {
typealias Element = O.E
let _lock = NSRecursiveLock()
private let _arity: Int
private var _numberOfValues = 0
private var _numberOfDone = 0
private var _hasValue: [Bool]
private var _isDone: [Bool]
init(arity: Int, observer: O, cancel: Cancelable) {
_arity = arity
_hasValue = [Bool](repeating: false, count: arity)
_isDone = [Bool](repeating: false, count: arity)
super.init(observer: observer, cancel: cancel)
}
func getResult() throws -> Element {
abstractMethod()
}
func next(_ index: Int) {
if !_hasValue[index] {
_hasValue[index] = true
_numberOfValues += 1
}
if _numberOfValues == _arity {
do {
let result = try getResult()
forwardOn(.next(result))
}
catch let e {
forwardOn(.error(e))
dispose()
}
}
else {
var allOthersDone = true
for i in 0 ..< _arity {
if i != index && !_isDone[i] {
allOthersDone = false
break
}
}
if allOthersDone {
forwardOn(.completed)
dispose()
}
}
}
func fail(_ error: Swift.Error) {
forwardOn(.error(error))
dispose()
}
func done(_ index: Int) {
if _isDone[index] {
return
}
_isDone[index] = true
_numberOfDone += 1
if _numberOfDone == _arity {
forwardOn(.completed)
dispose()
}
}
}
class CombineLatestObserver<ElementType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = ElementType
typealias ValueSetter = (Element) -> Void
private let _parent: CombineLatestProtocol
let _lock: NSRecursiveLock
private let _index: Int
private let _this: Disposable
private let _setLatestValue: ValueSetter
init(lock: NSRecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: @escaping ValueSetter, this: Disposable) {
_lock = lock
_parent = parent
_index = index
_this = this
_setLatestValue = setLatestValue
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let value):
_setLatestValue(value)
_parent.next(_index)
case .error(let error):
_this.dispose()
_parent.fail(error)
case .completed:
_this.dispose()
_parent.done(_index)
}
}
}
| mit | 3d4a3820974684f8aad91fb65e5a3689 | 23.059701 | 133 | 0.525434 | 4.672464 | false | true | false | false |
shahmishal/swift | test/Constraints/generics.swift | 1 | 31948 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
infix operator +++
protocol ConcatToAnything {
static func +++ <T>(lhs: Self, other: T)
}
func min<T : Comparable>(_ x: T, y: T) -> T {
if y < x { return y }
return x
}
func weirdConcat<T : ConcatToAnything, U>(_ t: T, u: U) {
t +++ u
t +++ 1
u +++ t // expected-error{{argument type 'U' does not conform to expected type 'ConcatToAnything'}}
}
// Make sure that the protocol operators don't get in the way.
var b1, b2 : Bool
_ = b1 != b2
extension UnicodeScalar {
func isAlpha2() -> Bool {
return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z")
}
}
protocol P {
static func foo(_ arg: Self) -> Self
}
struct S : P {
static func foo(_ arg: S) -> S {
return arg
}
}
func foo<T : P>(_ arg: T) -> T {
return T.foo(arg)
}
// Associated types and metatypes
protocol SomeProtocol {
associatedtype SomeAssociated
}
func generic_metatypes<T : SomeProtocol>(_ x: T)
-> (T.Type, T.SomeAssociated.Type)
{
return (type(of: x), type(of: x).SomeAssociated.self)
}
// Inferring a variable's type from a call to a generic.
struct Pair<T, U> { } // expected-note 3 {{'T' declared as parameter to type 'Pair'}} expected-note 3 {{'U' declared as parameter to type 'Pair'}}
func pair<T, U>(_ x: T, _ y: U) -> Pair<T, U> { }
var i : Int, f : Float
var p = pair(i, f)
// Conformance constraints on static variables.
func f1<S1 : Sequence>(_ s1: S1) {}
var x : Array<Int> = [1]
f1(x)
// Inheritance involving generics and non-generics.
class X {
func f() {}
}
class Foo<T> : X {
func g() { }
}
class Y<U> : Foo<Int> {
}
func genericAndNongenericBases(_ x: Foo<Int>, y: Y<()>) {
x.f()
y.f()
y.g()
}
func genericAndNongenericBasesTypeParameter<T : Y<()>>(_ t: T) {
t.f()
t.g()
}
protocol P1 {}
protocol P2 {}
func foo<T : P1>(_ t: T) -> P2 {
return t // expected-error{{return expression of type 'T' does not conform to 'P2'}}
}
func foo2(_ p1: P1) -> P2 {
return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}}
}
// <rdar://problem/14005696>
protocol BinaryMethodWorkaround {
associatedtype MySelf
}
protocol Squigglable : BinaryMethodWorkaround {
}
infix operator ~~~
func ~~~ <T : Squigglable>(lhs: T, rhs: T) -> Bool where T.MySelf == T {
return true
}
extension UInt8 : Squigglable {
typealias MySelf = UInt8
}
var rdar14005696 : UInt8
_ = rdar14005696 ~~~ 5
// <rdar://problem/15168483>
public struct SomeIterator<C: Collection, Indices: Sequence>
: IteratorProtocol, Sequence
where C.Index == Indices.Iterator.Element {
var seq : C
var indices : Indices.Iterator
public typealias Element = C.Iterator.Element
public mutating func next() -> Element? {
fatalError()
}
public init(elements: C, indices: Indices) {
fatalError()
}
}
func f1<T>(seq: Array<T>) {
let x = (seq.indices).lazy.reversed()
SomeIterator(elements: seq, indices: x) // expected-warning{{unused}}
SomeIterator(elements: seq, indices: seq.indices.reversed()) // expected-warning{{unused}}
}
// <rdar://problem/16078944>
func count16078944<T>(_ x: Range<T>) -> Int { return 0 }
func test16078944 <T: Comparable>(lhs: T, args: T) -> Int {
return count16078944(lhs..<args) // don't crash
}
// <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy()
class r22409190ManagedBuffer<Value, Element> {
final var value: Value { get {} set {}}
func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) -> R) -> R {
}
}
class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> {
deinit {
self.withUnsafeMutablePointerToElements { elems -> Void in
// FIXME(diagnostics): Diagnostic regressed here from `cannot convert value of type 'UInt' to expected argument type 'Int'`.
// Once argument-to-parameter mismatch diagnostics are moved to the new diagnostic framework, we'll be able to restore
// original contextual conversion failure diagnostic here. Note that this only happens in Swift 4 mode.
elems.deinitialize(count: self.value) // expected-error {{ambiguous reference to member 'deinitialize(count:)'}}
}
}
}
// <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))'
func r22459135() {
func h<S : Sequence>(_ sequence: S) -> S.Iterator.Element
where S.Iterator.Element : FixedWidthInteger {
return 0
}
func g(_ x: Any) {}
func f(_ x: Int) {
g(h([3]))
}
func f2<TargetType: AnyObject>(_ target: TargetType, handler: @escaping (TargetType) -> ()) {
let _: (AnyObject) -> () = { internalTarget in
handler(internalTarget as! TargetType)
}
}
}
// <rdar://problem/19710848> QoI: Friendlier error message for "[] as Set"
// <rdar://problem/22326930> QoI: "argument for generic parameter 'Element' could not be inferred" lacks context
_ = [] as Set // expected-error {{protocol type 'Any' cannot conform to 'Hashable' because only concrete types can conform to protocols}}
//<rdar://problem/22509125> QoI: Error when unable to infer generic archetype lacks greatness
func r22509125<T>(_ a : T?) { // expected-note {{in call to function 'r22509125'}}
r22509125(nil) // expected-error {{generic parameter 'T' could not be inferred}}
}
// <rdar://problem/24267414> QoI: error: cannot convert value of type 'Int' to specified type 'Int'
struct R24267414<T> { // expected-note {{'T' declared as parameter to type 'R24267414'}}
static func foo() -> Int {}
}
var _ : Int = R24267414.foo() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{24-24=<Any>}}
// https://bugs.swift.org/browse/SR-599
func SR599<T: FixedWidthInteger>() -> T.Type { return T.self } // expected-note {{in call to function 'SR599()'}}
_ = SR599() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/19215114> QoI: Poor diagnostic when we are unable to infer type
protocol Q19215114 {}
protocol P19215114 {}
// expected-note @+1 {{in call to function 'body9215114'}}
func body9215114<T: P19215114, U: Q19215114>(_ t: T) -> (_ u: U) -> () {}
func test9215114<T: P19215114, U: Q19215114>(_ t: T) -> (U) -> () {
let f = body9215114(t) // expected-error {{generic parameter 'U' could not be inferred}}
return f
}
// <rdar://problem/21718970> QoI: [uninferred generic param] cannot invoke 'foo' with an argument list of type '(Int)'
class Whatever<A: Numeric, B: Numeric> { // expected-note 2 {{'A' declared as parameter to type 'Whatever'}} expected-note {{'B' declared as parameter to type 'Whatever'}}
static func foo(a: B) {}
static func bar() {}
}
Whatever.foo(a: 23) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, Int>}}
// <rdar://problem/21718955> Swift useless error: cannot invoke 'foo' with no arguments
// TODO(diagnostics): We should try to produce a single note in this case.
Whatever.bar() // expected-error {{generic parameter 'A' could not be inferred}} expected-note 2 {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}}
// expected-error@-1 {{generic parameter 'B' could not be inferred}}
// <rdar://problem/27515965> Type checker doesn't enforce same-type constraint if associated type is Any
protocol P27515965 {
associatedtype R
func f() -> R
}
struct S27515965 : P27515965 {
func f() -> Any { return self }
}
struct V27515965 {
init<T : P27515965>(_ tp: T) where T.R == Float {}
// expected-note@-1 {{where 'T.R' = 'Any'}}
}
func test(x: S27515965) -> V27515965 {
return V27515965(x)
// expected-error@-1 {{initializer 'init(_:)' requires the types 'Any' and 'Float' be equivalent}}
}
protocol BaseProto {}
protocol SubProto: BaseProto {}
@objc protocol NSCopyish {
func copy() -> Any
}
struct FullyGeneric<Foo> {} // expected-note 13 {{'Foo' declared as parameter to type 'FullyGeneric'}} expected-note 1 {{generic type 'FullyGeneric' declared here}}
struct AnyClassBound<Foo: AnyObject> {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound'}} expected-note {{generic type 'AnyClassBound' declared here}}
// expected-note@-1{{requirement specified as 'Foo' : 'AnyObject'}}
struct AnyClassBound2<Foo> where Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound2'}}
// expected-note@-1{{requirement specified as 'Foo' : 'AnyObject' [with Foo = Any]}}
struct ProtoBound<Foo: SubProto> {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound'}} expected-note {{generic type 'ProtoBound' declared here}}
struct ProtoBound2<Foo> where Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound2'}}
struct ObjCProtoBound<Foo: NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound'}} expected-note {{generic type 'ObjCProtoBound' declared here}}
struct ObjCProtoBound2<Foo> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound2'}}
struct ClassBound<Foo: X> {} // expected-note {{generic type 'ClassBound' declared here}}
struct ClassBound2<Foo> where Foo: X {} // expected-note {{generic type 'ClassBound2' declared here}}
struct ProtosBound<Foo> where Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound'}} expected-note {{generic type 'ProtosBound' declared here}}
struct ProtosBound2<Foo: SubProto & NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound2'}}
struct ProtosBound3<Foo: SubProto> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound3'}}
struct AnyClassAndProtoBound<Foo> where Foo: AnyObject, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound'}}
struct AnyClassAndProtoBound2<Foo> where Foo: SubProto, Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound2'}}
struct ClassAndProtoBound<Foo> where Foo: X, Foo: SubProto {} // expected-note {{where 'Foo' = 'X'}}
struct ClassAndProtosBound<Foo> where Foo: X, Foo: SubProto, Foo: NSCopyish {} // expected-note 2 {{where 'Foo' = 'X'}}
struct ClassAndProtosBound2<Foo> where Foo: X, Foo: SubProto & NSCopyish {} // expected-note 2 {{where 'Foo' = 'X'}}
extension Pair {
init(first: T) {}
init(second: U) {}
var first: T { fatalError() }
var second: U { fatalError() }
}
func testFixIts() {
_ = FullyGeneric() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<Any>}}
_ = FullyGeneric<Any>()
_ = AnyClassBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<AnyObject>}}
_ = AnyClassBound<Any>() // expected-error {{'AnyClassBound' requires that 'Any' be a class type}}
_ = AnyClassBound<AnyObject>()
_ = AnyClassBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<AnyObject>}}
_ = AnyClassBound2<Any>() // expected-error {{'AnyClassBound2' requires that 'Any' be a class type}}
_ = AnyClassBound2<AnyObject>()
_ = ProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#Foo: SubProto#>>}}
_ = ProtoBound<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: SubProto#>>}}
_ = ProtoBound2<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ObjCProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<NSCopyish>}}
_ = ObjCProtoBound<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound<NSCopyish>()
_ = ObjCProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{22-22=<NSCopyish>}}
_ = ObjCProtoBound2<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound2<NSCopyish>()
_ = ProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound3() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = AnyClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{28-28=<<#Foo: SubProto & AnyObject#>>}}
_ = AnyClassAndProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{29-29=<<#Foo: SubProto & AnyObject#>>}}
_ = ClassAndProtoBound() // expected-error {{referencing initializer 'init()' on 'ClassAndProtoBound' requires that 'X' conform to 'SubProto'}}
_ = ClassAndProtosBound()
// expected-error@-1 {{referencing initializer 'init()' on 'ClassAndProtosBound' requires that 'X' conform to 'NSCopyish'}}
// expected-error@-2 {{referencing initializer 'init()' on 'ClassAndProtosBound' requires that 'X' conform to 'SubProto'}}
_ = ClassAndProtosBound2()
// expected-error@-1 {{referencing initializer 'init()' on 'ClassAndProtosBound2' requires that 'X' conform to 'NSCopyish'}}
// expected-error@-2 {{referencing initializer 'init()' on 'ClassAndProtosBound2' requires that 'X' conform to 'SubProto'}}
_ = Pair()
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-error@-2 {{generic parameter 'U' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, Any>}}
_ = Pair(first: S()) // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<S, Any>}}
_ = Pair(second: S()) // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, S>}}
}
func testFixItClassBound() {
// We infer a single class bound for simple cases in expressions...
let x = ClassBound()
let x1: String = x // expected-error {{cannot convert value of type 'ClassBound<X>' to specified type 'String'}}
let y = ClassBound2()
let y1: String = y // expected-error {{cannot convert value of type 'ClassBound2<X>' to specified type 'String'}}
// ...but not in types.
let z1: ClassBound // expected-error {{reference to generic type 'ClassBound' requires arguments in <...>}} {{21-21=<X>}}
let z2: ClassBound2 // expected-error {{reference to generic type 'ClassBound2' requires arguments in <...>}} {{22-22=<X>}}
}
func testFixItCasting(x: Any) {
_ = x as! FullyGeneric // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}}
}
func testFixItContextualKnowledge() {
// FIXME: These could propagate backwards.
let _: Int = Pair().first // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Int, Any>}}
let _: Int = Pair().second // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Int>}}
}
func testFixItTypePosition() {
let _: FullyGeneric // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{22-22=<Any>}}
let _: ProtoBound // expected-error {{reference to generic type 'ProtoBound' requires arguments in <...>}} {{20-20=<<#Foo: SubProto#>>}}
let _: ObjCProtoBound // expected-error {{reference to generic type 'ObjCProtoBound' requires arguments in <...>}} {{24-24=<NSCopyish>}}
let _: AnyClassBound // expected-error {{reference to generic type 'AnyClassBound' requires arguments in <...>}} {{23-23=<AnyObject>}}
let _: ProtosBound // expected-error {{reference to generic type 'ProtosBound' requires arguments in <...>}} {{21-21=<<#Foo: NSCopyish & SubProto#>>}}
}
func testFixItNested() {
_ = Array<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}}
_ = [FullyGeneric]() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any>}}
_ = FullyGeneric<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{32-32=<Any>}}
_ = Pair<
FullyGeneric,
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
>()
_ = Pair<
FullyGeneric<Any>,
FullyGeneric
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
>()
_ = Pair<
FullyGeneric,
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric<Any>
>()
_ = pair(
FullyGeneric(),
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric()
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
)
_ = pair(
FullyGeneric<Any>(),
FullyGeneric()
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
)
_ = pair(
FullyGeneric(),
// expected-error@-1 {{generic parameter 'Foo' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric<Any>()
)
}
// rdar://problem/26845038
func occursCheck26845038(a: [Int]) {
_ = Array(a)[0]
}
// rdar://problem/29633747
extension Array where Element: Hashable {
public func trimmed(_ elements: [Element]) -> SubSequence {
return []
}
}
func rdar29633747(characters: String) {
let _ = Array(characters).trimmed(["("])
}
// Null pointer dereference in noteArchetypeSource()
class GenericClass<A> {}
// expected-note@-1 {{'A' declared as parameter to type 'GenericClass'}}
func genericFunc<T>(t: T) {
_ = [T: GenericClass] // expected-error {{generic parameter 'A' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
}
struct SR_3525<T> {}
func sr3525_arg_int(_: inout SR_3525<Int>) {}
func sr3525_arg_gen<T>(_: inout SR_3525<T>) {}
func sr3525_1(t: SR_3525<Int>) {
let _ = sr3525_arg_int(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
func sr3525_2(t: SR_3525<Int>) {
let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
func sr3525_3<T>(t: SR_3525<T>) {
let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
class testStdlibType {
let _: Array // expected-error {{reference to generic type 'Array' requires arguments in <...>}} {{15-15=<Any>}}
}
// rdar://problem/32697033
protocol P3 {
associatedtype InnerAssoc
}
protocol P4 {
associatedtype OuterAssoc: P3
}
struct S3 : P3 {
typealias InnerAssoc = S4
}
struct S4: P4 {
typealias OuterAssoc = S3
}
public struct S5 {
func f<Model: P4, MO> (models: [Model])
where Model.OuterAssoc == MO, MO.InnerAssoc == Model {
}
func g<MO, Model: P4> (models: [Model])
where Model.OuterAssoc == MO, MO.InnerAssoc == Model {
}
func f(arr: [S4]) {
f(models: arr)
g(models: arr)
}
}
// rdar://problem/24329052 - QoI: call argument archetypes not lining up leads to ambiguity errors
struct S_24329052<T> { // expected-note {{generic parameter 'T' of generic struct 'S_24329052' declared here}}
var foo: (T) -> Void
// expected-note@+1 {{generic parameter 'T' of instance method 'bar(_:)' declared here}}
func bar<T>(_ v: T) { foo(v) }
// expected-error@-1 {{cannot convert value of type 'T' (generic parameter of instance method 'bar(_:)') to expected argument type 'T' (generic parameter of generic struct 'S_24329052')}}
}
extension Sequence {
var rdar24329052: (Element) -> Void { fatalError() }
// expected-note@+1 {{generic parameter 'Element' of instance method 'foo24329052(_:)' declared here}}
func foo24329052<Element>(_ v: Element) { rdar24329052(v) }
// expected-error@-1 {{cannot convert value of type 'Element' (generic parameter of instance method 'foo24329052(_:)') to expected argument type 'Self.Element' (associated type of protocol 'Sequence')}}
}
func rdar27700622<E: Comparable>(_ input: [E]) -> [E] {
let pivot = input.first!
let lhs = input.dropFirst().filter { $0 <= pivot }
let rhs = input.dropFirst().filter { $0 > pivot }
return rdar27700622(lhs) + [pivot] + rdar27700622(rhs) // Ok
}
// rdar://problem/22898292 - Type inference failure with constrained subclass
protocol P_22898292 {}
do {
func construct_generic<T: P_22898292>(_ construct: () -> T) -> T { return construct() }
class A {}
class B : A, P_22898292 {}
func foo() -> B { return B() }
func bar(_ value: A) {}
func baz<T: A>(_ value: T) {}
func rdar_22898292_1() {
let x = construct_generic { foo() } // returns A
bar(x) // Ok
bar(construct_generic { foo() }) // Ok
}
func rdar22898292_2<T: B>(_ d: T) {
_ = { baz($0) }(construct_generic { d }) // Ok
}
}
// rdar://problem/35541153 - Generic parameter inference bug
func rdar35541153() {
func foo<U: Equatable, V: Equatable, C: Collection>(_ c: C) where C.Element == (U, V) {}
func bar<K: Equatable, V, C: Collection>(_ c: C, _ k: K, _ v: V) where C.Element == (K, V) {}
let x: [(a: Int, b: Int)] = []
let y: [(k: String, v: Int)] = []
foo(x) // Ok
bar(y, "ultimate question", 42) // Ok
}
// rdar://problem/38159133 - [SR-7125]: Swift 4.1 Xcode 9.3b4 regression
protocol P_38159133 {}
do {
class Super {}
class A: Super, P_38159133 {}
class B: Super, P_38159133 {}
func rdar38159133(_ a: A?, _ b: B?) {
let _: [P_38159133] = [a, b].compactMap { $0 } // Ok
}
}
func rdar35890334(_ arr: inout [Int]) {
_ = arr.popFirst() // expected-error {{referencing instance method 'popFirst()' on 'Collection' requires the types '[Int]' and 'ArraySlice<Int>' be equivalent}}
}
// rdar://problem/39616039
func rdar39616039() {
func foo<V>(default: V, _ values: [String: V]) -> V {
return values["foo"] ?? `default`
}
var a = foo(default: 42, ["foo": 0])
a += 1 // ok
var b = foo(default: 42.0, ["foo": 0])
b += 1 // ok
var c = foo(default: 42.0, ["foo": Float(0)])
c += 1 // ok
}
// https://bugs.swift.org/browse/SR-8075
func sr8075() {
struct UIFont {
init(ofSize: Float) {}
}
func switchOnCategory<T>(_ categoryToValue: [Int: T]) -> T {
fatalError()
}
let _: UIFont = .init(ofSize: switchOnCategory([0: 15.5, 1: 20.5]))
}
// rdar://problem/40537858 - Ambiguous diagnostic when type is missing conformance
func rdar40537858() {
struct S {
struct Id {}
var id: Id
}
struct List<T: Collection, E: Hashable> { // expected-note {{where 'E' = 'S.Id'}}
typealias Data = T.Element
init(_: T, id: KeyPath<Data, E>) {}
}
var arr: [S] = []
_ = List(arr, id: \.id) // expected-error {{referencing initializer 'init(_:id:)' on 'List' requires that 'S.Id' conform to 'Hashable'}}
enum E<T: P> { // expected-note 2 {{where 'T' = 'S'}}
case foo(T)
case bar([T])
}
var s = S(id: S.Id())
let _: E = .foo(s) // expected-error {{enum case 'foo' requires that 'S' conform to 'P'}}
let _: E = .bar([s]) // expected-error {{enum case 'bar' requires that 'S' conform to 'P'}}
}
// https://bugs.swift.org/browse/SR-8934
struct BottleLayout {
let count : Int
}
let arr = [BottleLayout]()
let layout = BottleLayout(count:1)
let ix = arr.firstIndex(of:layout) // expected-error {{argument type 'BottleLayout' does not conform to expected type 'Equatable'}}
let _: () -> UInt8 = { .init("a" as Unicode.Scalar) } // expected-error {{missing argument label 'ascii:' in call}}
// https://bugs.swift.org/browse/SR-9068
func compare<C: Collection, Key: Hashable, Value: Equatable>(c: C)
-> Bool where C.Element == (key: Key, value: Value)
{
_ = Dictionary(uniqueKeysWithValues: Array(c))
}
// https://bugs.swift.org/browse/SR-7984
struct SR_7984<Bar> {
func doSomething() {}
}
extension SR_7984 where Bar: String {} // expected-error {{type 'Bar' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'Bar == String' to require 'Bar' to be 'String'}} {{28-29= ==}}
protocol SR_7984_Proto {
associatedtype Bar
}
extension SR_7984_Proto where Bar: String {} // expected-error {{type 'Self.Bar' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'Bar == String' to require 'Bar' to be 'String'}} {{34-35= ==}}
protocol SR_7984_HasFoo {
associatedtype Foo
}
protocol SR_7984_HasAssoc {
associatedtype Assoc: SR_7984_HasFoo
}
struct SR_7984_X<T: SR_7984_HasAssoc> {}
extension SR_7984_X where T.Assoc.Foo: String {} // expected-error {{type 'T.Assoc.Foo' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Assoc.Foo == String' to require 'T.Assoc.Foo' to be 'String'}} {{38-39= ==}}
struct SR_7984_S<T: Sequence> where T.Element: String {} // expected-error {{type 'T.Element' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Element == String' to require 'T.Element' to be 'String'}} {{46-47= ==}}
func SR_7984_F<T: Sequence>(foo: T) where T.Element: String {} // expected-error {{type 'T.Element' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Element == String' to require 'T.Element' to be 'String'}} {{52-53= ==}}
protocol SR_7984_P {
func S<T : Sequence>(bar: T) where T.Element: String // expected-error {{type 'T.Element' constrained to non-protocol, non-class type 'String'}} expected-note {{use 'T.Element == String' to require 'T.Element' to be 'String'}} {{47-48= ==}}
}
struct A<T: String> {} // expected-error {{type 'T' constrained to non-protocol, non-class type 'String'}}
struct B<T> where T: String {} // expected-error {{type 'T' constrained to non-protocol, non-class type 'String'}}
protocol C {
associatedtype Foo: String // expected-error {{type 'Self.Foo' constrained to non-protocol, non-class type 'String'}}
}
protocol D {
associatedtype Foo where Foo: String // expected-error {{type 'Self.Foo' constrained to non-protocol, non-class type 'String'}}
}
func member_ref_with_explicit_init() {
struct S<T: P> { // expected-note {{where 'T' = 'Int'}}
init(_: T) {}
init(_: T, _ other: Int = 42) {}
}
_ = S.init(42)
// expected-error@-1 {{generic struct 'S' requires that 'Int' conform to 'P'}}
}
protocol Q {
init<T : P>(_ x: T) // expected-note 2{{where 'T' = 'T'}}
}
struct SR10694 {
init<T : P>(_ x: T) {} // expected-note 2{{where 'T' = 'T'}}
func bar<T>(_ x: T, _ s: SR10694, _ q: Q) {
SR10694.self(x) // expected-error {{initializer 'init(_:)' requires that 'T' conform to 'P'}}
type(of: s)(x) // expected-error {{initializer 'init(_:)' requires that 'T' conform to 'P'}}
// expected-error@-1 {{initializing from a metatype value must reference 'init' explicitly}}
Q.self(x) // expected-error {{initializer 'init(_:)' requires that 'T' conform to 'P'}}
// expected-error@-1 {{protocol type 'Q' cannot be instantiated}}
type(of: q)(x) // expected-error {{initializer 'init(_:)' requires that 'T' conform to 'P'}}
// expected-error@-1 {{initializing from a metatype value must reference 'init' explicitly}}
}
}
// SR-7003 (rdar://problem/51203824) - Poor diagnostics when attempting to access members on unfulfilled generic type
func sr_7003() {
struct E<T> { // expected-note 4 {{'T' declared as parameter to type 'E'}}
static var foo: String { return "" }
var bar: String { return "" }
static func baz() -> String { return "" }
func qux() -> String { return "" }
}
let _: Any = E.foo
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
let _: Any = E().bar
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
let _: Any = E.baz()
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
let _: Any = E().qux()
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
}
func test_generic_subscript_with_missing_arg() {
struct S<T> {
subscript<U>(_: T) -> S<U> { fatalError() }
// expected-note@-1 {{in call to 'subscript(_:)'}}
}
func test(_ s: S<Int>) {
_ = s[0] // expected-error {{generic parameter 'U' could not be inferred}}
}
}
func rdar_50007727() {
struct A<T> { // expected-note {{'T' declared as parameter to type 'A'}}
struct B<U> : ExpressibleByStringLiteral {
init(stringLiteral value: String) {}
}
}
struct S {}
let _ = A.B<S>("hello")
// expected-error@-1 {{generic parameter 'T' could not be inferred in cast to 'A.B'}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{12-12=<Any>}}
}
// rdar://problem/51413254
infix operator ==>
struct Key {
init(_ key: String) {}
}
func ==> (lhs: Any, rhs: Key) throws -> Any {
return 0
}
func ==> <A>(lhs: Any, rhs: Key) throws -> A {
fatalError()
}
struct R_51413254 {
var str: String = ""
mutating func test(_ anyDict: Any) throws {
self.str = try anyDict ==> Key("a") // Ok
}
}
| apache-2.0 | b18516b98b93f0eaffd154aeb261b6e4 | 38.935 | 250 | 0.666395 | 3.625922 | false | false | false | false |
shergin/PeterParker | Sources/PeterParker/Routing/RouteType.swift | 1 | 951 | //
// RouteType.swift
// PeterParker
//
// Created by Valentin Shergin on 5/16/16.
// Copyright © 2016 The PeterParker Authors. All rights reserved.
//
import Foundation
import PeterParkerPrivate.ifaddrs
/// Mapping of messages operating on routing table
///
/// See [route(4)](https://www.freebsd.org/cgi/man.cgi?query=route&sektion=4&apropos=0&manpath=FreeBSD+10.3-RELEASE+and+Ports)
public enum RouteType: CUnsignedChar {
case add = 1
case delete
case change
case get
case losing
case redirect
case miss
case lock
case oldAdd
case oldDel
case resolve
case newAddress
case deleteAddress
case interfaceInfo
case newMembershipAddress
case deleteMembershipAddress
case getSilent
case interfaceInfo2
case newMembershipAddress2
case get2
}
extension RouteType {
public init(_ _routeType: CUnsignedChar) {
self = RouteType(rawValue: _routeType)!
}
}
| mit | f66f7d89133f25807922b8dc4a487eeb | 21.093023 | 126 | 0.702105 | 4.008439 | false | false | false | false |
novi/mysql-swift | Sources/MySQL/ConnectionPool.swift | 1 | 4966 | //
// ConnectionPool.swift
// MySQL
//
// Created by ito on 12/24/15.
// Copyright © 2015 Yusuke Ito. All rights reserved.
//
import Dispatch
#if os(Linux)
import Glibc
#endif
import CMySQL
fileprivate var LibraryInitialized: Atomic<Bool> = Atomic(false)
fileprivate func InitializeMySQLLibrary() {
LibraryInitialized.syncWriting {
guard $0 == false else {
return
}
if mysql_server_init(0, nil, nil) != 0 { // mysql_library_init
fatalError("could not initialize MySQL library with `mysql_server_init`.")
}
$0 = true
}
}
extension Array where Element == Connection {
mutating func preparedNewConnection(option: ConnectionOption, pool: ConnectionPool) -> Connection {
let newConn = Connection(option: option, pool: pool)
_ = try? newConn.connect()
append(newConn)
return newConn
}
func getUsableConnection() -> Connection? {
for c in self {
if c.isInUse == false && c.ping() {
c.isInUse = true
return c
}
}
return nil
}
internal var inUseConnections: Int {
var count: Int = 0
for c in self {
if c.isInUse {
count += 1
}
}
return count
}
}
final public class ConnectionPool: CustomStringConvertible {
private var initialConnections_: Atomic<Int> = Atomic(1)
public var initialConnections: Int {
get {
return initialConnections_.sync { $0 }
}
set {
initialConnections_.syncWriting {
$0 = newValue
}
pool.syncWriting {
while $0.count < newValue {
_ = $0.preparedNewConnection(option: self.option, pool: self)
}
}
}
}
public var maxConnections: Int {
get {
return maxConnections_.sync { $0 }
}
set {
maxConnections_.syncWriting {
$0 = newValue
}
}
}
private var maxConnections_: Atomic<Int> = Atomic(10)
internal private(set) var pool: Atomic<[Connection]> = Atomic([])
@available(*, deprecated, renamed: "option")
public var options: ConnectionOption {
return option
}
public let option: ConnectionOption
@available(*, deprecated, renamed: "init(option:)")
public convenience init(options: ConnectionOption) {
self.init(option: options)
}
public init(option: ConnectionOption) {
self.option = option
InitializeMySQLLibrary()
for _ in 0..<initialConnections {
pool.syncWriting {
_ = $0.preparedNewConnection(option: option, pool: self)
}
}
}
public var timeoutForGetConnection: Int {
get {
return timeoutForGetConnection_.sync { $0 }
}
set {
timeoutForGetConnection_.syncWriting {
$0 = newValue
}
}
}
private var timeoutForGetConnection_: Atomic<Int> = Atomic(60)
internal func getConnection() throws -> Connection {
var connection: Connection? =
pool.syncWriting {
if let conn = $0.getUsableConnection() {
return conn
}
if $0.count < maxConnections {
let conn = $0.preparedNewConnection(option: option, pool: self)
conn.isInUse = true
return conn
}
return nil
}
if let conn = connection {
return conn
}
let tickInMs = 50 // ms
var timeoutCount = (timeoutForGetConnection*1000)/tickInMs
while timeoutCount > 0 {
usleep(useconds_t(1000*tickInMs))
connection = pool.sync {
$0.getUsableConnection()
}
if connection != nil {
break
}
timeoutCount -= 1
}
guard let conn = connection else {
throw ConnectionError.connectionPoolGetConnectionTimeoutError
}
return conn
}
internal func releaseConnection(_ conn: Connection) {
pool.sync { _ in
conn.isInUse = false
}
}
public var description: String {
let inUseConnections = pool.sync {
$0.inUseConnections
}
return "connections:\n\tinitial:\(initialConnections), max:\(maxConnections), in-use:\(inUseConnections)"
}
}
extension ConnectionPool {
public func execute<T>( _ block: (_ conn: Connection) throws -> T ) throws -> T {
let conn = try getConnection()
defer {
releaseConnection(conn)
}
return try block(conn)
}
}
| mit | 466b03a36cbcce7a679acff31c5b4621 | 24.859375 | 113 | 0.529104 | 4.97994 | false | false | false | false |
bryzinski/skype-ios-app-sdk-samples | BankingAppSwift/BankingAppSwift/MainViewController.swift | 1 | 6065 | //+----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Module name: MainViewController.swift
//----------------------------------------------------------------
/*
MainViewController implements the meeting call flow for
Onprem CU4 / Onprem CU3 / {Online meeting-enablePreviewFeatures = True} scenarios.
*/
import UIKit
class MainViewController: UIViewController,SfBAlertDelegate, MicrosoftLicenseViewControllerDelegate {
/** Called when new alert appears in the context where this delegate is attached.
*
* Each alert is passed to a delegate once and dismissed unconditionally.
* If no delegate is attached, alerts are accumulated and reported as soon
* as delegate is set. Accumulated alerts of the same category and type
* are coalesced, only the last one will be reported.
*/
fileprivate var sfb: SfBApplication?
fileprivate var conversation: SfBConversation?
@IBOutlet weak var askAgentButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.initializeSkype()
// Do any additional setup after loading the view.
}
@IBAction func askAgent(_ sender: AnyObject) {
let alertController:UIAlertController = UIAlertController(title: "Ask Agent", message: nil, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Ask using Text Chat", style: .default, handler: { (action:UIAlertAction) in
self.askAgentText()
}))
alertController.addAction(UIAlertAction(title: "Ask using Video Chat", style: .default, handler: { (action:UIAlertAction) in
self.askAgentVideo()
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
if let popoverController = alertController.popoverPresentationController {
popoverController.sourceView = sender as? UIView
popoverController.sourceRect = sender.bounds
}
self.present(alertController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func askAgentText() {
if(didJoinMeeting()){
self.performSegue(withIdentifier: "askAgentText", sender: nil)
}
}
func askAgentVideo() {
if let sfb = sfb{
let config = sfb.configurationManager
let key = "AcceptedVideoLicense"
let defaults = UserDefaults.standard
if defaults.bool(forKey: key) {
config.setEndUserAcceptedVideoLicense()
if(didJoinMeeting()){
self.performSegue(withIdentifier: "askAgentVideo", sender: nil)
}
} else {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "MicrosoftLicenseViewController") as! MicrosoftLicenseViewController
vc.delegate = self
self.present(vc, animated: true, completion: nil)
}
}
}
func initializeSkype(){
sfb = SfBApplication.shared()
if let sfb = sfb{
sfb.configurationManager.maxVideoChannels = 1
sfb.configurationManager.requireWifiForAudio = false
sfb.configurationManager.requireWifiForVideo = false
sfb.devicesManager.selectedSpeaker.activeEndpoint = .loudspeaker
sfb.configurationManager.enablePreviewFeatures = getEnablePreviewSwitchState
sfb.alertDelegate = self
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
func didReceive(_ alert: SfBAlert) {
alert.showSfBAlertInController(self)
}
func didJoinMeeting() -> Bool {
let meetingURLString:String = getMeetingURLString
let meetingDisplayName:String = getMeetingDisplayName
do {
let urlText:String = meetingURLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string:urlText)
conversation = try sfb!.joinMeetingAnonymous(withUri: url!, displayName: meetingDisplayName).conversation
return true
}
catch {
print("ERROR! Joining online meeting>\(error)")
showErrorAlert("Joining online meeting failed. Try again later!", viewController: self)
return false
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "askAgentText"){
guard let destination = segue.destination as? ChatViewController else {
return
}
destination.conversation = self.conversation
}
else if(segue.identifier == "askAgentVideo"){
guard let destination = segue.destination as? VideoViewController else {
return
}
destination.deviceManagerInstance = sfb!.devicesManager
destination.conversationInstance = conversation
destination.displayName = getMeetingDisplayName
}
conversation = nil
}
func controller(_ controller: MicrosoftLicenseViewController, didAcceptLicense acceptedLicense: Bool) {
if(acceptedLicense){
if let sfb = sfb{
let config = sfb.configurationManager
config.setEndUserAcceptedVideoLicense()
if(didJoinMeeting()){
self.performSegue(withIdentifier: "askAgentVideo", sender: nil)
}
}
}
}
}
| mit | 2fbe201dcfe74f9191e13b26039443a8 | 35.536145 | 152 | 0.603792 | 5.814957 | false | true | false | false |
fabiomassimo/eidolon | Kiosk/App/Models/BidderPosition.swift | 2 | 841 | import Foundation
import SwiftyJSON
public class BidderPosition: JSONAble {
public let id: String
public let highestBid:Bid?
public let maxBidAmountCents: Int
init(id: String, highestBid:Bid?, maxBidAmountCents: Int) {
self.id = id
self.highestBid = highestBid
self.maxBidAmountCents = maxBidAmountCents
}
override public class func fromJSON(source:[String: AnyObject]) -> JSONAble {
let json = JSON(source)
let id = json["id"].stringValue
let maxBidAmount = json["max_bid_amount_cents"].intValue
var bid: Bid?
if let bidDictionary = json["highest_bid"].object as? [String: AnyObject] {
bid = Bid.fromJSON(bidDictionary) as? Bid
}
return BidderPosition(id: id, highestBid: bid, maxBidAmountCents: maxBidAmount)
}
}
| mit | cbc9c232e024e0c1e7b6b7643c7ef195 | 29.035714 | 87 | 0.657551 | 4.595628 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/记忆题 - 只需要记住最优解/12_Integer to Roman.swift | 1 | 2211 | // 12_Integer to Roman
// https://leetcode.com/problems/integer-to-roman/
//
// Created by Honghao Zhang on 10/23/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
//
//Symbol Value
//I 1
//V 5
//X 10
//L 50
//C 100
//D 500
//M 1000
//For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
//
//Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
//
//I can be placed before V (5) and X (10) to make 4 and 9.
//X can be placed before L (50) and C (100) to make 40 and 90.
//C can be placed before D (500) and M (1000) to make 400 and 900.
//Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
//
//Example 1:
//
//Input: 3
//Output: "III"
//Example 2:
//
//Input: 4
//Output: "IV"
//Example 3:
//
//Input: 9
//Output: "IX"
//Example 4:
//
//Input: 58
//Output: "LVIII"
//Explanation: L = 50, V = 5, III = 3.
//Example 5:
//
//Input: 1994
//Output: "MCMXCIV"
//Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
//
// 阿拉伯数字转换位罗马数字
import Foundation
class Num12 {
// MARK: - Maps fixed roman combination to integer
func intToRoman_mapping(_ num: Int) -> String {
let M = ["", "M", "MM", "MMM"] // 0, 1000, 2000...
let C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] // 0, 100, 200...
let X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] // 0, 10, 20, 30 ...
let I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] // 0, 1, 2...
return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]
}
}
| mit | a1c6dd1bb165ab70d1b1692c85e8e562 | 33.15625 | 347 | 0.589204 | 3.023513 | false | false | false | false |
nickqiao/NKBill | NKBill/View/CircularProgressView.swift | 1 | 14939 | /*
CircularProgressView.swift
CircularProgressView
Created by Wagner Truppel on 26/04/2015.
The MIT License (MIT)
Copyright (c) 2015 Wagner Truppel ([email protected]).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
When crediting me (Wagner Truppel) for this work, please use one
of the following two suggested formats:
Uses "CircularProgressView" code by Wagner Truppel
http://www.restlessbrain.com/wagner/
or
CircularProgressView code by Wagner Truppel
http://www.restlessbrain.com/wagner/
Where possible, a hyperlink to http://www.restlessbrain.com/wagner/
would be appreciated.
*/
import UIKit
@IBDesignable
class CircularProgressView: UIView
{
// The color of the full track.
@IBInspectable var trackTint: UIColor {
get { return iTrackTint }
set
{
if newValue != iTrackTint
{
iTrackTint = newValue
setNeedsDisplay()
if newValue == iProgressTint
{
print("[CircularProgressView] WARNING: setting trackTint to the same color as progressTint " +
"will make the circular progress view appear as if it's not progressing.", terminator: "")
}
}
}
}
private var iTrackTint: UIColor = UIColor.blackColor()
// The color of the part of the track representing progress.
@IBInspectable var progressTint: UIColor {
get { return iProgressTint }
set
{
if newValue != iProgressTint
{
iProgressTint = newValue
setNeedsDisplay()
if newValue == iTrackTint
{
print("[CircularProgressView] WARNING: setting progressTint to the same color as trackTint " +
"will make the circular progress view appear as if it's not progressing.", terminator: "")
}
}
}
}
private var iProgressTint: UIColor = UIColor.whiteColor()
// The thickness of the full track, in points. It shouldn't be less than minTrackThickness,
// and is clipped to that value if set otherwise. Always set this value before setting the
// values of either progressThickness or progressThicknessFraction.
@IBInspectable var trackThickness: CGFloat {
get { return iTrackThickness }
set
{
if newValue != iTrackThickness
{
iTrackThickness = max(minTrackThickness, newValue)
updateProgressThickness(iProgressThickness)
setNeedsDisplay()
}
}
}
private var iTrackThickness: CGFloat = 30.0 // points
private let minTrackThickness: CGFloat = 6.0 // points
// The thickness of the part of the track representing progress, in points. Alternatively,
// use progressThicknessFraction (see below) to set the progress thickness. progressThickness
// should be in the range [minProgressThickness, trackThickness]. Note that the range depends
// on the current value of trackThickness so always set that value first before setting the value
// of progressThickness.
@IBInspectable var progressThickness: CGFloat {
get { return iProgressThickness }
set
{
if newValue != iProgressThickness
{
updateProgressThickness(newValue)
setNeedsDisplay()
}
}
}
private var iProgressThickness: CGFloat = 10.0 // points
private let minProgressThickness: CGFloat = 2.0 // points
// The thickness of the part of the track representing progress, as a fraction of the full track
// thickness. Alternatively, use progressThickness (see above) to set the progress thickness.
// progressThicknessFraction should be a floating point number in the range
// [minProgressThickness/trackThickness, 1]. Values outside that range are clipped to that range.
// Note that the range depends on the current value of trackThickness so always set that value
// first before setting the value of progressThicknessFraction.
/*@IBInspectable*/ var progressThicknessFraction: CGFloat {
get { return iProgressThicknessFraction }
set
{
if newValue != iProgressThicknessFraction
{
iProgressThicknessFraction = max(minProgressThickness / iTrackThickness, newValue)
iProgressThicknessFraction = min(iProgressThicknessFraction, 1)
self.progressThickness = iProgressThicknessFraction * iTrackThickness
setNeedsDisplay()
}
}
}
private var iProgressThicknessFraction: CGFloat = 0.5
// Whether the progress track grows clockwise or counterclockwise as the progress value increases.
@IBInspectable var clockwise: Bool {
get { return iClockwise }
set
{
if newValue != iClockwise
{
iClockwise = newValue
setNeedsDisplay()
}
}
}
private var iClockwise = true
// Whether the progress track shows the progress made (normal mode) or the progress remaining (reversed mode).
// The default value is false, ie, show the progress made.
@IBInspectable var reversed: Bool {
get { return iReversed }
set
{
if newValue != iReversed
{
iReversed = newValue
updateLabel()
setNeedsDisplay()
}
}
}
private var iReversed = false
// Whether to display the percent label. Setting this property is equivalent to accessing the
// percent label directly and hiding or unhiding it so it's just a convenience.
@IBInspectable var showPercent: Bool {
get { return iShowPercent }
set
{
// if showing then we want to have a label; do something innocuous to force the label to be created.
if newValue { self.percentLabel?.alpha = 1.0 }
if newValue != iShowPercent
{
iShowPercent = newValue
iPercentLabel?.hidden = !iShowPercent
if iShowPercent { updateLabel() }
setNeedsDisplay()
}
}
}
private var iShowPercent = true
// The color of the percent text when it's showing. Setting this property is equivalent to accessing the
// percent label directly and setting its text color property so it's just a convenience.
@IBInspectable var percentTint: UIColor {
get { return iPercentTint }
set
{
if newValue != iPercentTint
{
iPercentTint = newValue
iPercentLabel?.textColor = iPercentTint
setNeedsDisplay()
}
}
}
private var iPercentTint = UIColor.blackColor()
// The font size of the percent text when it's showing. Setting this property is equivalent to
// accessing the percent label directly and setting its text font size so it's just a convenience.
@IBInspectable var percentSize: CGFloat {
get { return iPercentSize }
set
{
if newValue != iPercentSize
{
iPercentSize = newValue
updateLabelFontSize()
setNeedsDisplay()
}
}
}
private var iPercentSize: CGFloat = 48
// Whether to display the percent text using the bold or regular system font. Setting this property is
// equivalent to accessing the percent label directly and setting its font property so it's just a convenience.
@IBInspectable var percentBold: Bool {
get { return iPercentBold }
set
{
if newValue != iPercentBold
{
iPercentBold = newValue
updateLabelFontSize()
setNeedsDisplay()
}
}
}
private var iPercentBold = true
// The value representing the progress made. It should be in the range [0, 1]. Values outside
// that range will be clipped to that range.
@IBInspectable var value: CGFloat {
get { return iValue }
set
{
let val: CGFloat
#if TARGET_INTERFACE_BUILDER
val = 0.01 * newValue // interpret the integers in the inspector stepper as percentages
#else
val = newValue
#endif
if val != iValue
{
iValue = max(0, val)
iValue = min(iValue, 1)
updateLabel()
setNeedsDisplay()
}
}
}
private var iValue: CGFloat = 0.75
// An optional UILabel to appear at the center of the circular progress view. This property can
// be set with any UILabel instance or one can be automatically provided, then accessed and
// customized as desired. Note that, either way, certain layout constraints are created to
// keep the label centered. Those constraints should not be messed with.
@IBOutlet var percentLabel: UILabel? {
get
{
if iPercentLabel == nil { self.percentLabel = UILabel() }
return iPercentLabel
}
set(newLabel)
{
if newLabel != iPercentLabel
{
iPercentLabel?.removeFromSuperview()
iPercentLabel = newLabel
if let label = iPercentLabel
{
addSubview(label)
updateLabelFontSize()
label.textColor = iPercentTint
label.textAlignment = .Center
label.adjustsFontSizeToFitWidth = true
label.baselineAdjustment = .AlignCenters
label.minimumScaleFactor = 0.5
label.translatesAutoresizingMaskIntoConstraints = false
label.removeConstraints(label.constraints)
var constraint: NSLayoutConstraint
constraint = NSLayoutConstraint(item: label, attribute: .CenterX,
relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0)
addConstraint(constraint)
constraint = NSLayoutConstraint(item: label, attribute: .CenterY,
relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0)
addConstraint(constraint)
let w = CGRectGetWidth(bounds)
let h = CGRectGetHeight(bounds)
var s = (min(w, h) - iTrackThickness) / 2
s *= 0.9 // Use up to 90% of the space between opposite sides of the inner circle.
constraint = NSLayoutConstraint(item: label, attribute: .Width,
relatedBy: .LessThanOrEqual, toItem: self, attribute: .Width, multiplier: 0.0, constant: s)
addConstraint(constraint)
constraint = NSLayoutConstraint(item: label, attribute: .Height,
relatedBy: .LessThanOrEqual, toItem: self, attribute: .Height, multiplier: 0.0, constant: s)
addConstraint(constraint)
updateLabel()
setNeedsDisplay()
}
}
}
}
private var iPercentLabel: UILabel?
override func drawRect(rect: CGRect)
{
let w = CGRectGetWidth(bounds)
let h = CGRectGetHeight(bounds)
let r = (min(w, h) - iTrackThickness) / 2
let cp = CGPoint(x: w/2, y: h/2) // *not* 'let cp = center' because center will be in the frame's coord system!
// Draw the full track.
fillTrack(center: cp, radius: r, sangle: 0, eangle: CGFloat(2*M_PI),
color: iTrackTint, thickness: iTrackThickness, clockwise: true)
// Draw the progress track.
var val = (iReversed ? (1 - iValue) : iValue)
val = (iClockwise ? +iValue : -iValue)
let clockwise = (iReversed ? !iClockwise : iClockwise)
fillTrack(center: cp, radius: r, sangle: CGFloat(-M_PI/2), eangle: CGFloat(2*M_PI*Double(val) - M_PI/2),
color: iProgressTint, thickness: iProgressThickness, clockwise: clockwise)
}
private func fillTrack(center center: CGPoint, radius: CGFloat, sangle: CGFloat, eangle: CGFloat,
color: UIColor, thickness: CGFloat, clockwise: Bool)
{
color.set()
let p = UIBezierPath()
p.lineWidth = thickness
p.lineCapStyle = CGLineCap.Round
p.addArcWithCenter(center, radius: radius, startAngle: sangle, endAngle: eangle, clockwise: clockwise)
p.stroke()
}
private func updateProgressThickness(value: CGFloat)
{
iProgressThickness = max(minProgressThickness, value)
iProgressThickness = min(iProgressThickness, iTrackThickness)
self.progressThicknessFraction = iProgressThickness / iTrackThickness
}
private func updateLabelFontSize()
{
if iPercentBold
{
iPercentLabel?.font = UIFont.boldSystemFontOfSize(iPercentSize)
}
else
{
iPercentLabel?.font = UIFont.systemFontOfSize(iPercentSize)
}
}
private func updateLabel()
{
if let label = iPercentLabel where !label.hidden
{
let val = (iReversed ? (1 - iValue) : iValue)
label.text = "\(Int(val * 100.0) % 101) %"
label.sizeToFit()
setNeedsLayout()
}
}
#if TARGET_INTERFACE_BUILDER
override func prepareForInterfaceBuilder()
{
super.prepareForInterfaceBuilder()
percentLabel?.hidden = !showPercent
}
#endif
}
| apache-2.0 | 531f0883e213d93abea1ed47cb33d54b | 32.570787 | 119 | 0.609479 | 5.448213 | false | false | false | false |
dcutting/song | Sources/Song/Interpreter/Interpreter.swift | 1 | 3077 | import Syft
public struct InterpreterError: Error {
let remainder: String
}
public struct InterpreterResult {
let output: InterpreterOutput
let state: InterpreterState
}
public enum InterpreterOutput {
case expression(Expression)
case output(String)
case error(Error)
case none
}
public enum InterpreterState {
case ok
case waiting
}
public class Interpreter {
public var context: Context
private let interactive: Bool
private var multilines = [String]()
private let parser = makeParser()
private let transformer = makeTransformer()
public init(context: Context, interactive: Bool) {
self.context = context
self.interactive = interactive
}
public func finish() -> String? {
if interactive || multilines.isEmpty {
return nil
}
return multilines.joined()
}
private var state: InterpreterState {
return multilines.isEmpty ? .ok : .waiting
}
private func makeResult(_ output: InterpreterOutput) -> InterpreterResult {
return InterpreterResult(output: output, state: state)
}
public func interpret(line: String) throws -> InterpreterResult {
if line.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
line.trimmingCharacters(in: .whitespaces).hasPrefix("#") {
return makeResult(.none)
}
if line.trimmingCharacters(in: .whitespacesAndNewlines) == "?" {
return makeResult(.output(describeContext(context)))
}
if line.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix("?del ") {
var tokens = line.components(separatedBy: .whitespaces)
guard tokens.count > 1 else {
return makeResult(.output("Try \"?del SYMBOL [...]\""))
}
tokens.removeFirst()
for token in tokens {
context.removeValue(forKey: String(token))
}
return makeResult(.none)
}
multilines.append(line)
let joinedLine = multilines.joined(separator: "\n")
let result = parser.parse(joinedLine)
let (_, remainder) = result
if remainder.text.isEmpty {
multilines.removeAll()
let ast = try transformer.transform(result)
let expression = try ast.evaluate(context: context)
if case .closure(let name, _, _) = expression {
if let name = name {
context = extendContext(context: context, name: name, value: expression)
}
}
if case .assign(let variable, let value) = expression {
if case .name(let name) = variable {
context = extendContext(context: context, name: name, value: value)
}
}
return makeResult(.expression(expression))
} else if !parsedLastCharacter {
return makeResult(.error(InterpreterError(remainder: remainder.text)))
}
return makeResult(.none)
}
}
| mit | d7578283397c65272591e966c4938256 | 30.080808 | 92 | 0.60156 | 5.052545 | false | false | false | false |
BjornRuud/HTTPSession | Pods/Swifter/Sources/Socket+Server.swift | 4 | 3665 | //
// Socket+Server.swift
// Swifter
//
// Created by Damian Kolakowski on 13/07/16.
//
import Foundation
extension Socket {
public class func tcpSocketForListen(_ port: in_port_t, _ forceIPv4: Bool = false, _ maxPendingConnection: Int32 = SOMAXCONN) throws -> Socket {
#if os(Linux)
let socketFileDescriptor = socket(forceIPv4 ? AF_INET : AF_INET6, Int32(SOCK_STREAM.rawValue), 0)
#else
let socketFileDescriptor = socket(forceIPv4 ? AF_INET : AF_INET6, SOCK_STREAM, 0)
#endif
if socketFileDescriptor == -1 {
throw SocketError.socketCreationFailed(Errno.description())
}
var value: Int32 = 1
if setsockopt(socketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(MemoryLayout<Int32>.size)) == -1 {
let details = Errno.description()
Socket.close(socketFileDescriptor)
throw SocketError.socketSettingReUseAddrFailed(details)
}
Socket.setNoSigPipe(socketFileDescriptor)
var bindResult: Int32 = -1
if forceIPv4 {
#if os(Linux)
var addr = sockaddr_in(
sin_family: sa_family_t(AF_INET),
sin_port: port.bigEndian,
sin_addr: in_addr(s_addr: in_addr_t(0)),
sin_zero:(0, 0, 0, 0, 0, 0, 0, 0))
#else
var addr = sockaddr_in(
sin_len: UInt8(MemoryLayout<sockaddr_in>.stride),
sin_family: UInt8(AF_INET),
sin_port: port.bigEndian,
sin_addr: in_addr(s_addr: in_addr_t(0)),
sin_zero:(0, 0, 0, 0, 0, 0, 0, 0))
#endif
bindResult = withUnsafePointer(to: &addr) {
bind(socketFileDescriptor, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size))
}
} else {
#if os(Linux)
var addr = sockaddr_in6(
sin6_family: sa_family_t(AF_INET6),
sin6_port: port.bigEndian,
sin6_flowinfo: 0,
sin6_addr: in6addr_any,
sin6_scope_id: 0)
#else
var addr = sockaddr_in6(
sin6_len: UInt8(MemoryLayout<sockaddr_in6>.stride),
sin6_family: UInt8(AF_INET6),
sin6_port: port.bigEndian,
sin6_flowinfo: 0,
sin6_addr: in6addr_any,
sin6_scope_id: 0)
#endif
bindResult = withUnsafePointer(to: &addr) {
bind(socketFileDescriptor, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in6>.size))
}
}
if bindResult == -1 {
let details = Errno.description()
Socket.close(socketFileDescriptor)
throw SocketError.bindFailed(details)
}
if listen(socketFileDescriptor, maxPendingConnection) == -1 {
let details = Errno.description()
Socket.close(socketFileDescriptor)
throw SocketError.listenFailed(details)
}
return Socket(socketFileDescriptor: socketFileDescriptor)
}
public func acceptClientSocket() throws -> Socket {
var addr = sockaddr()
var len: socklen_t = 0
let clientSocket = accept(self.socketFileDescriptor, &addr, &len)
if clientSocket == -1 {
throw SocketError.acceptFailed(Errno.description())
}
Socket.setNoSigPipe(clientSocket)
return Socket(socketFileDescriptor: clientSocket)
}
}
| mit | 7a58d07458b96d1652ecf5639d3b5716 | 36.397959 | 148 | 0.556344 | 4.327037 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/25968-std-function-func-mapsignaturetype.swift | 11 | 2581 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
}
protocol P{func g:{
}
{
import n}
struct c<T: NSManagedObject {
let end = nil
let end = nil
protocol A{enum S<H
for c {
}
protocol c<T where g<T: Array) {
struct c{
class A"\(}
class a
typealias e:
var e:S{
class A : {class A{
}
func f A{
protocol A{let:A?typealias e:a
class A{
<T. : {
<d where f<T where g<T A : Array) {
class A? {
struct c<T where g: {
let s=[]if true{
struct D {
class
struct S{r
let a init(}
class a
}
struct Q{
let
func a{
}
}
}
class A?typealias b<H.b:a<T f<T where k.b:A
let a {
struct Q{
}
protocol P{protocol a {
}
protocol A{
enum S<T where g:a
import n}
protocol a {
typealias e:a{
{func a<T:
protocol P{
class A{
class func a
struct S{
var A?typealias b{protocol A
class a{
let a {
struct S<T: a {
func f:{let:b{
}
protocol a {{
}
class A"\(t
var _=Void{
}
class func f A< T where T: Array) {
let s=Void{
for c {let:A? {
protocol A? = A{
class A? {
class func f A{
var A{
let:a{typealias e
let b : NSManagedObject {
class
{
class A : <b<H. : {
let a {
enum S<T where f<T where k. : b(t
}
let:A{
}
for c {
class A{
let b : <T:
protocol A{
struct S
var e:ExtensibleCollectionType
protocol a {let:a{let:a
protocol a {r
class S<d where H.b
struct S<T where g:
}
<T where g: {
protocol P{
protocol A< T where T: NSManagedObject {enum S{
func f A
< T where k.b:a{
var _=Void{
var e: d where T:{
struct c<T where f<H : <H:A:a
<T where f: {
class func b<T. : a {
func a=[]if true{class a=Void{struct c<H : {
func a{
let end = nil
{
struct S{let
class A{
{
let d:a
class C<d = A
<T where H. : NSManagedObject {
class a
struct S
class C<b(T:
protocol A{
struct S
protocol A{
{class C<H:e
func a<b
func a
{enum :a=[]if true{protocol A? {
struct D {
let a init(t
var b : a {
}
}
func a=[]if true{
let b {
let s=[
var e
func a
protocol a {
func a
enum S<d = {
protocol A{
}
{
let d:S<T where f<d = {
let
{
typealias b
var e
for c {
struct Q{r
}class a{
let
class A{
func a{let
}
protocol P{class C<T: d where f<T: <d where f: d = {
}
func f A
class
{
let
}
class a
class A :
}
var a{
class a{
var _=Void{
class :S<H
}
var e
var b {
import n}
protocol A{
func a{r
class a<T where g:A{let:A{
}
let a {
protocol P{
let s=[]if true{
}
let a {class A"\(}
protocol a {
struct
| apache-2.0 | 96043454f9da68740cc9e914daa1bcc3 | 12.656085 | 78 | 0.651685 | 2.446445 | false | false | false | false |
AckeeCZ/ACKategories | ACKategories-iOS/UIDeviceExtensions.swift | 1 | 829 | //
// UIDeviceExtensions.swift
// ACKategories
//
// Created by Jakub Olejník on 13/04/2018.
// Copyright © 2018 Josef Dolezal. All rights reserved.
//
import UIKit
extension UIDevice {
/// Return **true** if device is iPad
public var isPad: Bool {
return userInterfaceIdiom == .pad
}
/// Returns device model name e.g. "iPhone11,6" for XS Max
public var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
| mit | 4c616e229f01b3c6dc346deb46a81ee3 | 28.535714 | 91 | 0.64208 | 4.375661 | false | false | false | false |
arslanbilal/cryptology-project | Cryptology Project/Cryptology Project/Classes/Views/KeyList Cell/KeyListTableViewCell.swift | 1 | 2562 | //
// KeyListTableViewCell.swift
// Cryptology Project
//
// Created by Bilal Arslan on 08/04/16.
// Copyright © 2016 Bilal Arslan. All rights reserved.
//
import UIKit
class KeyListTableViewCell: UITableViewCell {
private let usersLabel = UILabel.newAutoLayoutView()
private let keyLabel = UILabel.newAutoLayoutView()
private let keyImageView = UIImageView.newAutoLayoutView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.whiteColor()
self.selectionStyle = .None
keyImageView.layer.cornerRadius = 22.5
keyImageView.contentMode = .ScaleAspectFit
self.addSubview(keyImageView)
keyImageView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(15.0, 10.0, 15.0, 0), excludingEdge: .Right)
keyImageView.autoSetDimension(.Width, toSize: 45)
let keyInfoView = UIView.newAutoLayoutView()
self.addSubview(keyInfoView)
keyInfoView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(10.0, 0, 10.0, 10.0), excludingEdge: .Left)
keyInfoView.autoPinEdge(.Left, toEdge: .Right, ofView: keyImageView, withOffset: 10.0)
usersLabel.numberOfLines = 1
usersLabel.textColor = UIColor.blackColor()
usersLabel.textAlignment = .Left
usersLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 15)
keyInfoView.addSubview(usersLabel)
usersLabel.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Bottom)
usersLabel.autoSetDimension(.Height, toSize: 15)
keyLabel.numberOfLines = 2
keyLabel.textColor = UIColor.blackColor()
keyLabel.textAlignment = .Left
keyLabel.font = UIFont(name: "HelveticaNeue", size: 14)
keyInfoView.addSubview(keyLabel)
keyLabel.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top)
keyLabel.autoSetDimension(.Height, toSize: 40)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setContent(messageList: MessageList) {
self.usersLabel.text = ActiveUser.sharedInstance.user.username + " <=> " + messageList.otherUser.username
self.keyLabel.text = messageList.messageKey!.key
self.keyImageView.image = UIImage(named: "key")
}
}
| mit | 9f269eec3df9d36c7572beea85350f6c | 36.661765 | 121 | 0.67786 | 5.280412 | false | false | false | false |
omaralbeik/SwifterSwift | Examples/Examples.playground/Pages/01-SwiftStdlibExtensions.xcplaygroundpage/Contents.swift | 1 | 2475 | //: [Table of Contents](00-ToC)
//: [Previous](@previous)
import SwifterSwift
//: ## SwiftStdlib extensions
//: ### Array extensions
// Remove duplicates from an array
var array = ["h", "e", "l", "l", "o"]
array.removeDuplicates()
//: ### Dictionary extensions
var dict: [String: Any] = ["id": 1, "Product-Name": "SwifterSwift"]
// Check if key exists in dictionary.
dict.has(key: "id")
// Lowercase all keys in dictionary.
dict.lowercaseAllKeys()
// Create JSON Data and string from a dictionary
let json = dict.jsonString(prettify: true)
//: ### Int extensions
// Return square root of a number
√9
// Return square power of a number
5 ** 2
// Return a number plus or minus another number
5 ± 2
// Return roman numeral for a number
134.romanNumeral
//: ### Random Access Collection extensions
// Return all indices of specified item
["h", "e", "l", "l", "o"].indices(of: "l")
//: ### String extensions
// Return count of substring in string
"hello world".count(of: "", caseSensitive: false)
// Return string with no spaces or new lines in beginning and end
"\n Hello ".trimmed
// Return most common character in string
"swifterSwift is making swift more swifty".mostCommonCharacter()
// Returns CamelCase of string
"Some variable nAme".camelCased
// Check if string is in valid email format
"[email protected]".isEmail
// Check if string contains at least one letter and one number
"123abc".isAlphaNumeric
// Reverse string
var str1 = "123abc"
str1.reverse()
// Return latinized string
var str2 = "Hèllö Wórld!"
str2.latinize()
// Create random string of length
String.random(ofLength: 10)
// Check if string contains one or more instance of substring
"Hello World!".contains("o", caseSensitive: false)
// Check if string contains one or more emojis
"string👨with😍emojis✊🏿".containEmoji
// Subscript strings easily
"Hello"[safe: 2]
// Slice strings
let str = "Hello world"
str.slicing(from: 6, length: 5)
// Convert string to numbers
"12.12".double
// Encode and decode URLs
"it's easy to encode strings".urlEncoded
"it's%20easy%20to%20encode%20strings".urlDecoded
// Encode and decode base64
"Hello World!".base64Encoded
"SGVsbG8gV29ybGQh".base64Decoded
// Truncate strings with a trailing
"This is a very long sentence".truncated(toLength: 14, trailing: "...")
// Repeat a string n times
"s" * 5
// NSString has never been easier
let boldString = "this is string".bold.colored(with: .red)
//: [Next](@next)
| mit | 0d8951441f8cb008b69d957be30e74d5 | 21.126126 | 71 | 0.712541 | 3.544012 | false | false | false | false |
YevhenHerasymenko/SwiftGroup1 | ControllerCommunication/ControllerCommunication/ViewController.swift | 1 | 2273 | //
// ViewController.swift
// ControllerCommunication
//
// Created by Yevhen Herasymenko on 05/07/2016.
// Copyright © 2016 Yevhen Herasymenko. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var collectionOfImages: [UIImageView]!
@IBOutlet var collectionOfLabels: [UILabel]!
let imageNames = ["image1", "image2", "image3", "image4"]
let texts = ["nature 1", "nature 2", "nature 3", "nature 4"]
var index: Int?
override func viewDidLoad() {
super.viewDidLoad()
for (index, imageView) in collectionOfImages.enumerate() {
imageView.userInteractionEnabled = true
imageView.image = UIImage(named: imageNames[index])
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openNatureDetails(_:)))
imageView.addGestureRecognizer(tapRecognizer)
}
for (index, label) in collectionOfLabels.enumerate() {
label.text = texts[index]
}
let swipeRecognizer = UISwipeGestureRecognizer()
swipeRecognizer.direction = [.Down, .Left, .Right]
}
func openNatureDetails(sender: UITapGestureRecognizer) {
guard let imageView = sender.view as? UIImageView,
let index = collectionOfImages.indexOf(imageView) else { return }
self.index = index
//performSegueWithIdentifier("showSegue", sender: nil)
//performSegueWithIdentifier("showSegue", sender: index)
let detailsController = storyboard?.instantiateViewControllerWithIdentifier("detailsController") as! DetailsViewController
detailsController.text = texts[index]
detailsController.imageName = imageNames[index]
navigationController?.pushViewController(detailsController, animated: true)
//Int(arc4random_uniform(6))
}
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// guard let detailsController = segue.destinationViewController as? DetailsViewController, let index = sender as? Int else { return }
// detailsController.imageName = imageNames[index]
// detailsController.text = texts[index]
// }
}
| apache-2.0 | f560a17df05527ac6a2c980fe0ee777b | 35.645161 | 141 | 0.664613 | 5.163636 | false | false | false | false |
richterd/BirthdayGroupReminder | BirthdayGroupReminder/AppDelegate.swift | 1 | 3221 | //
// AppDelegate.swift
// BirthdayGroupReminder
//
// Created by Daniel Richter on 11.07.14.
// Copyright (c) 2014 Daniel Richter. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storage = BGRStorage()
var notificationCenter = BGRNotificationCenter()
var selectedGroups : [ABRecordID] = []
//The address book, nil if no access granted
var addressBook : RHAddressBook = RHAddressBook()
var update : Int = 0
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if #available(iOS 9.0, *) {
let types: UIUserNotificationType = [.sound, .alert, .badge]
let settings = UIUserNotificationSettings(types: types, categories: nil)
application.registerUserNotificationSettings(settings)
} else {
// Fallback on earlier versions
}
selectedGroups = storage.loadFromFile()
return true
}
func application(_ application: UIApplication, didReceive localNotification: UILocalNotification){
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
storage.saveToFile(selectedGroups)
notificationCenter.createNotifications(selectedGroups)
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
storage.saveToFile(selectedGroups)
notificationCenter.createNotifications(selectedGroups)
}
}
| gpl-2.0 | 9087fafcd6f80cba61a91ef890709b7e | 43.736111 | 285 | 0.716858 | 5.762075 | false | false | false | false |
BennyKJohnson/OpenCloudKit | Sources/CKPredicateReader.swift | 1 | 9600 | //
// CKPredicateReader.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 19/07/2016.
//
//
import Foundation
struct CKPredicateReader {
typealias Index = Int
typealias IndexDistance = Int
let source: ASCIISource
static let numberFormatter = NumberFormatter()
init(string: String) {
source = ASCIISource(buffer: string)
}
struct ASCIISource {
let buffer: String
let position: Int = 0
let step = 1
init(buffer: String) {
self.buffer = buffer
}
func hasNext(_ input: Index) -> Bool {
return input + step <= buffer.count
}
func takeCharacter(_ input: Index) -> (Character, Index)? {
guard hasNext(input) else {
return nil
}
let ascii = buffer[buffer.index(buffer.startIndex, offsetBy: input)]
return (ascii, input + step)
}
func takeString(begin: Index, end: Index) -> String {
return buffer[buffer.index(buffer.startIndex, offsetBy: begin)..<buffer.index(buffer.startIndex, offsetBy: end)]
}
}
struct IndexPosition {
var chunkIndex: Index
var currentIndex: Index
mutating func advance() {
currentIndex += 1
}
mutating func set(_ index: Index) {
currentIndex = index
chunkIndex = currentIndex
}
}
func parseLocation(index: Index) throws -> CKLocationCoordinate2D? {
var chunkIndex = index
var currentIndex = chunkIndex
var latitude: Double?
while source.hasNext(currentIndex) {
guard let (ascii, index) = source.takeCharacter(currentIndex) else {
currentIndex += source.step
continue
}
switch ascii {
case "<":
currentIndex += 1
chunkIndex = currentIndex
case ">":
if let longitudeValue = takeValue(begin: chunkIndex, end: currentIndex) as? NSNumber, let latitude = latitude {
return CKLocationCoordinate2D(latitude: latitude, longitude: longitudeValue.doubleValue)
} else {
return nil
}
case "+":
currentIndex += 1
chunkIndex = currentIndex
case ",":
if let latitudeValue = takeValue(begin: chunkIndex, end: currentIndex) as? NSNumber {
latitude = latitudeValue.doubleValue
currentIndex += 1
chunkIndex = currentIndex
} else {
return nil
}
default:
currentIndex = index
}
}
return nil
}
func consumeWhitespace(_ input: Index) -> Index? {
var index = input
while let (char, nextIndex) = source.takeCharacter(index) , char == " " {
index = nextIndex
}
return index
}
func parseLocationExpression(_ input: Index) throws -> (fieldName: String, coordinate: CKLocationCoordinate2D)? {
let locationFunction = try parseFunction(input)
guard locationFunction.0 == "distanceToLocation:fromLocation:" else {
return nil
}
guard let fieldName = locationFunction.parameters.first as? String, let locationData = locationFunction.parameters.last as? String else {
return nil
}
let locationReader = CKPredicateReader(string: locationData)
if let coordinate = try locationReader.parseLocation(index: 0) {
return (fieldName, coordinate)
}
return nil
}
func parseFunction(_ input: Index) throws -> (String, parameters: [Any]) {
var chunkIndex = input
var currentIndex = chunkIndex
var functionName: String = ""
var parameters: [Any] = []
var inBracket: Int = 0
while source.hasNext(currentIndex) {
guard let (ascii, index) = source.takeCharacter(currentIndex) else {
currentIndex += source.step
continue
}
switch ascii {
case "(":
if (inBracket == 0) {
functionName = source.takeString(begin: chunkIndex, end: currentIndex)
currentIndex += 1
chunkIndex = currentIndex
} else {
currentIndex += 1
}
inBracket += 1
case ")":
inBracket -= 1
// Add parameter
if (inBracket == 0) {
if let value = takeValue(begin: chunkIndex, end: currentIndex) {
parameters.append(value)
}
currentIndex += 1
chunkIndex = currentIndex
} else {
currentIndex += 1
}
case "<":
inBracket += 1
currentIndex += 1
case ">":
inBracket -= 1
currentIndex += 1
case "\"":
currentIndex += 1
let string = try parseString(currentIndex)!
parameters.append(string.0)
currentIndex = string.1
chunkIndex = currentIndex
case ",":
if(inBracket == 1) {
// Add Parameter
if let value = takeValue(begin: chunkIndex, end: currentIndex) {
parameters.append(value)
}
currentIndex += 1
currentIndex = consumeWhitespace(currentIndex) ?? currentIndex
chunkIndex = currentIndex
} else {
currentIndex += 1
}
default:
currentIndex = index
}
}
return (functionName, parameters)
}
func takeValue(begin: Index, end: Index) -> Any? {
let token = source.takeString(begin: begin, end: end)
if !token.isEmpty {
let number = CKPredicateReader.numberFormatter.number(from: token)
if let number = number {
return number
} else {
return token
}
} else {
return nil
}
}
func parse(_ input: Index) throws -> [String] {
var chunkIndex = input
var currentIndex = chunkIndex
var tokens: [String] = []
var inBracket: Int = 0
while source.hasNext(currentIndex) {
guard let (ascii, index) = source.takeCharacter(currentIndex) else {
currentIndex += source.step
continue
}
switch ascii {
case "\"":
currentIndex = index
if (inBracket == 0) {
if let parse = try parseString(currentIndex) {
let string = parse.0
currentIndex = parse.1
chunkIndex = parse.1
tokens.append(string)
}
}
case "(":
inBracket += 1
currentIndex = index
case ")":
inBracket -= 1
currentIndex = index
case " ":
if (inBracket == 0) {
let token = source.takeString(begin: chunkIndex, end: currentIndex)
if !token.isEmpty {
tokens.append(token)
}
currentIndex = index
chunkIndex = currentIndex
} else {
currentIndex = index
}
default:
currentIndex = index
}
}
let token = source.takeString(begin: chunkIndex, end: currentIndex)
if !token.isEmpty {
tokens.append(token)
}
return tokens
}
func parseString(_ input: Index) throws -> (String, Index)? {
let chunkIndex = input
var currentIndex = chunkIndex
var output: String = ""
while source.hasNext(currentIndex) {
guard let (ascii, index) = source.takeCharacter(currentIndex) else {
currentIndex += source.step
continue
}
switch ascii {
case "\"":
output += source.takeString(begin: chunkIndex, end: currentIndex)
return(output,index)
default:
currentIndex = index
}
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Invalid escape sequence at position \(currentIndex)"
])
}
}
| mit | aea233ef1119721e8baafb02eab95534 | 30.067961 | 145 | 0.463646 | 6.205559 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructure/BinarySearch.swift | 1 | 1648 | //
// BinarySearch.swift
// DataStructure
//
// Created by Jigs Sheth on 11/20/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import Foundation
func findIndices(of value:Int, in array:[Int]) -> CountableRange<Int>? {
guard let startIndex = array.firstIndex(of: value) else {
return nil
}
guard let endIndex = array.reversed().firstIndex(of: value) else {
return nil
}
return startIndex..<endIndex.base
}
/// Find Indices based on the binary search
/// - Parameters:
/// - value: value in the array
/// - array: array
/// - Returns: range for the indices of that value
/// //// TODO: Jigs Not implementing since I am not sure it will be useful for preparation.
func findIndicesWithBinarySearch(of value:Int, in array:[Int]) -> CountableRange<Int>? {
guard let startIndex = array.index(of: value) else {
return nil
}
guard let endIndex = array.reversed().index(of: value) else {
return nil
}
return startIndex..<endIndex.base
}
extension RandomAccessCollection where Element:Comparable {
func binarySearch(for value:Element, in range: Range<Index>? = nil) -> Index? {
let range = range ?? startIndex..<endIndex
guard range.lowerBound < range.upperBound else {
return nil
}
let size = distance(from: range.lowerBound, to: range.upperBound)
let middle = index(range.lowerBound, offsetBy: size/2)
if self[middle] == value {
return middle
}else if self[middle] > value {
return binarySearch(for: value, in: range.lowerBound..<middle)
}else {
return binarySearch(for: value, in: index(after: middle)..<range.upperBound)
}
}
}
| mit | 5e24119ff3c2ecb275513435388096b8 | 22.528571 | 93 | 0.68306 | 3.511727 | false | false | false | false |
EGF2/ios-client | EGF2/EGF2/Graph/EGF2Graph+CoreData.swift | 1 | 6010 | //
// EGF2Graph+CoreData.swift
// EGF2
//
// Created by LuzanovRoman on 09.11.16.
// Copyright © 2016 EigenGraph. All rights reserved.
//
import Foundation
import CoreData
extension EGF2Graph {
// MARK: Fileprivate
fileprivate func objects(withName name: String, predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]? = nil, fetchLimit: Int = 0, completion: @escaping ([NSManagedObject]?) -> Void) {
let request = NSFetchRequest<NSManagedObject>(entityName: name)
request.sortDescriptors = sortDescriptors
request.fetchLimit = fetchLimit
request.predicate = predicate
let asynchronousRequest = NSAsynchronousFetchRequest(fetchRequest: request) { (asynchronousResult) -> Void in
DispatchQueue.main.async {
completion(asynchronousResult.finalResult)
}
}
do {
try self.container.viewContext.execute(asynchronousRequest)
} catch {
print("EGF2Graph fetch error. \(error.localizedDescription)")
completion(nil)
}
}
// MARK: Object
func findGraphObject(withId id: String, completion: @escaping (GraphObject?) -> Void) {
objects(withName: "GraphObject", predicate: NSPredicate(format: "id = %@", id), fetchLimit: 1) { (objects) in
completion(objects?.first as? GraphObject)
}
}
func newGraphObject(withId id: String) -> GraphObject? {
if let object = NSEntityDescription.insertNewObject(forEntityName: "GraphObject", into: container.viewContext) as? GraphObject {
object.id = id
return object
}
return nil
}
func delete(graphObject: GraphObject) {
self.container.viewContext.delete(graphObject)
}
func graphObject(withId id: String, completion: @escaping (GraphObject?) -> Void) {
findGraphObject(withId: id) { (graphObject) in
guard let object = graphObject else {
completion(self.newGraphObject(withId: id))
return
}
completion(object)
}
}
// MARK: Edge
func findGraphEdge(withSource source: String, edge: String, completion: @escaping (GraphEdge?) -> Void) {
let predicate = NSPredicate(format: "source = %@ AND edge = %@", source, edge)
objects(withName: "GraphEdge", predicate: predicate, fetchLimit: 1) { (objects) in
completion(objects?.first as? GraphEdge)
}
}
func newGraphEdge(withSource source: String, edge: String) -> GraphEdge? {
if let graphEdge = NSEntityDescription.insertNewObject(forEntityName: "GraphEdge", into: container.viewContext) as? GraphEdge {
graphEdge.source = source
graphEdge.edge = edge
return graphEdge
}
return nil
}
func graphEdge(withSource source: String, edge: String, completion: @escaping (GraphEdge?) -> Void) {
findGraphEdge(withSource: source, edge: edge) { (graphEdge) in
guard let edgeObject = graphEdge else {
completion(self.newGraphEdge(withSource: source, edge: edge))
return
}
completion(edgeObject)
}
}
// MARK: Edge objects
func newGraphEdgeObject(withSource source: String, edge: String, target: String, index: Int) -> GraphEdgeObject? {
if let object = NSEntityDescription.insertNewObject(forEntityName: "GraphEdgeObject", into: container.viewContext) as? GraphEdgeObject {
object.source = source
object.target = target
object.index = NSNumber(value: index)
object.edge = edge
return object
}
return nil
}
func findGraphEdgeObjects(withSource source: String, edge: String, completion: @escaping ([GraphEdgeObject]?) -> Void) {
let predicate = NSPredicate(format: "source = %@ AND edge = %@", source, edge)
let sortDescriptor = NSSortDescriptor(key: "index", ascending: true)
objects(withName: "GraphEdgeObject", predicate: predicate, sortDescriptors: [sortDescriptor]) { (objects) in
completion(objects as? [GraphEdgeObject])
}
}
func findGraphEdgeObject(withSource source: String, edge: String, target: String, completion: @escaping (GraphEdgeObject?) -> Void) {
let predicate = NSPredicate(format: "source = %@ AND edge = %@ AND target = %@", source, edge, target)
objects(withName: "GraphEdgeObject", predicate: predicate) { (objects) in
completion(objects?.first as? GraphEdgeObject)
}
}
func deleteGraphEdgeObjects(withSource source: String, edge: String, completion: @escaping () -> Void) {
let predicate = NSPredicate(format: "source = %@ AND edge = %@", source, edge)
objects(withName: "GraphEdgeObject", predicate: predicate) { (objects) in
if let theObjects = objects {
for object in theObjects {
self.container.viewContext.delete(object)
}
}
completion()
}
}
// MARK: Common methods
func deleteAllCoreDataObjects() {
let edgeObjectsRequest = NSBatchDeleteRequest(fetchRequest: GraphEdgeObject.fetchRequest())
let objectsRequest = NSBatchDeleteRequest(fetchRequest: GraphObject.fetchRequest())
let edgesRequest = NSBatchDeleteRequest(fetchRequest: GraphEdge.fetchRequest())
do {
try container.viewContext.execute(edgeObjectsRequest)
try container.viewContext.execute(objectsRequest)
try container.viewContext.execute(edgesRequest)
} catch {
print("EGF2Graph error. Can't clear database. \(error.localizedDescription)")
}
}
func coreDataSave() {
do {
try container.viewContext.save()
} catch {
print("EGF2Graph error. Can't save changes. \(error.localizedDescription)")
}
}
}
| mit | a3e46a253246869124fede64288c8ca6 | 38.794702 | 195 | 0.631053 | 4.966116 | false | false | false | false |
binarylevel/Tinylog-iOS | Tinylog/Views/TLIMenuColorsView.swift | 1 | 3215 | //
// TLIMenuColorsView.swift
// Tinylog
//
// Created by Spiros Gerokostas on 18/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
class TLIMenuColorsView: UIView {
var colors = ["#6a6de2", "#008efe", "#fe4565", "#ffa600", "#50de72", "#ffd401"]
var buttonsContainer:UIView?
var tagOffset:Int
var radius:CGFloat = 40.0
var selectedIndex:Int?
var currentColor:String?
func findIndexByColor(color:String)->Int {
switch color {
case "#6a6de2":
return 0
case "#008efe":
return 1
case "#fe4565":
return 2
case "#ffa600":
return 3
case "#50de72":
return 4
case "#ffd401":
return 5
default:
return -1
}
}
override init(frame: CGRect) {
tagOffset = 1000
super.init(frame: frame)
selectedIndex = 0
currentColor = colors[0]
addButtons()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addButtons() {
buttonsContainer = UIView(frame: CGRectMake(0.0, 0.0, self.frame.size.width, 51.0))
self.addSubview(buttonsContainer!)
var index:Int = 0;
for item in colors {
let button:TLICircleButton = TLICircleButton(frame: CGRectMake(0.0, 0.0, radius, radius))
button.tag = tagOffset + index
button.backgroundColor = UIColor(rgba: item)
button.addTarget(self, action: #selector(TLIMenuColorsView.buttonPressed(_:)), forControlEvents: UIControlEvents.TouchDown)
buttonsContainer?.addSubview(button)
index += 1
}
setSelectedIndex(0)
}
func selectButton(button:UIButton) {
button.layer.borderWidth = 2.0
}
func deselectButton(button:UIButton) {
button.layer.borderWidth = 0.0
}
func setSelectedIndex(newSelectedIndex:Int) {
if selectedIndex != NSNotFound {
let fromButton:UIButton = buttonsContainer!.viewWithTag(tagOffset + selectedIndex!) as! UIButton
deselectButton(fromButton)
}
selectedIndex = newSelectedIndex
var toButton:UIButton
if selectedIndex != NSNotFound {
toButton = buttonsContainer!.viewWithTag(tagOffset + selectedIndex!) as! UIButton
selectButton(toButton)
}
}
func buttonPressed(button:UIButton) {
currentColor = colors[button.tag - tagOffset]
setSelectedIndex(button.tag - tagOffset)
}
override func layoutSubviews() {
super.layoutSubviews()
layoutButtons()
}
func layoutButtons() {
var index:Int = 0
let buttons:NSArray = buttonsContainer!.subviews as NSArray
var rect:CGRect = CGRectMake(0.0, 0.0, radius, radius)
for item in buttons {
let button:UIButton = item as! UIButton
button.frame = rect
rect.origin.x += rect.size.width + 10.0
index += 1
}
}
}
| mit | ec33831b9855de5c4405322b6689ae25 | 26.947826 | 135 | 0.576229 | 4.664731 | false | false | false | false |
koba-uy/chivia-app-ios | src/Chivia/Services/ChiviaService.swift | 1 | 721 | //
// ChiviaService.swift
// Chivia
//
// Created by Agustín Rodríguez on 10/21/17.
// Copyright © 2017 Agustín Rodríguez. All rights reserved.
//
import Foundation
class ChiviaService {
let geocoding: GeocodingService
let report: ReportService
let route: RouteService
let stand: StandService
private static var instance: ChiviaService?
private init() {
geocoding = GeocodingService()
report = ReportService()
route = RouteService()
stand = StandService()
}
static func singleton() -> ChiviaService {
if instance == nil {
instance = ChiviaService()
}
return instance!
}
}
| lgpl-3.0 | eb39510e4d352f9f728f3171efaa84bc | 19.457143 | 60 | 0.604749 | 4.531646 | false | false | false | false |
czerenkow/LublinWeather | App/Stations List/StationsListBuilder.swift | 1 | 977 | //
// StationsListBuilder.swift
// LublinWeather
//
// Created by Damian Rzeszot on 24/04/2018.
// Copyright © 2018 Damian Rzeszot. All rights reserved.
//
import UIKit
protocol StationsListDependency: Dependency {
var localizer: Localizer { get }
func tracker() -> Tracker<StationsEvent>
}
final class StationsListBuilder: Builder<StationsListDependency> {
func build() -> StationsListRouter {
let vc = StationsListViewController()
let interactor = StationsListInteractor()
let router = StationsListRouter()
router.controller = vc
router.interactor = interactor
interactor.router = router
interactor.presentable = vc
interactor.tracker = dependency.tracker()
interactor.selected = UserDefaultsSelectedStationWorker()
interactor.provider = StationsListProvider()
vc.output = interactor
vc.localizer = dependency.localizer
return router
}
}
| mit | 9c3ec71e19939d2527fa8aa8e169e2f4 | 22.804878 | 66 | 0.684426 | 5.083333 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | src/HumanKontact Extension/ResultsController.swift | 1 | 16992 | //
// ResultsController.swift
// keyboardTest
//
// Created by Sean McGee on 7/23/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import WatchKit
import Foundation
import RealmSwift
var peopleLimit = 15
var peopleInit = 0
class ResultsController: WKInterfaceController, ContactRowDelegate {
@IBOutlet weak var headerGroup: WKInterfaceGroup!
@IBOutlet weak var contactsTable: WKInterfaceTable!
@IBOutlet weak var loadingImage: WKInterfaceImage!
@IBOutlet weak var searchResultsLabel: WKInterfaceLabel!
@IBOutlet weak var homeButton: WKInterfaceButton!
var indexSet = NSIndexSet()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self._loadMoreButton.setHidden(true)
self.loadingImage!.setImageNamed("circleani1_")
self.timelineQueue(context)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
contactInit = 0
contactLimit = 15
}
func timelineQueue(context: AnyObject?) {
Timeline.with("Loading") { (queue) -> Void in
self.searchResultsLabel.setText(activeSearch)
activeSearch = ""
selectionValues.removeAll(keepCapacity: false)
queue.add(delay: 0, duration: 1.0, execution: {
// some code that will take assumed 2.0 seconds
self.loadingContacts()
}, completion: {
// some code that will excutes after 'delay' + 'duration'
self.loadingImage!.stopAnimating()
self.loadingImage!.setHidden(true)
self.homeButton!.setEnabled(true)
self.reloadTableData(false)
})
// any code between queue adding functions will executes immediately
}.start
}
func loadingContacts() {
loadingImage.startAnimatingWithImagesInRange(NSRange(location: 1,length: 9), duration: 1, repeatCount: 50)
}
func indexReset() {
lookupWatchController?.restart()
self.roundToFour(keyValues.count)
overFlow = self.remFromFour(keyValues.count)
}
func reloadTableData(more: Bool) {
if People.people.count < 15 {
peopleLimit = People.people.count
}
if more == true {
contactsTable.insertRowsAtIndexes(indexSet, withRowType: "TripleColumnRowController")
} else {
let contactRows = Int(self.roundUp(peopleLimit, divisor: 3) / 3)
contactsTable.setNumberOfRows(contactRows, withRowType: "TripleColumnRowController")
}
for _ in 0..<1 {
autoreleasepool({ () -> () in
for index in peopleInit..<peopleLimit {
let hkPerson = People.people[Int(index)] as HKPerson
contactIndex = roundDown(index, divisor: 3) / 3
if let hkAvatar = hkPerson.avatar as NSData! {
if let person = self.contactsTable.rowControllerAtIndex(contactIndex) as? TripleColumnRowController {
person.delegate = self
person.rowControllerGroup.setHidden(false)
var imageIndex: Int!
if hkAvatar.length > 0 {
switch index {
case let index where index == 0:
imageIndex = index
setImageWithData(person.leftContactImage, data: hkAvatar)
populateTableAvatars(imageIndex)
person.leftTag = index
person.leftHasImage = true
case let index where index == 1:
imageIndex = index
setImageWithData(person.centerContactImage, data: hkAvatar)
populateTableAvatars(imageIndex)
person.centerTag = index
person.centerHasImage = true
case let index where index == 2:
imageIndex = index
setImageWithData(person.rightContactImage, data: hkAvatar)
populateTableAvatars(imageIndex)
person.rightTag = index
person.rightHasImage = true
case let index where index % 3 == 0:
imageIndex = index
setImageWithData(person.leftContactImage, data: hkAvatar)
populateTableAvatars(imageIndex)
person.leftTag = index
person.leftHasImage = true
case let index where index % 3 == 1:
imageIndex = index
setImageWithData(person.centerContactImage, data: hkAvatar)
populateTableAvatars(imageIndex)
person.centerTag = index
person.centerHasImage = true
case let index where index % 3 == 2:
imageIndex = index
setImageWithData(person.rightContactImage, data: hkAvatar)
populateTableAvatars(imageIndex)
person.rightTag = index
person.rightHasImage = true
default:
print("done")
}
}
if hkAvatar.length == 0 {
switch index {
case let index where index == 0:
imageIndex = index
populateTableAvatars(imageIndex)
person.leftTag = index
person.leftHasImage = false
case let index where index == 1:
imageIndex = index
populateTableAvatars(imageIndex)
person.centerTag = index
person.centerHasImage = false
case let index where index == 2:
imageIndex = index
populateTableAvatars(imageIndex)
person.rightTag = index
person.rightHasImage = false
case let index where index % 3 == 0:
imageIndex = index
populateTableAvatars(imageIndex)
person.leftTag = index
person.leftHasImage = false
case let index where index % 3 == 1:
imageIndex = index
populateTableAvatars(imageIndex)
person.centerTag = index
person.centerHasImage = false
case let index where index % 3 == 2:
imageIndex = index
populateTableAvatars(imageIndex)
person.rightTag = index
person.rightHasImage = false
default:
print("done")
}
}
}
}
}
updateLoadMoreButton()
})
}
}
@IBAction func callKeyboard() {
first = true
indexReset()
peopleLimit = 15
contactInit = 0
contactLimit = 15
WKInterfaceController.reloadRootControllersWithNames(["Landing"], contexts: nil)
}
@IBOutlet weak var _loadMoreButton: WKInterfaceButton!
lazy var loadMoreButton: WKUpdatableButton = WKUpdatableButton(self._loadMoreButton, defaultHidden: true)
@IBAction func loadMore() {
if (People.people.count - peopleLimit) > 15 {
peopleInit = peopleLimit
peopleLimit += 15
} else {
let contactsLeft = People.people.count - peopleLimit
peopleInit = peopleLimit
peopleLimit += contactsLeft
}
let moreInit = roundDown(peopleInit, divisor: 3) / 3
let moreLimit = roundUp(peopleLimit, divisor: 3) / 3
indexSet = NSIndexSet(indexesInRange: NSRange(moreInit..<moreLimit))
self.reloadTableData(true)
}
func updateLoadMoreButton() {
let moreToLoad = People.people.count > peopleLimit
print(moreToLoad)
loadMoreButton.updateHidden(!moreToLoad)
}
func leftButtonWasPressed(button: WKInterfaceButton, tag: Int, image: Bool) {
if let index = tag as Int! {
let selectedIndex = index
if image != false {
self.selectContactWithImage(selectedIndex)
} else {
self.selectContactWithoutImage(selectedIndex)
}
} else {
return
}
}
func centerButtonWasPressed(button: WKInterfaceButton, tag: Int, image: Bool) {
if let index = tag as Int! {
let selectedIndex = index
if image != false {
self.selectContactWithImage(selectedIndex)
} else {
self.selectContactWithoutImage(selectedIndex)
}
} else {
return
}
}
func rightButtonWasPressed(button: WKInterfaceButton, tag: Int, image: Bool) {
if let index = tag as Int! {
let selectedIndex = index
if image != false {
self.selectContactWithImage(selectedIndex)
} else {
self.selectContactWithoutImage(selectedIndex)
}
} else {
return
}
}
func selectContactWithImage(index: Int) {
let appDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
if let contactSelected = People.people[Int(index)] as HKPerson! {
let profileData = ["firstName": contactSelected.firstName, "lastName": contactSelected.lastName,
"avatar": contactSelected.avatar, "color": UIColor(hex: contactSelected.nameColor), "phone": contactSelected.phoneNumbers, "person": contactSelected.fullName]
let profileEmailData = ["firstName": contactSelected.firstName, "lastName": contactSelected.lastName, "avatar": contactSelected.avatar, "color": UIColor(hex: contactSelected.nameColor), "email": contactSelected.emails, "person": contactSelected.uuid]
switch contactSelected.phoneNumbers.count {
case 0:
if contactSelected.emails.count != 0 {
profilePages = ["ProfileEmail"]
profileContexts = [profileEmailData]
} else {
profilePages = ["Profile"]
profileContexts = [profileData]
}
case 1:
if contactSelected.emails.count != 0 {
profilePages = ["Profile","ProfileEmail"]
profileContexts = [profileData, profileEmailData]
} else {
profilePages = ["Profile"]
profileContexts = [profileData]
}
case 2:
if contactSelected.emails.count != 0 {
profilePages = ["Profile","Profile2","ProfileEmail"]
profileContexts = [profileData, profileData, profileEmailData]
} else {
profilePages = ["Profile","Profile2"]
profileContexts = [profileData, profileData]
}
case 3:
if contactSelected.emails.count != 0 {
profilePages = ["Profile","Profile2","Profile3","ProfileEmail"]
profileContexts = [profileData, profileData, profileData, profileEmailData]
} else {
profilePages = ["Profile","Profile2","Profile3"]
profileContexts = [profileData, profileData, profileData]
}
default:
print("too many numbers")
}
self.addRecent("\(contactSelected.uuid)")
appDelegate.sendRecentToPhone("\(contactSelected.uuid)")
self.presentControllerWithNames(profilePages, contexts: profileContexts)
}
}
func selectContactWithoutImage(index: Int) {
let appDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
if let contactSelected = People.people[Int(index)] as HKPerson! {
let profileData = ["firstName": contactSelected.firstName, "lastName": contactSelected.lastName,
"initials": avatarInitials(contactSelected.firstName, lastName: contactSelected.lastName), "color": UIColor(hex: contactSelected.nameColor), "phone": contactSelected.phoneNumbers, "person": contactSelected.fullName]
let profileEmailData = ["firstName": contactSelected.firstName, "lastName": contactSelected.lastName,
"initials": avatarInitials(contactSelected.firstName, lastName: contactSelected.lastName), "color": UIColor(hex: contactSelected.nameColor), "email": contactSelected.emails, "person": contactSelected.uuid]
switch contactSelected.phoneNumbers.count {
case 0:
if contactSelected.emails.count != 0 {
profilePages = ["ProfileEmail"]
profileContexts = [profileEmailData]
} else {
profilePages = ["Profile"]
profileContexts = [profileData]
}
case 1:
if contactSelected.emails.count != 0 {
profilePages = ["Profile","ProfileEmail"]
profileContexts = [profileData, profileEmailData]
} else {
profilePages = ["Profile"]
profileContexts = [profileData]
}
case 2:
if contactSelected.emails.count != 0 {
profilePages = ["Profile","Profile2","ProfileEmail"]
profileContexts = [profileData, profileData, profileEmailData]
} else {
profilePages = ["Profile","Profile2"]
profileContexts = [profileData, profileData]
}
case 3:
if contactSelected.emails.count != 0 {
profilePages = ["Profile","Profile2","Profile3","ProfileEmail"]
profileContexts = [profileData, profileData, profileData, profileEmailData]
} else {
profilePages = ["Profile","Profile2","Profile3"]
profileContexts = [profileData, profileData, profileData]
}
default:
print("too many numbers")
}
self.addRecent("\(contactSelected.uuid)")
appDelegate.sendRecentToPhone("\(contactSelected.uuid)")
self.presentControllerWithNames(profilePages, contexts: profileContexts)
}
}
func addRecent(key: String) {
self.addRecentSubTask(key)
}
func addRecentSubTask(key: String) {
let person = peopleRealm.objectForPrimaryKey(HKPerson.self, key: key)
var recentIndexCount = Int()
if People.contacts.count > 0 {
recentIndexCount = People.contacts.first!.recentIndex
} else {
recentIndexCount = 0
}
do {
peopleRealm.beginWrite()
person!.recent = true
person!.recentIndex = recentIndexCount + 1
try peopleRealm.commitWrite()
} catch let error as NSError {
print("Error moving file: \(error.description)")
}
}
}
| mit | 26ed8fa2c0cc6d55832324232a4bc4a8 | 44.55496 | 262 | 0.51177 | 6.431491 | false | false | false | false |
benlangmuir/swift | test/SILGen/deinit_recursive_linear_generic.swift | 9 | 4178 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
class Node<A, B> {
var next: Node<A, B>?
}
// CHECK: sil hidden [ossa] @$s31deinit_recursive_linear_generic4NodeCfd : $@convention(method) <A, B> (@guaranteed Node<A, B>) -> @owned Builtin.NativeObject {
// CHECK: [[SELF:%.*]] "self"
// CHECK: bb0([[SELF]] : @guaranteed $Node<A, B>):
// CHECK: [[NIL:%.*]] = enum $Optional<Node<A, B>>, #Optional.none!enumelt
// CHECK: [[SELF_NEXT:%.*]] = ref_element_addr [[SELF]] : $Node<A, B>, #Node.next
// CHECK: [[ITER:%.*]] = alloc_stack $Optional<Node<A, B>>
// CHECK: [[SELF_NEXT_ACCESS:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[SELF_NEXT]] : $*Optional<Node<A, B>>
// CHECK: [[SELF_NEXT_COPY:%.*]] = load [take] [[SELF_NEXT_ACCESS]] : $*Optional<Node<A, B>>
// CHECK: store [[NIL]] to [init] [[SELF_NEXT_ACCESS]] : $*Optional<Node<A, B>>
// CHECK: end_access [[SELF_NEXT_ACCESS]] : $*Optional<Node<A, B>>
// CHECK: store [[SELF_NEXT_COPY]] to [init] [[ITER]] : $*Optional<Node<A, B>>
// CHECK: br [[LOOPBB:bb.*]] //
// CHECK: [[LOOPBB]]:
// CHECK: [[ITER_COPY:%.*]] = load [copy] [[ITER]] : $*Optional<Node<A, B>>
// CHECK: switch_enum [[ITER_COPY]] : $Optional<Node<A, B>>, case #Optional.some!enumelt: [[IS_SOME_BB:bb.*]], case #Optional.none!enumelt: [[IS_NONE_BB:bb[0-9]+]]
// CHECK: [[IS_SOME_BB]]([[NODE:%.*]] : @owned $Node<A, B>):
// CHECK: destroy_value [[NODE]] : $Node<A, B>
// CHECK: [[IS_UNIQUE:%.*]] = is_unique [[ITER]] : $*Optional<Node<A, B>>
// CHECK: cond_br [[IS_UNIQUE]], [[IS_UNIQUE_BB:bb.*]], [[NOT_UNIQUE_BB:bb[0-9]*]]
// CHECK: [[IS_UNIQUE_BB]]:
// CHECK: [[ITER_BORROW:%.*]] = load_borrow [[ITER]] : $*Optional<Node<A, B>>
// CHECK: [[ITER_UNWRAPPED:%.*]] = unchecked_enum_data [[ITER_BORROW]] : $Optional<Node<A, B>>, #Optional.some!enumelt
// CHECK: [[NEXT_ADDR:%.*]] = ref_element_addr [[ITER_UNWRAPPED]] : $Node<A, B>, #Node.next
// CHECK: [[NEXT_ADDR_ACCESS:%.*]] = begin_access [read] [static] [no_nested_conflict] [[NEXT_ADDR]] : $*Optional<Node<A, B>>
// CHECK: [[NEXT_COPY:%.*]] = load [copy] [[NEXT_ADDR_ACCESS]] : $*Optional<Node<A, B>>
// CHECK: end_access [[NEXT_ADDR_ACCESS]] : $*Optional<Node<A, B>>
// CHECK: end_borrow [[ITER_BORROW]] : $Optional<Node<A, B>>
// CHECK: store [[NEXT_COPY]] to [assign] [[ITER]] : $*Optional<Node<A, B>>
// CHECK: br [[LOOPBB]]
// CHECK: [[NOT_UNIQUE_BB]]:
// CHECK: br bb6
// CHECK: [[IS_NONE_BB]]:
// CHECK: br [[CLEAN_BB:bb[0-9]+]]
// CHECK: [[CLEAN_BB]]:
// CHECK: destroy_addr [[ITER]] : $*Optional<Node<A, B>>
// CHECK: dealloc_stack [[ITER]] : $*Optional<Node<A, B>>
// CHECK: [[SELF_NATIVE:%.*]] = unchecked_ref_cast [[SELF]] : $Node<A, B> to $Builtin.NativeObject
// CHECK: [[SELF_NATIVE_OWNED:%.*]] = unchecked_ownership_conversion [[SELF_NATIVE]] : $Builtin.NativeObject, @guaranteed to @owned
// CHECK: return [[SELF_NATIVE_OWNED]] : $Builtin.NativeObject
// CHECK: } // end sil function '$s31deinit_recursive_linear_generic4NodeCfd'
// Types of `self` and `next` don't match, so this should not be optimized
class Node2<A, B> {
var next: Node2<Int, (A, B)>?
}
// CHECK: sil hidden [ossa] @$s31deinit_recursive_linear_generic5Node2Cfd : $@convention(method) <A, B> (@guaranteed Node2<A, B>) -> @owned Builtin.NativeObject {
// CHECK: [[SELF:%.*]] "self"
// CHECK: bb0([[SELF]] : @guaranteed $Node2<A, B>):
// CHECK: debug_value [[SELF]] : $Node2<A, B>, let, name "self", argno 1, implicit
// CHECK: [[NEXT_ADDR:%.*]] = ref_element_addr [[SELF]] : $Node2<A, B>, #Node2.next
// CHECK: [[NEXT_ACCESS:%.*]] = begin_access [deinit] [static] [[NEXT_ADDR]] : $*Optional<Node2<Int, (A, B)>>
// CHECK: destroy_addr [[NEXT_ACCESS]] : $*Optional<Node2<Int, (A, B)>>
// CHECK: end_access [[NEXT_ACCESS]] : $*Optional<Node2<Int, (A, B)>>
// CHECK: [[SELF_NATIVE:%.*]] = unchecked_ref_cast [[SELF]] : $Node2<A, B> to $Builtin.NativeObject
// CHECK: [[SELF_OWNED:%.*]] = unchecked_ownership_conversion [[SELF_NATIVE]] : $Builtin.NativeObject, @guaranteed to @owned
// CHECK: return [[SELF_OWNED]] : $Builtin.NativeObject
// CHECK: } // end sil function '$s31deinit_recursive_linear_generic5Node2Cfd' | apache-2.0 | a9f1f5d144f1ee0be9a211384583a553 | 57.859155 | 165 | 0.599569 | 2.895357 | false | false | false | false |
HeartOfCarefreeHeavens/TestKitchen_pww | TestKitchen/TestKitchen/classes/cookbook/recommend/model/CBRecommendADCellTableViewCell.swift | 1 | 4738 | //
// CBRecommendADCellTableViewCell.swift
// TestKitchen
//
// Created by qianfeng on 16/8/17.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CBRecommendADCellTableViewCell: UITableViewCell {
//图片的点击事件
var clickClosure:CBCellClosure?
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pageCtrl: UIPageControl!
var bannerArray:Array<CBRecommendBannerModel>?{
didSet{
showData()
}
}
func showData(){
for sub in scrollView.subviews{
sub.removeFromSuperview()
}
//0.添加容器视图
let containerView = UIView.createView()
scrollView.addSubview(containerView)
containerView.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView)
make.height.equalTo(self!.scrollView)
}
let cnt = bannerArray?.count
if cnt > 0 {
var lastView:UIView? = nil
for i in 0..<cnt!{
//获取模型对象
let model = bannerArray![i]
//循环创建对象
let tmpImageView = UIImageView.createImageView(nil)
//progressBlock获取下载的进度
//completionHandler:下载结束后的操作
let url = NSURL(string: model.banner_picture!)
let image = UIImage(named: "sdefaultImage")
tmpImageView.kf_setImageWithURL(url, placeholderImage: image, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
containerView.addSubview(tmpImageView)
//添加一个手势
tmpImageView.userInteractionEnabled = true
tmpImageView.tag = 500 + i
let g = UITapGestureRecognizer(target: self, action: #selector(tapImage(_:)))
tmpImageView.addGestureRecognizer(g)
tmpImageView.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
if i == 0{
make.left.equalTo(containerView)
}else{
make.left.equalTo((lastView?.snp_right)!)
}
})
lastView = tmpImageView
}
containerView.snp_makeConstraints(closure: { (make) in
make.right.equalTo(lastView!.snp_right)
})
pageCtrl.numberOfPages = cnt!
scrollView.delegate = self
scrollView.pagingEnabled = true
}
}
func tapImage(g:UIGestureRecognizer){
let index = (g.view?.tag)!-500
//获取模型对象
let imageModel = bannerArray![index]
//要将点击事件传到视图控制器
clickClosure!(nil,imageModel.banner_link!)
}
//创建cell的方法
/*
参数:
(1)tableView:cell所在表格
(2)index:
*/
class func createAdCellFor(tableView:UITableView,atIndexPath index:NSIndexPath,withModel model:CBRecommendModel,cellClosure:CBCellClosure?)->CBRecommendADCellTableViewCell{
let cellId = "recommendADCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendADCellTableViewCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CBRecommendADCellTableViewCell", owner: nil, options: nil).last as? CBRecommendADCellTableViewCell
}
cell?.bannerArray = model.data?.banner
cell?.clickClosure = cellClosure
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension CBRecommendADCellTableViewCell:UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width)
pageCtrl.currentPage = index
}
}
| mit | a92b31e31e3a7288aaf418b926abb9cb | 27.465839 | 176 | 0.536548 | 5.875641 | false | false | false | false |
richarddan/Flying-Swift | test-swift/UIDynamicsCatalog/ItemPropertiesViewController.swift | 3 | 4001 | //
// ItemPropertiesViewController.swift
// test-swift
//
// Created by Su Wei on 14-6-6.
// Copyright (c) 2014年 OBJCC.COM. All rights reserved.
//
import UIKit
class ItemPropertiesViewController: UIViewController {
@IBOutlet var square1 : UIImageView!
@IBOutlet var square2 : UIImageView!
var square1PropertiesBehavior:UIDynamicItemBehavior!
var square2PropertiesBehavior:UIDynamicItemBehavior!
var animator : UIDynamicAnimator!
//| ----------------------------------------------------------------------------
override func viewDidAppear(animated:Bool)
{
super.viewDidAppear(animated)
let animator:UIDynamicAnimator = UIDynamicAnimator(referenceView: self.view)
// We want to show collisions between views and boundaries with different
// elasticities, we thus associate the two views to gravity and collision
// behaviors. We will only change the restitution parameter for one of these
// views.
let gravityBeahvior:UIGravityBehavior = UIGravityBehavior(items:[self.square1, self.square2])
let collisionBehavior:UICollisionBehavior = UICollisionBehavior(items:[self.square1, self.square2])
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
// A dynamic item behavior gives access to low-level properties of an item
// in Dynamics, here we change restitution on collisions only for square2,
// and keep square1 with its default value.
self.square2PropertiesBehavior = UIDynamicItemBehavior(items:[self.square2])
self.square2PropertiesBehavior!.elasticity = 0.5
// A dynamic item behavior is created for square1 so it's velocity can be
// manipulated in the -resetAction: method.
self.square1PropertiesBehavior = UIDynamicItemBehavior(items:[self.square1])
animator.addBehavior(self.square1PropertiesBehavior)
animator.addBehavior(self.square2PropertiesBehavior)
animator.addBehavior(gravityBeahvior)
animator.addBehavior(collisionBehavior)
self.animator = animator
}
@IBAction func replayAction(sender : AnyObject) {
// Moving an item does not reset its velocity. Here we do that manually
// using the dynamic item behaviors, adding the inverse velocity for each
// square.
self.square1PropertiesBehavior!.addLinearVelocity(CGPointMake(0, -1 * self.square1PropertiesBehavior!.linearVelocityForItem(self.square1).y), forItem:self.square1)
self.square1.center = CGPointMake(90, 171)
self.animator!.updateItemUsingCurrentState(self.square1)
self.square2PropertiesBehavior!.addLinearVelocity(CGPointMake(0, -1 * self.square2PropertiesBehavior!.linearVelocityForItem(self.square2).y), forItem:self.square2)
self.square2.center = CGPointMake(230, 171)
self.animator!.updateItemUsingCurrentState(self.square2)
}
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 82b1f7df65fad9efcf96ca6315639afe | 37.825243 | 171 | 0.68042 | 5.113811 | false | false | false | false |
firebase/firebase-ios-sdk | FirebaseSharedSwift/Tests/Codable/FirebaseDataEncoderTests.swift | 1 | 14606 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import FirebaseSharedSwift
import XCTest
class FirebaseFirebaseDataEncoderTests: XCTestCase {
func testInt() {
struct Model: Codable, Equatable {
let x: Int
}
let model = Model(x: 42)
let dict = ["x": 42]
assertThat(model).roundTrips(to: dict)
}
func testNullDecodesAsNil() throws {
let decoder = FirebaseDataDecoder()
let opt = try decoder.decode(Int?.self, from: NSNull())
XCTAssertNil(opt)
}
func testEmpty() {
struct Model: Codable, Equatable {}
assertThat(Model()).roundTrips(to: [String: Any]())
}
func testString() throws {
struct Model: Codable, Equatable {
let s: String
}
assertThat(Model(s: "abc")).roundTrips(to: ["s": "abc"])
}
func testCaseConversion() throws {
struct Model: Codable, Equatable {
let snakeCase: Int
}
let model = Model(snakeCase: 42)
let dict = ["snake_case": 42]
let encoder = FirebaseDataEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let decoder = FirebaseDataDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
assertThat(model).roundTrips(to: dict, using: encoder, decoder: decoder)
}
func testOptional() {
struct Model: Codable, Equatable {
let x: Int
let opt: Int?
}
assertThat(Model(x: 42, opt: nil)).roundTrips(to: ["x": 42])
assertThat(Model(x: 42, opt: 7)).roundTrips(to: ["x": 42, "opt": 7])
assertThat(["x": 42, "opt": 5]).decodes(to: Model(x: 42, opt: 5))
assertThat(["x": 42, "opt": true]).failsDecoding(to: Model.self)
assertThat(["x": 42, "opt": "abc"]).failsDecoding(to: Model.self)
assertThat(["x": 45.55, "opt": 5]).failsDecoding(to: Model.self)
assertThat(["opt": 5]).failsDecoding(to: Model.self)
// TODO: - handle encoding keys with nil values
// See https://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder
// and https://bugs.swift.org/browse/SR-9232
// XCTAssertTrue(encodedDict.keys.contains("x"))
}
func testEnum() {
enum MyEnum: Codable, Equatable {
case num(number: Int)
case text(String)
private enum CodingKeys: String, CodingKey {
case num
case text
}
private enum DecodingError: Error {
case decoding(String)
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? values.decode(Int.self, forKey: .num) {
self = .num(number: value)
return
}
if let value = try? values.decode(String.self, forKey: .text) {
self = .text(value)
return
}
throw DecodingError.decoding("Decoding error: \(dump(values))")
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .num(number):
try container.encode(number, forKey: .num)
case let .text(value):
try container.encode(value, forKey: .text)
}
}
}
struct Model: Codable, Equatable {
let x: Int
let e: MyEnum
}
assertThat(Model(x: 42, e: MyEnum.num(number: 4)))
.roundTrips(to: ["x": 42, "e": ["num": 4]])
assertThat(Model(x: 43, e: MyEnum.text("abc")))
.roundTrips(to: ["x": 43, "e": ["text": "abc"]])
}
func testBadValue() {
struct Model: Codable, Equatable {
let x: Int
}
assertThat(["x": "abc"]).failsDecoding(to: Model.self) // Wrong type
}
func testValueTooBig() {
struct Model: Codable, Equatable {
let x: CChar
}
assertThat(Model(x: 42)).roundTrips(to: ["x": 42])
assertThat(["x": 12345]).failsDecoding(to: Model.self) // Overflow
}
// Inspired by https://github.com/firebase/firebase-android-sdk/blob/master/firebase-firestore/src/test/java/com/google/firebase/firestore/util/MapperTest.java
func testBeans() {
struct Model: Codable, Equatable {
let s: String
let d: Double
let f: Float
let l: CLongLong
let i: Int
let b: Bool
let sh: CShort
let byte: CChar
let uchar: CUnsignedChar
let ai: [Int]
let si: [String]
let caseSensitive: String
let casESensitive: String
let casESensitivE: String
}
let model = Model(
s: "abc",
d: 123,
f: -4,
l: 1_234_567_890_123,
i: -4444,
b: false,
sh: 123,
byte: 45,
uchar: 44,
ai: [1, 2, 3, 4],
si: ["abc", "def"],
caseSensitive: "aaa",
casESensitive: "bbb",
casESensitivE: "ccc"
)
let dict = [
"s": "abc",
"d": 123,
"f": -4,
"l": Int64(1_234_567_890_123),
"i": -4444,
"b": false,
"sh": 123,
"byte": 45,
"uchar": 44,
"ai": [1, 2, 3, 4],
"si": ["abc", "def"],
"caseSensitive": "aaa",
"casESensitive": "bbb",
"casESensitivE": "ccc",
] as [String: Any]
assertThat(model).roundTrips(to: dict)
}
func testCodingKeysCanCustomizeEncodingAndDecoding() throws {
struct Model: Codable, Equatable {
var s: String
var ms: String = "filler"
var d: Double
var md: Double = 42.42
// Use CodingKeys to only encode part of the struct.
enum CodingKeys: String, CodingKey {
case s
case d
}
}
assertThat(Model(s: "abc", ms: "dummy", d: 123.3, md: 0))
.encodes(to: ["s": "abc", "d": 123.3])
.decodes(to: Model(s: "abc", ms: "filler", d: 123.3, md: 42.42))
}
func testNestedObjects() {
struct SecondLevelNestedModel: Codable, Equatable {
var age: Int8
var weight: Double
}
struct NestedModel: Codable, Equatable {
var group: String
var groupList: [SecondLevelNestedModel]
var groupMap: [String: SecondLevelNestedModel]
}
struct Model: Codable, Equatable {
var id: Int64
var group: NestedModel
}
let model = Model(
id: 123,
group: NestedModel(
group: "g1",
groupList: [
SecondLevelNestedModel(age: 20, weight: 80.1),
SecondLevelNestedModel(age: 25, weight: 85.1),
],
groupMap: [
"name1": SecondLevelNestedModel(age: 30, weight: 64.2),
"name2": SecondLevelNestedModel(age: 35, weight: 79.2),
]
)
)
let dict = [
"group": [
"group": "g1",
"groupList": [
[
"age": 20,
"weight": 80.1,
],
[
"age": 25,
"weight": 85.1,
],
],
"groupMap": [
"name1": [
"age": 30,
"weight": 64.2,
],
"name2": [
"age": 35,
"weight": 79.2,
],
],
],
"id": 123,
] as [String: Any]
assertThat(model).roundTrips(to: dict)
}
func testCollapsingNestedObjects() {
// The model is flat but the document has a nested Map.
struct Model: Codable, Equatable {
var id: Int64
var name: String
init(id: Int64, name: String) {
self.id = id
self.name = name
}
private enum CodingKeys: String, CodingKey {
case id
case nested
}
private enum NestedCodingKeys: String, CodingKey {
case name
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try id = container.decode(Int64.self, forKey: .id)
let nestedContainer = try container
.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .nested)
try name = nestedContainer.decode(String.self, forKey: .name)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
var nestedContainer = container
.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .nested)
try nestedContainer.encode(name, forKey: .name)
}
}
assertThat(Model(id: 12345, name: "ModelName"))
.roundTrips(to: [
"id": 12345,
"nested": ["name": "ModelName"],
])
}
class SuperModel: Codable, Equatable {
var superPower: Double? = 100.0
var superName: String? = "superName"
init(power: Double, name: String) {
superPower = power
superName = name
}
static func == (lhs: SuperModel, rhs: SuperModel) -> Bool {
return (lhs.superName == rhs.superName) && (lhs.superPower == rhs.superPower)
}
private enum CodingKeys: String, CodingKey {
case superPower
case superName
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
superPower = try container.decode(Double.self, forKey: .superPower)
superName = try container.decode(String.self, forKey: .superName)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(superPower, forKey: .superPower)
try container.encode(superName, forKey: .superName)
}
}
class SubModel: SuperModel {
var timestamp: Double? = 123_456_789.123
init(power: Double, name: String, seconds: Double) {
super.init(power: power, name: name)
timestamp = seconds
}
static func == (lhs: SubModel, rhs: SubModel) -> Bool {
return ((lhs as SuperModel) == (rhs as SuperModel)) && (lhs.timestamp == rhs.timestamp)
}
private enum CodingKeys: String, CodingKey {
case timestamp
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
timestamp = try container.decode(Double.self, forKey: .timestamp)
try super.init(from: container.superDecoder())
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(timestamp, forKey: .timestamp)
try super.encode(to: container.superEncoder())
}
}
func testClassHierarchy() {
assertThat(SubModel(power: 100, name: "name", seconds: 123_456_789.123))
.roundTrips(to: [
"super": ["superPower": 100, "superName": "name"],
"timestamp": 123_456_789.123,
])
}
}
private func assertThat(_ dictionary: [String: Any],
file: StaticString = #file,
line: UInt = #line) -> DictionarySubject {
return DictionarySubject(dictionary, file: file, line: line)
}
func assertThat<X: Equatable & Codable>(_ model: X, file: StaticString = #file,
line: UInt = #line) -> CodableSubject<X> {
return CodableSubject(model, file: file, line: line)
}
func assertThat<X: Equatable & Encodable>(_ model: X, file: StaticString = #file,
line: UInt = #line) -> EncodableSubject<X> {
return EncodableSubject(model, file: file, line: line)
}
class EncodableSubject<X: Equatable & Encodable> {
var subject: X
var file: StaticString
var line: UInt
init(_ subject: X, file: StaticString, line: UInt) {
self.subject = subject
self.file = file
self.line = line
}
@discardableResult
func encodes(to expected: [String: Any],
using encoder: FirebaseDataEncoder = .init()) -> DictionarySubject {
let encoded = assertEncodes(to: expected, using: encoder)
return DictionarySubject(encoded, file: file, line: line)
}
func failsToEncode() {
do {
let encoder = FirebaseDataEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
_ = try encoder.encode(subject)
} catch {
return
}
XCTFail("Failed to throw")
}
func failsEncodingAtTopLevel() {
do {
let encoder = FirebaseDataEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
_ = try encoder.encode(subject)
XCTFail("Failed to throw", file: file, line: line)
} catch EncodingError.invalidValue(_, _) {
return
} catch {
XCTFail("Unrecognized error: \(error)", file: file, line: line)
}
}
private func assertEncodes(to expected: [String: Any],
using encoder: FirebaseDataEncoder = .init()) -> [String: Any] {
do {
let enc = try encoder.encode(subject)
XCTAssertEqual(enc as? NSDictionary, expected as NSDictionary, file: file, line: line)
return (enc as! NSDictionary) as! [String: Any]
} catch {
XCTFail("Failed to encode \(X.self): error: \(error)")
return ["": -1]
}
}
}
class CodableSubject<X: Equatable & Codable>: EncodableSubject<X> {
func roundTrips(to expected: [String: Any],
using encoder: FirebaseDataEncoder = .init(),
decoder: FirebaseDataDecoder = .init()) {
let reverseSubject = encodes(to: expected, using: encoder)
reverseSubject.decodes(to: subject, using: decoder)
}
}
class DictionarySubject {
var subject: [String: Any]
var file: StaticString
var line: UInt
init(_ subject: [String: Any], file: StaticString, line: UInt) {
self.subject = subject
self.file = file
self.line = line
}
func decodes<X: Equatable & Codable>(to expected: X,
using decoder: FirebaseDataDecoder = .init()) -> Void {
do {
let decoded = try decoder.decode(X.self, from: subject)
XCTAssertEqual(decoded, expected)
} catch {
XCTFail("Failed to decode \(X.self): \(error)", file: file, line: line)
}
}
func failsDecoding<X: Equatable & Codable>(to _: X.Type,
using decoder: FirebaseDataDecoder = .init()) -> Void {
XCTAssertThrowsError(
try decoder.decode(X.self, from: subject),
file: file,
line: line
)
}
}
| apache-2.0 | 8c000dde9461d3cbd6af1cc53998f6a7 | 28.153693 | 161 | 0.597563 | 4.012637 | false | false | false | false |
tbointeractive/bytes | Example/bytesTests/Specs/UIView+ConstraintsSpec.swift | 1 | 4761 | //
// UIViewExtensionsSpec.swift
// bytes
//
// Created by Thorsten Stark on 27.10.16.
// Copyright © 2016 TBO INTERACTIVE GmbH & Co. KG. All rights reserved.
//
import bytes
import Quick
import Nimble
class UIViewExtensionsSpec: QuickSpec {
override func spec() {
describe("constrain") {
it("should add one default constraint to first view") {
let firstView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
let secondView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
firstView.addSubview(secondView)
firstView.constrain(.top, to: secondView, attribute: .top, relation: .equal)
expect(firstView.constraints.count).to(equal(1))
let constraint = firstView.constraints.first as NSLayoutConstraint?
expect(constraint?.constant).to(equal(0.0))
expect(constraint?.relation.rawValue).to(equal(0))
}
it("should add one constraint with constant 3.0 and bottom attribute") {
let firstView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
let secondView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
firstView.addSubview(secondView)
firstView.constrain(.bottom, to: secondView, attribute: .bottom, relation: .equal, constant: 3.0)
let constraint = firstView.constraints.first as NSLayoutConstraint?
expect(constraint?.constant).to(equal(3.0))
expect(constraint?.firstAttribute.rawValue).to(equal(4))
}
}
describe("constrainEqual") {
it("should add a Equal constraint to first view") {
let firstView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
let secondView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
firstView.addSubview(secondView)
firstView.constrainEqual(attribute: .top, to: secondView)
let constraint = firstView.constraints.first as NSLayoutConstraint?
expect(constraint?.relation.rawValue).to(equal(0))
}
}
describe("constrainEqual Constant") {
it("") {
let view = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
view.constrainEqual(attribute: .height, to: 100)
let constraint = view.constraints.first as NSLayoutConstraint?
expect(constraint?.constant).to(equal(100))
}
}
describe("constrainLessThanOrEqual") {
it("should add a LessThanOrEqual constraint to first view") {
let firstView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
let secondView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
firstView.addSubview(secondView)
firstView.constrainLessThanOrEqual(attribute: .top, to: secondView)
let constraint = firstView.constraints.first as NSLayoutConstraint?
expect(constraint?.relation.rawValue).to(equal(-1))
}
}
describe("constrainGreaterThanOrEqual") {
it("should add a GreaterThanOrEqual constraint to first view") {
let firstView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
let secondView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
firstView.addSubview(secondView)
firstView.constrainGreaterThanOrEqual(attribute: .top, to: secondView)
let constraint = firstView.constraints.first as NSLayoutConstraint?
expect(constraint?.relation.rawValue).to(equal(1))
}
}
describe("constrainEdgesToMargin") {
it("should add 4 constraints to first view") {
let firstView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
let secondView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
firstView.addSubview(secondView)
firstView.constrainEdges(toMarginOf: secondView)
expect(firstView.constraints.count).to(equal(4))
}
}
describe("constrainEdgesTo") {
it("should add 4 constraints to first view") {
let firstView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
let secondView = UIView(frame: CGRect(x:0, y:0, width: 10, height:10))
firstView.addSubview(secondView)
firstView.constrainEdges(to: secondView)
expect(firstView.constraints.count).to(equal(4))
}
}
}
}
| mit | 193872958c1d36cca2990db79bbd37e7 | 49.105263 | 113 | 0.586975 | 4.473684 | false | false | false | false |
Codeido/swift-basics | Playground Codebase/Closures.playground/section-1.swift | 1 | 794 | // Playground - noun: a place where people can play
import UIKit
//Functions are special case closures ({})
// Closure example.
// `->` separates the arguments and return type
// `in` separates the closure header from the closure body
var numbers = [1, 2, 3, 4, 5]
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
// When the type is known, like above, we can do this
numbers = [1, 2, 6]
numbers = numbers.map({ number in 3 * number })
println(numbers) // [3, 6, 18]
// When a closure is the last argument, you can place it after the )
// When a closure is the only argument, you can omit the () entirely
// You can also refer to closure arguments by position ($0, $1, ...) rather than name
numbers = [2, 5, 1]
numbers.map { 3 * $0 } // [6, 15, 3] | gpl-2.0 | b5b290d8080440fb209d6bd9054dca38 | 29.576923 | 85 | 0.65869 | 3.452174 | false | false | false | false |
mdznr/WWDC-2014-Scholarship-Application | Matt Zanchelli/LabelStyles.swift | 1 | 11139 | //
// LabelStyles.swift
// Matt Zanchelli
//
// Created by Matt Zanchelli on 6/5/14.
// Copyright (c) 2014 Matt Zanchelli. All rights reserved.
//
import UIKit
/// Defines the style of labels in particular sections of the app.
enum MTZStyle {
// About
case Name
case PersonalDescription
case InterestDescription
// Background
case EventDate
case EventTitle
case EventDetail
// Projects
case ProjectTitle
case ProjectDescription
case ProjectDescriptionCenter
case ProjectSectionHeader
case ProjectSectionDescription
case ProjectSectionQuote
case ProjectSectionAnnotation
case GoodnightSectionTitle
case GoodnightSectionSubtitle
}
protocol UILabel_MTZStyle {
/// Apply a prticular style to an instance of @c UILabel .
func applyMTZStyle(style: MTZStyle)
}
extension UILabel: UILabel_MTZStyle {
// Mark: Public API
func applyMTZStyle(style: MTZStyle) {
switch style {
case .Name: applyMTZStyleName()
case .PersonalDescription: applyMTZStylePersonalDescription()
case .InterestDescription: applyMTZStyleInterestDescription()
case .EventDate: applyMTZStyleEventDate()
case .EventTitle: applyMTZStyleEventTitle()
case .EventDetail: applyMTZStyleEventDetail()
case .ProjectTitle: applyMTZStyleProjectTitle()
case .ProjectDescription: applyMTZStyleProjectDescription()
case .ProjectDescriptionCenter: applyMTZStyleProjectDescriptionCentered()
case .ProjectSectionHeader: applyMTZStyleProjectSectionHeader()
case .ProjectSectionDescription: applyMTZStyleProjectSectionDescription()
case .ProjectSectionQuote: applyMTZStyleProjectSectionQuote()
case .ProjectSectionAnnotation: applyMTZStyleProjectSectionAnnotation()
case .GoodnightSectionTitle: applyMTZStyleGoodnightSectionTitle()
case .GoodnightSectionSubtitle: applyMTZStyleGoodnightSectionSubtitle()
}
}
// Mark: Private API
func applyMTZStyleName() {
// Set the proper font.
font = UIFont.fontForName()
// Set the proper text color.
textColor = UIColor.blackColor()
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 0
paragraphStyle.alignment = .Center
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStylePersonalDescription() {
// Set the proper font.
font = UIFont.fontForPersonalDescription()
// Set the proper text color.
textColor = UIColor(white: 0.5, alpha: 1)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5 // 26 - 21
paragraphStyle.alignment = .Center
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleInterestDescription() {
// Set the proper font.
font = UIFont.fontForInterestDescription()
// Set the proper text color.
textColor = UIColor(white: 0.5, alpha: 1)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2 // 16 - 14
paragraphStyle.alignment = .Center
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleEventDate() {
// Set the proper font.
font = UIFont.fontForEventDate()
// Set the proper text color.
textColor = UIColor(white: 0.65, alpha: 1)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 7 // 25 - 18
paragraphStyle.alignment = .Right
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleEventTitle() {
// Set the proper font.
font = UIFont.fontForEventTitle()
// Set the proper text color.
textColor = UIColor(white: 0.1, alpha: 1)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 7 // 25 - 18
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleEventDetail() {
// Set the proper font.
font = UIFont.fontForEventDetail()
// Set the proper text color.
textColor = UIColor(white: 0.33, alpha: 1)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 7 // 25 - 18
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleProjectTitle() {
// Set the proper font.
font = UIFont.fontForProjectTitle()
}
func applyMTZStyleProjectDescription() {
// Set the proper font.
font = UIFont.fontForProjectDescription()
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5 // 26 - 21
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleProjectDescriptionCentered() {
// Set the proper font.
font = UIFont.fontForProjectDescription()
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5 // 26 - 21
paragraphStyle.alignment = .Center
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleProjectSectionHeader() {
// Set the proper font.
font = UIFont.fontForSectionHeader()
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = -8 // 26 - 34
paragraphStyle.alignment = .Left
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleProjectSectionDescription() {
// Set the proper font.
font = UIFont.fontForSectionDescription()
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 8 // 26 - 18
paragraphStyle.alignment = .Left
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location:0, length:attributedString.length))
self.attributedText = attributedString;
// Make the first line bold.
let firstNewLine = (text as NSString).rangeOfString("\n")
let firstLine = NSRange(location:0, length:firstNewLine.location-1)
attributedString.addAttribute(NSFontAttributeName, value:UIFont.fontForSectionDescriptionFirstLine(), range:firstLine)
self.attributedText = attributedString
}
func applyMTZStyleProjectSectionQuote() {
// Set the proper font.
font = UIFont.fontForSectionQuote()
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 7
paragraphStyle.alignment = .Center
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleProjectSectionAnnotation() {
// Set the proper font.
font = UIFont.fontForSectionAnnotation()
// Set the proper text color.
textColor = UIColor(white: 0.5, alpha: 1)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4.0
paragraphStyle.alignment = .Center
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleGoodnightSectionTitle() {
// Set the proper font.
font = UIFont(name: "MyriadSetPro-Thin", size:48)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 16 // 64 - 48
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString;
}
func applyMTZStyleGoodnightSectionSubtitle() {
// Set the proper font.
font = UIFont(name: "MyriadSetPro-Thin", size: 24)
// Set the proper text color.
textColor = UIColor(white: 1, alpha: 0.8)
// Get the attributed string.
let attributedString = NSMutableAttributedString(string: text)
// Add the paragraph style.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 8 // 32 - 24
attributedString.addAttribute(NSParagraphStyleAttributeName,
value:paragraphStyle,
range:NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString;
}
} | mit | dc06aa0832674628aaacce01f8cd16d4 | 32.05638 | 120 | 0.733279 | 4.750107 | false | false | false | false |
PaulWoodIII/tipski | TipskyiOS/Tipski/PurchaseManager.swift | 1 | 5483 | //
// PurchaseManager.swift
// Tipski
//
// Created by Paul Wood on 10/20/16.
// Copyright © 2016 Paul Wood. All rights reserved.
//
import Foundation
import StoreKit
// Define identifier
let PurchaseManagerProductsUpdatedNotification = Notification.Name("PurchaseManagerProductsUpdatedNotification")
let PurchaseManagerTransactionFailedNotification = Notification.Name("PurchaseManagerTransactionFailedNotification")
let PurchaseManagerTransactionSucceededNotification = Notification.Name("PurchaseManagerTransactionSucceededNotification")
let FullUnlock = "ski.tip.full.unlock.1"
let FullUnlockChangedNotification = Notification.Name("ski.tip.full.unlock.1")
class PurchaseManager : NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
static let shared = PurchaseManager()
var fullUnlockProduct : SKProduct?
var fullUnlockRequest : SKProductsRequest!
func requestProduct(){
let productIdentifiers : Set<String> = [FullUnlock];
fullUnlockRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
fullUnlockRequest.delegate = self
fullUnlockRequest.start()
}
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
if let product = response.products.first {
fullUnlockProduct = product
NotificationCenter.default.post(name: PurchaseManagerProductsUpdatedNotification, object: self)
}
if response.invalidProductIdentifiers.count > 0 {
print(response.invalidProductIdentifiers)
}
}
// public methods
func loadStore(){
SKPaymentQueue.default().add(self)
requestProduct()
}
func unloadStore(){
SKPaymentQueue.default().remove(self)
}
func canMakePurchases() -> Bool {
return SKPaymentQueue.canMakePayments()
}
func purchaseFullUpgrade() {
guard let fullUnlockProduct = fullUnlockProduct else {
print("no product to pay for")
return
}
let payment = SKPayment(product: fullUnlockProduct)
SKPaymentQueue.default().add(payment)
}
func restorePastTransactions(){
SKPaymentQueue.default().restoreCompletedTransactions()
}
func recordTransaction(transaction : SKPaymentTransaction){
if transaction.payment.productIdentifier == FullUnlock {
// save the transaction receipt to disk
// This uses UserDefaults
UserDefaults.standard.set(true, forKey: FullUnlock)
UserDefaults.standard.synchronize()
NotificationCenter.default.post(name: FullUnlockChangedNotification, object: self, userInfo: nil)
}
}
func finishTransaction(transaction: SKPaymentTransaction, wasSuccessful : Bool){
let userInfo = Dictionary(dictionaryLiteral: ("transaction",transaction))
SKPaymentQueue.default().finishTransaction(transaction)
if wasSuccessful {
NotificationCenter.default.post(name: PurchaseManagerTransactionSucceededNotification, object: self, userInfo: userInfo)
}
else {
NotificationCenter.default.post(name: PurchaseManagerTransactionFailedNotification, object: self, userInfo: userInfo)
}
}
func completeTransaction(transaction : SKPaymentTransaction){
recordTransaction(transaction: transaction)
finishTransaction(transaction: transaction, wasSuccessful: true)
}
func failedTransation(transaction : SKPaymentTransaction) {
if let _ = transaction.error {
//Only do this if NOT canceled
finishTransaction(transaction: transaction, wasSuccessful: false)
}
else {
SKPaymentQueue.default().finishTransaction(transaction)
}
}
func restoreTransaction(transaction : SKPaymentTransaction) {
recordTransaction(transaction: transaction)
finishTransaction(transaction: transaction, wasSuccessful: true)
}
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
for transaction in transactions {
print(transaction.transactionState.rawValue)
switch transaction.transactionState {
case .purchased:
completeTransaction(transaction: transaction)
case .failed:
failedTransation(transaction: transaction)
case .restored:
restoreTransaction(transaction: transaction)
default:
break
}
}
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
}
public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error){
print(error)
for transaction in queue.transactions {
print(transaction.transactionState.rawValue)
switch transaction.transactionState {
case .failed:
failedTransation(transaction: transaction)
default:
break
}
}
}
public func checkReceipts(){
if let url = Bundle.main.appStoreReceiptURL {
let receipt = NSData(contentsOf: url)
}
}
}
| mit | 0568ce9736535fc2005c54cb3aa794cf | 33.696203 | 132 | 0.662532 | 6.097887 | false | false | false | false |
OscarSwanros/swift | stdlib/public/core/Zip.swift | 2 | 5707 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Creates a sequence of pairs built out of two underlying sequences.
///
/// In the `Zip2Sequence` instance returned by this function, the elements of
/// the *i*th pair are the *i*th elements of each underlying sequence. The
/// following example uses the `zip(_:_:)` function to iterate over an array
/// of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
///
/// If the two sequences passed to `zip(_:_:)` are different lengths, the
/// resulting sequence is the same length as the shorter sequence. In this
/// example, the resulting array is the same length as `words`:
///
/// let naturalNumbers = 1...Int.max
/// let zipped = Array(zip(words, naturalNumbers))
/// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
///
/// - Parameters:
/// - sequence1: The first sequence or collection to zip.
/// - sequence2: The second sequence or collection to zip.
/// - Returns: A sequence of tuple pairs, where the elements of each pair are
/// corresponding elements of `sequence1` and `sequence2`.
@_inlineable // FIXME(sil-serialize-all)
public func zip<Sequence1, Sequence2>(
_ sequence1: Sequence1, _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> {
return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2)
}
/// An iterator for `Zip2Sequence`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Zip2Iterator<
Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol
> : IteratorProtocol {
/// The type of element returned by `next()`.
public typealias Element = (Iterator1.Element, Iterator2.Element)
/// Creates an instance around a pair of underlying iterators.
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) {
(_baseStream1, _baseStream2) = (iterator1, iterator2)
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@_inlineable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
// The next() function needs to track if it has reached the end. If we
// didn't, and the first sequence is longer than the second, then when we
// have already exhausted the second sequence, on every subsequent call to
// next() we would consume and discard one additional element from the
// first sequence, even though next() had already returned nil.
if _reachedEnd {
return nil
}
guard let element1 = _baseStream1.next(),
let element2 = _baseStream2.next() else {
_reachedEnd = true
return nil
}
return (element1, element2)
}
@_versioned // FIXME(sil-serialize-all)
internal var _baseStream1: Iterator1
@_versioned // FIXME(sil-serialize-all)
internal var _baseStream2: Iterator2
@_versioned // FIXME(sil-serialize-all)
internal var _reachedEnd: Bool = false
}
/// A sequence of pairs built out of two underlying sequences.
///
/// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th
/// elements of each underlying sequence. To create a `Zip2Sequence` instance,
/// use the `zip(_:_:)` function.
///
/// The following example uses the `zip(_:_:)` function to iterate over an
/// array of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
@_fixed_layout // FIXME(sil-serialize-all)
public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence>
: Sequence {
@available(*, deprecated, renamed: "Sequence1.Iterator")
public typealias Stream1 = Sequence1.Iterator
@available(*, deprecated, renamed: "Sequence2.Iterator")
public typealias Stream2 = Sequence2.Iterator
/// A type whose instances can produce the elements of this
/// sequence, in order.
public typealias Iterator = Zip2Iterator<Sequence1.Iterator, Sequence2.Iterator>
/// Creates an instance that makes pairs of elements from `sequence1` and
/// `sequence2`.
@_inlineable // FIXME(sil-serialize-all)
public // @testable
init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) {
(_sequence1, _sequence2) = (sequence1, sequence2)
}
/// Returns an iterator over the elements of this sequence.
@_inlineable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(
_sequence1.makeIterator(),
_sequence2.makeIterator())
}
@_versioned // FIXME(sil-serialize-all)
internal let _sequence1: Sequence1
@_versioned // FIXME(sil-serialize-all)
internal let _sequence2: Sequence2
}
| apache-2.0 | 76504b24fdb580ae09908b6d05a1e0ef | 36.546053 | 82 | 0.650605 | 3.990909 | false | false | false | false |
taylorguo/douyuZB | douyuzb/douyuzb/Classes/Home/PageContentView.swift | 1 | 5684 | //
// PageContentView.swift
// douyuzb
//
// Created by mac on 2017/10/24.
// Copyright © 2017年 mac. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView: PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
//MARK:- 自定义属性
private var childVcs : [UIViewController]
private weak var parentViewController : UIViewController?
private var startOffsetX : CGFloat = 0
private var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
//MARK:- 懒加载属性
private lazy var collectionView: UICollectionView = {[weak self] in
//1. 创建Layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//2. 创建UICollectionView
let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout) // ??????????????
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
//MARK:- 自定义构造函数
init(frame: CGRect, childVcs : [UIViewController], parentViewController: UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
// 设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:- 设置UI界面
extension PageContentView{
private func setupUI(){
// 1. 将所有子控制器添加到父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
// 2. 添加UICollectionView,用于在Cell中存放控制器View
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1. 创建Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
//2. 给cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK:- 遵守UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//0. 判断是否是点击事件
if isForbidScrollDelegate {return}
//1. 获取需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
// 2. 判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX{ //左滑
// 1.计算Progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2. 计算sourceIndex
sourceIndex = Int(currentOffsetX/scrollViewW)
//3. 计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count{
targetIndex = childVcs.count - 1
}
//4. 滑动之后的index处理
if currentOffsetX - startOffsetX == scrollViewW{
progress = 1
targetIndex = sourceIndex
}
}else{//右滑
//1. 计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2. 计算targetIndex
targetIndex = Int(currentOffsetX/scrollViewW)
//3. 计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count{ sourceIndex = childVcs.count - 1 }
}
//3.将Progress/ sourceIndex / targetIndex 传递给titleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK:- 对外暴露方法
extension PageContentView{
func setCurrentIndex(currentIndex : Int){
// 1. 记录需要禁止执行的代理方法
isForbidScrollDelegate = true
// 2. 滚动到正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| mit | 05331447a41e389cb9ab560a0cbc816b | 31.5 | 124 | 0.637627 | 5.66107 | false | false | false | false |
arminm/SwiftCalculator | SwiftCalculator/SwiftCalculator/CalcViewController.swift | 1 | 2389 | //
// ViewController.swift
// SwiftCalculator
//
// Created by Armin Mahmoudi on 2014-10-30.
// Copyright (c) 2014 Armin. All rights reserved.
//
import UIKit
class CalcViewController : UIViewController {
@IBOutlet weak var resultLabel: UILabel!
// brain is the model that does the calculations and holds onto the operands and operations
lazy var brain = CalcBrainModel()
@IBAction func digitPressed(sender: UIButton) {
// Check if pressing 0 at the beginning:
if resultLabel.text! == "0" && sender.titleLabel!.text! == "0" {
brain.operand = 0.0
return
}
// Clear the resultLabel text before appending the first non-zero digit
if brain.operand == nil || brain.operand == 0.0{
resultLabel.text = ""
}
// Append digits
resultLabel.text! += sender.titleLabel!.text!
// Set brain's operand
brain.operand = (resultLabel.text! as NSString).doubleValue
}
@IBAction func clearPressed(sender: UIButton) {
// reset resultLabel
resultLabel.text = "0"
//reset the brain
brain.reset()
}
@IBAction func operationPressed(sender: UIButton) {
// Perform previous operation if a new operation button is pressed
// (result would be nil, thus not triggering, for the first operation press)
if let result = brain.performOperation() {
// Check for decimals
if floor(result) == result && result < Double(Int.max) && result > Double(Int.min) {
resultLabel.text = "\(Int(result))" // No .0 decimal shown
} else {
resultLabel.text = "\(result)"
}
}
// Check for operation type and set brain.operation
switch sender.titleLabel!.text! {
case Operations.addition.rawValue:
brain.operation = .addition
case Operations.subtraction.rawValue:
brain.operation = .subtraction
case Operations.multiplication.rawValue:
brain.operation = .multiplication
case Operations.division.rawValue:
brain.operation = .division
default:
break
}
}
} | mit | 8130258f15c48cf5f42b8a4683ade43e | 28.875 | 96 | 0.563416 | 5.082979 | false | false | false | false |
sdonly/GRMustache.swift | Mustache/Rendering/MustacheBox.swift | 2 | 10781 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
Mustache templates don't eat raw values: they eat values boxed in `MustacheBox`.
To box something in a `MustacheBox`, you use one variant of the `Box()`
function. It comes in several variants so that nearly anything can be boxed and
feed templates:
- Basic Swift values:
`template.render(Box("foo"))`
- Dictionaries & collections:
template.render(Box(["numbers": [1,2,3]]))
- Custom types via the `MustacheBoxable` protocol:
extension User: MustacheBoxable { ... }
template.render(Box(user))
- Functions such as `FilterFunction`, `RenderFunction`, `WillRenderFunction` and
`DidRenderFunction`:
let square = Filter { (x?: Int, _) in Box(x! * x!) }
template.registerInBaseContext("square", Box(square))
**Warning**: the fact that `MustacheBox` is an @objc class is an implementation
detail that is enforced by the Swift 1.2 language itself. This may change in the
future: do not rely on it.
*/
@objc public class MustacheBox {
// IMPLEMENTATION NOTE
//
// Why is MustacheBox a subclass of NSObject, and not, say, a Swift struct?
//
// Swift does not allow a class extension to override a method that is
// inherited from an extension to its superclass and incompatible with
// Objective-C.
//
// If MustacheBox were a pure Swift type, this Swift limit would prevent
// NSObject subclasses such as NSNull, NSNumber, etc. to override
// MustacheBoxable.mustacheBox, and provide custom rendering behavior.
//
// For an example of this limitation, see example below:
//
// import Foundation
//
// // A type that is not compatible with Objective-C
// struct MustacheBox { }
//
// // So far so good
// extension NSObject {
// var mustacheBox: MustacheBox { return MustacheBox() }
// }
//
// // Error: declarations in extensions cannot override yet
// extension NSNull {
// override var mustacheBox: MustacheBox { return MustacheBox() }
// }
//
// This problem does not apply to Objc-C compatible protocols:
//
// import Foundation
//
// // So far so good
// extension NSObject {
// var prop: String { return "NSObject" }
// }
//
// // No error
// extension NSNull {
// override var prop: String { return "NSNull" }
// }
//
// NSObject().prop // "NSObject"
// NSNull().prop // "NSNull"
//
// In order to let the user easily override NSObject.mustacheBox, we had to
// keep its return type compatible with Objective-C, that is to say make
// MustacheBox a subclass of NSObject.
// -------------------------------------------------------------------------
// MARK: - The boxed value
/// The boxed value.
public let value: Any?
/// The only empty box is `Box()`.
public let isEmpty: Bool
/**
The boolean value of the box.
It tells whether the Box should trigger or prevent the rendering of regular
`{{#section}}...{{/}}` and inverted `{{^section}}...{{/}}`.
*/
public let boolValue: Bool
/**
If the boxed value can be iterated (Swift collection, NSArray, NSSet, etc.),
returns an array of `MustacheBox`.
*/
public var arrayValue: [MustacheBox]? {
return converter?.arrayValue()
}
/**
If the boxed value is a dictionary (Swift dictionary, NSDictionary, etc.),
returns a dictionary `[String: MustacheBox]`.
*/
public var dictionaryValue: [String: MustacheBox]? {
return converter?.dictionaryValue()
}
/**
Extracts a key out of a box.
let box = Box(["firstName": "Arthur"])
box["firstName"].value // "Arthur"
:param: key A key
:returns: the MustacheBox for this key.
*/
public subscript (key: String) -> MustacheBox {
return keyedSubscript?(key: key) ?? Box()
}
// -------------------------------------------------------------------------
// MARK: - Other facets
/// See the documentation of `RenderFunction`.
public private(set) var render: RenderFunction
/// See the documentation of `FilterFunction`.
public let filter: FilterFunction?
/// See the documentation of `WillRenderFunction`.
public let willRender: WillRenderFunction?
/// See the documentation of `DidRenderFunction`.
public let didRender: DidRenderFunction?
// -------------------------------------------------------------------------
// MARK: - Internal
let keyedSubscript: KeyedSubscriptFunction?
let converter: Converter?
init(
boolValue: Bool? = nil,
value: Any? = nil,
converter: Converter? = nil,
keyedSubscript: KeyedSubscriptFunction? = nil,
filter: FilterFunction? = nil,
render: RenderFunction? = nil,
willRender: WillRenderFunction? = nil,
didRender: DidRenderFunction? = nil)
{
let empty = (value == nil) && (keyedSubscript == nil) && (render == nil) && (filter == nil) && (willRender == nil) && (didRender == nil)
self.isEmpty = empty
self.value = value
self.converter = converter
self.boolValue = boolValue ?? !empty
self.keyedSubscript = keyedSubscript
self.filter = filter
self.willRender = willRender
self.didRender = didRender
if let render = render {
self.render = render
} else {
// The default render function: it renders {{variable}} tags as the
// boxed value, and {{#section}}...{{/}} tags by adding the box to
// the context stack.
//
// IMPLEMENTATIN NOTE
//
// We have to set self.render twice in order to avoid the compiler
// error: "variable 'self.render' captured by a closure before being
// initialized"
//
// Despite this message, the `self` "captured" in the second closure
// is the one whose `render` property contains that same second
// closure: everything works as if no value was actually captured.
self.render = { (_, _) in return nil }
self.render = { [unowned self] (info: RenderingInfo, error: NSErrorPointer) in
switch info.tag.type {
case .Variable:
// {{ box }}
if let value = value {
return Rendering("\(value)")
} else {
return Rendering("")
}
case .Section:
// {{# box }}...{{/ box }}
let context = info.context.extendedContext(self)
return info.tag.render(context, error: error)
}
}
}
}
// Converter wraps all the conversion closures that help MustacheBox expose
// its raw value (typed Any) as useful types such as Int, Double, etc.
//
// Without those conversions, it would be very difficult for the library
// user to write code that processes, for example, a boxed number: she
// would have to try casting the boxed value to Int, UInt, Double, NSNumber
// etc. until she finds its actual type.
struct Converter {
let arrayValue: (() -> [MustacheBox]?)
let dictionaryValue: (() -> [String: MustacheBox]?)
init(
@autoclosure(escaping) arrayValue: () -> [MustacheBox]? = nil,
@autoclosure(escaping) dictionaryValue: () -> [String: MustacheBox]? = nil)
{
self.arrayValue = arrayValue
self.dictionaryValue = dictionaryValue
}
// IMPLEMENTATION NOTE
//
// It looks like Swift does not provide any way to perform a safe
// conversion between its numeric types.
//
// For example, there exists a UInt(Int) initializer, but it fails
// with EXC_BAD_INSTRUCTION when given a negative Int.
//
// So we implement below our own numeric conversion functions.
static func uint(x: Int) -> UInt? {
if x >= 0 {
return UInt(x)
} else {
return nil
}
}
static func uint(x: Double) -> UInt? {
if x == Double(UInt.max) {
return UInt.max
} else if x >= 0 && x < Double(UInt.max) {
return UInt(x)
} else {
return nil
}
}
static func int(x: UInt) -> Int? {
if x <= UInt(Int.max) {
return Int(x)
} else {
return nil
}
}
static func int(x: Double) -> Int? {
if x == Double(Int.max) {
return Int.max
} else if x >= Double(Int.min) && x < Double(Int.max) {
return Int(x)
} else {
return nil
}
}
}
}
extension MustacheBox : DebugPrintable {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
if let value = value {
return "MustacheBox(\(value))" // remove "Optional" from the output
} else {
return "MustacheBox(nil)"
}
}
}
| mit | ac5c473af68058f0db24ba9f9e04c6e0 | 33.662379 | 144 | 0.564471 | 4.906691 | false | false | false | false |
cruisediary/Diving | Diving/Scenes/TravelDetail/TravelDetailRouter.swift | 1 | 2400 | //
// TravelDetailRouter.swift
// Diving
//
// Created by CruzDiary on 5/23/16.
// Copyright (c) 2016 DigitalNomad. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol TravelDetailRouterInput {
func navigateToSomewhere()
func navigateToTravelListScene()
}
class TravelDetailRouter {
weak var viewController: TravelDetailViewController!
let DTravelListSceneIdentifier = "ShowTravelScene"
// MARK: Navigation
func navigateToTravelListScene(){
viewController.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
func navigateToSomewhere() {
// NOTE: Teach the router how to navigate to another scene. Some examples follow:
// 1. Trigger a storyboard segue
// viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil)
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
// MARK: Communication
func passDataToNextScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router which scenes it can communicate with
if segue.identifier == "ShowSomewhereScene" {
passDataToSomewhereScene(segue)
}
}
func passDataToSomewhereScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router how to pass data to the next scene
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.output.name = viewController.output.name
}
}
| mit | 73e35fe11095db9999ffd7cf867a9919 | 37.095238 | 114 | 0.7075 | 5.797101 | false | false | false | false |
wltrup/Swift-WTUniquePrimitiveType | WTUniquePrimitiveType/Classes/UniqueBooleanType.swift | 1 | 2092 | //
// UniqueBooleanType.swift
// WTUniquePrimitiveTypes
//
// Created by Wagner Truppel on 31/05/2017.
// Copyright © 2017 wtruppel. All rights reserved.
//
// swiftlint:disable vertical_whitespace
// swiftlint:disable trailing_newline
import Foundation
public protocol UniqueBooleanType: WTUniquePrimitiveType, ExpressibleByBooleanLiteral {
associatedtype PrimitiveType: ExpressibleByBooleanLiteral
}
// MARK: - ExpressibleByBooleanLiteral
extension UniqueBooleanType {
public init(booleanLiteral value: Self.PrimitiveType) {
self.init(value)
}
}
// MARK: - Boolean operators
extension UniqueBooleanType where Self.PrimitiveType == Bool {
public static prefix func !(a: Self) -> Self {
return self.init(!a.value)
}
public static func && (lhs: Self, rhs: @autoclosure () throws -> Self) rethrows -> Self {
let result = try lhs.value && rhs().value
return self.init(result)
}
public static func && (lhs: Self, rhs: @autoclosure () throws -> Bool) rethrows -> Self {
let result = try lhs.value && rhs()
return self.init(result)
}
public static func || (lhs: Self, rhs: @autoclosure () throws -> Self) rethrows -> Self {
let result = try lhs.value || rhs().value
return self.init(result)
}
public static func || (lhs: Self, rhs: @autoclosure () throws -> Bool) rethrows -> Self {
let result = try lhs.value || rhs()
return self.init(result)
}
}
extension Bool: Comparable {
public static func <(lhs: Bool, rhs: Bool) -> Bool {
return !lhs && rhs
}
}
extension Bool {
public static func && <T: UniqueBooleanType>(lhs: Bool, rhs: @autoclosure () throws -> T) rethrows -> T
where T.PrimitiveType == Bool {
let result = try lhs && rhs().value
return T(result)
}
public static func || <T: UniqueBooleanType>(lhs: Bool, rhs: @autoclosure () throws -> T) rethrows -> T
where T.PrimitiveType == Bool {
let result = try lhs || rhs().value
return T(result)
}
}
| mit | 5fe3b4f7ce82c2750edeb8462e658159 | 24.814815 | 107 | 0.634625 | 4.232794 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/UI/Styles/Presets/UIFontStyles.swift | 1 | 4087 | import UIKit
// swiftlint:disable valid_docs
extension UIFont {
/// Returns a bolded version of `self`.
public var bolded: UIFont {
return self.fontDescriptor.withSymbolicTraits(.traitBold)
.map { UIFont(descriptor: $0, size: 0.0) } ?? self
}
/// Returns a italicized version of `self`.
public var italicized: UIFont {
return self.fontDescriptor.withSymbolicTraits(.traitItalic)
.map { UIFont(descriptor: $0, size: 0.0) } ?? self
}
/// Returns a fancy monospaced font for the countdown.
public var countdownMonospaced: UIFont {
let monospacedDescriptor = self.fontDescriptor
.addingAttributes(
[
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector
],
[
UIFontDescriptor.FeatureKey.featureIdentifier: kStylisticAlternativesType,
UIFontDescriptor.FeatureKey.typeIdentifier: kStylisticAltTwoOnSelector
],
[
UIFontDescriptor.FeatureKey.featureIdentifier: kStylisticAlternativesType,
UIFontDescriptor.FeatureKey.typeIdentifier: kStylisticAltOneOnSelector
]
]
]
)
return UIFont(descriptor: monospacedDescriptor, size: 0.0)
}
/// regular, 17pt font, 22pt leading, -24pt tracking
public static func ksr_body(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .body, size: size)
}
/// regular, 16pt font, 21pt leading, -20pt tracking
public static func ksr_callout(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .body, size: size)
}
/// regular, 12pt font, 16pt leading, 0pt tracking
public static func ksr_caption1(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .caption1, size: size)
}
/// regular, 11pt font, 13pt leading, 6pt tracking
public static func ksr_caption2(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .caption2, size: size)
}
/// regular, 13pt font, 18pt leading, -6pt tracking
public static func ksr_footnote(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .footnote, size: size)
}
/// semi-bold, 17pt font, 22pt leading, -24pt tracking
public static func ksr_headline(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .headline, size: size)
}
/// regular, 15pt font, 20pt leading, -16pt tracking
public static func ksr_subhead(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .subheadline, size: size)
}
/// light, 28pt font, 34pt leading, 13pt tracking
public static func ksr_title1(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .body, size: size)
}
/// regular, 22pt font, 28pt leading, 16pt tracking
public static func ksr_title2(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .body, size: size)
}
/// regular, 20pt font, 24pt leading, 19pt tracking
public static func ksr_title3(size: CGFloat? = nil) -> UIFont {
return .preferredFont(style: .body, size: size)
}
// swiftlint:disable cyclomatic_complexity
fileprivate static func preferredFont(style: UIFont.TextStyle, size: CGFloat? = nil) -> UIFont {
let defaultSize: CGFloat
switch style {
case UIFont.TextStyle.body: defaultSize = 17
case UIFont.TextStyle.caption1: defaultSize = 12
case UIFont.TextStyle.caption2: defaultSize = 11
case UIFont.TextStyle.footnote: defaultSize = 13
case UIFont.TextStyle.headline: defaultSize = 17
case UIFont.TextStyle.subheadline: defaultSize = 15
default: defaultSize = 17
}
let font = UIFont.preferredFont(forTextStyle: style)
let descriptor = font.fontDescriptor
return UIFont(descriptor: descriptor,
size: ceil(font.pointSize / defaultSize * (size ?? defaultSize)))
}
// swiftlint:enable cyclomatic_complexity
}
| mit | 30b56ce2ff55e61b276e0bbc59ed95d2 | 35.491071 | 98 | 0.672131 | 4.361793 | false | false | false | false |
007HelloWorld/DouYuZhiBo | DYZB/DYZB/Main/Model/AnchorModel.swift | 1 | 891 | //
// AnchorModel.swift
// DYZB
//
// Created by MacMini on 2017/8/7.
// Copyright © 2017年 MacMini. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
//房间ID
var room_id : Int = 0
//房间图片对应的URLString
var vertical_src : String = ""
//判断是手机直播还是电脑直播
//0: 电脑直播 1:手机直播
var isVertical : Int = 0
//房间昵称
var room_name : String = ""
//主播昵称
var nickname : String = ""
//观看人数
var online : Int = 0
//所在城市
var anchor_city : String = ""
//构造函数
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | 5efbb8c705946f226d38c3383e302d36 | 14.45098 | 73 | 0.506345 | 4.061856 | false | false | false | false |
macemmi/HBCI4Swift | HBCI4Swift/HBCI4Swift/Source/Orders/HBCICustodyAccountBalanceOrder.swift | 1 | 1932 | //
// HBCICustodyAccountBalanceOrder.swift
// HBCI4Swift
//
// Created by Frank Emminghaus on 07.05.21.
// Copyright © 2021 Frank Emminghaus. All rights reserved.
//
import Foundation
open class HBCICustodyAccountBalanceOrder : HBCIOrder {
public let account:HBCIAccount;
public var balance:HBCICustodyAccountBalance?
public init?(message: HBCICustomMessage, account:HBCIAccount) {
self.account = account;
super.init(name: "CustodyAccountBalance", message: message);
if self.segment == nil {
return nil;
}
}
open func enqueue() ->Bool {
// check if order is supported
if !user.parameters.isOrderSupportedForAccount(self, number: account.number, subNumber: account.subNumber) {
logInfo(self.name + " is not supported for account " + account.number);
return false;
}
var values:Dictionary<String,Any> = ["KTV.number":account.number, "KTV.KIK.country":"280", "KTV.KIK.blz":account.bankCode ];
if account.subNumber != nil {
values["KTV.subnumber"] = account.subNumber!
}
if !segment.setElementValues(values) {
logInfo("Custody Account Balance Order values could not be set");
return false;
}
// add to message
return msg.addOrder(self);
}
override open func updateResult(_ result:HBCIResultMessage) {
super.updateResult(result);
if let retSeg = resultSegments.first {
if let de = retSeg.elementForPath("info") as? HBCIDataElement {
if let info = de.value as? Data {
if let mt535 = String(data: info, encoding: String.Encoding.isoLatin1) {
let parser = HBCIMT535Parser(mt535);
self.balance = parser.parse();
}
}
}
}
}
}
| gpl-2.0 | 030b7fc7a936ec20c0f861dfebce62ab | 30.655738 | 132 | 0.592439 | 4.291111 | false | false | false | false |
mapsme/omim | iphone/Maps/Core/Ads/Mopub/MopubBanner.swift | 4 | 5182 | import MoPub_FacebookAudienceNetwork_Adapters
final class MopubBanner: NSObject, Banner {
private enum Limits {
static let minTimeOnScreen: TimeInterval = 3
static let minTimeSinceLastRequest: TimeInterval = 5
}
fileprivate var success: Banner.Success!
fileprivate var failure: Banner.Failure!
fileprivate var click: Banner.Click!
private var requestDate: Date?
private var showDate: Date?
private var remainingTime = Limits.minTimeOnScreen
private let placementID: String
func reload(success: @escaping Banner.Success, failure: @escaping Banner.Failure, click: @escaping Click) {
self.success = success
self.failure = failure
self.click = click
load()
requestDate = Date()
}
func unregister() {
nativeAd?.unregister()
}
var isBannerOnScreen = false {
didSet {
if isBannerOnScreen {
startCountTimeOnScreen()
} else {
stopCountTimeOnScreen()
}
}
}
private(set) var isNeedToRetain = false
var isPossibleToReload: Bool {
if let date = requestDate {
return Date().timeIntervalSince(date) > Limits.minTimeSinceLastRequest
}
return true
}
var type: BannerType { return .mopub(bannerID) }
var mwmType: MWMBannerType { return type.mwmType }
var bannerID: String { return placementID }
var statisticsDescription: [String: String] {
return [kStatBanner: bannerID, kStatProvider: kStatMopub]
}
init(bannerID: String) {
placementID = bannerID
super.init()
let center = NotificationCenter.default
center.addObserver(self,
selector: #selector(enterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil)
center.addObserver(self,
selector: #selector(enterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func enterForeground() {
if isBannerOnScreen {
startCountTimeOnScreen()
}
}
@objc private func enterBackground() {
if isBannerOnScreen {
stopCountTimeOnScreen()
}
}
private func startCountTimeOnScreen() {
if showDate == nil {
showDate = Date()
}
if remainingTime > 0 {
perform(#selector(setEnoughTimeOnScreen), with: nil, afterDelay: remainingTime)
}
}
private func stopCountTimeOnScreen() {
guard let date = showDate else {
assert(false)
return
}
let timePassed = Date().timeIntervalSince(date)
if timePassed < Limits.minTimeOnScreen {
remainingTime = Limits.minTimeOnScreen - timePassed
NSObject.cancelPreviousPerformRequests(withTarget: self)
} else {
remainingTime = 0
}
}
@objc private func setEnoughTimeOnScreen() {
isNeedToRetain = false
}
// MARK: - Content
private(set) var nativeAd: MPNativeAd?
var title: String {
return nativeAd?.properties[kAdTitleKey] as? String ?? ""
}
var text: String {
return nativeAd?.properties[kAdTextKey] as? String ?? ""
}
var iconURL: String {
return nativeAd?.properties[kAdIconImageKey] as? String ?? ""
}
var ctaText: String {
return nativeAd?.properties[kAdCTATextKey] as? String ?? ""
}
var privacyInfoURL: URL? {
guard let nativeAd = nativeAd else { return nil }
if nativeAd.adAdapter is FacebookNativeAdAdapter {
return (nativeAd.adAdapter as! FacebookNativeAdAdapter).fbNativeAdBase.adChoicesLinkURL
}
return URL(string: kPrivacyIconTapDestinationURL)
}
// MARK: - Helpers
private var request: MPNativeAdRequest!
private func load() {
let settings = MPStaticNativeAdRendererSettings()
let config = MPStaticNativeAdRenderer.rendererConfiguration(with: settings)!
let fbConfig = FacebookNativeAdRenderer.rendererConfiguration(with: settings)
request = MPNativeAdRequest(adUnitIdentifier: placementID, rendererConfigurations: [config, fbConfig])
let targeting = MPNativeAdRequestTargeting()
targeting?.keywords = "user_lang:\(AppInfo.shared().twoLetterLanguageId)"
targeting?.desiredAssets = [kAdTitleKey, kAdTextKey, kAdIconImageKey, kAdCTATextKey]
if let location = LocationManager.lastLocation() {
targeting?.location = location
}
request.targeting = targeting
request.start { [weak self] _, nativeAd, error in
guard let s = self else { return }
if let error = error as NSError? {
let params: [String: Any] = [
kStatBanner: s.bannerID,
kStatProvider: kStatMopub,
]
let event = kStatPlacePageBannerError
s.failure(s.type, event, params, error)
} else {
nativeAd?.delegate = self
s.nativeAd = nativeAd
s.success(s)
}
}
}
}
extension MopubBanner: MPNativeAdDelegate {
func willPresentModal(for nativeAd: MPNativeAd!) {
guard nativeAd === self.nativeAd else { return }
click(self)
}
func viewControllerForPresentingModalView() -> UIViewController! {
return UIViewController.topViewController()
}
}
| apache-2.0 | 87cc031b739636c0fac58e874742f54f | 26.417989 | 109 | 0.676187 | 4.954111 | false | false | false | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/Filters/LevelProgressionFilter.swift | 1 | 717 | //
// LevelProgressionFilter.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
public struct LevelProgressionFilter {
public let ids: [Int]?
public let updatedAfter: Date?
public init(ids: [Int]? = nil,
updatedAfter: Date? = nil) {
self.ids = ids
self.updatedAfter = updatedAfter
}
}
extension LevelProgressionFilter: RequestFilter {
func asQueryItems() -> [URLQueryItem]? {
var elements = [URLQueryItem]()
elements.appendItemsIfSet(name: "ids", values: ids)
elements.appendItemIfSet(name: "updated_after", value: updatedAfter)
return elements.count == 0 ? nil : elements
}
}
| mit | 064a822718ad8e912690daf3024d87bb | 25.518519 | 76 | 0.631285 | 4.138728 | false | false | false | false |
fscz/AppUnderControl-Bridge | Pod/Classes/TokenVerification.swift | 1 | 3936 | //
// Config.swift
// AppUnderControl
//
// Created by Fabian Schuetz on 01/10/15.
// Copyright © 2015 Lohmann & Birkner Mobile Services. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
import SwiftyBase64
import CryptoSwift
//import CommonCrypto
class TokenVerification {
private class func sha256(data: NSData) -> NSData {
return CryptoSwift.Hash.sha256(data).calculate()!
}
/*
private class func sha256(data : NSData) -> NSData {
var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA256(data.bytes, CC_LONG(data.length), &hash)
let res = NSData(bytes: hash, length: Int(CC_SHA256_DIGEST_LENGTH))
return res
}*/
private class func getStringForDate(date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(name: "UTC")!
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minute = components.minute
return "\(year)-\(month)-\(day)-\(hour)-\(minute)"
}
private class func getCurrentTimeStrings(callback: (String?, String?)->Void) {
let dateNow = NSDate()
let dateOneMinuteEarlier = NSDate(timeInterval: -60.0, sinceDate: dateNow)
callback(getStringForDate(dateOneMinuteEarlier), getStringForDate(dateNow))
}
private class func getTokenSeed() -> String? {
let appUnderControlDelegate = UIApplication.sharedApplication().delegate as? AppUnderControlDelegate
let seed = appUnderControlDelegate?.appUnderControlGetTokenSeed()
return seed
}
private class func tokensForCurrentTime(callback: ([String])->Void) {
getCurrentTimeStrings({(minuteEarly:String?, now: String?) in
if minuteEarly == nil {
callback([])
} else {
if let seed = getTokenSeed() {
let dataEarly = sha256("\(seed)-\(minuteEarly!)".dataUsingEncoding(NSASCIIStringEncoding)!)
let dataNow = sha256("\(seed)-\(now!)".dataUsingEncoding(NSASCIIStringEncoding)!)
let countEarly = dataEarly.length / sizeof(UInt8)
let countNow = dataNow.length / sizeof(UInt8)
var arrayEarly = [UInt8](count: countEarly, repeatedValue: 0)
dataEarly.getBytes(&arrayEarly, length: dataEarly.length / sizeof(UInt8) * sizeof(UInt8))
var arrayNow = [UInt8](count: countNow, repeatedValue: 0)
dataNow.getBytes(&arrayNow, length: dataNow.length / sizeof(UInt8) * sizeof(UInt8))
callback([
SwiftyBase64.EncodeString(arrayEarly, alphabet: .URLAndFilenameSafe),
SwiftyBase64.EncodeString(arrayNow, alphabet: .URLAndFilenameSafe)
])
} else {
callback([])
}
}
})
}
class func verfifyOpenUrl(app: AppUnderControlDelegate, openURL: NSURL) {
let array = openURL.description.componentsSeparatedByString("%23")
if array.count == 2 {
let tokenEncoded = array[1]
TokenVerification.tokensForCurrentTime({ (tokens) -> Void in
if tokens.contains(tokenEncoded as String) {
app.appUnderControl(app, didReceiveValidToken: tokenEncoded)
}
})
}
}
}
| mit | 077e9c69ddd126f0c1c11b09c66ab257 | 36.836538 | 169 | 0.584244 | 5.031969 | false | false | false | false |
SereivoanYong/Charts | Source/Charts/Charts/HorizontalBarChartView.swift | 1 | 6385 | //
// HorizontalBarChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
/// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched.
open class HorizontalBarChartView: BarChartView {
internal override func initialize() {
super.initialize()
_leftAxisTransformer = TransformerHorizontalBarChart(viewPortHandler: viewPortHandler)
_rightAxisTransformer = TransformerHorizontalBarChart(viewPortHandler: viewPortHandler)
renderer = HorizontalBarRenderer(dataProvider: self, animator: animator, viewPortHandler: viewPortHandler)
_leftYAxisRenderer = HorizontalBarYAxisRenderer(viewPortHandler: viewPortHandler, axis: leftAxis, transformer: _leftAxisTransformer)
_rightYAxisRenderer = HorizontalBarYAxisRenderer(viewPortHandler: viewPortHandler, axis: rightAxis, transformer: _rightAxisTransformer)
_xAxisRenderer = HorizontalBarXAxisRenderer(viewPortHandler: viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self)
self.highlighter = HorizontalBarHighlighter(chart: self)
}
internal override func calculateOffsets() {
var offsetLeft: CGFloat = 0.0,
offsetRight: CGFloat = 0.0,
offsetTop: CGFloat = 0.0,
offsetBottom: CGFloat = 0.0
calculateLegendOffsets(offsetLeft: &offsetLeft,
offsetTop: &offsetTop,
offsetRight: &offsetRight,
offsetBottom: &offsetBottom)
// offsets for y-labels
if leftAxis.needsOffset {
offsetTop += leftAxis.requiredSize().height
}
if rightAxis.needsOffset {
offsetBottom += rightAxis.requiredSize().height
}
let xlabelwidth = _xAxis.labelRotatedSize.width
if _xAxis.isEnabled {
// offsets for x-labels
if _xAxis.labelPosition == .bottom {
offsetLeft += xlabelwidth
}
else if _xAxis.labelPosition == .top {
offsetRight += xlabelwidth
}
else if _xAxis.labelPosition == .bothSided {
offsetLeft += xlabelwidth
offsetRight += xlabelwidth
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
prepareOffsetMatrix()
prepareValuePxMatrix()
}
internal override func prepareValuePxMatrix() {
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: rightAxis._axisMinimum, deltaX: rightAxis.axisRange, deltaY: _xAxis.axisRange, chartYMin: _xAxis._axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: leftAxis._axisMinimum, deltaX: leftAxis.axisRange, deltaY: _xAxis.axisRange, chartYMin: _xAxis._axisMinimum)
}
open override func getMarkerPosition(highlight: Highlight) -> CGPoint {
return highlight.drawPosition.reversed()
}
open override func getBarBounds(entry e: BarEntry) -> CGRect {
guard let data = data as? BarData, let set = data.getDataSetForEntry(e) as? IBarChartDataSet else {
return .null
}
let y = e.y
let x = e.x
let barWidth = data.barWidth
let top = x - 0.5 + barWidth / 2.0
let bottom = x + 0.5 - barWidth / 2.0
let left = y >= 0.0 ? y : 0.0
let right = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(forAxis: set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
open override func getPosition(entry e: Entry, axis: YAxis.AxisDependency) -> CGPoint {
var vals = CGPoint(x: e.y, y: e.x)
getTransformer(forAxis: axis).pointValueToPixel(&vals)
return vals
}
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? {
if data == nil {
print("Can't select by touch. No data set.", terminator: "\n")
return nil
}
return highlighter?.highlight(at: pt.reversed())
}
/// - returns: The lowest x-index (value on the x-axis) that is still visible on he chart.
open override var lowestVisibleX: CGFloat {
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)
getTransformer(forAxis: .left).pixelToValues(&pt)
return max(xAxis._axisMinimum, pt.y)
}
/// - returns: The highest x-index (value on the x-axis) that is still visible on the chart.
open override var highestVisibleX: CGFloat {
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)
getTransformer(forAxis: .left).pixelToValues(&pt)
return min(xAxis._axisMaximum, pt.y)
}
// MARK: - Viewport
open override func setVisibleXRangeMaximum(_ maxXRange: CGFloat) {
let xScale = xAxis.axisRange / maxXRange
viewPortHandler.setMinimumScaleY(xScale)
}
open override func setVisibleXRangeMinimum(_ minXRange: CGFloat) {
let xScale = xAxis.axisRange / minXRange
viewPortHandler.setMaximumScaleY(xScale)
}
open override func setVisibleXRange(minXRange: CGFloat, maxXRange: CGFloat) {
let minScale = xAxis.axisRange / minXRange
let maxScale = xAxis.axisRange / maxXRange
viewPortHandler.setMinMaxScaleY(minScaleY: minScale, maxScaleY: maxScale)
}
open override func setVisibleYRangeMaximum(_ maxYRange: CGFloat, axis: YAxis.AxisDependency) {
let yScale = getAxisRange(axis: axis) / maxYRange
viewPortHandler.setMinimumScaleX(yScale)
}
open override func setVisibleYRangeMinimum(_ minYRange: CGFloat, axis: YAxis.AxisDependency) {
let yScale = getAxisRange(axis: axis) / minYRange
viewPortHandler.setMaximumScaleX(yScale)
}
open override func setVisibleYRange(minYRange: CGFloat, maxYRange: CGFloat, axis: YAxis.AxisDependency) {
let minScale = getAxisRange(axis: axis) / minYRange
let maxScale = getAxisRange(axis: axis) / maxYRange
viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale)
}
}
| apache-2.0 | 06c0f5d1c92b668782e6d394adec4370 | 34.276243 | 168 | 0.697886 | 4.915319 | false | false | false | false |
crsantos/BundledCocoapodDynamicFrameworkError | Example/Tests/Tests.swift | 1 | 1186 | // https://github.com/Quick/Quick
import Quick
import Nimble
import BundledCocoapodDynamicFrameworkError
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 737d18a649d42c1e1ea2cb386807e63d | 22.6 | 60 | 0.372034 | 5.488372 | false | false | false | false |
thislooksfun/Tavi | Tavi/API/Helper/JSON.swift | 1 | 4144 | //
// JSON.swift
// Tavi
//
// Copyright (C) 2016 thislooksfun
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
/// A basic [JSON](http://www.json.org) implemention
class JSON: CustomStringConvertible
{
/// The dictionary the information is stored in
private var dict: NSDictionary!
/// The JSON information stored in string format
private var string: String!
/// Initalizes the JSON instance from a generic object
///
/// - Warning: Can return nil if given invalid data
init?(obj: AnyObject?) {
guard obj != nil else { return nil }
if obj is NSDictionary {
self.dict = obj! as! NSDictionary
} else if obj is String {
if let data = (obj as! String).dataUsingEncoding(NSUTF8StringEncoding) {
do {
self.dict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
Logger.warn(error)
}
}
guard self.dict != nil else { return nil }
} else {
Logger.warn("Unknown for object: '\(obj!)'")
return nil
}
}
/// Initalizes the JSON instance from an `NSData` object
///
/// - Throws: Can throw an NSError if given invalid data
init(data: NSData) throws {
self.string = NSString(data: data, encoding: NSUTF8StringEncoding)! as String
let error: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil)
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as? NSDictionary
guard json != nil else {
throw error
}
self.dict = json!
}
/// Initalizes the JSON instance from an NSDictionary object
///
/// - Warning: Can return nil if given invalid data
init?(dict: NSDictionary?) {
guard dict != nil else { return nil }
self.dict = dict!
}
/// Returns a string version of this JSON object
var description: String {
get {
do {
return NSString(data: try NSJSONSerialization.dataWithJSONObject(self.dict, options: NSJSONWritingOptions.PrettyPrinted), encoding: NSUTF8StringEncoding)! as String
} catch _ {
return ""
}
}
}
/// Gets the specified key, or nil if it doesn't exist
///
/// - Parameter key: The key to find
func getKey(key: String) -> AnyObject? {
return dict[key]
}
/// Gets the specified key as a String, or nil if it can't be cast or doesn't exist
///
/// - Parameter key: The key to find
func getString(key: String) -> String? {
let k = getKey(key) as? NSString
return k as? String
}
/// Gets the specified key as an Int, or nil if it can't be cast or doesn't exist
///
/// - Parameter key: The key to find
func getInt(key: String) -> Int? {
return getKey(key) as? Int
}
/// Gets the specified key as an array, or nil if it can't be cast or doesn't exist
///
/// - Parameter key: The key to find
func getArray(key: String) -> [AnyObject]? {
return getKey(key) as? [AnyObject]
}
/// Gets the specified key as new JSON object, or nil if it can't be cast or doesn't exist
///
/// - Parameter key: The key to find
func getJson(key: String) -> JSON? {
return JSON(dict: getKey(key) as? NSDictionary)
}
/// Gets the specified key as an array of new JSON objects, or nil if it can't be cast or doesn't exist
///
/// - Parameter key: The key to find
func getJsonArray(key: String) -> [JSON]? {
guard dict[key] is [NSDictionary] else { return nil }
var out = [JSON]()
for obj in dict[key] as! [NSDictionary] {
let nextJson = JSON(dict: obj)
guard nextJson != nil else { return nil }
out.append(nextJson!)
}
return out
}
} | gpl-3.0 | 901e0882df19b9ccdd3d3ffa5dc161b5 | 28.820144 | 168 | 0.6764 | 3.557082 | false | false | false | false |
trungphamduc/Calendar | Pod/Classes/UIColorExtension.swift | 2 | 1916 | //
// UIColorExtension.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = advance(rgba.startIndex, 1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (count(hex)) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
println("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
} | mit | 84a45b00e6e46e6756c88977b2735766 | 34.5 | 99 | 0.533925 | 3.515596 | false | false | false | false |
joerocca/GitHawk | Local Pods/FlatCache/FlatCacheTests/FlatCacheTests.swift | 1 | 4515 | //
// FlatCacheTests.swift
// FreetimeTests
//
// Created by Ryan Nystrom on 10/21/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import XCTest
struct CacheModel: Cachable {
let id: String
let value: String
}
class CacheModelListener: FlatCacheListener {
var receivedItemQueue = [CacheModel]()
var receivedListQueue = [[CacheModel]]()
func flatCacheDidUpdate(cache: FlatCache, update: FlatCache.Update) {
switch update {
case .item(let item): receivedItemQueue.append(item as! CacheModel)
case .list(let list): receivedListQueue.append(list as! [CacheModel])
}
}
}
struct OtherCacheModel: Cachable {
let id: String
}
class FlatCacheTests: XCTestCase {
func test_whenSettingSingleModel_thatResultExistsForType() {
let cache = FlatCache()
cache.set(value: CacheModel(id: "1", value: ""))
XCTAssertNotNil(cache.get(id: "1") as CacheModel?)
}
func test_whenSettingSingleModel_withUupdatedModel_thatResultMostRecent() {
let cache = FlatCache()
cache.set(value: CacheModel(id: "1", value: "foo"))
cache.set(value: CacheModel(id: "1", value: "bar"))
XCTAssertEqual((cache.get(id: "1") as CacheModel?)?.value, "bar")
}
func test_whenSettingSingleModel_thatNoResultExsistForUnsetId() {
let cache = FlatCache()
cache.set(value: CacheModel(id: "1", value: ""))
XCTAssertNil(cache.get(id: "2") as CacheModel?)
}
func test_whenSettingSingleModel_thatNoResultExistsForOtherType() {
let cache = FlatCache()
cache.set(value: CacheModel(id: "1", value: ""))
XCTAssertNil(cache.get(id: "1") as OtherCacheModel?)
}
func test_whenSettingManyModels_thatResultsExistForType() {
let cache = FlatCache()
cache.set(values: [
CacheModel(id: "1", value: ""),
CacheModel(id: "2", value: ""),
CacheModel(id: "3", value: ""),
])
XCTAssertNotNil(cache.get(id: "1") as CacheModel?)
XCTAssertNotNil(cache.get(id: "2") as CacheModel?)
XCTAssertNotNil(cache.get(id: "3") as CacheModel?)
}
func test_whenSettingSingleModel_withListeners_whenMultipleUpdates_thatCorrectListenerReceivesUpdate() {
let cache = FlatCache()
let l1 = CacheModelListener()
let l2 = CacheModelListener()
let m1 = CacheModel(id: "1", value: "")
let m2 = CacheModel(id: "2", value: "")
cache.add(listener: l1, value: m1)
cache.add(listener: l2, value: m2)
cache.set(value: m1)
cache.set(value: CacheModel(id: "1", value: "foo"))
XCTAssertEqual(l1.receivedItemQueue.count, 2)
XCTAssertEqual(l1.receivedListQueue.count, 0)
XCTAssertEqual(l1.receivedItemQueue.last?.id, "1")
XCTAssertEqual(l1.receivedItemQueue.last?.value, "foo")
XCTAssertEqual(l2.receivedItemQueue.count, 0)
XCTAssertEqual(l2.receivedListQueue.count, 0)
}
func test_whenSettingMultipleModels_withListenerOnAll_whenMultipleUpdates_thatListenerReceivesUpdate() {
let cache = FlatCache()
let l1 = CacheModelListener()
let m1 = CacheModel(id: "1", value: "foo")
let m2 = CacheModel(id: "2", value: "bar")
cache.add(listener: l1, value: m1)
cache.add(listener: l1, value: m2)
cache.set(values: [m1, m2])
XCTAssertEqual(l1.receivedItemQueue.count, 0)
XCTAssertEqual(l1.receivedListQueue.count, 1)
XCTAssertEqual(l1.receivedListQueue.last?.count, 2)
XCTAssertEqual(l1.receivedListQueue.last?.first?.value, "foo")
XCTAssertEqual(l1.receivedListQueue.last?.last?.value, "bar")
}
func test_whenSettingTwoModels_withListenerForEach_thatListenersReceiveItemUpdates() {
let cache = FlatCache()
let l1 = CacheModelListener()
let l2 = CacheModelListener()
let m1 = CacheModel(id: "1", value: "foo")
let m2 = CacheModel(id: "2", value: "bar")
cache.add(listener: l1, value: m1)
cache.add(listener: l2, value: m2)
cache.set(values: [m1, m2])
XCTAssertEqual(l1.receivedItemQueue.count, 1)
XCTAssertEqual(l1.receivedListQueue.count, 0)
XCTAssertEqual(l1.receivedItemQueue.last?.value, "foo")
XCTAssertEqual(l2.receivedItemQueue.count, 1)
XCTAssertEqual(l2.receivedListQueue.count, 0)
XCTAssertEqual(l2.receivedItemQueue.last?.value, "bar")
}
}
| mit | c87ebe735cb3f9631f03dfc51594f75a | 36.305785 | 108 | 0.644661 | 3.984113 | false | true | false | false |
adamnemecek/WebMIDIKit | Sources/WebMIDIKit/MIDIPacketList.swift | 1 | 6456 | import AVFoundation
extension MIDIPacket {
var status: MIDIStatus {
MIDIStatus(packet: self)!
}
}
extension MIDIPacketList {
public var sizeInBytes: Int {
withUnsafePointer(to: self) {
Self.sizeInBytes(pktList: $0)
}
}
/// this needs to be mutating since we are potentionally changint the timestamp
/// we cannot make a copy since that woulnd't copy the whole list
internal mutating func send(to output: MIDIOutput, offset: Double? = nil) {
_ = offset.map {
// NOTE: AudioGetCurrentHostTime() CoreAudio method is only available on macOS
let current = AudioGetCurrentHostTime()
let _offset = AudioConvertNanosToHostTime(UInt64($0 * 1000000))
let ts = current + _offset
packet.timeStamp = ts
}
OSAssert(MIDISend(output.ref, output.endpoint.ref, &self))
/// this let's us propagate the events to everyone subscribed to this
/// endpoint not just this port, i'm not sure if we actually want this
/// but for now, it let's us create multiple ports from different MIDIAccess
/// objects and have them all receive the same messages
OSAssert(MIDIReceived(output.endpoint.ref, &self))
}
internal init<S: Sequence>(_ data: S, timestamp: MIDITimeStamp = 0) where S.Iterator.Element == UInt8 {
self.init(packet: MIDIPacket(data, timestamp: timestamp))
}
internal init(packet: MIDIPacket) {
self.init(numPackets: 1, packet: packet)
}
func clone() -> Self {
fatalError()
}
}
extension UnsafeMutablePointer where Pointee == UInt8 {
@inline(__always)
init(ptr: UnsafeMutableRawBufferPointer) {
self = ptr.baseAddress!.assumingMemoryBound(to: UInt8.self)
}
}
extension MIDIPacket {
@inline(__always)
internal init<S: Sequence>(_ data: S, timestamp: MIDITimeStamp = 0) where S.Iterator.Element == UInt8 {
self.init()
timeStamp = timestamp
let d = Data(data)
length = UInt16(d.count)
/// write out bytes to data
withUnsafeMutableBytes(of: &self.data) {
d.copyBytes(to: .init(ptr: $0), count: d.count)
}
// var ptr = UnsafeMutableRawBufferPointer(packet: &self)
}
mutating func buffer() -> UnsafeRawBufferPointer {
withUnsafePointer(to: &self.data) {
UnsafeRawBufferPointer(start: $0, count: Int(self.length))
}
}
mutating func mutableBuffer() -> UnsafeMutableRawBufferPointer {
withUnsafePointer(to: &self.data) {
UnsafeMutableRawBufferPointer(start: UnsafeMutablePointer(mutating: $0), count: Int(self.length))
}
}
// internal init(data: UnsafeRawBufferPointer, timestamp: MIDITimeStamp = 0) {
// self.init()
// withUnsafeMutablePointer(to: &self.data) {
// data.copyBytes(to: <#T##UnsafeMutableRawBufferPointer#>)
// }
//
// }
}
// extension Data {
// @inline(__always)
// init(packet p: inout MIDIPacket) {
// self = Swift.withUnsafeBytes(of: &p.data) {
// .init(bytes: $0.baseAddress!, count: Int(p.length))
// }
// }
// }
//
// extension MIDIEvent {
// @inline(__always)
// fileprivate init(packet p: inout MIDIPacket) {
// timestamp = p.timeStamp
// data = .init(packet: &p)
// }
// }
// extension MIDIPacketList: Sequence {
// public typealias Element = MIDIEvent
//
// public func makeIterator() -> AnyIterator<Element> {
// var p: MIDIPacket = packet
// var idx: UInt32 = 0
//
// return AnyIterator {
// guard idx < self.numPackets else {
// return nil
// }
// defer {
// p = MIDIPacketNext(&p).pointee
// idx += 1
// }
// return .init(packet: &p)
// }
// }
// }
extension MIDIPacketList: Sequence {
public typealias Element = UnsafeMutablePointer<MIDIPacket>
public func makeIterator() -> AnyIterator<Element> {
var idx = 0
let count = self.numPackets
return withUnsafePointer(to: packet) { ptr in
var p = UnsafeMutablePointer(mutating: ptr)
return AnyIterator {
guard idx < count else { return nil }
defer {
p = MIDIPacketNext(p)
idx += 1
}
return p
}
}
}
}
extension UnsafeMutablePointer where Pointee == MIDIPacket {
// public var count: Int {
// Int(self.pointee.length)
// }
//
//// var bufferPointer: UnsafeMutableBufferPointer<UInt8> {
//// withUnsafePointer(to: self.pointee.data) { ptr in
//// return ptr.withMemoryRebound(to: UInt8.self, capacity: count) { ptr1 in
//// return UnsafeMutableBufferPointer(start: UnsafeMutablePointer(mutating: ptr1), count: self.count)
//// }
//// }
//// }
// mutating func buffer() -> UnsafeMutableRawBufferPointer {
// self.pointee.buff
// }
}
// extension MIDIPacketList: Sequence {
// public typealias Element = MIDIPacket
//
// public func makeIterator() -> AnyIterator<Element> {
// var p: MIDIPacket = packet
// var idx: UInt32 = 0
//
// return AnyIterator {
// guard idx < self.numPackets else {
// return nil
// }
// defer {
// p = MIDIPacketNext(&p).pointee
// idx += 1
// }
// return p
// }
// }
// }
//
// extension MIDIPacketList: MutableCollection {
// public typealias Index = Int
//
// public var startIndex: Index {
// 0
// }
//
// public var endIndex: Index {
// Int(self.numPackets)
// }
//
// public subscript(position: Index) -> Element {
// get {
// withUnsafeBytes(of: &self.packet) { idx in
//
// }
//
// fatalError()
// }
// set {
// fatalError()
// }
// }
//
// public func index(after i: Index) -> Index {
// i + 1
// }
// }
extension UnsafePointer: Sequence where Pointee == MIDIPacketList {
public typealias Element = UnsafeMutablePointer<MIDIPacket>
public func makeIterator() -> AnyIterator<Element> {
self.pointee.makeIterator()
}
}
| mit | aa7ed110593c68167a442b0322004616 | 27.566372 | 117 | 0.566914 | 4.298269 | false | false | false | false |
icecrystal23/ios-charts | Source/Charts/Charts/BarLineChartViewBase.swift | 2 | 69450 | //
// BarLineChartViewBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
open class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, NSUIGestureRecognizerDelegate
{
/// the maximum number of entries to which values will be drawn
/// (entry numbers greater than this value will cause value-labels to disappear)
internal var _maxVisibleCount = 100
/// flag that indicates if auto scaling on the y axis is enabled
private var _autoScaleMinMaxEnabled = false
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragXEnabled = true
private var _dragYEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
@objc open var gridBackgroundColor = NSUIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
@objc open var borderColor = NSUIColor.black
@objc open var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
@objc open var drawGridBackgroundEnabled = false
/// When enabled, the borders rectangle will be rendered.
/// If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
@objc open var drawBordersEnabled = false
/// When enabled, the values will be clipped to contentRect, otherwise they can bleed outside the content rect.
@objc open var clipValuesToContentEnabled: Bool = false
/// When disabled, the data and/or highlights will not be clipped to contentRect. Disabling this option can
/// be useful, when the data lies fully within the content rect, but is drawn in such a way (such as thick lines)
/// that there is unwanted clipping.
@objc open var clipDataToContentEnabled: Bool = true
/// Sets the minimum offset (padding) around the chart, defaults to 10
@objc open var minOffset = CGFloat(10.0)
/// Sets whether the chart should keep its position (zoom / scroll) after a rotation (orientation change)
/// **default**: false
@objc open var keepPositionOnRotation: Bool = false
/// The left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
@objc open internal(set) var leftAxis = YAxis(position: .left)
/// The right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
@objc open internal(set) var rightAxis = YAxis(position: .right)
/// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of YAxisRenderer
@objc open lazy var leftYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: leftAxis, transformer: _leftAxisTransformer)
/// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of YAxisRenderer
@objc open lazy var rightYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: rightAxis, transformer: _rightAxisTransformer)
internal var _leftAxisTransformer: Transformer!
internal var _rightAxisTransformer: Transformer!
/// The X axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of XAxisRenderer
@objc open lazy var xAxisRenderer = XAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer)
internal var _tapGestureRecognizer: NSUITapGestureRecognizer!
internal var _doubleTapGestureRecognizer: NSUITapGestureRecognizer!
#if !os(tvOS)
internal var _pinchGestureRecognizer: NSUIPinchGestureRecognizer!
#endif
internal var _panGestureRecognizer: NSUIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
stopDeceleration()
}
internal override func initialize()
{
super.initialize()
_leftAxisTransformer = Transformer(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = Transformer(viewPortHandler: _viewPortHandler)
self.highlighter = ChartHighlighter(chart: self)
_tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:)))
_doubleTapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(doubleTapGestureRecognized(_:)))
_doubleTapGestureRecognizer.nsuiNumberOfTapsRequired = 2
_panGestureRecognizer = NSUIPanGestureRecognizer(target: self, action: #selector(panGestureRecognized(_:)))
_panGestureRecognizer.delegate = self
self.addGestureRecognizer(_tapGestureRecognizer)
self.addGestureRecognizer(_doubleTapGestureRecognizer)
self.addGestureRecognizer(_panGestureRecognizer)
_doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled
_panGestureRecognizer.isEnabled = _dragXEnabled || _dragYEnabled
#if !os(tvOS)
_pinchGestureRecognizer = NSUIPinchGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.pinchGestureRecognized(_:)))
_pinchGestureRecognizer.delegate = self
self.addGestureRecognizer(_pinchGestureRecognizer)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
// Saving current position of chart.
var oldPoint: CGPoint?
if (keepPositionOnRotation && (keyPath == "frame" || keyPath == "bounds"))
{
oldPoint = viewPortHandler.contentRect.origin
getTransformer(forAxis: .left).pixelToValues(&oldPoint!)
}
// Superclass transforms chart.
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
// Restoring old position of chart
if var newPoint = oldPoint , keepPositionOnRotation
{
getTransformer(forAxis: .left).pointValueToPixel(&newPoint)
viewPortHandler.centerViewPort(pt: newPoint, chart: self)
}
else
{
viewPortHandler.refresh(newMatrix: viewPortHandler.touchMatrix, chart: self, invalidate: true)
}
}
open override func draw(_ rect: CGRect)
{
super.draw(rect)
guard data != nil, let renderer = renderer else { return }
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
// execute all drawing commands
drawGridBackground(context: context)
if _autoScaleMinMaxEnabled
{
autoScale()
}
if leftAxis.isEnabled
{
leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted)
}
if rightAxis.isEnabled
{
rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted)
}
if _xAxis.isEnabled
{
xAxisRenderer.computeAxis(min: _xAxis._axisMinimum, max: _xAxis._axisMaximum, inverted: false)
}
xAxisRenderer.renderAxisLine(context: context)
leftYAxisRenderer.renderAxisLine(context: context)
rightYAxisRenderer.renderAxisLine(context: context)
// The renderers are responsible for clipping, to account for line-width center etc.
xAxisRenderer.renderGridLines(context: context)
leftYAxisRenderer.renderGridLines(context: context)
rightYAxisRenderer.renderGridLines(context: context)
if _xAxis.isEnabled && _xAxis.isDrawLimitLinesBehindDataEnabled
{
xAxisRenderer.renderLimitLines(context: context)
}
if leftAxis.isEnabled && leftAxis.isDrawLimitLinesBehindDataEnabled
{
leftYAxisRenderer.renderLimitLines(context: context)
}
if rightAxis.isEnabled && rightAxis.isDrawLimitLinesBehindDataEnabled
{
rightYAxisRenderer.renderLimitLines(context: context)
}
context.saveGState()
// make sure the data cannot be drawn outside the content-rect
if clipDataToContentEnabled {
context.clip(to: _viewPortHandler.contentRect)
}
renderer.drawData(context: context)
// if highlighting is enabled
if (valuesToHighlight())
{
renderer.drawHighlighted(context: context, indices: _indicesToHighlight)
}
context.restoreGState()
renderer.drawExtras(context: context)
if _xAxis.isEnabled && !_xAxis.isDrawLimitLinesBehindDataEnabled
{
xAxisRenderer.renderLimitLines(context: context)
}
if leftAxis.isEnabled && !leftAxis.isDrawLimitLinesBehindDataEnabled
{
leftYAxisRenderer.renderLimitLines(context: context)
}
if rightAxis.isEnabled && !rightAxis.isDrawLimitLinesBehindDataEnabled
{
rightYAxisRenderer.renderLimitLines(context: context)
}
xAxisRenderer.renderAxisLabels(context: context)
leftYAxisRenderer.renderAxisLabels(context: context)
rightYAxisRenderer.renderAxisLabels(context: context)
if clipValuesToContentEnabled
{
context.saveGState()
context.clip(to: _viewPortHandler.contentRect)
renderer.drawValues(context: context)
context.restoreGState()
}
else
{
renderer.drawValues(context: context)
}
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
private var _autoScaleLastLowestVisibleX: Double?
private var _autoScaleLastHighestVisibleX: Double?
/// Performs auto scaling of the axis by recalculating the minimum and maximum y-values based on the entries currently in view.
internal func autoScale()
{
guard let data = _data
else { return }
data.calcMinMaxY(fromX: self.lowestVisibleX, toX: self.highestVisibleX)
_xAxis.calculate(min: data.xMin, max: data.xMax)
// calculate axis range (min / max) according to provided data
if leftAxis.isEnabled
{
leftAxis.calculate(min: data.getYMin(axis: .left), max: data.getYMax(axis: .left))
}
if rightAxis.isEnabled
{
rightAxis.calculate(min: data.getYMin(axis: .right), max: data.getYMax(axis: .right))
}
calculateOffsets()
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(rightAxis.axisRange), chartYMin: rightAxis._axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(leftAxis.axisRange), chartYMin: leftAxis._axisMinimum)
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(inverted: rightAxis.isInverted)
_leftAxisTransformer.prepareMatrixOffset(inverted: leftAxis.isInverted)
}
open override func notifyDataSetChanged()
{
renderer?.initBuffers()
calcMinMax()
leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted)
rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted)
if let data = _data
{
xAxisRenderer.computeAxis(
min: _xAxis._axisMinimum,
max: _xAxis._axisMaximum,
inverted: false)
if _legend !== nil
{
legendRenderer?.computeLegend(data: data)
}
}
calculateOffsets()
setNeedsDisplay()
}
internal override func calcMinMax()
{
// calculate / set x-axis range
_xAxis.calculate(min: _data?.xMin ?? 0.0, max: _data?.xMax ?? 0.0)
// calculate axis range (min / max) according to provided data
leftAxis.calculate(min: _data?.getYMin(axis: .left) ?? 0.0, max: _data?.getYMax(axis: .left) ?? 0.0)
rightAxis.calculate(min: _data?.getYMin(axis: .right) ?? 0.0, max: _data?.getYMax(axis: .right) ?? 0.0)
}
internal func calculateLegendOffsets(offsetLeft: inout CGFloat, offsetTop: inout CGFloat, offsetRight: inout CGFloat, offsetBottom: inout CGFloat)
{
// setup offsets for legend
if _legend !== nil && _legend.isEnabled && !_legend.drawInside
{
switch _legend.orientation
{
case .vertical:
switch _legend.horizontalAlignment
{
case .left:
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset
case .right:
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset
case .center:
switch _legend.verticalAlignment
{
case .top:
offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
case .bottom:
offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
default:
break
}
}
case .horizontal:
switch _legend.verticalAlignment
{
case .top:
offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
if xAxis.isEnabled && xAxis.isDrawLabelsEnabled
{
offsetTop += xAxis.labelRotatedHeight
}
case .bottom:
offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
if xAxis.isEnabled && xAxis.isDrawLabelsEnabled
{
offsetBottom += xAxis.labelRotatedHeight
}
default:
break
}
}
}
}
internal override func calculateOffsets()
{
if !_customViewPortEnabled
{
var offsetLeft = CGFloat(0.0)
var offsetRight = CGFloat(0.0)
var offsetTop = CGFloat(0.0)
var offsetBottom = CGFloat(0.0)
calculateLegendOffsets(offsetLeft: &offsetLeft,
offsetTop: &offsetTop,
offsetRight: &offsetRight,
offsetBottom: &offsetBottom)
// offsets for y-labels
if leftAxis.needsOffset
{
offsetLeft += leftAxis.requiredSize().width
}
if rightAxis.needsOffset
{
offsetRight += rightAxis.requiredSize().width
}
if xAxis.isEnabled && xAxis.isDrawLabelsEnabled
{
let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset
// offsets for x-labels
if xAxis.labelPosition == .bottom
{
offsetBottom += xlabelheight
}
else if xAxis.labelPosition == .top
{
offsetTop += xlabelheight
}
else if xAxis.labelPosition == .bothSided
{
offsetBottom += xlabelheight
offsetTop += xlabelheight
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
_viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
}
prepareOffsetMatrix()
prepareValuePxMatrix()
}
/// draws the grid background
internal func drawGridBackground(context: CGContext)
{
if drawGridBackgroundEnabled || drawBordersEnabled
{
context.saveGState()
}
if drawGridBackgroundEnabled
{
// draw the grid background
context.setFillColor(gridBackgroundColor.cgColor)
context.fill(_viewPortHandler.contentRect)
}
if drawBordersEnabled
{
context.setLineWidth(borderLineWidth)
context.setStrokeColor(borderColor.cgColor)
context.stroke(_viewPortHandler.contentRect)
}
if drawGridBackgroundEnabled || drawBordersEnabled
{
context.restoreGState()
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case both
case x
case y
}
private var _isDragging = false
private var _isScaling = false
private var _gestureScaleAxis = GestureScaleAxis.both
private var _closestDataSetToTouch: IChartDataSet!
private var _panGestureReachedEdge: Bool = false
private weak var _outerScrollView: NSUIScrollView?
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: TimeInterval = 0.0
private var _decelerationDisplayLink: NSUIDisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer)
{
if _data === nil
{
return
}
if recognizer.state == NSUIGestureRecognizerState.ended
{
if !isHighLightPerTapEnabled { return }
let h = getHighlightByTouchPoint(recognizer.location(in: self))
if h === nil || h == self.lastHighlighted
{
lastHighlighted = nil
highlightValue(nil, callDelegate: true)
}
else
{
lastHighlighted = h
highlightValue(h, callDelegate: true)
}
}
}
@objc private func doubleTapGestureRecognized(_ recognizer: NSUITapGestureRecognizer)
{
if _data === nil
{
return
}
if recognizer.state == NSUIGestureRecognizerState.ended
{
if _data !== nil && _doubleTapToZoomEnabled && (data?.entryCount ?? 0) > 0
{
var location = recognizer.location(in: self)
location.x = location.x - _viewPortHandler.offsetLeft
if isTouchInverted()
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom)
}
self.zoom(scaleX: isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y)
}
}
}
#if !os(tvOS)
@objc private func pinchGestureRecognized(_ recognizer: NSUIPinchGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.began
{
stopDeceleration()
if _data !== nil &&
(_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)
{
_isScaling = true
if _pinchZoomEnabled
{
_gestureScaleAxis = .both
}
else
{
let x = abs(recognizer.location(in: self).x - recognizer.nsuiLocationOfTouch(1, inView: self).x)
let y = abs(recognizer.location(in: self).y - recognizer.nsuiLocationOfTouch(1, inView: self).y)
if _scaleXEnabled != _scaleYEnabled
{
_gestureScaleAxis = _scaleXEnabled ? .x : .y
}
else
{
_gestureScaleAxis = x > y ? .x : .y
}
}
}
}
else if recognizer.state == NSUIGestureRecognizerState.ended ||
recognizer.state == NSUIGestureRecognizerState.cancelled
{
if _isScaling
{
_isScaling = false
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
else if recognizer.state == NSUIGestureRecognizerState.changed
{
let isZoomingOut = (recognizer.nsuiScale < 1)
var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX
var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY
if _isScaling
{
canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .x)
canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .y)
if canZoomMoreX || canZoomMoreY
{
var location = recognizer.location(in: self)
location.x = location.x - _viewPortHandler.offsetLeft
if isTouchInverted()
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom)
}
let scaleX = canZoomMoreX ? recognizer.nsuiScale : 1.0
let scaleY = canZoomMoreY ? recognizer.nsuiScale : 1.0
var matrix = CGAffineTransform(translationX: location.x, y: location.y)
matrix = matrix.scaledBy(x: scaleX, y: scaleY)
matrix = matrix.translatedBy(x: -location.x, y: -location.y)
matrix = _viewPortHandler.touchMatrix.concatenating(matrix)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if delegate !== nil
{
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY)
}
}
recognizer.nsuiScale = 1.0
}
}
}
#endif
@objc private func panGestureRecognized(_ recognizer: NSUIPanGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.began && recognizer.nsuiNumberOfTouches() > 0
{
stopDeceleration()
if _data === nil || !self.isDragEnabled
{ // If we have no data, we have nothing to pan and no data to highlight
return
}
// If drag is enabled and we are in a position where there's something to drag:
// * If we're zoomed in, then obviously we have something to drag.
// * If we have a drag offset - we always have something to drag
if !self.hasNoDragOffset || !self.isFullyZoomedOut
{
_isDragging = true
_closestDataSetToTouch = getDataSetByTouchPoint(point: recognizer.nsuiLocationOfTouch(0, inView: self))
var translation = recognizer.translation(in: self)
if !self.dragXEnabled
{
translation.x = 0.0
}
else if !self.dragYEnabled
{
translation.y = 0.0
}
let didUserDrag = translation.x != 0.0 || translation.y != 0.0
// Check to see if user dragged at all and if so, can the chart be dragged by the given amount
if didUserDrag && !performPanChange(translation: translation)
{
if _outerScrollView !== nil
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil
_isDragging = false
}
}
else
{
if _outerScrollView !== nil
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.nsuiIsScrollEnabled = false
}
}
_lastPanPoint = recognizer.translation(in: self)
}
else if self.isHighlightPerDragEnabled
{
// We will only handle highlights on NSUIGestureRecognizerState.Changed
_isDragging = false
}
}
else if recognizer.state == NSUIGestureRecognizerState.changed
{
if _isDragging
{
let originalTranslation = recognizer.translation(in: self)
var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y)
if !self.dragXEnabled
{
translation.x = 0.0
}
else if !self.dragYEnabled
{
translation.y = 0.0
}
let _ = performPanChange(translation: translation)
_lastPanPoint = originalTranslation
}
else if isHighlightPerDragEnabled
{
let h = getHighlightByTouchPoint(recognizer.location(in: self))
let lastHighlighted = self.lastHighlighted
if h != lastHighlighted
{
self.lastHighlighted = h
self.highlightValue(h, callDelegate: true)
}
}
}
else if recognizer.state == NSUIGestureRecognizerState.ended || recognizer.state == NSUIGestureRecognizerState.cancelled
{
if _isDragging
{
if recognizer.state == NSUIGestureRecognizerState.ended && isDragDecelerationEnabled
{
stopDeceleration()
_decelerationLastTime = CACurrentMediaTime()
_decelerationVelocity = recognizer.velocity(in: self)
_decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(BarLineChartViewBase.decelerationLoop))
_decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.common)
}
_isDragging = false
}
if _outerScrollView !== nil
{
_outerScrollView?.nsuiIsScrollEnabled = true
_outerScrollView = nil
}
}
}
private func performPanChange(translation: CGPoint) -> Bool
{
var translation = translation
if isTouchInverted()
{
if self is HorizontalBarChartView
{
translation.x = -translation.x
}
else
{
translation.y = -translation.y
}
}
let originalMatrix = _viewPortHandler.touchMatrix
var matrix = CGAffineTransform(translationX: translation.x, y: translation.y)
matrix = originalMatrix.concatenating(matrix)
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if delegate !== nil
{
delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y)
}
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty
}
private func isTouchInverted() -> Bool
{
return isAnyAxisInverted &&
_closestDataSetToTouch !== nil &&
getAxis(_closestDataSetToTouch.axisDependency).isInverted
}
@objc open func stopDeceleration()
{
if _decelerationDisplayLink !== nil
{
_decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoop.Mode.common)
_decelerationDisplayLink = nil
}
}
@objc private func decelerationLoop()
{
let currentTime = CACurrentMediaTime()
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef
let timeInterval = CGFloat(currentTime - _decelerationLastTime)
let distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
)
if !performPanChange(translation: distance)
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0
_decelerationVelocity.y = 0.0
}
_decelerationLastTime = currentTime
if abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001
{
stopDeceleration()
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
private func nsuiGestureRecognizerShouldBegin(_ gestureRecognizer: NSUIGestureRecognizer) -> Bool
{
if gestureRecognizer == _panGestureRecognizer
{
let velocity = _panGestureRecognizer.velocity(in: self)
if _data === nil || !isDragEnabled ||
(self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled) ||
(!_dragYEnabled && abs(velocity.y) > abs(velocity.x)) ||
(!_dragXEnabled && abs(velocity.y) < abs(velocity.x))
{
return false
}
}
else
{
#if !os(tvOS)
if gestureRecognizer == _pinchGestureRecognizer
{
if _data === nil || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)
{
return false
}
}
#endif
}
return true
}
#if !os(OSX)
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool
{
if !super.gestureRecognizerShouldBegin(gestureRecognizer)
{
return false
}
return nsuiGestureRecognizerShouldBegin(gestureRecognizer)
}
#endif
#if os(OSX)
public func gestureRecognizerShouldBegin(gestureRecognizer: NSGestureRecognizer) -> Bool
{
return nsuiGestureRecognizerShouldBegin(gestureRecognizer)
}
#endif
open func gestureRecognizer(_ gestureRecognizer: NSUIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: NSUIGestureRecognizer) -> Bool
{
#if !os(tvOS)
if ((gestureRecognizer is NSUIPinchGestureRecognizer && otherGestureRecognizer is NSUIPanGestureRecognizer) ||
(gestureRecognizer is NSUIPanGestureRecognizer && otherGestureRecognizer is NSUIPinchGestureRecognizer))
{
return true
}
#endif
if gestureRecognizer is NSUIPanGestureRecognizer,
otherGestureRecognizer is NSUIPanGestureRecognizer,
gestureRecognizer == _panGestureRecognizer
{
var scrollView = self.superview
while scrollView != nil && !(scrollView is NSUIScrollView)
{
scrollView = scrollView?.superview
}
// If there is two scrollview together, we pick the superview of the inner scrollview.
// In the case of UITableViewWrepperView, the superview will be UITableView
if let superViewOfScrollView = scrollView?.superview,
superViewOfScrollView is NSUIScrollView
{
scrollView = superViewOfScrollView
}
var foundScrollView = scrollView as? NSUIScrollView
if !(foundScrollView?.nsuiIsScrollEnabled ?? true)
{
foundScrollView = nil
}
let scrollViewPanGestureRecognizer = foundScrollView?.nsuiGestureRecognizers?.first {
$0 is NSUIPanGestureRecognizer
}
if otherGestureRecognizer === scrollViewPanGestureRecognizer
{
_outerScrollView = foundScrollView
return true
}
}
return false
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4, into the charts center.
@objc open func zoomIn()
{
let center = _viewPortHandler.contentCenter
let matrix = _viewPortHandler.zoomIn(x: center.x, y: -center.y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out by 0.7, from the charts center.
@objc open func zoomOut()
{
let center = _viewPortHandler.contentCenter
let matrix = _viewPortHandler.zoomOut(x: center.x, y: -center.y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out to original size.
@objc open func resetZoom()
{
let matrix = _viewPortHandler.resetZoom()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter x:
/// - parameter y:
@objc open func zoom(
scaleX: CGFloat,
scaleY: CGFloat,
x: CGFloat,
y: CGFloat)
{
let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor.
/// x and y are the values (**not pixels**) of the zoom center.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis:
@objc open func zoom(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency)
{
let job = ZoomViewJob(
viewPortHandler: viewPortHandler,
scaleX: scaleX,
scaleY: scaleY,
xValue: xValue,
yValue: yValue,
transformer: getTransformer(forAxis: axis),
axis: axis,
view: self)
addViewportJob(job)
}
/// Zooms to the center of the chart with the given scale factor.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis:
@objc open func zoomToCenter(
scaleX: CGFloat,
scaleY: CGFloat)
{
let center = centerOffsets
let matrix = viewPortHandler.zoom(
scaleX: scaleX,
scaleY: scaleY,
x: center.x,
y: -center.y)
viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - parameter scaleX:
/// - parameter scaleY:
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let origin = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let job = AnimatedZoomViewJob(
viewPortHandler: viewPortHandler,
transformer: getTransformer(forAxis: axis),
view: self,
yAxis: getAxis(axis),
xAxisRange: _xAxis.axisRange,
scaleX: scaleX,
scaleY: scaleY,
xOrigin: viewPortHandler.scaleX,
yOrigin: viewPortHandler.scaleY,
zoomCenterX: CGFloat(xValue),
zoomCenterY: CGFloat(yValue),
zoomOriginX: origin.x,
zoomOriginY: origin.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - parameter scaleX:
/// - parameter scaleY:
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - parameter scaleX:
/// - parameter scaleY:
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
@objc open func fitScreen()
{
let matrix = _viewPortHandler.fitScreen()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
calculateOffsets()
setNeedsDisplay()
}
/// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen
@objc open func setScaleMinima(_ scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX)
_viewPortHandler.setMinimumScaleY(scaleY)
}
@objc open var visibleXRange: Double
{
return abs(highestVisibleX - lowestVisibleX)
}
/// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zooming out allowed).
///
/// If this is e.g. set to 10, no more than a range of 10 values on the x-axis can be viewed at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRangeMaximum(_ maxXRange: Double)
{
let xScale = _xAxis.axisRange / maxXRange
_viewPortHandler.setMinimumScaleX(CGFloat(xScale))
}
/// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed).
///
/// If this is e.g. set to 10, no less than a range of 10 values on the x-axis can be viewed at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRangeMinimum(_ minXRange: Double)
{
let xScale = _xAxis.axisRange / minXRange
_viewPortHandler.setMaximumScaleX(CGFloat(xScale))
}
/// Limits the maximum and minimum value count that can be visible by pinching and zooming.
///
/// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed
/// at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRange(minXRange: Double, maxXRange: Double)
{
let minScale = _xAxis.axisRange / maxXRange
let maxScale = _xAxis.axisRange / minXRange
_viewPortHandler.setMinMaxScaleX(
minScaleX: CGFloat(minScale),
maxScaleX: CGFloat(maxScale))
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// - parameter yRange:
/// - parameter axis: - the axis for which this limit should apply
@objc open func setVisibleYRangeMaximum(_ maxYRange: Double, axis: YAxis.AxisDependency)
{
let yScale = getAxisRange(axis: axis) / maxYRange
_viewPortHandler.setMinimumScaleY(CGFloat(yScale))
}
/// Sets the size of the area (range on the y-axis) that should be minimum visible at once, no further zooming in possible.
///
/// - parameter yRange:
/// - parameter axis: - the axis for which this limit should apply
@objc open func setVisibleYRangeMinimum(_ minYRange: Double, axis: YAxis.AxisDependency)
{
let yScale = getAxisRange(axis: axis) / minYRange
_viewPortHandler.setMaximumScaleY(CGFloat(yScale))
}
/// Limits the maximum and minimum y range that can be visible by pinching and zooming.
///
/// - parameter minYRange:
/// - parameter maxYRange:
/// - parameter axis:
@objc open func setVisibleYRange(minYRange: Double, maxYRange: Double, axis: YAxis.AxisDependency)
{
let minScale = getAxisRange(axis: axis) / minYRange
let maxScale = getAxisRange(axis: axis) / maxYRange
_viewPortHandler.setMinMaxScaleY(minScaleY: CGFloat(minScale), maxScaleY: CGFloat(maxScale))
}
/// Moves the left side of the current viewport to the specified x-value.
/// This also refreshes the chart by calling setNeedsDisplay().
@objc open func moveViewToX(_ xValue: Double)
{
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: 0.0,
transformer: getTransformer(forAxis: .left),
view: self)
addViewportJob(job)
}
/// Centers the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
@objc open func moveViewToY(_ yValue: Double, axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: 0.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
@objc open func moveViewTo(xValue: Double, yValue: Double, axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let bounds = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = AnimatedMoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self,
xOrigin: bounds.x,
yOrigin: bounds.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
moveViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
moveViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// This will move the center of the current viewport to the specified x-value and y-value.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
@objc open func centerViewTo(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let xInView = xAxis.axisRange / Double(_viewPortHandler.scaleX)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue - xInView / 2.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let bounds = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let xInView = xAxis.axisRange / Double(_viewPortHandler.scaleX)
let job = AnimatedMoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue - xInView / 2.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self,
xOrigin: bounds.x,
yOrigin: bounds.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
centerViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
centerViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this.
/// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`.
@objc open func setViewPortOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true
if Thread.isMainThread
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom)
prepareOffsetMatrix()
prepareValuePxMatrix()
}
else
{
DispatchQueue.main.async(execute: {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom)
})
}
}
/// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically.
@objc open func resetViewPortOffsets()
{
_customViewPortEnabled = false
calculateOffsets()
}
// MARK: - Accessors
/// - returns: The range of the specified axis.
@objc open func getAxisRange(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
return leftAxis.axisRange
}
else
{
return rightAxis.axisRange
}
}
/// - returns: The position (in pixels) the provided Entry has inside the chart view
@objc open func getPosition(entry e: ChartDataEntry, axis: YAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y))
getTransformer(forAxis: axis).pointValueToPixel(&vals)
return vals
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
@objc open var dragEnabled: Bool
{
get
{
return _dragXEnabled || _dragYEnabled
}
set
{
_dragYEnabled = newValue
_dragXEnabled = newValue
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
@objc open var isDragEnabled: Bool
{
return dragEnabled
}
/// is dragging on the X axis enabled?
@objc open var dragXEnabled: Bool
{
get
{
return _dragXEnabled
}
set
{
_dragXEnabled = newValue
}
}
/// is dragging on the Y axis enabled?
@objc open var dragYEnabled: Bool
{
get
{
return _dragYEnabled
}
set
{
_dragYEnabled = newValue
}
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
@objc open func setScaleEnabled(_ enabled: Bool)
{
if _scaleXEnabled != enabled || _scaleYEnabled != enabled
{
_scaleXEnabled = enabled
_scaleYEnabled = enabled
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
@objc open var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if _scaleXEnabled != newValue
{
_scaleXEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
@objc open var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if _scaleYEnabled != newValue
{
_scaleYEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
@objc open var isScaleXEnabled: Bool { return scaleXEnabled }
@objc open var isScaleYEnabled: Bool { return scaleYEnabled }
/// flag that indicates if double tap zoom is enabled or not
@objc open var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled
}
set
{
if _doubleTapToZoomEnabled != newValue
{
_doubleTapToZoomEnabled = newValue
_doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled
}
}
}
/// **default**: true
/// - returns: `true` if zooming via double-tap is enabled `false` ifnot.
@objc open var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
@objc open var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a `NSUIScrollView`
///
/// **default**: true
@objc open var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled
}
/// **default**: true
/// - returns: `true` if drawing the grid background is enabled, `false` ifnot.
@objc open var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled
}
/// **default**: false
/// - returns: `true` if drawing the borders rectangle is enabled, `false` ifnot.
@objc open var isDrawBordersEnabled: Bool
{
return drawBordersEnabled
}
/// - returns: The x and y values in the chart at the given touch point
/// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// `getPixelsForValues(...)`.
@objc open func valueForTouchPoint(point pt: CGPoint, axis: YAxis.AxisDependency) -> CGPoint
{
return getTransformer(forAxis: axis).valueForTouchPoint(pt)
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to `valueForTouchPoint(...)`.
@objc open func pixelForValues(x: Double, y: Double, axis: YAxis.AxisDependency) -> CGPoint
{
return getTransformer(forAxis: axis).pixelForValues(x: x, y: y)
}
/// - returns: The Entry object displayed at the touched position of the chart
@objc open func getEntryByTouchPoint(point pt: CGPoint) -> ChartDataEntry!
{
if let h = getHighlightByTouchPoint(pt)
{
return _data!.entryForHighlight(h)
}
return nil
}
/// - returns: The DataSet object displayed at the touched position of the chart
@objc open func getDataSetByTouchPoint(point pt: CGPoint) -> IBarLineScatterCandleBubbleChartDataSet?
{
let h = getHighlightByTouchPoint(pt)
if h !== nil
{
return _data?.getDataSetByIndex(h!.dataSetIndex) as? IBarLineScatterCandleBubbleChartDataSet
}
return nil
}
/// - returns: The current x-scale factor
@objc open var scaleX: CGFloat
{
if _viewPortHandler === nil
{
return 1.0
}
return _viewPortHandler.scaleX
}
/// - returns: The current y-scale factor
@objc open var scaleY: CGFloat
{
if _viewPortHandler === nil
{
return 1.0
}
return _viewPortHandler.scaleY
}
/// if the chart is fully zoomed out, return true
@objc open var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut }
/// - returns: The y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
@objc open func getAxis(_ axis: YAxis.AxisDependency) -> YAxis
{
if axis == .left
{
return leftAxis
}
else
{
return rightAxis
}
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately
@objc open var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled
}
set
{
if _pinchZoomEnabled != newValue
{
_pinchZoomEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
/// **default**: false
/// - returns: `true` if pinch-zoom is enabled, `false` ifnot
@objc open var isPinchZoomEnabled: Bool { return pinchZoomEnabled }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
@objc open func setDragOffsetX(_ offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset)
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
@objc open func setDragOffsetY(_ offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset)
}
/// - returns: `true` if both drag offsets (x and y) are zero or smaller.
@objc open var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset }
open override var chartYMax: Double
{
return max(leftAxis._axisMaximum, rightAxis._axisMaximum)
}
open override var chartYMin: Double
{
return min(leftAxis._axisMinimum, rightAxis._axisMinimum)
}
/// - returns: `true` if either the left or the right or both axes are inverted.
@objc open var isAnyAxisInverted: Bool
{
return leftAxis.isInverted || rightAxis.isInverted
}
/// flag that indicates if auto scaling on the y axis is enabled.
/// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes
@objc open var autoScaleMinMaxEnabled: Bool
{
get { return _autoScaleMinMaxEnabled }
set { _autoScaleMinMaxEnabled = newValue }
}
/// **default**: false
/// - returns: `true` if auto scaling on the y axis is enabled.
@objc open var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled }
/// Sets a minimum width to the specified y axis.
@objc open func setYAxisMinWidth(_ axis: YAxis.AxisDependency, width: CGFloat)
{
if axis == .left
{
leftAxis.minWidth = width
}
else
{
rightAxis.minWidth = width
}
}
/// **default**: 0.0
/// - returns: The (custom) minimum width of the specified Y axis.
@objc open func getYAxisMinWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.minWidth
}
else
{
return rightAxis.minWidth
}
}
/// Sets a maximum width to the specified y axis.
/// Zero (0.0) means there's no maximum width
@objc open func setYAxisMaxWidth(_ axis: YAxis.AxisDependency, width: CGFloat)
{
if axis == .left
{
leftAxis.maxWidth = width
}
else
{
rightAxis.maxWidth = width
}
}
/// Zero (0.0) means there's no maximum width
///
/// **default**: 0.0 (no maximum specified)
/// - returns: The (custom) maximum width of the specified Y axis.
@objc open func getYAxisMaxWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.maxWidth
}
else
{
return rightAxis.maxWidth
}
}
/// - returns the width of the specified y axis.
@objc open func getYAxisWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.requiredSize().width
}
else
{
return rightAxis.requiredSize().width
}
}
// MARK: - BarLineScatterCandleBubbleChartDataProvider
/// - returns: The Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
open func getTransformer(forAxis axis: YAxis.AxisDependency) -> Transformer
{
if axis == .left
{
return _leftAxisTransformer
}
else
{
return _rightAxisTransformer
}
}
/// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled
open override var maxVisibleCount: Int
{
get
{
return _maxVisibleCount
}
set
{
_maxVisibleCount = newValue
}
}
open func isInverted(axis: YAxis.AxisDependency) -> Bool
{
return getAxis(axis).isInverted
}
/// - returns: The lowest x-index (value on the x-axis) that is still visible on he chart.
open var lowestVisibleX: Double
{
var pt = CGPoint(
x: viewPortHandler.contentLeft,
y: viewPortHandler.contentBottom)
getTransformer(forAxis: .left).pixelToValues(&pt)
return max(xAxis._axisMinimum, Double(pt.x))
}
/// - returns: The highest x-index (value on the x-axis) that is still visible on the chart.
open var highestVisibleX: Double
{
var pt = CGPoint(
x: viewPortHandler.contentRight,
y: viewPortHandler.contentBottom)
getTransformer(forAxis: .left).pixelToValues(&pt)
return min(xAxis._axisMaximum, Double(pt.x))
}
}
| apache-2.0 | b9be34128fc25408ce5f71865ed1867e | 34.872934 | 238 | 0.585774 | 5.541813 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/LanguageViewController.swift | 1 | 5133 | import Foundation
import WordPressShared
/// This class will display the Blog's Language setting, and will allow the user to pick a new value.
/// Upon selection, WordPress.com backend will get hit, and the new value will be persisted.
///
public class LanguageViewController : UITableViewController
{
/// Callback to be executed whenever the Blog's selected language changes.
///
var onChange : (NSNumber -> Void)?
/// Designated Initializer
///
/// - Parameters
/// - Blog: The blog for which we wanna display the languages picker
///
public convenience init(blog: Blog) {
self.init(style: .Grouped)
self.blog = blog
}
public override func viewDidLoad() {
super.viewDidLoad()
// Setup tableViewController
title = NSLocalizedString("Language", comment: "Title for the Language Picker Screen")
clearsSelectionOnViewWillAppear = false
// Setup tableView
WPStyleGuide.configureColorsForView(view, andTableView: tableView)
WPStyleGuide.resetReadableMarginsForTableView(tableView)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Reload + Clear selection. Let's avoid flickers by dispatching the deselect call asynchronously
tableView.reloadDataPreservingSelection()
dispatch_async(dispatch_get_main_queue()) {
self.tableView.deselectSelectedRowWithAnimation(true)
}
}
// MARK: - UITableViewDataSource Methods
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
if cell == nil {
cell = WPTableViewCell(style: .Value1, reuseIdentifier: reuseIdentifier)
cell?.accessoryType = .DisclosureIndicator
WPStyleGuide.configureTableViewCell(cell)
}
configureTableViewCell(cell!)
return cell!
}
public override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return WPTableViewSectionHeaderFooterView.heightForFooter(footerText, width: view.bounds.width)
}
public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let headerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer)
headerView.title = footerText
return headerView
}
// MARK: - UITableViewDelegate Methods
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
pressedLanguageRow()
}
// MARK: - Private Methods
private func configureTableViewCell(cell: UITableViewCell) {
let languageId = blog.settings.languageID.integerValue
cell.textLabel?.text = NSLocalizedString("Language", comment: "Language of the current blog")
cell.detailTextLabel?.text = Languages.sharedInstance.nameForLanguageWithId(languageId)
}
private func pressedLanguageRow() {
// Setup Properties
let headers = [
NSLocalizedString("Popular languages", comment: "Section title for Popular Languages"),
NSLocalizedString("All languages", comment: "Section title for All Languages")
]
let languages = Languages.sharedInstance.grouped
let titles = languages.map { $0.map { $0.name } }
let subtitles = languages.map { $0.map { $0.description } }
let values = languages.map { $0.map { $0.languageId } } as [[NSObject]]
// Setup ListPickerViewController
let listViewController = SettingsListPickerViewController(headers: headers, titles: titles, subtitles: subtitles, values: values)
listViewController.title = NSLocalizedString("Site Language", comment: "Title for the Language Picker View")
listViewController.selectedValue = blog.settings.languageID
listViewController.onChange = { [weak self] (selected: AnyObject) in
guard let newLanguageID = selected as? NSNumber else {
return
}
self?.onChange?(newLanguageID)
}
navigationController?.pushViewController(listViewController, animated: true)
}
// MARK: - Private Constants
private let reuseIdentifier = "reuseIdentifier"
private let footerText = NSLocalizedString("The language in which this site is primarily written.",
comment: "Footer Text displayed in Blog Language Settings View")
// MARK: - Private Properties
private var blog : Blog!
}
| gpl-2.0 | e9587822486b8452bb73775a5fb0b3a7 | 37.022222 | 137 | 0.66355 | 5.813137 | false | false | false | false |
alecthomas/FileSystemEvents | Project/Sources/FileSystemEventMonitor.swift | 1 | 3478 | //
// FileSystemEventMonitor.swift
// EonilFileSystemEvents
//
// Created by Hoon H. on 2015/01/17.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
/// - parameter events:
/// An array of `FileSystemEvent` objects. Ordered as provided.
public typealias FileSystemEventMonitorCallback = (events:[FileSystemEvent])->()
public typealias FileSystemEventFlag = EonilFileSystemEventFlag
/// Tailored for use with Swift.
/// This starts monitoring automatically at creation, and stops at deallocation.
/// This notifies all events immediately on the specified GCD queue.
public final class FileSystemEventMonitor {
public convenience init(pathsToWatch:[String], callback:FileSystemEventMonitorCallback) {
self.init(pathsToWatch: pathsToWatch, latency: 0, watchRoot: true, queue: dispatch_get_main_queue(), callback: callback)
}
/// Creates a new instance with everything setup and starts immediately.
///
/// - parameter callback:
/// Called when some events notified. See `FileSystemEventMonitorCallback` for details.
public init(pathsToWatch:[String], latency:NSTimeInterval, watchRoot:Bool, queue:dispatch_queue_t, callback:FileSystemEventMonitorCallback) {
_queue = queue
_callback = callback
let fs1 = kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer
let fs2 = fs1 | (watchRoot ? kFSEventStreamCreateFlagWatchRoot : 0)
let cb = { (stream:ConstFSEventStreamRef, numEvents:Int, eventPaths:UnsafeMutablePointer<Void>, eventFlags:UnsafePointer<FSEventStreamEventFlags>, eventIds:UnsafePointer<FSEventStreamEventId>) -> Void in
let ps = unsafeBitCast(eventPaths, NSArray.self)
var a1 = [] as [FileSystemEvent]
a1.reserveCapacity(numEvents)
for i in 0..<Int(numEvents) {
let path = ps[i] as! NSString as String
let flag = eventFlags[i]
let ID = eventIds[i]
let ev = FileSystemEvent(path: path, flag: FileSystemEventFlag(rawValue: flag), ID: ID)
a1.append(ev)
callback(events: a1)
}
}
let ps2 = pathsToWatch.map({ $0 as NSString }) as [AnyObject]
_lowlevel = EonilJustFSEventStreamWrapper(
allocator : nil,
callback : cb,
pathsToWatch : ps2,
sinceWhen : FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
latency : CFTimeInterval(latency),
flags : FSEventStreamCreateFlags(fs2))
EonilFileSystemEventFlag.UserDropped
_lowlevel.setDispatchQueue(_queue)
_lowlevel.start()
}
deinit {
_lowlevel.stop()
_lowlevel.invalidate()
}
public var queue:dispatch_queue_t {
get {
return _queue
}
}
////
private let _queue:dispatch_queue_t
private let _callback:FileSystemEventMonitorCallback
private let _lowlevel:EonilJustFSEventStreamWrapper
}
public struct FileSystemEvent {
public var path:String
public var flag:FileSystemEventFlag
public var ID:FSEventStreamEventId
}
/// MARK:
extension FileSystemEvent: CustomStringConvertible {
public var description:String {
get {
return "(path: \(path), flag: \(flag), ID: \(ID))"
}
}
}
extension FileSystemEventFlag: CustomStringConvertible {
public var description:String {
get {
let v1 = self.rawValue
var a1 = [] as [String]
for i:UInt32 in 0..<16 {
let v2 = 0b01 << i
let ok = (v2 & v1) > 0
if ok {
let s = NSStringFromFSEventStreamEventFlags(v2)!
a1.append(s)
}
}
let s1 = a1.joinWithSeparator(", ")
return s1
}
}
}
| mit | 07a298952674daf614b4866b5a307831 | 22.5 | 205 | 0.718804 | 3.509586 | false | false | false | false |
oisinlavery/HackingWithSwift | project14-oisin/project14-oisin/GameViewController.swift | 1 | 1402 | //
// GameViewController.swift
// project14-oisin
//
// Created by Oisín Lavery on 12/2/15.
// Copyright (c) 2015 Google. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
// skView.showsFPS = true
// skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| unlicense | d461949f958bd86b81652173e7f86fa7 | 25.433962 | 94 | 0.606709 | 5.430233 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.