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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
niunaruto/DeDaoAppSwift | testSwift/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift | 16 | 2210 | //
// UIBarButtonItem+Rx.swift
// RxCocoa
//
// Created by Daniel Tartaglia on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
import RxSwift
fileprivate var rx_tap_key: UInt8 = 0
extension Reactive where Base: UIBarButtonItem {
/// Bindable sink for `enabled` property.
public var isEnabled: Binder<Bool> {
return Binder(self.base) { element, value in
element.isEnabled = value
}
}
/// Bindable sink for `title` property.
public var title: Binder<String> {
return Binder(self.base) { element, value in
element.title = value
}
}
/// Reactive wrapper for target action pattern on `self`.
public var tap: ControlEvent<()> {
let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in
Observable.create { [weak control = self.base] observer in
guard let control = control else {
observer.on(.completed)
return Disposables.create()
}
let target = BarButtonItemTarget(barButtonItem: control) {
observer.on(.next(()))
}
return target
}
.takeUntil(self.deallocated)
.share()
}
return ControlEvent(events: source)
}
}
@objc
final class BarButtonItemTarget: RxTarget {
typealias Callback = () -> Void
weak var barButtonItem: UIBarButtonItem?
var callback: Callback!
init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) {
self.barButtonItem = barButtonItem
self.callback = callback
super.init()
barButtonItem.target = self
barButtonItem.action = #selector(BarButtonItemTarget.action(_:))
}
override func dispose() {
super.dispose()
#if DEBUG
MainScheduler.ensureRunningOnMainThread()
#endif
barButtonItem?.target = nil
barButtonItem?.action = nil
callback = nil
}
@objc func action(_ sender: AnyObject) {
callback()
}
}
#endif
| mit | 62bceb8484a59425f3bc4f76bd380772 | 24.390805 | 82 | 0.575826 | 4.844298 | false | false | false | false |
adib/Core-ML-Playgrounds | Photo-Explorations/EnlargeImages.playground/Sources/BackgroundPipeline.swift | 1 | 1438 | //
// BackgroundPipeline.swift
// waifu2x-ios
//
// Created by 谢宜 on 2017/11/5.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
class BackgroundPipeline <T> {
/// Count of all input objects
private let count: Int
private var index: Int = 0
private let work_sem = DispatchSemaphore(value: 0)
private let wait_sem = DispatchSemaphore(value: 1)
private let queue = Queue<T>()
private let background: DispatchQueue
/// Constructor
///
/// - Parameters:
/// - name: The unique name of the background thread
/// - count: How many objects will this pipeline receive?
init(_ name: String, count: Int, task: @escaping (Int, T) -> Void) {
self.count = count
background = DispatchQueue(label: name)
background.async {
var index = 0
while index < self.count {
autoreleasepool {
self.work_sem.wait()
task(index, self.queue.dequeue()!)
index += 1
}
}
self.wait_sem.signal()
}
wait_sem.wait()
}
public func appendObject(_ obj: T) {
queue.enqueue(obj)
work_sem.signal()
}
/// Wait for work to complete, must be called
public func wait() {
wait_sem.wait()
wait_sem.signal()
}
}
| bsd-3-clause | b158dcd6d39c18cbb81450881cd72c12 | 23.254237 | 72 | 0.536688 | 4.284431 | false | false | false | false |
jflinter/Dwifft | DwifftExample/Shared/Stuff.swift | 1 | 2249 | //
// Stuff.swift
// DwifftExample
//
// Created by Jack Flintermann on 3/30/17.
// Copyright © 2017 jflinter. All rights reserved.
//
import Foundation
import Dwifft
struct Stuff {
// I shamelessly stole this list of things from my friend Pasquale's blog post because I thought it was funny. You can see it at https://medium.com/elepath-exports/spatial-interfaces-886bccc5d1e9
static func wordStuff() -> SectionedValues<String, String> {
let possibleStuff = [
("foods", [
"Onions",
"Pineapples",
]),
("animal-related", [
"Cats",
"A used lobster",
"Fish legs",
"Adam's apple",
]),
("muddy things", [
"Mud",
]),
("other", [
"Splinters",
"Igloo cream",
"Self-flying car"
])
]
var mutable = [(String, [String])]()
for (key, values) in possibleStuff {
let filtered = values.filter { _ in arc4random_uniform(2) == 0 }
if !filtered.isEmpty { mutable.append((key, filtered)) }
}
return SectionedValues(mutable)
}
static func onlyWordItems() -> [String] {
return Stuff.wordStuff().sectionsAndValues.flatMap() { $0.1 }
}
static func emojiStuff() -> SectionedValues<String, String> {
let possibleStuff = [
("foods", [
"🍆",
"🍑",
"🌯",
]),
("animal-related", [
"🐈",
"🐙",
"🦑",
"🦍",
]),
("muddy things", [
"💩",
]),
("other", [
"🌚",
"🌝",
"🗿"
])
]
var mutable = [(String, [String])]()
for (key, values) in possibleStuff {
let filtered = values.filter { _ in arc4random_uniform(2) == 0 }
if !filtered.isEmpty { mutable.append((key, filtered)) }
}
return SectionedValues(mutable)
}
}
| mit | 7bfba89c5cf36338259f0b9514d6bac3 | 27.397436 | 199 | 0.435666 | 4.412351 | false | false | false | false |
lorentey/swift | test/SILOptimizer/constant_propagation_diagnostics.swift | 5 | 805 | // RUN: %target-swift-frontend -emit-sil -sdk %S/../SILGen/Inputs %s -o /dev/null -verify
// RUN: %target-swift-frontend -enable-ownership-stripping-after-serialization -emit-sil -sdk %S/../SILGen/Inputs %s -o /dev/null -verify
// <rdar://problem/18213320> enum with raw values that are too big are not diagnosed
enum EnumWithTooLargeElements : UInt8 {
case negativeOne = -1 // expected-error 2 {{negative integer '-1' overflows when stored into unsigned type 'UInt8'}}
case one = 1
case two = 2
case three
case twoHundredFiftyFour = 254
case twoHundredFiftyFive
case twoHundredFiftySix // expected-error 2 {{integer literal '256' overflows when stored into 'UInt8'}}
case tooFarByFar = 123456 // expected-error 2 {{integer literal '123456' overflows when stored into 'UInt8'}}
}
| apache-2.0 | b7a69a27489e3ef97150ce618a42eec0 | 56.5 | 137 | 0.724224 | 3.59375 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/longest-substring-without-repeating-characters.swift | 2 | 1168 | /**
* Problem Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
*
* In Swift Language, String doesnt have a native support for subscript. So we convert the String to an Array of String, where each String contains a single character. This will save tons of time, since String manipulation is very expensive operation.
*
* String.characters.count will take Linear time.
*
*/
class Solution {
func lengthOfLongestSubstring(_ ss: String) -> Int {
let s = ss.characters.map({String($0)})
if s.count == 0 {
return 0
}
var dict = [String : Int]()
var maxl = 0
var start = 0
for (i, c) in s.enumerated() {
if let x = dict[c] {
maxl = max(maxl, i - start)
for j in start..<i {
if s[j] == c {
start = j + 1
break
}
dict[s[j]] = nil
}
} else {
dict[c] = i
}
}
maxl = max(maxl, s.count - start)
return maxl
}
}
| mit | 8cd0c730231d6fcba3365d2f5c7191f3 | 29.736842 | 251 | 0.48887 | 4.294118 | false | false | false | false |
matvdg/Triangle | Triangle.swift | 2 | 898 | import UIKit
@IBDesignable class Triangle: UIView {
@IBInspectable var color: UIColor = .red
@IBInspectable var firstPointX: CGFloat = 0
@IBInspectable var firstPointY: CGFloat = 0
@IBInspectable var secondPointX: CGFloat = 0.5
@IBInspectable var secondPointY: CGFloat = 1
@IBInspectable var thirdPointX: CGFloat = 1
@IBInspectable var thirdPointY: CGFloat = 0
override func draw(_ rect: CGRect) {
let aPath = UIBezierPath()
aPath.move(to: CGPoint(x: self.firstPointX * rect.width, y: self.firstPointY * rect.height))
aPath.addLine(to: CGPoint(x: self.secondPointX * rect.width, y: self.secondPointY * rect.height))
aPath.addLine(to: CGPoint(x: self.thirdPointX * rect.width, y: self.thirdPointY * rect.height))
aPath.close()
self.color.set()
self.backgroundColor = .clear
aPath.fill()
}
}
| apache-2.0 | e04cc55d3820b5c9dac3531bd448cce6 | 36.416667 | 105 | 0.670379 | 4.045045 | false | false | false | false |
CaptainTeemo/IGKit | IGKit/Models/Tag.swift | 1 | 1891 | //
// Tag.swift
// IGKit
//
// Created by CaptainTeemo on 5/16/16.
// Copyright © 2016 CaptainTeemo. All rights reserved.
//
import Foundation
/// Tag
public final class Tag: NSObject, JSONConvertible {
public var name = ""
public var media_count = ""
}
// MARK: - Tag information.
extension Tag {
/**
Get information about a tag object.
Require scope: public_content.
- parameter name: Tag name.
- returns: `Promise` with Tag.
*/
public class func fetchTag(name: String) -> Promise<Tag> {
return Fetcher.fetch("/tags/\(name)").then { (result, page) -> Tag in
let tag = Tag.generateModel(result.dictionaryValue)
return tag
}
}
/**
Get a list of recently tagged media.
Require scope: public_content.
- parameter name: Tag name.
- parameter pagination: Optional.
- returns: `Promise` with ([Media], Pagination?).
*/
public class func fetchTagMedia(name: String, pagination: Pagination? = nil) -> Promise<([Media], Pagination?)> {
return Fetcher.fetch("/tags/\(name)/media/recent").then { (result, page) -> ([Media], Pagination?) in
let media = result.jsonArrayValue.map { Media.generateModel($0.dictionaryValue) }
return (media, page)
}
}
/**
Search for tags by name.
Require scope: public_content.
- parameter query: A valid tag name without a leading #. (eg. snowy, nofilter).
- returns: `Promise` with [Tag].
*/
public class func searchTag(query: String) -> Promise<[Tag]> {
return Fetcher.fetch("/tags/search", parameters: ["q": query]).then { (result, page) -> [Tag] in
let tags = result.jsonArrayValue.map { Tag.generateModel($0.dictionaryValue) }
return tags
}
}
} | mit | d0574dd4ab16164e742dc16af9cf2264 | 26.808824 | 117 | 0.586243 | 4.162996 | false | false | false | false |
patrick-sheehan/cwic | Source/SponsorDetailViewController.swift | 1 | 2514 | //
// SponsorDetailViewController.swift
// CWIC
//
// Created by Patrick Sheehan on 1/14/18.
// Copyright © 2018 Síocháin Solutions. All rights reserved.
//
import UIKit
class SponsorDetailViewController: UIViewController {
// MARK: - Member Variables
var sponsorId: Int = 0
var sponsor: Sponsor? = nil
// MARK: - IB Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var textViewHeight: NSLayoutConstraint!
// MARK: - Initialization
static func generate(sponsorId: Int) -> SponsorDetailViewController {
let vc = UIViewController.create("SponsorDetailViewController") as! SponsorDetailViewController
vc.sponsorId = sponsorId
return vc
}
// MARK: - Networking
func refreshData() {
SponsorService.detail(sponsorId: sponsorId) { s in
self.sponsor = s
DispatchQueue.main.async {
self.title = s.name
// Sponsor Description
if s.description.isEmpty {
self.textViewHeight.constant = 0
} else {
self.textViewHeight.constant = 250
self.textView.text = s.description
}
// Sponsor logo
print(s)
// let imgLength = self.imageView.frame.width
self.imageView.downloadedFrom(link: s.logo, contentMode: .scaleAspectFit)
self.imageView.round(corners: .allCorners, radius: 10)
}
}
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshData()
}
}
// MARK: - Table View Methods (for actions at the bottom)
extension SponsorDetailViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
// return event.actions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
// return tableView.defaultCell(event.actions[indexPath.row])
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let action = event.actions[indexPath.row]
// showPopupInfo("'\(action)' coming soon!")
//
// tableView.deselectRow(at: indexPath, animated: true)
}
}
| gpl-3.0 | bad6419e0bfbfd77158d61fd7f7f8fab | 26.593407 | 99 | 0.671446 | 4.632841 | false | false | false | false |
tikoyesayan/AnimatedImage | AnimatedImage/Classes/AnimatedImageView.swift | 1 | 1974 | //
// AnimatedImageView.swift
// AnimatedImage
//
// Created by Tigran Yesayan on 6/26/17.
// Copyright © 2017 Tigran Yesayan. All rights reserved.
//
import UIKit
private let kContentChangeAnimation = "__contentChangeAnimation"
public class AnimatedImageView: UIImageView {
public override class var layerClass: AnyClass {
get {
return AnimatedImageLayer.self
}
}
private var animatedLayer: AnimatedImageLayer {
return self.layer as! AnimatedImageLayer
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK - Setup
private func setup() -> Void {
animatedLayer.contentsGravity = kCAGravityResizeAspect
}
public var animatedImage: AnimatedImage? {
set {
animatedLayer.animatedImage = newValue
animatedLayer.removeAnimation(forKey: kContentChangeAnimation)
if let image = newValue {
animatedLayer.add(contentChangeAnimation(frameCount: image.frameCount - 1, duration: image.duration), forKey: kContentChangeAnimation)
}
}
get {
return self.animatedLayer.animatedImage
}
}
private func contentChangeAnimation(frameCount: Int, duration: CFTimeInterval) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "index")
animation.fromValue = 0
animation.toValue = frameCount
animation.fillMode = kCAFillModeForwards
animation.repeatCount = Float.infinity
animation.duration = duration
return animation
}
public var paused: Bool {
set {
animatedLayer.speed = newValue ? 0 : 1
}
get {
return animatedLayer.speed == 0
}
}
}
| mit | e65cfd33fb34baa72d3fe692896a2f24 | 25.662162 | 150 | 0.614293 | 5.085052 | false | false | false | false |
wojteklu/nsregularexpression.com | Sources/App/Utils.swift | 1 | 2243 | //
// Utils.swift
// NSRegularExpression
//
// Created by wojteklu on 11/12/2016.
//
import Foundation
#if os(Linux)
typealias NSRegularExpression = RegularExpression
#endif
public extension String {
func matches(for regex: String) -> [NSRange] {
// crash occurs on Linux
// when RegularExpression has not balanced parantheses
guard regex.hasBalancedParentheses(left: "(", right: ")"),
regex.hasBalancedParentheses(left: "[", right: "]") else {
return []
}
// or when throws an exception
var cRegex = regex_t()
let result = regcomp(&cRegex, regex, REG_EXTENDED)
if result != 0 {
return []
}
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = NSString(string: self)
return regex.matches(in: self, options: [], range: NSRange(location: 0, length: nsString.length)).map { $0.range }
} catch _ {
return []
}
}
private func hasBalancedParentheses(left: String, right: String) -> Bool {
let array = self.characters.map { String($0) }
var leftCount = 0
var rightCount = 0
for (index, letter) in array.enumerated() {
if letter == left && (index == 0 || (index>0 && array[index-1] != "\\")) {
leftCount += 1
}
if letter == right && (index == 0 || (index>0 && array[index-1] != "\\")) {
rightCount += 1
}
}
if leftCount != rightCount {
return false
}
return true
}
var unescaped: String {
let entities = ["\0": "\\0",
"\t": "\\t",
"\n": "\\n",
"\r": "\\r",
"\"": "\\\"",
"\'": "\\'"]
return entities
.reduce(self) { (string, entity) in
string.replacingOccurrences(of: entity.value, with: entity.key)
}
.replacingOccurrences(of: "\\\\", with: "\\")
}
}
| mit | 6719b275e974420da73ff33ab5782e53 | 27.392405 | 126 | 0.460544 | 4.712185 | false | false | false | false |
grafiti-io/SwiftCharts | SwiftCharts/AxisValues/ChartAxisValue.swift | 3 | 1770 | //
// ChartAxisValue.swift
// swift_charts
//
// Created by ischuetz on 01/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/**
A ChartAxisValue models a value along a particular chart axis. For example, two ChartAxisValues represent the two components of a ChartPoint. It has a backing Double scalar value, which provides a canonical form for all subclasses to be laid out along an axis. It also has one or more labels that are drawn in the chart.
This class is not meant to be instantiated directly. Use one of the existing subclasses or create a new one.
*/
open class ChartAxisValue: Equatable, Hashable, CustomStringConvertible {
/// The backing value for all other types of axis values
open let scalar: Double
open let labelSettings: ChartLabelSettings
open var hidden = false
/// The labels that will be displayed in the chart
open var labels: [ChartAxisLabel] {
let axisLabel = ChartAxisLabel(text: description, settings: labelSettings)
axisLabel.hidden = hidden
return [axisLabel]
}
public init(scalar: Double, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
self.scalar = scalar
self.labelSettings = labelSettings
}
open var copy: ChartAxisValue {
return copy(scalar)
}
open func copy(_ scalar: Double) -> ChartAxisValue {
return ChartAxisValue(scalar: scalar, labelSettings: labelSettings)
}
// MARK: CustomStringConvertible
open var description: String {
return String(scalar)
}
open var hashValue: Int {
return scalar.hashValue
}
}
public func ==(lhs: ChartAxisValue, rhs: ChartAxisValue) -> Bool {
return lhs.scalar =~ rhs.scalar
}
| apache-2.0 | 1827930571dd642421fcaeb932eadc5e | 31.181818 | 321 | 0.69661 | 4.903047 | false | false | false | false |
adrfer/swift | test/IDE/print_usrs.swift | 4 | 6238 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -disable-objc-attr-requires-foundation-module %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -print-usrs -source-filename %s | FileCheck %s -strict-whitespace
import macros
// CHECK: [[@LINE+1]]:8 s:V14swift_ide_test1S{{$}}
struct S {
// CHECK: [[@LINE+1]]:7 s:vV14swift_ide_test1S1xSi{{$}}
var x : Int
}
// CHECK: [[@LINE+1]]:11 s:14swift_ide_test6MyGInt{{$}}
typealias MyGInt = Int
// CHECK: [[@LINE+1]]:7 s:C14swift_ide_test5MyCls{{$}}
class MyCls {
// CHECK: [[@LINE+1]]:13 s:C14swift_ide_test5MyCls2TA{{$}}
typealias TA = Int
// CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test5MyCls3wwwSi{{$}}
var www : Int = 0
// CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test5MyCls3fooFSiT_{{$}}
func foo(x : Int) {}
// CHECK: [[@LINE+1]]:3 s:iC14swift_ide_test5MyCls9subscriptFSiSf{{$}}
subscript(i: Int) -> Float {
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test5MyClsg9subscriptFSiSf{{$}}
get { return 0.0 }
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test5MyClss9subscriptFSiSf{{$}}
set {}
}
}
// CHECK: [[@LINE+1]]:7 s:C14swift_ide_test12GenericClass{{$}}
class GenericClass {
// CHECK: [[@LINE+1]]:13 s:C14swift_ide_test12GenericClass2TA{{$}}
typealias TA = Int
// CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test12GenericClass11instanceVarSi{{$}}
var instanceVar: Int = 0
// CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test12GenericClass12instanceFuncFT_T_{{$}}
func instanceFunc() {
// CHECK: [[@LINE+2]]:18 s:ZFC14swift_ide_test12GenericClass9classFuncFS0_T_{{$}}
// CHECK: [[@LINE+1]]:28 s:vFC14swift_ide_test12GenericClass12instanceFuncFT_T_L_4selfS0_{{$}}
GenericClass.classFunc(self)
}
// CHECK: [[@LINE+2]]:3 s:iC14swift_ide_test12GenericClass9subscriptFSiSf{{$}}
// CHECK: [[@LINE+1]]:13 s:vC14swift_ide_test12GenericClassL_1iSi{{$}}
subscript(i: Int) -> Float {
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test12GenericClassg9subscriptFSiSf{{$}}
get { return 0.0 }
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test12GenericClasss9subscriptFSiSf{{$}}
set {}
}
// CHECK: [[@LINE+1]]:3 s:FC14swift_ide_test12GenericClassd{{$}}
deinit {
// CHECK: [[@LINE+2]]:18 s:ZFC14swift_ide_test12GenericClass9classFuncFS0_T_{{$}}
// CHECK: [[@LINE+1]]:28 ERROR:no-usr{{$}}
GenericClass.classFunc(self)
}
// CHECK: [[@LINE+2]]:14 s:ZFC14swift_ide_test12GenericClass9classFuncFS0_T_{{$}}
// CHECK: [[@LINE+1]]:24 s:vZFC14swift_ide_test12GenericClass9classFuncFS0_T_L_1aS0_{{$}}
class func classFunc(a: GenericClass) {}
}
// CHECK: [[@LINE+1]]:10 s:P14swift_ide_test4Prot{{$}}
protocol Prot {
// CHECK: [[@LINE+1]]:18 s:P14swift_ide_test4Prot5Blarg{{$}}
associatedtype Blarg
// CHECK: [[@LINE+1]]:8 s:FP14swift_ide_test4Prot8protMethFwx5BlargwxS1_{{$}}
func protMeth(x: Blarg) -> Blarg
// CHECK: [[@LINE+2]]:7 s:vP14swift_ide_test4Prot17protocolProperty1Si{{$}}
// CHECK: [[@LINE+1]]:32 s:FP14swift_ide_test4Protg17protocolProperty1Si{{$}}
var protocolProperty1: Int { get }
}
protocol Prot2 {}
class SubCls : MyCls, Prot {
// CHECK: [[@LINE+1]]:13 s:C14swift_ide_test6SubCls5Blarg{{$}}
typealias Blarg = Prot2
// CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test6SubCls8protMethFPS_5Prot2_PS1__{{$}}
func protMeth(x: Blarg) -> Blarg {}
// CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test6SubCls17protocolProperty1Si{{$}}
var protocolProperty1 = 0
}
// CHECK: [[@LINE+1]]:6 s:F14swift_ide_test5genFnuRxS_4Protwx5BlargS_5Prot2rFxSi{{$}}
func genFn<T : Prot where T.Blarg : Prot2>(p : T) -> Int {}
// CHECK: [[@LINE+1]]:6 s:F14swift_ide_test3barFSiTSiSf_{{$}}
func bar(x: Int) -> (Int, Float) {}
// CHECK: [[@LINE+1]]:7 s:C14swift_ide_test6GenCls{{$}}
class GenCls<T> {
// CHECK: [[@LINE+1]]:3 s:FC14swift_ide_test6GenClscFT_GS0_x_{{$}}
init() {}
// CHECK: [[@LINE+1]]:3 s:FC14swift_ide_test6GenClsd{{$}}
deinit {}
// CHECK: [[@LINE+1]]:14 s:ZFC14swift_ide_test6GenCls4cfooFT_T_{{$}}
class func cfoo() {}
// CHECK: [[@LINE+1]]:3 s:iC14swift_ide_test6GenCls9subscriptFTSiSi_Si{{$}}
subscript (i : Int, j : Int) -> Int {
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test6GenClsg9subscriptFTSiSi_Si{{$}}
get {
return i + j
}
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test6GenClss9subscriptFTSiSi_Si{{$}}
set(v) {
v + i - j
}
}
}
class C4 {
// CHECK: [[@LINE+1]]:9 s:CC14swift_ide_test2C42In{{$}}
class In {
// CHECK: [[@LINE+1]]:16 s:ZFCC14swift_ide_test2C42In3gooFT_T_{{$}}
class func goo() {}
}
}
class C5 {}
extension C5 {
// CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test2C55extFnFT_T_{{$}}
func extFn() {}
}
class Observers {
func doit() {}
// CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test9Observers2p1Si{{$}}
var p1 : Int = 0 {
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9Observersw2p1Si{{$}}
willSet(newValue) { doit() }
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9ObserversW2p1Si{{$}}
didSet { doit() }
}
// CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test9Observers2p2Si{{$}}
var p2 = 42 {
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9Observersw2p2Si{{$}}
willSet(newValue) { doit() }
// CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9ObserversW2p2Si{{$}}
didSet { doit() }
}
}
// CHECK: [[@LINE+2]]:7 s:C14swift_ide_test10ObjCClass1{{$}}
@objc
class ObjCClass1 {
// CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test10ObjCClass113instanceFunc1FSiT_{{$}}
func instanceFunc1(a: Int) {}
// CHECK: [[@LINE+1]]:14 s:ZFC14swift_ide_test10ObjCClass111staticFunc1FSiT_{{$}}
class func staticFunc1(a: Int) {}
}
// CHECK: [[@LINE+1]]:6 s:O14swift_ide_test5Suits{{$}}
enum Suits {
// CHECK: [[@LINE+1]]:8 s:FO14swift_ide_test5Suits5ClubsFMS0_S0_{{$}}
case Clubs
// CHECK: [[@LINE+1]]:8 s:FO14swift_ide_test5Suits8DiamondsFMS0_S0_{{$}}
case Diamonds
// CHECK: [[@LINE+1]]:8 s:FO14swift_ide_test5Suits5enfooFT_T_{{$}}
func enfoo() {}
}
func importedMacros() {
// CHECK: [[@LINE+1]]:12 c:@macro@M_PI{{$}}
let m1 = M_PI
// CHECK: [[@LINE+1]]:12 c:@macro@MACRO_FROM_IMPL{{$}}
let m2 = MACRO_FROM_IMPL
// CHECK: [[@LINE+1]]:12 c:@macro@USES_MACRO_FROM_OTHER_MODULE_1{{$}}
let m3 = USES_MACRO_FROM_OTHER_MODULE_1
_ = m1; _ = m2; _ = m3
}
| apache-2.0 | 3050a236e1aa6a7b6813a75753574799 | 33.274725 | 127 | 0.630811 | 2.832879 | false | true | false | false |
VladasZ/iOSTools | Sources/iOS/XibView.swift | 1 | 1400 | //
// XibView.swift
// iOSTools
//
// Created by Vladas Zakrevskis on 12/27/17.
// Copyright © 2017 Vladas Zakrevskis. All rights reserved.
//
import UIKit
fileprivate func viewWithSize<T: XibView>(_ size: CGSize) -> T{
return T(frame: CGRect(0, 0, size.width, size.height))
}
open class XibView : UIView {
open class var defaultSize: CGSize { return CGSize(width: 100, height: 100) }
public class func fromNib() -> Self { return viewWithSize(defaultSize) }
private static var identifier: String { return String(describing: self) }
var identifier: String { return type(of: self).identifier }
//MARK: - Initialization
public required override init(frame: CGRect) {
super.init(frame: frame)
addSubview(loadFromXib())
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(loadFromXib())
setup()
}
private func loadFromXib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: identifier, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = self.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return view
}
open func setup() {
}
}
| mit | 2d6a3d1c3d7425cdc72ed3c156ba4db6 | 25.396226 | 81 | 0.61258 | 4.16369 | false | false | false | false |
Sam-WEI/SwiftWeatherFork | SwiftWeather/WeatherViewModel.swift | 1 | 2786 | //
// Created by Jake Lin on 8/26/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import Foundation
import CoreLocation
class WeatherViewModel {
// MARK: - Constants
private let emptyString = ""
// MARK: - Properties
let hasError: Observable<Bool>
let errorMessage: Observable<String?>
let location: Observable<String>
let iconText: Observable<String>
let temperature: Observable<String>
let forecasts: Observable<[ForecastViewModel]>
// MARK: - Services
fileprivate var locationService: LocationService
fileprivate var weatherService: WeatherServiceProtocol
// MARK: - init
init() {
hasError = Observable(false)
errorMessage = Observable(nil)
location = Observable(emptyString)
iconText = Observable(emptyString)
temperature = Observable(emptyString)
forecasts = Observable([])
// Can put Dependency Injection here
locationService = LocationService()
weatherService = OpenWeatherMapService()
}
// MARK: - public
func startLocationService() {
locationService.delegate = self
locationService.requestLocation()
}
// MARK: - private
fileprivate func update(weather: Weather) {
hasError.value = false
errorMessage.value = nil
location.value = weather.location
iconText.value = weather.iconText
temperature.value = weather.temperature
let tempForecasts = weather.forecasts.map { forecast in
return ForecastViewModel(forecast)
}
forecasts.value = tempForecasts
}
fileprivate func update(error: Error) {
hasError.value = true
switch error.errorCode {
case .URLError:
errorMessage.value = "The weather service is not working."
case .NetworkRequestFailed:
errorMessage.value = "The network appears to be down."
case .JSONSerializationFailed:
errorMessage.value = "We're having trouble processing weather data."
case .JSONParsingFailed:
errorMessage.value = "We're having trouble parsing weather data."
}
location.value = emptyString
iconText.value = emptyString
temperature.value = emptyString
self.forecasts.value = []
}
}
// MARK: LocationServiceDelegate
extension WeatherViewModel: LocationServiceDelegate {
func locationDidUpdate(service: LocationService, location: CLLocation) {
weatherService.retrieveWeatherInfo(location: location) { (weather, error) -> Void in
DispatchQueue.main.async {
if let unwrappedError = error {
print(unwrappedError)
self.update(error: unwrappedError)
return
}
guard let unwrappedWeather = weather else {
return
}
self.update(weather: unwrappedWeather)
}
}
}
}
| mit | 995d4df74e7fa7fea4558f276a056dd2 | 25.778846 | 88 | 0.68079 | 5.063636 | false | false | false | false |
audrl1010/EasyMakePhotoPicker | Example/EasyMakePhotoPicker/FacebookVideoCell.swift | 1 | 5564 | //
// FacebookVideoCell.swift
// EasyMakePhotoPicker
//
// Created by myung gi son on 2017. 7. 6..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import UIKit
import Photos
import RxSwift
import EasyMakePhotoPicker
class FacebookVideoCell: FacebookPhotoCell, VideoCellable {
// MARK: - Constant
struct Color {
static let selectedDurationBackgroundViewBGColor = UIColor(
red: 104/255,
green: 156/255,
blue: 255/255,
alpha: 1.0)
static let deselectedDurationBackgroundViewBGColor = UIColor(
red: 0,
green: 0,
blue: 0,
alpha: 0.6)
}
struct Metric {
static let durationBackgroundViewHeight = CGFloat(26)
static let videoIconImageViewWidth = CGFloat(16)
static let videoIconImageViewHeight = CGFloat(16)
static let videoIconImageViewLeft = CGFloat(5)
static let durationLabelRight = CGFloat(-5)
}
var durationLabel: UILabel = DurationLabel().then {
$0.textAlignment = .right
$0.backgroundColor = .clear
}
var playerView = PlayerView().then {
$0.playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
$0.isHidden = true
}
fileprivate var player: AVPlayer? {
didSet {
if let player = player {
playerView.playerLayer.player = player
NotificationCenter.default.addObserver(
forName: .AVPlayerItemDidPlayToEndTime,
object: player.currentItem,
queue: nil) { _ in
DispatchQueue.main.async {
player.seek(to: CMTime.zero)
player.play()
}
}
}
else {
playerView.playerLayer.player = nil
NotificationCenter.default.removeObserver(self)
}
}
}
var durationBackgroundView = UIView().then {
$0.backgroundColor = Color.deselectedDurationBackgroundViewBGColor
}
var videoIconImageView = UIImageView(image: #imageLiteral(resourceName: "video"))
var duration: TimeInterval = 0.0 {
didSet {
durationLabel.text = timeFormatted(timeInterval: duration)
}
}
// MARK: - Life Cycle
override func prepareForReuse() {
super.prepareForReuse()
player = nil
playerView.isHidden = true
}
override func addSubviews() {
super.addSubviews()
insertSubview(playerView, aboveSubview: imageView)
addSubview(durationLabel)
durationBackgroundView.addSubview(videoIconImageView)
insertSubview(durationBackgroundView, belowSubview: durationLabel)
}
override func setupConstraints() {
super.setupConstraints()
durationBackgroundView
.fs_heightAnchor(equalToConstant: Metric.durationBackgroundViewHeight)
.fs_leftAnchor(equalTo: leftAnchor)
.fs_rightAnchor(equalTo: rightAnchor)
.fs_bottomAnchor(equalTo: bottomAnchor)
.fs_endSetup()
videoIconImageView
.fs_leftAnchor(
equalTo: durationBackgroundView.leftAnchor,
constant: Metric.videoIconImageViewLeft)
.fs_centerYAnchor(equalTo: durationBackgroundView.centerYAnchor)
.fs_widthAnchor(equalToConstant: Metric.videoIconImageViewWidth)
.fs_heightAnchor(equalToConstant: Metric.videoIconImageViewHeight)
.fs_endSetup()
durationLabel
.fs_rightAnchor(
equalTo: durationBackgroundView.rightAnchor,
constant: Metric.durationLabelRight)
.fs_centerYAnchor(equalTo: durationBackgroundView.centerYAnchor)
.fs_endSetup()
playerView
.fs_leftAnchor(equalTo: leftAnchor)
.fs_topAnchor(equalTo: topAnchor)
.fs_rightAnchor(equalTo: rightAnchor)
.fs_bottomAnchor(equalTo: bottomAnchor)
.fs_endSetup()
}
// MARK: - Bind
override func bind(viewModel: PhotoCellViewModel) {
super.bind(viewModel: viewModel)
if let viewModel = viewModel as? VideoCellViewModel {
duration = viewModel.duration
viewModel.playEvent.asObserver()
.subscribe(onNext: { [weak self] playEvent in
guard let `self` = self else { return }
switch playEvent {
case .play: self.play()
case .stop: self.stop()
}
})
.disposed(by: disposeBag)
viewModel.isSelect
.subscribe(onNext: { [weak self] isSelect in
guard let `self` = self else { return }
if isSelect {
self.durationBackgroundView.backgroundColor =
Color.selectedDurationBackgroundViewBGColor
}
else {
self.durationBackgroundView.backgroundColor =
Color.deselectedDurationBackgroundViewBGColor
}
})
.disposed(by: disposeBag)
}
}
fileprivate func play() {
guard let viewModel = viewModel as? VideoCellViewModel,
let playerItem = viewModel.playerItem else { return }
self.player = AVPlayer(playerItem: playerItem)
if let player = player {
playerView.isHidden = false
player.play()
}
}
fileprivate func stop() {
if let player = player {
player.pause();
self.player = nil
playerView.isHidden = true
}
}
fileprivate func timeFormatted(timeInterval: TimeInterval) -> String {
let seconds = lround(timeInterval)
var hour = 0
var minute = (seconds / 60)
let second = seconds % 60
if minute > 59 {
hour = (minute / 60)
minute = (minute % 60)
return String(format: "%d:%d:%02d", hour, minute, second)
}
else {
return String(format: "%d:%02d", minute, second)
}
}
}
| mit | 8ab871671e1867e5d103b189d465c5df | 25.995146 | 83 | 0.647725 | 4.773391 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/FRP/Sugar/DateFormat+Extension.swift | 1 | 16793 | //
// DateFormat+Extension.swift
// PaversFRP
//
// Created by Keith on 02/01/2018.
// Copyright © 2018 Keith. All rights reserved.
//
import Foundation
public typealias DateFormat = String
public extension DateFormat {
static let yyyy =
DateFormatComponent.calendarYear.rawValue
+ DateFormatComponent.calendarYear.rawValue
+ DateFormatComponent.calendarYear.rawValue
+ DateFormatComponent.calendarYear.rawValue
static let mm =
DateFormatComponent.monthNumber.rawValue
+ DateFormatComponent.monthNumber.rawValue
static let dd =
DateFormatComponent.dayOfMonth.rawValue
+ DateFormatComponent.dayOfMonth.rawValue
static let h24 =
DateFormatComponent.hour24.rawValue
+ DateFormatComponent.hour24.rawValue
static let mi =
DateFormatComponent.minute.rawValue
+ DateFormatComponent.minute.rawValue
static let ss =
DateFormatComponent.second.rawValue
+ DateFormatComponent.second.rawValue
static let ms =
DateFormatComponent.fractionalSecond.rawValue
+ DateFormatComponent.fractionalSecond.rawValue
+ DateFormatComponent.fractionalSecond.rawValue
static let yyyymmdd = "\(yyyy)\(mm)\(dd)"
static let yyyy_mm_dd = "\(yyyy)-\(mm)-\(dd)"
static let h24miss = "\(h24)\(mi)\(ss)"
static let h24_mi_ss = "\(h24):\(mi):\(ss)"
static let h24_mi_ss_ms = "\(h24):\(mi):\(ss).\(ms)"
static let yyyymmddh24miss = "\(yyyymmdd)\(h24miss)"
static let yyyy_mm_dd_h24_mi_ss = "\(yyyy_mm_dd) \(h24_mi_ss)"
static let yyyy_mm_dd_h24_mi_ss_ms = "\(yyyy_mm_dd) \(h24_mi_ss_ms)"
}
public enum DateFormatComponent: DateFormat {
/**
Calendar year (numeric).
In most cases the length of the y field specifies the minimum number of digits to display,
zero-padded as necessary;
more digits will be displayed if needed to show the full year.
However, “yy” requests just the two low-order digits of the year, zero-padded as necessary.
For most use cases, “y” or “yy” should be adequate.
Y 2, 20, 201, 2017, 20173
YY 02, 20, 01, 17, 73
YYY 002, 020, 201, 2017, 20173
YYYY 0002, 0020, 0201, 2017, 20173
YYYYY+ ...
*/
case calendarYear = "y"
/**
Year in “Week of Year” based calendars in which the year transition occurs on a week boundary;
may differ from calendar year ‘y’ near a year transition.
This numeric year designation is used in conjunction with pattern character ‘w’
in the ISO year-week calendar as defined by ISO 8601,
but can be used in non-Gregorian based calendar systems
where week date processing is desired. The field length is interpreted
in the same was as for ‘y’; that is, “yy” specifies use of the two low-order year digits,
while any other field length specifies a minimum number of digits to display.
Y 2, 20, 201, 2017, 20173
YY 02, 20, 01, 17, 73
YYY 002, 020, 201, 2017, 20173
YYYY 0002, 0020, 0201, 2017, 20173
YYYYY+ ...
*/
case yearInWeekofYear = "Y"
/**
Extended year (numeric). This is a single number designating the year of this calendar system, encompassing all supra-year fields. For example, for the Julian calendar system, year numbers are positive, with an era of BCE or CE. An extended year value for the Julian calendar system assigns positive values to CE years and negative values to BCE years, with 1 BCE being year 0. For ‘u’, all field lengths specify a minimum number of digits; there is no special interpretation for “uu”.
u+ 4601
*/
case extendedYear = "u"
/**
Cyclic year name. Calendars such as the Chinese lunar calendar (and related calendars) and the Hindu calendars use 60-year cycles of year names. If the calendar does not provide cyclic year name data, or if the year value to be formatted is out of the range of years for which cyclic name data is provided, then numeric formatting is used (behaves like 'y').
Currently the data only provides abbreviated names, which will be used for all requested name widths.
U..UUU 甲子
UUUU 甲子 [for now] Wide
UUUUU 甲子 [for now]
*/
case cyclicYearName = "U"
/**
Related Gregorian year (numeric). For non-Gregorian calendars, this corresponds to the extended Gregorian year in which the calendar’s year begins. Related Gregorian years are often displayed, for example, when formatting dates in the Japanese calendar — e.g. “2012(平成24)年1月15日” — or in the Chinese calendar — e.g. “2012壬辰年腊月初四”. The related Gregorian year is usually displayed using the "latn" numbering system, regardless of what numbering systems may be used for other parts of the formatted date. If the calendar’s year is linked to the solar year (perhaps using leap months), then for that calendar the ‘r’ year will always be at a fixed offset from the ‘u’ year. For the Gregorian calendar, the ‘r’ year is the same as the ‘u’ year. For ‘r’, all field lengths specify a minimum number of digits; there is no special interpretation for “rr”.
r+ 2017
*/
case relatedGregorianYear = "r"
/**
Quarter number/name.
Q 2 Numeric: 1 digit
QQ 02 Numeric: 2 digits + zero pad
QQQ Q2 Abbreviated
QQQQ 2nd quarter Wide
QQQQQ 2 Narrow
*/
case quarterNumber = "Q"
/**
Stand-Alone Quarter number/name.
Q 2 Numeric: 1 digit
QQ 02 Numeric: 2 digits + zero pad
QQQ Q2 Abbreviated
QQQQ 2nd quarter Wide
QQQQQ 2 Narrow
*/
case standAloneQuarterNumber = "q"
/**
Month number/name, format style (intended to be used in conjunction with ‘d’ for day number).
M 9, 12 Numeric: minimum digits
MM 09, 12 Numeric: 2 digits, zero pad if needed
MMM Sep Abbreviated
MMMM September Wide
MMMMM S Narrow
*/
case monthNumber = "M"
/**
Stand-Alone Month number/name (intended to be used without ‘d’ for day number).
L 9, 12 Numeric: minimum digits
LL 09, 12 Numeric: 2 digits, zero pad if needed
LLL Sep Abbreviated
LLLL September Wide
LLLLL S Narrow
*/
case standAloneMonthNumber = "L"
/**
Week of Year (numeric). When used in a pattern with year, use ‘Y’ for the year field instead of ‘y’.
w 8, 27 Numeric: minimum digits
ww 08, 27 Numeric: 2 digits, zero pad if needed
*/
case weekOfYear = "w"
/**
Week of Month (numeric)
W 3 Numeric: 1 digit
*/
case weekOfMonth = "W"
/**
Day of month (numeric).
d 1 Numeric: minimum digits
dd 01 Numeric: 2 digits, zero pad if needed
*/
case dayOfMonth = "d"
/**
Day of year (numeric). The field length specifies the minimum number of digits, with zero-padding as necessary.
D...DDD 345
*/
case dayOfYear = "D"
/**
Day of Week in Month (numeric). The example is for the 2nd Wed in July
F 2
*/
case dayOfWeekInMonth = "F"
/**
Modified Julian day (numeric). This is different from the conventional Julian day number in two regards. First, it demarcates days at local zone midnight, rather than noon GMT. Second, it is a local number; that is, it depends on the local time zone. It can be thought of as a single number that encompasses all the date-related fields.The field length specifies the minimum number of digits, with zero-padding as necessary.
g+ 2451334
*/
case modifiedJulianDay = "g"
/**
Day of week name, format style.
E..EEE Tue Abbreviated
EEEE Tuesday Wide
EEEEE T Narrow
EEEEEE Tu Short
*/
case dateOfWeekName = "E"
/**
Local day of week number/name, format style. Same as E except adds a numeric value that will depend on the local starting day of the week. For this example, Monday is the first day of the week.
e 2 Numeric: 1 digit
ee 02 Numeric: 2 digits + zero pad
eee Tue Abbreviated
eeee Tuesday Wide
eeeee T Narrow
eeeeee Tu Short
*/
case localDayOfWeekNumberOrName = "e"
/**
Stand-Alone local day of week number/name.
c..cc 2 Numeric: 1 digit
ccc Tue Abbreviated
cccc Tuesday Wide
ccccc T Narrow
cccccc Tu Short
*/
case standAloneLocalDayOfWeekNumberOrName = "c"
/**
Abbreviated AM, PM
May be upper or lowercase depending on the locale and other options. The wide form may be the same as the short form if the “real” long form (eg ante meridiem) is not customarily used. The narrow form must be unique, unlike some other fields.
a..aaa am. [e.g. 12 am.]
aaaa am. [e.g. 12 am.] Wide
aaaaa a [e.g. 12a] Narrow
*/
case ampm = "a"
/**
Abbreviated am, pm, noon, midnight
May be upper or lowercase depending on the locale and other options. If the locale doesn't the notion of a unique "noon" = 12:00, then the PM form may be substituted. Similarly for "midnight" = 00:00 and the AM form. The narrow form must be unique, unlike some other fields.
b..bbb mid. [e.g. 12 mid.]
bbbb midnight
[e.g. 12 midnight] Wide
bbbbb md [e.g. 12 md] Narrow
*/
case amPmNoonMidnight = "b"
/**
Abbreviated flexible day periods
May be upper or lowercase depending on the locale and other options. Often there is only one width that is customarily used.
B..BBB at night
[e.g. 3:00 at night]
BBBB at night
[e.g. 3:00 at night] Wide
BBBBB at night
[e.g. 3:00 at night] Narrow
*/
case flexibleDayPeriod = "B"
/**
Hour [1-12]. When used in skeleton data or in a skeleton passed in an API for flexible date pattern generation, it should match the 12-hour-cycle format preferred by the locale (h or K); it should not match a 24-hour-cycle format (H or k).
h 1, 12 Numeric: minimum digits
hh 01, 12 Numeric: 2 digits, zero pad if needed
*/
case hour12 = "h"
/**
Hour [0-23]. When used in skeleton data or in a skeleton passed in an API for flexible date pattern generation, it should match the 24-hour-cycle format preferred by the locale (H or k); it should not match a 12-hour-cycle format (h or K).
H 0, 23 Numeric: minimum digits
HH 00, 23 Numeric: 2 digits, zero pad if needed
*/
case hour24 = "H"
/**
Hour [0-11]. When used in a skeleton, only matches K or h, see above.
K 0, 11 Numeric: minimum digits
KK 00, 11 Numeric: 2 digits, zero pad if needed
*/
case hour12k = "K"
/**
Hour [1-24]. When used in a skeleton, only matches k or H, see above.
k 1, 24 Numeric: minimum digits
kk 01, 24 Numeric: 2 digits, zero pad if needed
*/
case hour24k = "k"
/**
Minute (numeric). Truncated, not rounded.
m m 8, 59 Numeric: minimum digits
mm 08, 59 Numeric: 2 digits, zero pad if needed
*/
case minute = "m"
/**
Second (numeric). Truncated, not rounded.
s 8, 12 Numeric: minimum digits
ss 08, 12 Numeric: 2 digits, zero pad if needed
*/
case second = "s"
/**
Fractional Second (numeric). Truncates, like other numeric time fields, but in this case to the number of digits specified by the field length. (Example shows display using pattern SSSS for seconds value 12.34567)
S+ 3456
*/
case fractionalSecond = "S"
/**
Milliseconds in day (numeric). This field behaves exactly like a composite of all time-related fields, not including the zone fields. As such, it also reflects discontinuities of those fields on DST transition days. On a day of DST onset, it will jump forward. On a day of DST cessation, it will jump backward. This reflects the fact that is must be combined with the offset field to obtain a unique local time value. The field length specifies the minimum number of digits, with zero-padding as necessary.
A+ 69540000
*/
case millisecondInDay = "A"
/**
The short specific non-location format. Where that is unavailable, falls back to the short localized GMT format ("O").
z..zzz PDT
zzzz Pacific Daylight Time The long specific non-location format. Where that is unavailable, falls back to the long localized GMT format ("OOOO").
*/
case timeZone = "z"
/**
The ISO8601 basic format with hours, minutes and optional seconds fields. The format is equivalent to RFC 822 zone format (when optional seconds field is absent). This is equivalent to the "xxxx" specifier.
Z..ZZZ -0800
The long localized GMT format. This is equivalent to the "OOOO" specifier.
ZZZZ GMT-8:00
The ISO8601 extended format with hours, minutes and optional seconds fields. The ISO8601 UTC indicator "Z" is used when local time offset is 0. This is equivalent to the "XXXXX" specifier.
ZZZZZ -08:00
-07:52:58
*/
case timeZoneISO8601 = "Z"
/**
GMT format
O GMT-8 The short localized GMT format.
OOOO GMT-08:00 The long localized GMT format.
*/
case GTM = "O"
/**
The short generic non-location format. Where that is unavailable, falls back to the generic location format ("VVVV"), then the short localized GMT format as the final fallback.
v PT
The long generic non-location format. Where that is unavailable, falls back to generic location format ("VVVV").
vvvv Pacific Time
*/
case pacificTime = "v"
/**
V uslax The short time zone ID. Where that is unavailable, the special short time zone ID unk (Unknown Zone) is used.
Note: This specifier was originally used for a variant of the short specific non-location format, but it was deprecated in the later version of this specification. In CLDR 23, the definition of the specifier was changed to designate a short time zone ID.
VV America/Los_Angeles The long time zone ID.
VVV Los Angeles The exemplar city (location) for the time zone. Where that is unavailable, the localized exemplar city name for the special zone Etc/Unknown is used as the fallback (for example, "Unknown City").
VVVV Los Angeles Time The generic location format. Where that is unavailable, falls back to the long localized GMT format ("OOOO"; Note: Fallback is only necessary with a GMT-style Time Zone ID, like Etc/GMT-830.)
This is especially useful when presenting possible timezone choices for user selection, since the naming is more uniform than the "v" format.
*/
case timeZoneID = "V"
/**
X -08
+0530
Z The ISO8601 basic format with hours field and optional minutes field. The ISO8601 UTC indicator "Z" is used when local time offset is 0. (The same as x, plus "Z".)
XX -0800
Z The ISO8601 basic format with hours and minutes fields. The ISO8601 UTC indicator "Z" is used when local time offset is 0. (The same as xx, plus "Z".)
XXX -08:00
Z The ISO8601 extended format with hours and minutes fields. The ISO8601 UTC indicator "Z" is used when local time offset is 0. (The same as xxx, plus "Z".)
XXXX -0800
-075258
Z The ISO8601 basic format with hours, minutes and optional seconds fields. The ISO8601 UTC indicator "Z" is used when local time offset is 0. (The same as xxxx, plus "Z".)
Note: The seconds field is not supported by the ISO8601 specification.
XXXXX -08:00
-07:52:58
Z The ISO8601 extended format with hours, minutes and optional seconds fields. The ISO8601 UTC indicator "Z" is used when local time offset is 0. (The same as xxxxx, plus "Z".)
Note: The seconds field is not supported by the ISO8601 specification.
*/
case ISO8601UTC_XandZ = "X"
/**
x -08
+0530
+00 The ISO8601 basic format with hours field and optional minutes field. (The same as X, minus "Z".)
xx -0800
+0000 The ISO8601 basic format with hours and minutes fields. (The same as XX, minus "Z".)
xxx -08:00
+00:00 The ISO8601 extended format with hours and minutes fields. (The same as XXX, minus "Z".)
xxxx -0800
-075258
+0000 The ISO8601 basic format with hours, minutes and optional seconds fields. (The same as XXXX, minus "Z".)
Note: The seconds field is not supported by the ISO8601 specification.
xxxxx -08:00
-07:52:58
+00:00 The ISO8601 extended format with hours, minutes and optional seconds fields. (The same as XXXXX, minus "Z".)
Note: The seconds field is not supported by the ISO8601 specification.
*/
case ISO8601UTC_XdivZ = "x"
}
| mit | 6b50efed3a9b5a91befc7b8b8d9dfb15 | 29.726937 | 849 | 0.672151 | 3.917666 | false | false | false | false |
vipu1212/GhostPrompt | Pod/Classes/GhostPrompt.swift | 1 | 3371 | //
// ViewController.swift
// GhostPrompt
//
// Created by Divyansh Singh on 24/02/16.
// Copyright © 2016 Divyansh. All rights reserved.
//
import UIKit
public class GhostPrompt {
public lazy var promptHeight = 55
public lazy var bgColor = UIColor(red: 0.423, green: 0.356, blue: 0.925, alpha: 1)
public lazy var textColor = UIColor.white
public let view : UIView
public lazy var appearingDirection = UIView.Direction.Bottom
public lazy var animationTime = 0.4
public init(height : Int, ParentView view : UIView) {
self.view = view
self.promptHeight = height
}
public func showMessage(Message message : String) {
let frame = CGRect(x: 0, y: view.frame.height - CGFloat(self.promptHeight), width: view.frame.width, height: CGFloat(self.promptHeight))
let messageView = UIView(frame: frame)
messageView.backgroundColor = self.bgColor
messageView.isHidden = true
view.addSubview(messageView)
let label = UILabel(frame: messageView.frame)
label.text = message
label.textAlignment = .center
label.textColor = self.textColor
label.font = UIFont(name: "GothamRounded-Light", size: 15.0)
label.isHidden = true
label.numberOfLines = 0
view.addSubview(label)
messageView.translateAnimated(duration: self.animationTime, FromDirection: self.appearingDirection)
label.translateAnimated(duration: self.animationTime, FromDirection: self.appearingDirection)
UIView.animate(withDuration: self.animationTime, delay: 2, options: UIView.AnimationOptions.curveEaseOut, animations: {
switch self.appearingDirection {
case .Top, .Bottom :
messageView.frame.origin.y = self.view.frame.height
label.frame.origin.y = self.view.frame.height
case .Left :
messageView.frame.origin.x = self.view.frame.size.width
label.frame.origin.x = self.view.frame.size.width
case .Right :
messageView.frame.origin.x = self.view.frame.origin.x-self.view.frame.size.width
label.frame.origin.x = self.view.frame.origin.x-self.view.frame.size.width
}
}, completion: { _ in
messageView.removeFromSuperview()
label.removeFromSuperview()
})
}
}
public extension UIView {
enum Direction {
case Top
case Bottom
case Left
case Right
}
func translateAnimated(duration : TimeInterval, FromDirection direction : Direction) {
let actualOrigin = self.frame.origin
var origin : CGPoint = CGPoint(x: 0, y: 0)
switch direction {
case .Top : origin = CGPoint(x: self.frame.origin.x, y: 0 - self.frame.height)
case .Bottom : origin = CGPoint(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.height)
case .Left : origin = CGPoint(x: self.frame.origin.x - self.frame.width, y: self.frame.origin.y)
case .Right : origin = CGPoint(x: self.frame.origin.x + self.frame.width, y: self.frame.origin.y)
}
self.frame.origin = origin
self.isHidden = false
UIView.animate(withDuration: duration, animations: {
self.frame.origin = actualOrigin
})
}
}
| mit | aa6958f9af1db7850ae8f97c468f5c8f | 32.366337 | 144 | 0.636795 | 4.165637 | false | false | false | false |
zivboy/jetstream-ios | Jetstream/ScopeFetchMessage.swift | 4 | 2185 | //
// ScopeFetchMessage.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class ScopeFetchMessage: NetworkMessage {
class var messageType: String {
return "ScopeFetch"
}
override var type: String {
return ScopeFetchMessage.messageType
}
let name: String
let params: [String: AnyObject]
init(index: UInt, name: String, params: [String: AnyObject]) {
self.name = name
self.params = params
super.init(index: index)
}
convenience init(session: Session, name: String) {
self.init(index: session.getNextMessageIndex(), name: name, params: [String: AnyObject]())
}
convenience init(session: Session, name: String, params: [String: AnyObject]) {
self.init(index: session.getNextMessageIndex(), name: name, params: params)
}
override func serialize() -> [String: AnyObject] {
var dictionary = super.serialize()
dictionary["name"] = name
dictionary["params"] = params
return dictionary
}
}
| mit | eca80bf024bc6c7bc8fcd2c3bd1d0687 | 36.033898 | 98 | 0.691533 | 4.396378 | false | false | false | false |
practicalswift/swift | test/IRGen/objc.swift | 1 | 4799 |
// RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[BLAMMO:%T4objc6BlammoC]] = type
// CHECK: [[MYBLAMMO:%T4objc8MyBlammoC]] = type
// CHECK: [[TEST2:%T4objc5Test2C]] = type
// CHECK: [[OBJC:%objc_object]] = type
// CHECK: [[ID:%T4objc2idV]] = type <{ %AnyObject }>
// CHECK: [[GIZMO:%TSo5GizmoC]] = type
// CHECK: [[RECT:%TSo4RectV]] = type
// CHECK: [[FLOAT:%TSf]] = type
// CHECK: @"\01L_selector_data(bar)" = private global [4 x i8] c"bar\00", section "__TEXT,__objc_methname,cstring_literals", align 1
// CHECK: @"\01L_selector(bar)" = private externally_initialized global i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(bar)", i64 0, i64 0), section "__DATA,__objc_selrefs,literal_pointers,no_dead_strip", align 8
// CHECK: @"$sSo4RectVMn" = linkonce_odr hidden constant
// CHECK: @"$sSo4RectVN" = linkonce_odr hidden constant
// CHECK: @"\01L_selector_data(acquiesce)"
// CHECK-NOT: @"\01L_selector_data(disharmonize)"
// CHECK: @"\01L_selector_data(eviscerate)"
struct id {
var data : AnyObject
}
// Exporting something as [objc] doesn't make it an ObjC class.
@objc class Blammo {
}
// Class and methods are [objc] by inheritance.
class MyBlammo : Blammo {
func foo() {}
// CHECK: define hidden swiftcc void @"$s4objc8MyBlammoC3fooyyF"([[MYBLAMMO]]* swiftself) {{.*}} {
// CHECK: call {{.*}} @swift_release
// CHECK: ret void
}
// Class and methods are [objc] by inheritance.
class Test2 : Gizmo {
func foo() {}
// CHECK: define hidden swiftcc void @"$s4objc5Test2C3fooyyF"([[TEST2]]* swiftself) {{.*}} {
// CHECK: call {{.*}} @llvm.objc.release
// CHECK: ret void
@objc dynamic func bar() {}
}
// Test @nonobjc.
class Contrarian : Blammo {
@objc func acquiesce() {}
@nonobjc func disharmonize() {}
@nonobjc func eviscerate() {}
}
class Octogenarian : Contrarian {
// Override of @nonobjc is @objc again unless made @nonobjc.
@nonobjc override func disharmonize() {}
// Override of @nonobjc can be @objc.
@objc override func eviscerate() {}
}
@_silgen_name("unknown")
func unknown(_ x: id) -> id
// CHECK: define hidden swiftcc %objc_object* @"$s4objc5test0{{[_0-9a-zA-Z]*}}F"(%objc_object*)
// CHECK-NOT: call {{.*}} @swift_unknownObjectRetain
// CHECK: call {{.*}} @swift_unknownObjectRetain
// CHECK-NOT: call {{.*}} @swift_unknownObjectRelease
// CHECK: call {{.*}} @swift_unknownObjectRelease
// CHECK: ret %objc_object*
func test0(_ arg: id) -> id {
var x : id
x = arg
unknown(x)
var y = x
return y
}
func test1(_ cell: Blammo) {}
// CHECK: define hidden swiftcc void @"$s4objc5test1{{[_0-9a-zA-Z]*}}F"([[BLAMMO]]*) {{.*}} {
// CHECK-NEXT: entry
// CHECK-NEXT: alloca
// CHECK-NEXT: bitcast
// CHECK-NEXT: memset
// CHECK-NEXT: store
// CHECK-NEXT: ret void
// FIXME: These ownership convention tests should become SILGen tests.
func test2(_ v: Test2) { v.bar() }
func test3() -> NSObject {
return Gizmo()
}
// Normal message send with argument, no transfers.
func test5(_ g: Gizmo) {
Gizmo.inspect(g)
}
// The argument to consume: is __attribute__((ns_consumed)).
func test6(_ g: Gizmo) {
Gizmo.consume(g)
}
// fork is __attribute__((ns_consumes_self)).
func test7(_ g: Gizmo) {
g.fork()
}
// clone is __attribute__((ns_returns_retained)).
func test8(_ g: Gizmo) {
g.clone()
}
// duplicate has an object returned at +0.
func test9(_ g: Gizmo) {
g.duplicate()
}
func test10(_ g: Gizmo, r: Rect) {
Gizmo.run(with: r, andGizmo:g);
}
// Force the emission of the Rect metadata.
func test11_helper<T>(_ t: T) {}
// NSRect's metadata needs to be uniqued at runtime using getForeignTypeMetadata.
// CHECK-LABEL: define hidden swiftcc void @"$s4objc6test11yySo4RectVF"
// CHECK: call swiftcc %swift.metadata_response @swift_getForeignTypeMetadata(i64 %0, {{.*}} @"$sSo4RectVN"
func test11(_ r: Rect) { test11_helper(r) }
class WeakObjC {
weak var obj: NSObject?
weak var id: AnyObject?
init() {
var foo = obj
var bar: AnyObject? = id
}
}
// rdar://17528908
// CHECK: i32 1, !"Objective-C Version", i32 2}
// CHECK: i32 1, !"Objective-C Image Info Version", i32 0}
// CHECK: i32 1, !"Objective-C Image Info Section", !"__DATA,__objc_imageinfo,regular,no_dead_strip"}
// 83887872 == (5 << 24) | (0 << 16) | (7 << 8).
// 5 and 0 is the current major.minor version. 7 is the Swift ABI version.
// CHECK: i32 4, !"Objective-C Garbage Collection", i32 83887872}
// CHECK: i32 1, !"Swift Version", i32 7}
| apache-2.0 | 8f3d766b8ececb0d0de9b5af560754b4 | 30.366013 | 234 | 0.648468 | 3.130463 | false | true | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/RulerControllerWithScrollView.swift | 1 | 3574 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
import UIKit
import SnapKit
class RulerControllerWithScrollView: UIViewController, UIScrollViewDelegate {
let DIAMETER: CGFloat = 80
let MARGIN: CGFloat = 16
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.clipsToBounds = true
automaticallyAdjustsScrollViewInsets = false
let touchView = TouchDelegateView()
touchView.touchDelegateView = scrollView
view.addSubview(touchView)
touchView.snp.makeConstraints { (make) in
make.top.bottom.leading.trailing.equalTo(view)
}
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
make.top.bottom.equalTo(view)
make.width.equalTo(DIAMETER + MARGIN)
make.centerX.equalTo(view)
}
scrollView.clipsToBounds = false
scrollView.addSubview(contentView)
for subview in contentView.subviews {
subview.removeFromSuperview()
}
let count = 10000
let y = (scrollView.frame.height - (DIAMETER + MARGIN)) / 2
scrollView.contentSize = CGSize(width: (DIAMETER + MARGIN) * CGFloat(count), height: view.frame.height)
contentView.snp.makeConstraints { (make) in
make.height.equalTo(scrollView)
make.width.equalTo(scrollView.contentSize.width)
make.edges.equalTo(scrollView)
}
for i in 0 ..< count {
let x = MARGIN / 2 + CGFloat(i) * (DIAMETER + MARGIN)
let frame = CGRect(x: x, y: y, width: DIAMETER, height: 200)
let imageView = UIView(frame: frame)
imageView.backgroundColor = UIColor.lightGray
imageView.layer.masksToBounds = true
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin]
contentView.addSubview(imageView)
let graduationLine = CALayer()
graduationLine.frame = CGRect(x: (frame.width - 1) / 2, y: 0, width: 1, height: frame.height)
graduationLine.backgroundColor = UIColor.red.cgColor
imageView.layer.addSublayer(graduationLine)
}
let line = CALayer()
line.frame = CGRect(x: (view.frame.width - 1) / 2, y: 0, width: 1, height: view.frame.height)
line.backgroundColor = UIColor.red.cgColor
view.layer.addSublayer(line)
}
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.delegate = self
return scrollView
}()
private lazy var contentView: UIView = {
let contentView = UIView()
return contentView
}()
func nearestTargetOffset(for offset: CGPoint) -> CGPoint {
let pageSize: CGFloat = DIAMETER + MARGIN
let page = roundf(Float(offset.x / pageSize))
let targetX = pageSize * CGFloat(page)
return CGPoint(x: targetX, y: offset.y)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffset = nearestTargetOffset(for: targetContentOffset.pointee)
targetContentOffset.pointee.x = targetOffset.x
targetContentOffset.pointee.y = targetOffset.y
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
print("\(classForCoder)释放")
}
}
| mit | eb31e796e86e97ddbc42403438a4b89e | 33.970588 | 148 | 0.635548 | 4.872951 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Essence-精华/View/XMGTopicPictureView.swift | 1 | 4407 | //
// XMGTopicPictureView.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/2/22.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
import DACircularProgress
class XMGTopicPictureView: UIView {
/** 图片 */
@IBOutlet weak var imageView: UIImageView!
/** gif标识 */
@IBOutlet weak var gifView: UIImageView!
/** 查看大图按钮 */
@IBOutlet weak var seeBigButton: UIButton!
/** 进度条控件 */
@IBOutlet weak var progressView: XMGProgressView!
/*
/// 加载XIB
static func pictureView()->XMGTopicPictureView {
return NSBundle.mainBundle().loadNibNamed("XMGTopicPictureView", owner: nil, options: nil).first as! XMGTopicPictureView
}
*/
override func awakeFromNib() {
// 取消自动调整伸缩
self.autoresizingMask = UIViewAutoresizing.None;
// 给图片添加监听器
self.imageView.userInteractionEnabled = true
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "showPicture")
self.imageView.addGestureRecognizer(tap)
}
func showPicture(){
let showPicture:XMGShowPictureViewController = XMGShowPictureViewController()
showPicture.topic = self.topic;
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(showPicture, animated: true, completion: nil)
}
var topic:XMGTopic?{
didSet{
weak var weakSelf = self
// 立马显示最新的进度值(防止因为网速慢, 导致显示的是其他图片的下载进度)
self.progressView.setProgress(self.topic!.pictureProgress, animated: true)
// 设置图片带进度
self.imageView.sd_setImageWithURL(NSURL(string: topic!.large_image!),placeholderImage: nil, options: .CacheMemoryOnly, progress: { (receivedSize, expectedSize) -> Void in
//TODO:会报错
if let weakSelf = weakSelf {
weakSelf.progressView.hidden = false
weakSelf.topic!.pictureProgress = CGFloat(receivedSize)/CGFloat(expectedSize)
weakSelf.progressView.setProgress((weakSelf.topic!.pictureProgress), animated: false)
}
}) {(image, error, cacheType, imageURL) -> Void in
if let weakSelf = weakSelf {
weakSelf.progressView.hidden = true
// 如果是大图片, 才需要进行绘图处理
if (weakSelf.topic!.isBigPicture == false) {return}
// 开启图形上下文
UIGraphicsBeginImageContextWithOptions((weakSelf.topic!.pictureF.size), true, 0.0);
if image == nil{
return
}
let width:CGFloat = (weakSelf.topic!.pictureF.size.width)
let height:CGFloat = width * (image?.size.height)! / (image?.size.width)!;
image.drawInRect(CGRectMake(0, 0, width, height))
// 获得图片
weakSelf.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
// 关闭上下文
UIGraphicsEndImageContext();
}
}
// 判断是否为gif
let extensio:NSString = (topic!.large_image! as NSString).pathExtension
self.gifView.hidden = !(extensio.lowercaseString as NSString).isEqualToString("gif")
// 判断是否显示"点击查看全图"
if (topic!.isBigPicture) { // 大图
self.seeBigButton.hidden = false
self.imageView.contentMode = UIViewContentMode.ScaleAspectFill;
} else { // 非大图
self.seeBigButton.hidden = true
self.imageView.contentMode = UIViewContentMode.ScaleToFill;
}
}
}
}
| apache-2.0 | 904907bd38a7c7139a02a95bfc53d430 | 31.598425 | 183 | 0.528986 | 5.44021 | false | false | false | false |
meetkei/KxUI | KxUI/View/Switch/KUUserDefaultsSwitch.swift | 1 | 2246 | //
// Copyright (c) 2016 Keun young Kim <[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.
//
open class KUUserDefaultsSwitch: UISwitch {
open override var isOn: Bool {
didSet {
if let key = userDefaultsKey {
UserDefaults.standard.set(isOn, forKey: key)
}
}
}
@IBInspectable open var userDefaultsKey: String? = nil {
didSet {
update()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
update(false)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
update(false)
}
open override func setOn(_ on: Bool, animated: Bool) {
super.setOn(on, animated: animated)
if let key = userDefaultsKey {
UserDefaults.standard.set(on, forKey: key)
}
}
open func update(_ animated: Bool = true) {
if let key = userDefaultsKey {
let isTrue = UserDefaults.standard.bool(forKey: key)
print("UPDATE with \(key) \(isTrue)")
setOn(isTrue, animated: animated)
}
}
}
| mit | fe644e116356652162ed9372814036b3 | 33.030303 | 81 | 0.643811 | 4.51004 | false | false | false | false |
btanner/Eureka | Source/Rows/PopoverSelectorRow.swift | 8 | 2467 | // PopoverSelectorRow.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
open class _PopoverSelectorRow<Cell: CellType> : SelectorRow<Cell> where Cell: BaseCell {
public required init(tag: String?) {
super.init(tag: tag)
onPresentCallback = { [weak self] (_, viewController) -> Void in
guard let porpoverController = viewController.popoverPresentationController, let tableView = self?.baseCell.formViewController()?.tableView, let cell = self?.cell else {
fatalError()
}
porpoverController.sourceView = tableView
porpoverController.sourceRect = tableView.convert(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, from: cell)
}
presentationMode = .popover(controllerProvider: ControllerProvider.callback { return SelectorViewController<SelectorRow<Cell>> { _ in } }, onDismiss: { [weak self] in
$0.dismiss(animated: true)
self?.reload()
})
}
open override func didSelect() {
deselect()
super.didSelect()
}
}
public final class PopoverSelectorRow<T: Equatable> : _PopoverSelectorRow<PushSelectorCell<T>>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
| mit | b31b595839a748f65ed0c5b7c5851777 | 43.854545 | 181 | 0.708148 | 4.637218 | false | false | false | false |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/NewCardViewController.swift | 1 | 14428 | //
// NewCardViewController.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 29/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
import UIKit
public class NewCardViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, KeyboardDelegate {
// ViewController parameters
var key : String?
var keyType : String?
var paymentMethod: PaymentMethod?
var requireSecurityCode : Bool?
var callback: ((cardToken: CardToken) -> Void)?
var identificationType : IdentificationType?
var identificationTypes : [IdentificationType]?
var bundle : NSBundle? = MercadoPago.getBundle()
// Input controls
@IBOutlet weak private var tableView : UITableView!
var cardNumberCell : MPCardNumberTableViewCell!
var expirationDateCell : MPExpirationDateTableViewCell!
var cardholderNameCell : MPCardholderNameTableViewCell!
var userIdCell : MPUserIdTableViewCell!
var securityCodeCell : MPSecurityCodeTableViewCell!
var hasError : Bool = false
var loadingView : UILoadingView!
var inputsCells : NSMutableArray!
init(keyType: String, key: String, paymentMethod: PaymentMethod, requireSecurityCode: Bool, callback: ((cardToken: CardToken) -> Void)?) {
super.init(nibName: "NewCardViewController", bundle: bundle)
self.paymentMethod = paymentMethod
self.requireSecurityCode = requireSecurityCode
self.key = key
self.keyType = keyType
self.callback = callback
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public init() {
super.init(nibName: nil, bundle: nil)
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override public func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override public func viewDidLoad() {
super.viewDidLoad()
self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized)
self.title = "Datos de tu tarjeta".localized
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás".localized, style: UIBarButtonItemStyle.Plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Continuar".localized, style: UIBarButtonItemStyle.Plain, target: self, action: "submitForm")
self.view.addSubview(self.loadingView)
var mercadoPago : MercadoPago
mercadoPago = MercadoPago(keyType: self.keyType, key: self.key)
mercadoPago.getIdentificationTypes({(identificationTypes: [IdentificationType]?) -> Void in
self.identificationTypes = identificationTypes
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}, failure: { (error: NSError?) -> Void in
if error?.code == MercadoPago.ERROR_API_CODE {
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
self.userIdCell.hidden = true
}
}
)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willShowKeyboard:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willHideKeyboard:", name: UIKeyboardWillHideNotification, object: nil)
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func willHideKeyboard(notification: NSNotification) {
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, 0.0, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
func willShowKeyboard(notification: NSNotification) {
let s:NSValue? = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)
let keyboardBounds :CGRect = s!.CGRectValue()
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, keyboardBounds.size.height, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
public func getIndexForObject(object: AnyObject) -> Int {
var i = 0
for arr in self.inputsCells {
if let input = object as? UITextField {
if let arrTextField = (arr as! NSArray)[0] as? UITextField {
if input == arrTextField {
return i
}
}
}
i = i + 1
}
return -1
}
public func scrollToRow(indexPath: NSIndexPath) {
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
public func focusAndScrollForIndex(index: Int) {
var i = 0
for arr in self.inputsCells {
if i == index {
if let textField = (arr as! NSArray)[0] as? UITextField {
if let cell = (arr as! NSArray)[1] as? ErrorTableViewCell {
if !textField.isFirstResponder() {
textField.becomeFirstResponder()
}
let indexPath = self.tableView.indexPathForCell(cell)
if indexPath != nil {
scrollToRow(indexPath!)
}
}
}
}
i = i + 1
}
}
public func prev(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index >= 1 {
focusAndScrollForIndex(index-1)
}
}
}
public func next(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index < self.inputsCells.count - 1 {
focusAndScrollForIndex(index+1)
}
}
}
public func done(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index < self.inputsCells.count {
var i = 0
for arr in self.inputsCells {
if i == index {
if let textField = (arr as! NSArray)[0] as? UITextField {
textField.resignFirstResponder()
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
scrollToRow(indexPath)
}
}
i = i + 1
}
}
}
}
public func prepareTableView() {
self.inputsCells = NSMutableArray()
let cardNumberNib = UINib(nibName: "MPCardNumberTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardNumberNib, forCellReuseIdentifier: "cardNumberCell")
self.cardNumberCell = self.tableView.dequeueReusableCellWithIdentifier("cardNumberCell") as! MPCardNumberTableViewCell
self.cardNumberCell.height = 55.0
if self.paymentMethod != nil {
self.cardNumberCell.setIcon(self.paymentMethod!._id)
self.cardNumberCell._setSetting(self.paymentMethod!.settings[0])
}
self.cardNumberCell.cardNumberTextField.inputAccessoryView = MPToolbar(prevEnabled: false, nextEnabled: true, delegate: self, textFieldContainer: self.cardNumberCell.cardNumberTextField)
self.inputsCells.addObject([self.cardNumberCell.cardNumberTextField, self.cardNumberCell])
let expirationDateNib = UINib(nibName: "MPExpirationDateTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(expirationDateNib, forCellReuseIdentifier: "expirationDateCell")
self.expirationDateCell = self.tableView.dequeueReusableCellWithIdentifier("expirationDateCell") as! MPExpirationDateTableViewCell
self.expirationDateCell.height = 55.0
self.expirationDateCell.expirationDateTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.expirationDateCell.expirationDateTextField)
self.inputsCells.addObject([self.expirationDateCell.expirationDateTextField, self.expirationDateCell])
let cardholderNameNib = UINib(nibName: "MPCardholderNameTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardholderNameNib, forCellReuseIdentifier: "cardholderNameCell")
self.cardholderNameCell = self.tableView.dequeueReusableCellWithIdentifier("cardholderNameCell") as! MPCardholderNameTableViewCell
self.cardholderNameCell.height = 55.0
self.cardholderNameCell.cardholderNameTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.cardholderNameCell.cardholderNameTextField)
self.inputsCells.addObject([self.cardholderNameCell.cardholderNameTextField, self.cardholderNameCell])
let userIdNib = UINib(nibName: "MPUserIdTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(userIdNib, forCellReuseIdentifier: "userIdCell")
self.userIdCell = self.tableView.dequeueReusableCellWithIdentifier("userIdCell") as! MPUserIdTableViewCell
self.userIdCell._setIdentificationTypes(self.identificationTypes)
self.userIdCell.height = 55.0
self.userIdCell.userIdTypeTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdTypeTextField)
self.userIdCell.userIdValueTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdValueTextField)
self.inputsCells.addObject([self.userIdCell.userIdTypeTextField, self.userIdCell])
self.inputsCells.addObject([self.userIdCell.userIdValueTextField, self.userIdCell])
self.tableView.delegate = self
self.tableView.dataSource = self
}
public func submitForm() {
let cardToken = CardToken(cardNumber: self.cardNumberCell.getCardNumber(), expirationMonth: self.expirationDateCell.getExpirationMonth(), expirationYear: self.expirationDateCell.getExpirationYear(), securityCode: nil, cardholderName: self.cardholderNameCell.getCardholderName(), docType: self.userIdCell.getUserIdType(), docNumber: self.userIdCell.getUserIdValue())
self.view.addSubview(self.loadingView)
if validateForm(cardToken) {
callback!(cardToken: cardToken)
} else {
self.hasError = true
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell
} else if indexPath.row == 1 {
return self.expirationDateCell
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell
} else if indexPath.row == 1 {
return self.userIdCell
}
}
return UITableViewCell()
}
override public func viewDidLayoutSubviews() {
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
self.tableView.separatorInset = UIEdgeInsetsZero
}
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
if #available(iOS 8.0, *) {
self.tableView.layoutMargins = UIEdgeInsetsZero
} else {
}
}
}
public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
if #available(iOS 8.0, *) {
cell.layoutMargins = UIEdgeInsetsZero
} else {
}
}
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell.getHeight()
} else if indexPath.row == 1 {
return self.expirationDateCell.getHeight()
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell.getHeight()
} else if indexPath.row == 1 {
return self.userIdCell.getHeight()
}
}
return 55
}
public func validateForm(cardToken : CardToken) -> Bool {
var result : Bool = true
// Validate card number
let errorCardNumber = cardToken.validateCardNumber(paymentMethod!)
if errorCardNumber != nil {
self.cardNumberCell.setError(errorCardNumber!.userInfo["cardNumber"] as? String)
result = false
} else {
self.cardNumberCell.setError(nil)
}
// Validate expiry date
let errorExpiryDate = cardToken.validateExpiryDate()
if errorExpiryDate != nil {
self.expirationDateCell.setError(errorExpiryDate!.userInfo["expiryDate"] as? String)
result = false
} else {
self.expirationDateCell.setError(nil)
}
// Validate card holder name
let errorCardholder = cardToken.validateCardholderName()
if errorCardholder != nil {
self.cardholderNameCell.setError(errorCardholder!.userInfo["cardholder"] as? String)
result = false
} else {
self.cardholderNameCell.setError(nil)
}
// Validate identification number
let errorIdentificationType = cardToken.validateIdentificationType()
var errorIdentificationNumber : NSError? = nil
if self.identificationType != nil {
errorIdentificationNumber = cardToken.validateIdentificationNumber(self.identificationType!)
} else {
errorIdentificationNumber = cardToken.validateIdentificationNumber()
}
if errorIdentificationType != nil {
self.userIdCell.setError(errorIdentificationType!.userInfo["identification"] as? String)
result = false
} else if errorIdentificationNumber != nil {
self.userIdCell.setError(errorIdentificationNumber!.userInfo["identification"] as? String)
result = false
} else {
self.userIdCell.setError(nil)
}
return result
}
} | mit | 1062a03bbcf70efb773a11443dbbf0c4 | 37.068602 | 373 | 0.704235 | 4.610738 | false | false | false | false |
vimeo/VimeoNetworking | Sources/Shared/Requests/Request+Album.swift | 1 | 3918 | //
// Request+Album.swift
// VimeoNetworking
//
// Copyright © 2018 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
fileprivate enum Key {
static let name = "name"
static let description = "description"
static let password = "password"
static let privacy = "privacy"
}
public extension Request {
/// Returns a new request to fetch a specific album.
///
/// - Parameter uri: The album's URI.
/// - Returns: Returns a new `Request` for an individual album.
static func albumRequest(for uri: String) -> Request {
return Request(path: uri)
}
/// Returns a new request for creating an album.
/// - Parameter userURI: The URI for the current user, and owner of the album being created.
/// - Parameter name: The name of the album being created.
/// - Parameter description: An optional description for the album.
/// - Parameter privacy: The privacy parameter as a String. If none is specified it defaults to "anyone".
/// - Parameter password: An optional password parameter, only required when privacy is set to "password".
static func createAlbumRequest(
userURI: String,
name: String,
description: String? = nil,
privacy: String = VIMPrivacy_Public,
password: String? = nil
) -> Request {
var parameters = [String: String]()
parameters[Key.name] = name
parameters[Key.description] = description
parameters[Key.privacy] = privacy
password.map { parameters[Key.password] = $0 }
return Request(method: .post, path: userURI + "/albums", parameters: parameters)
}
/// Returns a new request for updating an exising album.
/// - Parameter albumURI: The URI for the album that will be updated.
/// - Parameter name: The name of the album.
/// - Parameter description: An optional description for the album.
/// - Parameter privacy: The privacy parameter as a String.
/// - Parameter password: An optional password parameter, only required when the privacy is set to "password".
static func updateAlbumRequest(
albumURI: String,
name: String,
description: String? = nil,
privacy: String?,
password: String? = nil
) -> Request {
var parameters = [String: String]()
parameters[Key.name] = name
parameters[Key.description] = description
privacy.map { parameters[Key.privacy] = $0 }
password.map { parameters[Key.password] = $0 }
return Request(method: .patch, path: albumURI, parameters: parameters)
}
/// Returns a new request to delete the album for the given URI.
/// - Parameter albumURI: The album's URI.
static func deleteAlbumRequest(for albumURI: String) -> Request {
return Request(method: .delete, path: albumURI)
}
}
| mit | 5d7fc470db2c2a40f6cb2983f2c78ec8 | 42.043956 | 114 | 0.680112 | 4.436014 | false | false | false | false |
pascalodek/Tip_calculator | Tip-Calculator/TipCalculatorModel.swift | 1 | 2317 | //
// TipCalculatorModel.swift
// Tip-Calculator
//
// Created by PASCAL ARINGO ODEK on 12/25/14.
// Copyright (c) 2014 Pascal Odek. All rights reserved.
//
import Foundation
class TipCalculatorModel {
var total: Double
var taxPct: Double
var subtotal: Double {
get {
return total / (taxPct + 1)
}
}
init(total: Double, taxPct: Double) {
self.total = total
self.taxPct = taxPct
}
func calcTipWithTipPct(tipPct:Double) -> (tipAmt:Double, total:Double) {
let tipAmt = subtotal * tipPct
let finalTotal = total + tipAmt
return (tipAmt, finalTotal)
}
func returnPossibleTips() -> [Int: (tipAmt:Double, total:Double)] {
let possibleTipsInferred = [0.15, 0.18, 0.20]
let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20]
var retval = Dictionary<Int, (tipAmt:Double, total:Double)>()
for possibleTip in possibleTipsInferred {
let intPct = Int(possibleTip*100)
retval[intPct] = calcTipWithTipPct(possibleTip)
}
return retval
}
}
// 1
import UIKit
// 2
class TestDataSource: NSObject, UITableViewDataSource {
// 3
let tipCalc = TipCalculatorModel(total: 33.25, taxPct: 0.06)
var possibleTips = Dictionary<Int, (tipAmt:Double, total:Double)>()
var sortedKeys:[Int] = []
// 4
override init() {
possibleTips = tipCalc.returnPossibleTips()
sortedKeys = sorted(Array(possibleTips.keys))
super.init()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedKeys.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 2
let cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: nil)
// 3
let tipPct = sortedKeys[indexPath.row]
// 4
let tipAmt = possibleTips[tipPct]!.tipAmt
let total = possibleTips[tipPct]!.total
// 5
cell.textLabel?.text = "\(tipPct)%:"
cell.detailTextLabel?.text = String(format:"Tip: $%0.2f, Total: $%0.2f", tipAmt, total)
return cell
}
}
| mit | f5579854700a159095f0ddbd947c1fa9 | 26.258824 | 109 | 0.598187 | 4.159785 | false | false | false | false |
benlangmuir/swift | test/DebugInfo/apple-types-accel.swift | 21 | 1039 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend %s -c -g -o %t.o
// RUN: %llvm-dwarfdump --apple-types %t.o \
// RUN: | %FileCheck --check-prefix=CHECK-ACCEL %s
// RUN: %llvm-dwarfdump --debug-info %t.o \
// RUN: | %FileCheck --check-prefix=CHECK-DWARF %s
// RUN: %llvm-dwarfdump --verify %t.o
// REQUIRES: OS=macosx
// Verify that the unmangles basenames end up in the accelerator table.
// CHECK-ACCEL-DAG: String: {{.*}}"Int64"
// CHECK-ACCEL-DAG: String: {{.*}}"foo"
// Verify that the mangled names end up in the debug info.
// CHECK-DWARF: TAG_module
// CHECK-DWARF-NEXT: AT_name ("main")
// CHECK-DWARF: TAG_structure_type
// CHECK-DWARF-NEXT: AT_name ("foo")
// CHECK-DWARF-NEXT: AT_linkage_name ("$s4main3fooCD")
// Verify the IR interface:
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "foo"
// CHECK-SAME: identifier: "$s4main3fooCD"
class foo {
var x : Int64 = 1
}
func main() -> Int64 {
var thefoo = foo();
return thefoo.x
}
main()
| apache-2.0 | 2a5b13cdab690eb259b831a1da05dfa7 | 30.484848 | 71 | 0.643888 | 2.698701 | false | false | false | false |
Handbid/Handbid-Swift | Handbid/AppDelegate.swift | 1 | 6116 | //
// AppDelegate.swift
// Handbid
//
// Created by Jon Hemstreet on 10/31/14.
// Copyright (c) 2014 Handbid. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.handbid.Handbid" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Handbid", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Handbid.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 793d6bc84ec74b55297ad39f618bea6e | 54.099099 | 290 | 0.715991 | 5.758945 | false | false | false | false |
kousun12/RxSwift | RxSwift/Observables/Implementations/Buffer.swift | 4 | 3017 | //
// Buffer.swift
// Rx
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class BufferTimeCount<Element, S: SchedulerType> : Producer<[Element]> {
private let _timeSpan: S.TimeInterval
private let _count: Int
private let _scheduler: S
private let _source: Observable<Element>
init(source: Observable<Element>, timeSpan: S.TimeInterval, count: Int, scheduler: S) {
_source = source
_timeSpan = timeSpan
_count = count
_scheduler = scheduler
}
override func run<O : ObserverType where O.E == [Element]>(observer: O) -> Disposable {
let sink = BufferTimeCountSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
}
class BufferTimeCountSink<S: SchedulerType, Element, O: ObserverType where O.E == [Element]>
: Sink<O>
, LockOwnerType
, ObserverType
, SynchronizedOnType {
typealias Parent = BufferTimeCount<Element, S>
typealias E = Element
private let _parent: Parent
let _lock = NSRecursiveLock()
// state
private let _timerD = SerialDisposable()
private var _buffer = [Element]()
private var _windowID = 0
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
createTimer(_windowID)
return StableCompositeDisposable.create(_timerD, _parent._source.subscribe(self))
}
func startNewWindowAndSendCurrentOne() {
_windowID = _windowID &+ 1
let windowID = _windowID
let buffer = _buffer
_buffer = []
forwardOn(.Next(buffer))
createTimer(windowID)
}
func on(event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<E>) {
switch event {
case .Next(let element):
_buffer.append(element)
if _buffer.count == _parent._count {
startNewWindowAndSendCurrentOne()
}
case .Error(let error):
_buffer = []
forwardOn(.Error(error))
dispose()
case .Completed:
forwardOn(.Next(_buffer))
forwardOn(.Completed)
dispose()
}
}
func createTimer(windowID: Int) {
if _timerD.disposed {
return
}
if _windowID != windowID {
return
}
_timerD.disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in
self._lock.performLocked {
if previousWindowID != self._windowID {
return
}
self.startNewWindowAndSendCurrentOne()
}
return NopDisposable.instance
}
}
} | mit | f104d3c20322fc4c5f102ccdcf2c88f8 | 25.234783 | 124 | 0.557029 | 4.727273 | false | false | false | false |
jjatie/Charts | Source/Charts/Renderers/LegendRenderer.swift | 1 | 17362 | //
// LegendRenderer.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 CoreGraphics
import Foundation
open class LegendRenderer: Renderer {
public let viewPortHandler: ViewPortHandler
/// the legend object this renderer renders
open var legend: Legend?
public init(viewPortHandler: ViewPortHandler, legend: Legend?) {
self.viewPortHandler = viewPortHandler
self.legend = legend
}
/// Prepares the legend and calculates all needed forms, labels and colors.
open func computeLegend(data: ChartData) {
guard let legend = legend else { return }
if !legend.isLegendCustom {
var entries: [LegendEntry] = []
// loop for building up the colors and labels used in the legend
for dataSet in data {
let clrs: [NSUIColor] = dataSet.colors
let entryCount = dataSet.count
// if we have a barchart with stacked bars
if dataSet is BarChartDataSet,
(dataSet as! BarChartDataSet).isStacked
{
let bds = dataSet as! BarChartDataSet
let sLabels = bds.stackLabels
let minEntries = min(clrs.count, bds.stackSize)
for j in 0 ..< minEntries {
let label: String?
if !sLabels.isEmpty, minEntries > 0 {
let labelIndex = j % minEntries
label = sLabels.indices.contains(labelIndex) ? sLabels[labelIndex] : nil
} else {
label = nil
}
var entry = LegendEntry(label: label)
entry.form = dataSet.form
entry.formSize = dataSet.formSize
entry.formLineWidth = dataSet.formLineWidth
entry.formLineDashPhase = dataSet.formLineDashPhase
entry.formLineDashLengths = dataSet.formLineDashLengths
entry.formColor = clrs[j]
entries.append(entry)
}
if dataSet.label != nil {
// add the legend description label
var entry = LegendEntry(label: dataSet.label)
entry.form = .none
entries.append(entry)
}
} else if dataSet is PieChartDataSet {
let pds = dataSet as! PieChartDataSet
for j in 0 ..< min(clrs.count, entryCount) {
var entry = LegendEntry(label: (pds[j] as? PieChartDataEntry)?.label)
entry.form = dataSet.form
entry.formSize = dataSet.formSize
entry.formLineWidth = dataSet.formLineWidth
entry.formLineDashPhase = dataSet.formLineDashPhase
entry.formLineDashLengths = dataSet.formLineDashLengths
entry.formColor = clrs[j]
entries.append(entry)
}
if dataSet.label != nil {
// add the legend description label
var entry = LegendEntry(label: dataSet.label)
entry.form = .none
entries.append(entry)
}
} else if dataSet is CandleChartDataSet,
(dataSet as! CandleChartDataSet).decreasingColor != nil
{
let candleDataSet = dataSet as! CandleChartDataSet
var decreasingEntry = LegendEntry(label: nil)
decreasingEntry.form = dataSet.form
decreasingEntry.formSize = dataSet.formSize
decreasingEntry.formLineWidth = dataSet.formLineWidth
decreasingEntry.formLineDashPhase = dataSet.formLineDashPhase
decreasingEntry.formLineDashLengths = dataSet.formLineDashLengths
decreasingEntry.formColor = candleDataSet.decreasingColor
entries.append(decreasingEntry)
var increasingEntry = LegendEntry(label: dataSet.label)
increasingEntry.form = dataSet.form
increasingEntry.formSize = dataSet.formSize
increasingEntry.formLineWidth = dataSet.formLineWidth
increasingEntry.formLineDashPhase = dataSet.formLineDashPhase
increasingEntry.formLineDashLengths = dataSet.formLineDashLengths
increasingEntry.formColor = candleDataSet.increasingColor
entries.append(increasingEntry)
} else { // all others
for j in 0 ..< min(clrs.count, entryCount) {
let label: String?
// if multiple colors are set for a DataSet, group them
if j < clrs.count - 1, j < entryCount - 1 {
label = nil
} else { // add label to the last entry
label = dataSet.label
}
var entry = LegendEntry(label: label)
entry.form = dataSet.form
entry.formSize = dataSet.formSize
entry.formLineWidth = dataSet.formLineWidth
entry.formLineDashPhase = dataSet.formLineDashPhase
entry.formLineDashLengths = dataSet.formLineDashLengths
entry.formColor = clrs[j]
entries.append(entry)
}
}
}
legend.entries = entries + legend.extraEntries
}
// calculate all dimensions of the legend
legend.calculateDimensions(labelFont: legend.font, viewPortHandler: viewPortHandler)
}
open func renderLegend(context: CGContext) {
guard let legend = legend else { return }
if !legend.isEnabled {
return
}
let labelFont = legend.font
let labelTextColor = legend.textColor
let labelLineHeight = labelFont.lineHeight
let formYOffset = labelLineHeight / 2.0
let entries = legend.entries
let defaultFormSize = legend.formSize
let formToTextSpace = legend.formToTextSpace
let xEntrySpace = legend.xEntrySpace
let yEntrySpace = legend.yEntrySpace
let orientation = legend.orientation
let horizontalAlignment = legend.horizontalAlignment
let verticalAlignment = legend.verticalAlignment
let direction = legend.direction
// space between the entries
let stackSpace = legend.stackSpace
let yoffset = legend.yOffset
let xoffset = legend.xOffset
var originPosX: CGFloat = 0.0
switch horizontalAlignment {
case .left:
if orientation == .vertical {
originPosX = xoffset
} else {
originPosX = viewPortHandler.contentLeft + xoffset
}
if direction == .rightToLeft {
originPosX += legend.neededWidth
}
case .right:
if orientation == .vertical {
originPosX = viewPortHandler.chartWidth - xoffset
} else {
originPosX = viewPortHandler.contentRight - xoffset
}
if direction == .leftToRight {
originPosX -= legend.neededWidth
}
case .center:
if orientation == .vertical {
originPosX = viewPortHandler.chartWidth / 2.0
} else {
originPosX = viewPortHandler.contentLeft
+ viewPortHandler.contentWidth / 2.0
}
originPosX += (direction == .leftToRight
? +xoffset
: -xoffset)
// Horizontally layed out legends do the center offset on a line basis,
// So here we offset the vertical ones only.
if orientation == .vertical {
if direction == .leftToRight {
originPosX -= legend.neededWidth / 2.0 - xoffset
} else {
originPosX += legend.neededWidth / 2.0 - xoffset
}
}
}
switch orientation {
case .horizontal:
let calculatedLineSizes = legend.calculatedLineSizes
let calculatedLabelSizes = legend.calculatedLabelSizes
let calculatedLabelBreakPoints = legend.calculatedLabelBreakPoints
var posX: CGFloat = originPosX
var posY: CGFloat
switch verticalAlignment {
case .top:
posY = yoffset
case .bottom:
posY = viewPortHandler.chartHeight - yoffset - legend.neededHeight
case .center:
posY = (viewPortHandler.chartHeight - legend.neededHeight) / 2.0 + yoffset
}
var lineIndex: Int = 0
for i in entries.indices {
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
if i < calculatedLabelBreakPoints.endIndex,
calculatedLabelBreakPoints[i]
{
posX = originPosX
posY += labelLineHeight + yEntrySpace
}
if posX == originPosX,
horizontalAlignment == .center,
lineIndex < calculatedLineSizes.endIndex
{
posX += (direction == .rightToLeft
? calculatedLineSizes[lineIndex].width
: -calculatedLineSizes[lineIndex].width) / 2.0
lineIndex += 1
}
let isStacked = e.label == nil // grouped forms have null labels
if drawingForm {
if direction == .rightToLeft {
posX -= formSize
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend
)
if direction == .leftToRight {
posX += formSize
}
}
if !isStacked {
if drawingForm {
posX += direction == .rightToLeft ? -formToTextSpace : formToTextSpace
}
if direction == .rightToLeft {
posX -= calculatedLabelSizes[i].width
}
drawLabel(
context: context,
x: posX,
y: posY,
label: e.label!,
font: labelFont,
textColor: e.labelColor ?? labelTextColor
)
if direction == .leftToRight {
posX += calculatedLabelSizes[i].width
}
posX += direction == .rightToLeft ? -xEntrySpace : xEntrySpace
} else {
posX += direction == .rightToLeft ? -stackSpace : stackSpace
}
}
case .vertical:
// contains the stacked legend size in pixels
var stack = CGFloat(0.0)
var wasStacked = false
var posY: CGFloat = 0.0
switch verticalAlignment {
case .top:
posY = (horizontalAlignment == .center
? 0.0
: viewPortHandler.contentTop)
posY += yoffset
case .bottom:
posY = (horizontalAlignment == .center
? viewPortHandler.chartHeight
: viewPortHandler.contentBottom)
posY -= legend.neededHeight + yoffset
case .center:
posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 + legend.yOffset
}
for i in entries.indices {
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
var posX = originPosX
if drawingForm {
if direction == .leftToRight {
posX += stack
} else {
posX -= formSize - stack
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend
)
if direction == .leftToRight {
posX += formSize
}
}
if e.label != nil {
if drawingForm, !wasStacked {
posX += direction == .leftToRight ? formToTextSpace : -formToTextSpace
} else if wasStacked {
posX = originPosX
}
if direction == .rightToLeft {
posX -= (e.label! as NSString).size(withAttributes: [.font: labelFont]).width
}
if !wasStacked {
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: e.labelColor ?? labelTextColor)
} else {
posY += labelLineHeight + yEntrySpace
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: e.labelColor ?? labelTextColor)
}
// make a step down
posY += labelLineHeight + yEntrySpace
stack = 0.0
} else {
stack += formSize + stackSpace
wasStacked = true
}
}
}
}
private var _formLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
/// Draws the Legend-form at the given position with the color at the given index.
open func drawForm(
context: CGContext,
x: CGFloat,
y: CGFloat,
entry: LegendEntry,
legend: Legend
) {
guard
let formColor = entry.formColor,
formColor != NSUIColor.clear
else { return }
var form = entry.form
if form == .default {
form = legend.form
}
let formSize = entry.formSize.isNaN ? legend.formSize : entry.formSize
context.saveGState()
defer { context.restoreGState() }
switch form {
case .none:
// Do nothing
break
case .empty:
// Do not draw, but keep space for the form
break
case .default: fallthrough
case .circle:
context.setFillColor(formColor.cgColor)
context.fillEllipse(in: CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .square:
context.setFillColor(formColor.cgColor)
context.fill(CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .line:
let formLineWidth = entry.formLineWidth.isNaN ? legend.formLineWidth : entry.formLineWidth
let formLineDashPhase = entry.formLineDashPhase.isNaN ? legend.formLineDashPhase : entry.formLineDashPhase
let formLineDashLengths = entry.formLineDashLengths == nil ? legend.formLineDashLengths : entry.formLineDashLengths
context.setLineWidth(formLineWidth)
if formLineDashLengths != nil, !formLineDashLengths!.isEmpty {
context.setLineDash(phase: formLineDashPhase, lengths: formLineDashLengths!)
} else {
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(formColor.cgColor)
_formLineSegmentsBuffer[0].x = x
_formLineSegmentsBuffer[0].y = y
_formLineSegmentsBuffer[1].x = x + formSize
_formLineSegmentsBuffer[1].y = y
context.strokeLineSegments(between: _formLineSegmentsBuffer)
}
}
/// Draws the provided label at the given position.
open func drawLabel(context: CGContext, x: CGFloat, y: CGFloat, label: String, font: NSUIFont, textColor: NSUIColor)
{
context.drawText(label, at: CGPoint(x: x, y: y), align: .left, attributes: [.font: font, .foregroundColor: textColor])
}
}
| apache-2.0 | 29b990f3bb26d9966cd4e6881c7dc926 | 35.246347 | 146 | 0.504377 | 6.258832 | false | false | false | false |
marcopolee/glimglam | Glimglam WatchKit Extension/NamespacesInterfaceController.swift | 1 | 1812 | //
// NamespacesInterfaceController.swift
// Glimglam WatchKit Extension
//
// Created by Tyrone Trevorrow on 15/10/17.
// Copyright © 2017 Marco Polee. All rights reserved.
//
import WatchKit
import Foundation
class NamespacesInterfaceController: WKInterfaceController {
var context: InterfaceContext!
@IBOutlet var table: WKInterfaceTable!
struct State {
let namespaces: [GitLab.Namespace]
}
var state = State(namespaces: []) {
didSet {
render()
}
}
override func awake(withContext context: Any?) {
self.context = context as! InterfaceContext
refreshData()
}
func refreshData() {
GitLab.API().getNamespaces(accessToken: context.context.gitLabLogin!) { res in
switch res {
case .Result(let namespaces):
self.state = State(namespaces: namespaces)
case .Error(let errStr):
print(errStr) // very sad
}
}
}
func render() {
table.setNumberOfRows(state.namespaces.count, withRowType: "Namespace")
for i in 0..<table.numberOfRows {
let row = table.rowController(at: i) as! NamespaceRowController
row.namespace = state.namespaces[i]
row.render()
}
}
override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? {
let namespace = state.namespaces[rowIndex]
return ProjectsInterfaceController.Context(context: context.context, namespace: namespace)
}
}
class NamespaceRowController: NSObject {
var namespace: GitLab.Namespace!
@IBOutlet var name: WKInterfaceLabel!
func render() {
name.setText(namespace.name)
}
}
| mit | 3a1ffe3382ed93646fc02589a5d4f008 | 27.296875 | 126 | 0.626726 | 4.778364 | false | false | false | false |
abunur/quran-ios | VFoundation/Crasher.swift | 1 | 2992 | //
// Crasher.swift
// Quran
//
// Created by Mohamed Afifi on 4/28/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
public class CrasherKeyBase {}
public final class CrasherKey<Type>: CrasherKeyBase {
public let key: String
public init(key: String) {
self.key = key
}
}
public protocol Crasher {
var tag: StaticString { get }
func setValue<T>(_ value: T?, forKey key: CrasherKey<T>)
func recordError(_ error: Error, reason: String, fatalErrorOnDebug: Bool, file: StaticString, line: UInt)
func log(_ message: String)
func logCriticalIssue(_ message: String)
var localizedUnkownError: String { get }
}
public struct Crash {
// should be set at the very begining of the app.
public static var crasher: Crasher?
public static func recordError(_ error: Error, reason: String, fatalErrorOnDebug: Bool = true, file: StaticString = #file, line: UInt = #line) {
Crash.crasher?.recordError(error, reason: reason, fatalErrorOnDebug: fatalErrorOnDebug, file: file, line: line)
}
public static func setValue<T>(_ value: T?, forKey key: CrasherKey<T>) {
Crash.crasher?.setValue(value, forKey: key)
}
}
public func log(_ items: Any..., separator: String = " ") {
let message = "[\(Crash.crasher?.tag ?? "_")]: " + items.map { "\($0)" }.joined(separator: separator)
NSLog(message)
}
public func CLog(_ items: Any..., separator: String = " ") {
let message = "[\(Crash.crasher?.tag ?? "_")]: " + items.map { "\($0)" }.joined(separator: separator)
NSLog(message)
Crash.crasher?.log(message)
}
public func logCriticalIssue(_ items: Any..., separator: String = " ") {
let message = "[\(Crash.crasher?.tag ?? "_")]: " + items.map { "\($0)" }.joined(separator: separator)
NSLog(message)
Crash.crasher?.logCriticalIssue(message)
}
public func fatalError(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Never {
CLog("message: \(message()), file:\(file.description), line:\(line)")
Swift.fatalError(message, file: file, line: line)
}
public func fatalError(_ message: @autoclosure () -> String = "", _ error: Error, file: StaticString = #file, line: UInt = #line) -> Never {
let fullMessage = "\(message()), error: \(error)"
CLog("message: \(fullMessage), file:\(file.description), line:\(line)")
Swift.fatalError(fullMessage, file: file, line: line)
}
| gpl-3.0 | e6b583a7c23dc80b36aa067373174958 | 36.873418 | 148 | 0.66377 | 3.801779 | false | false | false | false |
lorentey/swift | test/Serialization/Recovery/typedefs-in-enums.swift | 8 | 4722 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-sil -o - -emit-module-path %t/Lib.swiftmodule -module-name Lib -I %S/Inputs/custom-modules -disable-objc-attr-requires-foundation-module %s > /dev/null
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD | %FileCheck -check-prefix CHECK-RECOVERY %s
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s -verify
#if TEST
import Typedefs
import Lib
func use(_: OkayEnum) {}
// FIXME: Better to import the enum and make it unavailable.
func use(_: BadEnum) {} // expected-error {{use of undeclared type 'BadEnum'}}
func test() {
_ = producesOkayEnum()
_ = producesBadEnum() // expected-error {{use of unresolved identifier 'producesBadEnum'}}
// Force a lookup of the ==
_ = Optional(OkayEnum.noPayload).map { $0 == .noPayload }
}
#else // TEST
import Typedefs
public enum BadEnum {
case noPayload
case perfectlyOkayPayload(Int)
case problematic(Any, WrappedInt)
case alsoOkay(Any, Any, Any)
public static func ==(a: BadEnum, b: BadEnum) -> Bool {
return false
}
}
// CHECK-LABEL: enum BadEnum {
// CHECK-RECOVERY-NOT: enum BadEnum
public enum GenericBadEnum<T: HasAssoc> where T.Assoc == WrappedInt {
case noPayload
case perfectlyOkayPayload(Int)
public static func ==(a: GenericBadEnum<T>, b: GenericBadEnum<T>) -> Bool {
return false
}
}
// CHECK-LABEL: enum GenericBadEnum<T> where T : HasAssoc, T.Assoc == WrappedInt {
// CHECK-RECOVERY-NOT: enum GenericBadEnum
public enum OkayEnum {
case noPayload
case plainOldAlias(Any, UnwrappedInt)
case other(Int)
public static func ==(a: OkayEnum, b: OkayEnum) -> Bool {
return false
}
}
// CHECK-LABEL: enum OkayEnum {
// CHECK-NEXT: case noPayload
// CHECK-NEXT: case plainOldAlias(Any, UnwrappedInt)
// CHECK-NEXT: case other(Int)
// CHECK-NEXT: static func == (a: OkayEnum, b: OkayEnum) -> Bool
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: enum OkayEnum {
// CHECK-RECOVERY-NEXT: case noPayload
// CHECK-RECOVERY-NEXT: case plainOldAlias(Any, Int32)
// CHECK-RECOVERY-NEXT: case other(Int)
// CHECK-RECOVERY-NEXT: static func == (a: OkayEnum, b: OkayEnum) -> Bool
// CHECK-RECOVERY-NEXT: }
public enum OkayEnumWithSelfRefs {
public struct Nested {}
indirect case selfRef(OkayEnumWithSelfRefs)
case nested(Nested)
}
// CHECK-LABEL: enum OkayEnumWithSelfRefs {
// CHECK-NEXT: struct Nested {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: indirect case selfRef(OkayEnumWithSelfRefs)
// CHECK-NEXT: case nested(OkayEnumWithSelfRefs.Nested)
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: enum OkayEnumWithSelfRefs {
// CHECK-RECOVERY-NEXT: struct Nested {
// CHECK-RECOVERY-NEXT: init()
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEXT: indirect case selfRef(OkayEnumWithSelfRefs)
// CHECK-RECOVERY-NEXT: case nested(OkayEnumWithSelfRefs.Nested)
// CHECK-RECOVERY-NEXT: }
public protocol HasAssoc {
associatedtype Assoc
}
public func producesBadEnum() -> BadEnum { return .noPayload }
// CHECK-LABEL: func producesBadEnum() -> BadEnum
// CHECK-RECOVERY-NOT: func producesBadEnum() -> BadEnum
public func producesGenericBadEnum<T>() -> GenericBadEnum<T> { return .noPayload }
// CHECK-LABEL: func producesGenericBadEnum<T>() -> GenericBadEnum<T>
// CHECK-RECOVERY-NOT: func producesGenericBadEnum
public func producesOkayEnum() -> OkayEnum { return .noPayload }
// CHECK-LABEL: func producesOkayEnum() -> OkayEnum
// CHECK-RECOVERY-LABEL: func producesOkayEnum() -> OkayEnum
extension Int /* or any imported type, really */ {
public enum OkayEnumWithSelfRefs {
public struct Nested {}
indirect case selfRef(OkayEnumWithSelfRefs)
case nested(Nested)
}
}
// CHECK-LABEL: extension Int {
// CHECK-NEXT: enum OkayEnumWithSelfRefs {
// CHECK-NEXT: struct Nested {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: indirect case selfRef(Int.OkayEnumWithSelfRefs)
// CHECK-NEXT: case nested(Int.OkayEnumWithSelfRefs.Nested)
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: extension Int {
// CHECK-RECOVERY-NEXT: enum OkayEnumWithSelfRefs {
// CHECK-RECOVERY-NEXT: struct Nested {
// CHECK-RECOVERY-NEXT: init()
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEXT: indirect case selfRef(Int.OkayEnumWithSelfRefs)
// CHECK-RECOVERY-NEXT: case nested(Int.OkayEnumWithSelfRefs.Nested)
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEXT: }
#endif // TEST
| apache-2.0 | 070ac0f4d0f3f53a49a49a038c73098b | 32.728571 | 188 | 0.702245 | 3.339463 | false | false | false | false |
hackiftekhar/IQKeyboardManager | IQKeyboardManagerSwift/IQToolbar/IQTitleBarButtonItem.swift | 1 | 6918 | //
// IQTitleBarButtonItem.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@available(iOSApplicationExtension, unavailable)
@objc open class IQTitleBarButtonItem: IQBarButtonItem {
@objc open var titleFont: UIFont? {
didSet {
if let unwrappedFont = titleFont {
titleButton?.titleLabel?.font = unwrappedFont
} else {
titleButton?.titleLabel?.font = UIFont.systemFont(ofSize: 13)
}
}
}
@objc override open var title: String? {
didSet {
titleButton?.setTitle(title, for: .normal)
}
}
/**
titleColor to be used for displaying button text when displaying title (disabled state).
*/
@objc open var titleColor: UIColor? {
didSet {
if let color = titleColor {
titleButton?.setTitleColor(color, for: .disabled)
} else {
titleButton?.setTitleColor(UIColor.lightGray, for: .disabled)
}
}
}
/**
selectableTitleColor to be used for displaying button text when button is enabled.
*/
@objc open var selectableTitleColor: UIColor? {
didSet {
if let color = selectableTitleColor {
titleButton?.setTitleColor(color, for: .normal)
} else {
#if swift(>=5.1)
titleButton?.setTitleColor(UIColor.systemBlue, for: .normal)
#else
titleButton?.setTitleColor(UIColor(red: 0.0, green: 0.5, blue: 1.0, alpha: 1), for: .normal)
#endif
}
}
}
/**
Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method.
*/
@objc override open var invocation: IQInvocation? {
didSet {
if let target = invocation?.target, let action = invocation?.action {
self.isEnabled = true
titleButton?.isEnabled = true
titleButton?.addTarget(target, action: action, for: .touchUpInside)
} else {
self.isEnabled = false
titleButton?.isEnabled = false
titleButton?.removeTarget(nil, action: nil, for: .touchUpInside)
}
}
}
internal var titleButton: UIButton?
private var _titleView: UIView?
override init() {
super.init()
}
@objc public convenience init(title: String?) {
self.init(title: nil, style: .plain, target: nil, action: nil)
_titleView = UIView()
_titleView?.backgroundColor = UIColor.clear
titleButton = UIButton(type: .system)
titleButton?.isEnabled = false
titleButton?.titleLabel?.numberOfLines = 3
titleButton?.setTitleColor(UIColor.lightGray, for: .disabled)
#if swift(>=5.1)
titleButton?.setTitleColor(UIColor.systemBlue, for: .normal)
#else
titleButton?.setTitleColor(UIColor(red: 0.0, green: 0.5, blue: 1.0, alpha: 1), for: .normal)
#endif
titleButton?.backgroundColor = UIColor.clear
titleButton?.titleLabel?.textAlignment = .center
titleButton?.setTitle(title, for: .normal)
titleFont = UIFont.systemFont(ofSize: 13.0)
titleButton?.titleLabel?.font = self.titleFont
_titleView?.addSubview(titleButton!)
if #available(iOS 11, *) {
let layoutDefaultLowPriority = UILayoutPriority(rawValue: UILayoutPriority.defaultLow.rawValue-1)
let layoutDefaultHighPriority = UILayoutPriority(rawValue: UILayoutPriority.defaultHigh.rawValue-1)
_titleView?.translatesAutoresizingMaskIntoConstraints = false
_titleView?.setContentHuggingPriority(layoutDefaultLowPriority, for: .vertical)
_titleView?.setContentHuggingPriority(layoutDefaultLowPriority, for: .horizontal)
_titleView?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .vertical)
_titleView?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .horizontal)
titleButton?.translatesAutoresizingMaskIntoConstraints = false
titleButton?.setContentHuggingPriority(layoutDefaultLowPriority, for: .vertical)
titleButton?.setContentHuggingPriority(layoutDefaultLowPriority, for: .horizontal)
titleButton?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .vertical)
titleButton?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .horizontal)
let top = NSLayoutConstraint.init(item: titleButton!, attribute: .top, relatedBy: .equal, toItem: _titleView, attribute: .top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint.init(item: titleButton!, attribute: .bottom, relatedBy: .equal, toItem: _titleView, attribute: .bottom, multiplier: 1, constant: 0)
let leading = NSLayoutConstraint.init(item: titleButton!, attribute: .leading, relatedBy: .equal, toItem: _titleView, attribute: .leading, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint.init(item: titleButton!, attribute: .trailing, relatedBy: .equal, toItem: _titleView, attribute: .trailing, multiplier: 1, constant: 0)
_titleView?.addConstraints([top, bottom, leading, trailing])
} else {
_titleView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleButton?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
customView = _titleView
}
@objc required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
customView = nil
}
}
| mit | 1cb9d524f82a41bcfb77a956510cdce8 | 40.42515 | 181 | 0.661029 | 5.116864 | false | false | false | false |
warren-gavin/OBehave | OBehave/Classes/Animations/SlideIn/OBSlideInFromEdgeViewBehavior.swift | 1 | 2510 | //
// OBSlideInFromEdgeViewBehavior.swift
// OBehave
//
// Created by Warren Gavin on 25/10/15.
// Copyright © 2015 Apokrupto. All rights reserved.
//
import UIKit
public final class OBSlideInFromEdgeViewBehavior: OBAnimatingViewBehavior {
@IBOutlet public var slideIntoViewFromConstraints: [NSLayoutConstraint]?
// MARK: OBAnimatingViewBehaviorDelegate
override public func prepareForAnimation(_ behavior: OBAnimatingViewBehavior) {
makeViewsHidden(true, animated: false)
}
override public func executeAnimation(_ behavior: OBAnimatingViewBehavior) {
makeViewsHidden(false, animated: true)
}
override public func reverseAnimation(_ behavior: OBAnimatingViewBehavior) {
makeViewsHidden(true, animated: true)
}
}
private extension OBSlideInFromEdgeViewBehavior {
func setView(_ view: UIView?, constraints: [NSLayoutConstraint]?, hidden: Bool, animated: Bool) {
if let view = view, let constraints = constraints {
let setLayoutConstraints = { [unowned self] in
if self.fadeIn {
view.alpha = (hidden ? 0.0 : 1.0)
}
for constraint in constraints {
constraint.constant = -constraint.constant
}
self.owner?.view.layoutIfNeeded()
}
if animated {
UIView.animate(withDuration: duration,
delay: delay,
options: .allowUserInteraction,
animations: setLayoutConstraints,
completion: nil)
}
else {
setLayoutConstraints()
}
}
}
func constraintsFromView(_ view: UIView) -> [NSLayoutConstraint]? {
guard let constraints = slideIntoViewFromConstraints else {
return nil
}
return constraints.filter { (constraint: NSLayoutConstraint) -> Bool in
constraint.firstItem as? NSObject == view || constraint.secondItem as? NSObject == view
}
}
func makeViewsHidden(_ hidden: Bool, animated: Bool) {
guard let animatingViews = animatingViews else {
return
}
for view in animatingViews {
setView(view, constraints: constraintsFromView(view), hidden: hidden, animated: animated)
}
}
}
| mit | faf39155c323702f63851ebe8bc5bf06 | 32.453333 | 101 | 0.579514 | 5.419006 | false | false | false | false |
smartmobilefactory/FolioReaderKit | Source/FolioReaderContainer.swift | 1 | 8936 | //
// FolioReaderContainer.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 15/04/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import FontBlaster
/// Reader container
open class FolioReaderContainer : UIViewController {
var centerNavigationController: UINavigationController?
var centerViewController: FolioReaderCenter?
var audioPlayer: FolioReaderAudioPlayer?
var shouldHideStatusBar = true
var shouldRemoveEpub = true
var epubPath: String
var book: FRBook
// Mark those property as public so they can accessed from other classes/subclasses.
public var readerConfig: FolioReaderConfig
public var folioReader: FolioReader
fileprivate var errorOnLoad = false
// MARK: - Init
/// Init a Folio Reader Container
///
/// - Parameters:
/// - config: Current Folio Reader configuration
/// - folioReader: Current instance of the FolioReader kit.
/// - path: The ePub path on system. Must not be nil nor empty string.
/// - removeEpub: Should delete the original file after unzip? Default to `true` so the ePub will be unziped only once.
public init(withConfig config: FolioReaderConfig, folioReader: FolioReader, epubPath path: String, removeEpub: Bool = true) {
self.readerConfig = config
self.folioReader = folioReader
self.epubPath = path
self.shouldRemoveEpub = removeEpub
self.book = FRBook()
super.init(nibName: nil, bundle: Bundle.frameworkBundle())
// Configure the folio reader.
self.folioReader.readerContainer = self
// Initialize the default reader options.
if self.epubPath != "" {
self.initialization()
}
}
required public init?(coder aDecoder: NSCoder) {
// When a FolioReaderContainer object is instantiated from the storyboard this function is called before.
// At this moment, we need to initialize all non-optional objects with default values.
// The function `setupConfig(config:epubPath:removeEpub:)` MUST be called afterward.
// See the ExampleFolioReaderContainer.swift for more information?
self.readerConfig = FolioReaderConfig()
self.folioReader = FolioReader()
self.epubPath = ""
self.shouldRemoveEpub = false
self.book = FRBook()
super.init(coder: aDecoder)
// Configure the folio reader.
self.folioReader.readerContainer = self
// Set the shared instance to support old version.
FolioReader.shared = self.folioReader
}
/// Common Initialization
fileprivate func initialization() {
// Register custom fonts
FontBlaster.blast(bundle: Bundle.frameworkBundle())
// Register initial defaults
self.folioReader.register(defaults: [
kCurrentFontFamily: FolioReaderFont.andada.rawValue,
kNightMode: false,
kCurrentFontSize: 2,
kCurrentAudioRate: 1,
kCurrentHighlightStyle: 0,
kCurrentTOCMenu: 0,
kCurrentMediaOverlayStyle: MediaOverlayStyle.default.rawValue,
kCurrentScrollDirection: FolioReaderScrollDirection.defaultVertical.rawValue
])
}
/// Set the `FolioReaderConfig` and epubPath.
///
/// - Parameters:
/// - config: Current Folio Reader configuration
/// - path: The ePub path on system. Must not be nil nor empty string.
/// - removeEpub: Should delete the original file after unzip? Default to `true` so the ePub will be unziped only once.
open func setupConfig(_ config: FolioReaderConfig, epubPath path: String, removeEpub: Bool = true) {
self.readerConfig = config
self.folioReader = FolioReader()
self.folioReader.readerContainer = self
self.epubPath = path
self.shouldRemoveEpub = removeEpub
// Set the shared instance to support old version.
FolioReader.shared = self.folioReader
}
// MARK: - View life cicle
override open func viewDidLoad() {
super.viewDidLoad()
let canChangeScrollDirection = self.readerConfig.canChangeScrollDirection
self.readerConfig.canChangeScrollDirection = self.readerConfig.isDirection(canChangeScrollDirection, canChangeScrollDirection, false)
// If user can change scroll direction use the last saved
if self.readerConfig.canChangeScrollDirection == true {
var scrollDirection = FolioReaderScrollDirection(rawValue: self.folioReader.currentScrollDirection) ?? .vertical
if (scrollDirection == .defaultVertical && self.readerConfig.scrollDirection != .defaultVertical) {
scrollDirection = self.readerConfig.scrollDirection
}
self.readerConfig.scrollDirection = scrollDirection
}
let hideBars = (self.readerConfig.hideBars ?? false)
self.readerConfig.shouldHideNavigationOnTap = ((hideBars == true) ? true : self.readerConfig.shouldHideNavigationOnTap)
self.centerViewController = FolioReaderCenter(withContainer: self)
if let rootViewController = self.centerViewController {
self.centerNavigationController = UINavigationController(rootViewController: rootViewController)
}
self.centerNavigationController?.setNavigationBarHidden(self.readerConfig.shouldHideNavigationOnTap, animated: false)
if let _centerNavigationController = self.centerNavigationController {
self.view.addSubview(_centerNavigationController.view)
self.addChildViewController(_centerNavigationController)
}
self.centerNavigationController?.didMove(toParentViewController: self)
if (self.readerConfig.hideBars == true) {
self.readerConfig.shouldHideNavigationOnTap = false
self.navigationController?.navigationBar.isHidden = true
self.centerViewController?.pageIndicatorHeight = 0
}
// Read async book
guard (self.epubPath.isEmpty == false) else {
print("Epub path is nil.")
self.errorOnLoad = true
return
}
DispatchQueue.global(qos: .userInitiated).async {
do {
guard let parsedBook = try FREpubParser().readEpub(epubPath: self.epubPath, removeEpub: self.shouldRemoveEpub) else {
self.errorOnLoad = true
return
}
self.book = parsedBook
self.folioReader.isReaderOpen = true
// Reload data
DispatchQueue.main.async(execute: {
// Add audio player if needed
if (self.book.hasAudio() == true || self.readerConfig.enableTTS == true) {
self.addAudioPlayer()
}
self.centerViewController?.reloadData()
self.folioReader.isReaderReady = true
self.folioReader.delegate?.folioReader?(self.folioReader, didFinishedLoading: self.book)
})
} catch let e as FolioReaderError {
self.alert(message: e.localizedDescription)
} catch {
self.alert(message: "Unknown Error")
}
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (self.errorOnLoad == true) {
self.dismiss()
}
}
/// Save Reader state, book, page and scroll offset.
open func saveReaderState() {
self.folioReader.saveReaderState()
}
/**
Initialize the media player
*/
func addAudioPlayer() {
self.audioPlayer = FolioReaderAudioPlayer(withFolioReader: self.folioReader, book: self.book)
self.folioReader.readerAudioPlayer = audioPlayer
}
// MARK: - Status Bar
override open var prefersStatusBarHidden: Bool {
return (self.readerConfig.shouldHideNavigationOnTap == false ? false : self.shouldHideStatusBar)
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return UIStatusBarAnimation.slide
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
return self.folioReader.isNight(.lightContent, .default)
}
}
extension FolioReaderContainer {
func alert(message: String) {
let alertController = UIAlertController(
title: "Error",
message: message,
preferredStyle: UIAlertControllerStyle.alert
)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel) { [weak self]
(result : UIAlertAction) -> Void in
self?.dismiss()
}
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
}
| bsd-3-clause | 781fb1556c18e49472d73304c04667e3 | 36.704641 | 141 | 0.653872 | 5.488943 | false | true | false | false |
apple/swift-nio-http2 | Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests+XCTest.swift | 1 | 6922 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// HTTP2FramePayloadStreamMultiplexerTests+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension HTTP2FramePayloadStreamMultiplexerTests {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (HTTP2FramePayloadStreamMultiplexerTests) -> () throws -> Void)] {
return [
("testMultiplexerIgnoresFramesOnStream0", testMultiplexerIgnoresFramesOnStream0),
("testHeadersFramesCreateNewChannels", testHeadersFramesCreateNewChannels),
("testChannelsCloseThemselvesWhenToldTo", testChannelsCloseThemselvesWhenToldTo),
("testChannelsCloseAfterResetStreamFrameFirstThenEvent", testChannelsCloseAfterResetStreamFrameFirstThenEvent),
("testChannelsCloseAfterGoawayFrameFirstThenEvent", testChannelsCloseAfterGoawayFrameFirstThenEvent),
("testFramesForUnknownStreamsAreReported", testFramesForUnknownStreamsAreReported),
("testFramesForClosedStreamsAreReported", testFramesForClosedStreamsAreReported),
("testClosingIdleChannels", testClosingIdleChannels),
("testClosingActiveChannels", testClosingActiveChannels),
("testClosePromiseIsSatisfiedWithTheEvent", testClosePromiseIsSatisfiedWithTheEvent),
("testMultipleClosePromisesAreSatisfied", testMultipleClosePromisesAreSatisfied),
("testClosePromiseFailsWithError", testClosePromiseFailsWithError),
("testFramesAreNotDeliveredUntilStreamIsSetUp", testFramesAreNotDeliveredUntilStreamIsSetUp),
("testFramesAreNotDeliveredIfSetUpFails", testFramesAreNotDeliveredIfSetUpFails),
("testFlushingOneChannelDoesntFlushThemAll", testFlushingOneChannelDoesntFlushThemAll),
("testUnflushedWritesFailOnClose", testUnflushedWritesFailOnClose),
("testUnflushedWritesFailOnError", testUnflushedWritesFailOnError),
("testWritesFailOnClosedStreamChannels", testWritesFailOnClosedStreamChannels),
("testReadPullsInAllFrames", testReadPullsInAllFrames),
("testReadIsPerChannel", testReadIsPerChannel),
("testReadWillCauseAutomaticFrameDelivery", testReadWillCauseAutomaticFrameDelivery),
("testReadWithNoPendingDataCausesReadOnParentChannel", testReadWithNoPendingDataCausesReadOnParentChannel),
("testHandlersAreRemovedOnClosure", testHandlersAreRemovedOnClosure),
("testHandlersAreRemovedOnClosureWithError", testHandlersAreRemovedOnClosureWithError),
("testCreatingOutboundChannel", testCreatingOutboundChannel),
("testCreatingOutboundChannelClient", testCreatingOutboundChannelClient),
("testWritesOnCreatedChannelAreDelayed", testWritesOnCreatedChannelAreDelayed),
("testWritesAreCancelledOnFailingInitializer", testWritesAreCancelledOnFailingInitializer),
("testFailingInitializerDoesNotWrite", testFailingInitializerDoesNotWrite),
("testCreatedChildChannelDoesNotActivateEarly", testCreatedChildChannelDoesNotActivateEarly),
("testCreatedChildChannelActivatesIfParentIsActive", testCreatedChildChannelActivatesIfParentIsActive),
("testInitiatedChildChannelActivates", testInitiatedChildChannelActivates),
("testMultiplexerIgnoresPriorityFrames", testMultiplexerIgnoresPriorityFrames),
("testMultiplexerForwardsActiveToParent", testMultiplexerForwardsActiveToParent),
("testCreatedChildChannelCanBeClosedImmediately", testCreatedChildChannelCanBeClosedImmediately),
("testCreatedChildChannelCanBeClosedBeforeWritingHeaders", testCreatedChildChannelCanBeClosedBeforeWritingHeaders),
("testCreatedChildChannelCanBeClosedImmediatelyWhenBaseIsActive", testCreatedChildChannelCanBeClosedImmediatelyWhenBaseIsActive),
("testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive", testCreatedChildChannelCanBeClosedBeforeWritingHeadersWhenBaseIsActive),
("testMultiplexerCoalescesFlushCallsDuringChannelRead", testMultiplexerCoalescesFlushCallsDuringChannelRead),
("testMultiplexerDoesntFireReadCompleteForEachFrame", testMultiplexerDoesntFireReadCompleteForEachFrame),
("testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete", testMultiplexerCorrectlyTellsAllStreamsAboutReadComplete),
("testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens", testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens),
("testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability", testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability),
("testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability", testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability),
("testStreamChannelToleratesFailingInitializer", testStreamChannelToleratesFailingInitializer),
("testInboundChannelWindowSizeIsCustomisable", testInboundChannelWindowSizeIsCustomisable),
("testWeCanCreateFrameAndPayloadBasedStreamsOnAMultiplexer", testWeCanCreateFrameAndPayloadBasedStreamsOnAMultiplexer),
("testReadWhenUsingAutoreadOnChildChannel", testReadWhenUsingAutoreadOnChildChannel),
("testWindowUpdateIsNotEmittedAfterStreamIsClosed", testWindowUpdateIsNotEmittedAfterStreamIsClosed),
("testWindowUpdateIsNotEmittedAfterStreamIsClosedEvenOnLaterFrame", testWindowUpdateIsNotEmittedAfterStreamIsClosedEvenOnLaterFrame),
("testStreamChannelSupportsSyncOptions", testStreamChannelSupportsSyncOptions),
("testStreamErrorIsDeliveredToChannel", testStreamErrorIsDeliveredToChannel),
("testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive", testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive),
]
}
}
| apache-2.0 | 75bcb846b9142064ee9b9f141bf7ff98 | 79.488372 | 203 | 0.757151 | 6.055993 | false | true | false | false |
kperryua/swift | stdlib/public/core/ArrayBuffer.swift | 2 | 17178 | //===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This is the class that implements the storage and object management for
// Swift Array.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
internal typealias _ArrayBridgeStorage
= _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCore>
@_versioned
@_fixed_layout
internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
/// Create an empty buffer.
internal init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
@_versioned // FIXME(abi): Used from tests
internal init(nsArray: _NSArrayCore) {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_storage = _ArrayBridgeStorage(objC: nsArray)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements.
///
/// - Precondition: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
return _ArrayBuffer<U>(storage: _storage)
}
/// The spare bits that are set when a native array needs deferred
/// element type checking.
internal var deferredTypeCheckMask: Int { return 1 }
/// Returns an `_ArrayBuffer<U>` containing the same elements,
/// deferring checking each element's `U`-ness until it is accessed.
///
/// - Precondition: `U` is a class or `@objc` existential derived from
/// `Element`.
internal func downcast<U>(
toBufferWithDeferredTypeCheckOf _: U.Type
) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
// FIXME: can't check that U is derived from Element pending
// <rdar://problem/19915280> generic metatype casting doesn't work
// _sanityCheck(U.self is Element.Type)
return _ArrayBuffer<U>(
storage: _ArrayBridgeStorage(
native: _native._storage, bits: deferredTypeCheckMask))
}
internal var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
//===--- private --------------------------------------------------------===//
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
internal var _storage: _ArrayBridgeStorage
}
extension _ArrayBuffer {
/// Adopt the storage of `source`.
internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
/// `true`, if the array is native and does not need a deferred type check.
internal var arrayPropertyIsNativeTypeChecked: Bool {
return _isNativeTypeChecked
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
internal mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferenced_native_noSpareBits()
}
return _storage.isUniquelyReferencedNative() && _isNative
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned.
internal mutating func isUniquelyReferencedOrPinned() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedOrPinned_native_noSpareBits()
}
return _storage.isUniquelyReferencedOrPinnedNative() && _isNative
}
/// Convert to an NSArray.
///
/// O(1) if the element type is bridged verbatim, O(*n*) otherwise.
@_versioned // FIXME(abi): Used from tests
internal func _asCocoaArray() -> _NSArrayCore {
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative
}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)
-> NativeBuffer? {
if _fastPath(isUniquelyReferenced()) {
let b = _native
if _fastPath(b.capacity >= minimumCapacity) {
return b
}
}
return nil
}
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
internal func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
}
return _fastPath(_storage.isNative) ? _native : nil
}
// We have two versions of type check: one that takes a range and the other
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@inline(never)
internal func _typeCheckSlowPath(_ index: Int) {
if _fastPath(_isNative) {
let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
}
else {
let ns = _nonNative
_precondition(
ns.objectAt(index) is Element,
"NSArray element failed to match the Swift Array Element type")
}
}
internal func _typeCheck(_ subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
}
if _slowPath(needsElementTypeCheck) {
// Could be sped up, e.g. by using
// enumerateObjectsAtIndexes:options:usingBlock: in the
// non-native case.
for i in CountableRange(subRange) {
_typeCheckSlowPath(i)
}
}
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@discardableResult
internal func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native._copyContents(subRange: bounds, initializing: target)
}
let nonNative = _nonNative
let nsSubRange = SwiftShims._SwiftNSRange(
location: bounds.lowerBound,
length: bounds.upperBound - bounds.lowerBound)
let buffer = UnsafeMutableRawPointer(target).assumingMemoryBound(
to: AnyObject.self)
// Copies the references out of the NSArray without retaining them
nonNative.getObjects(buffer, range: nsSubRange)
// Make another pass to retain the copied objects
var result = target
for _ in CountableRange(bounds) {
result.initialize(to: result.pointee)
result += 1
}
return result
}
/// Returns a `_SliceBuffer` containing the given sub-range of elements in
/// `bounds` from this buffer.
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native[bounds]
}
let boundsCount = bounds.count
if boundsCount == 0 {
return _SliceBuffer(
_buffer: _ContiguousArrayBuffer<Element>(),
shiftedToStartIndex: bounds.lowerBound)
}
// Look for contiguous storage in the NSArray
let nonNative = self._nonNative
let cocoa = _CocoaArrayWrapper(nonNative)
let cocoaStorageBaseAddress =
cocoa.contiguousStorage(Range(self.indices))
if let cocoaStorageBaseAddress = cocoaStorageBaseAddress {
let basePtr = UnsafeMutableRawPointer(cocoaStorageBaseAddress)
.assumingMemoryBound(to: Element.self)
return _SliceBuffer(
owner: nonNative,
subscriptBaseAddress: basePtr,
indices: bounds,
hasNativeBuffer: false)
}
// No contiguous storage found; we must allocate
let result = _ContiguousArrayBuffer<Element>(
_uninitializedCount: boundsCount, minimumCapacity: 0)
// Tell Cocoa to copy the objects into our storage
cocoa.buffer.getObjects(
UnsafeMutableRawPointer(result.firstElementAddress)
.assumingMemoryBound(to: AnyObject.self),
range: _SwiftNSRange(location: bounds.lowerBound, length: boundsCount))
return _SliceBuffer(
_buffer: result, shiftedToStartIndex: bounds.lowerBound)
}
set {
fatalError("not implemented")
}
}
/// A pointer to the first element.
///
/// - Precondition: The elements are known to be stored contiguously.
@_versioned
internal var firstElementAddress: UnsafeMutablePointer<Element> {
_sanityCheck(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return _fastPath(_isNative) ? firstElementAddress : nil
}
/// The number of elements the buffer stores.
internal var count: Int {
@inline(__always)
get {
return _fastPath(_isNative) ? _native.count : _nonNative.count
}
set {
_sanityCheck(_isNative, "attempting to update count of Cocoa array")
_native.count = newValue
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and the subscript is out of range.
///
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNative) {
_native._checkValidSubscript(index)
}
}
// TODO: gyb this
/// Traps if an inout violation is detected or if the buffer is
/// native and typechecked and the subscript is out of range.
///
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
internal func _checkInoutAndNativeTypeCheckedBounds(
_ index: Int, wasNativeTypeChecked: Bool
) {
_precondition(
_isNativeTypeChecked == wasNativeTypeChecked,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNativeTypeChecked) {
_native._checkValidSubscript(index)
}
}
/// The number of elements the buffer can store without reallocation.
internal var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.count
}
@_versioned
@inline(__always)
internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element {
if _fastPath(wasNativeTypeChecked) {
return _nativeTypeChecked[i]
}
return unsafeBitCast(_getElementSlowPath(i), to: Element.self)
}
@_versioned
@inline(never)
internal func _getElementSlowPath(_ i: Int) -> AnyObject {
_sanityCheck(
_isClassOrObjCExistential(Element.self),
"Only single reference elements can be indexed here.")
let element: AnyObject
if _isNative {
// _checkInoutAndNativeTypeCheckedBounds does no subscript
// checking for the native un-typechecked case. Therefore we
// have to do it here.
_native._checkValidSubscript(i)
element = cast(toBufferOf: AnyObject.self)._native[i]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
} else {
// ObjC arrays do their own subscript checking.
element = _nonNative.objectAt(i)
_precondition(
element is Element,
"NSArray element failed to match the Swift Array Element type")
}
return element
}
/// Get or set the value of the ith element.
internal subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replace(
subRange: i..<(i + 1),
with: 1,
elementsOf: CollectionOfOne(newValue))
}
}
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
if _fastPath(_isNative) {
defer { _fixLifetime(self) }
return try body(
UnsafeBufferPointer(start: firstElementAddress, count: count))
}
return try ContiguousArray(self).withUnsafeBufferPointer(body)
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
_sanityCheck(
_isNative || count == 0,
"Array is bridging an opaque NSArray; can't get a pointer to the elements"
)
defer { _fixLifetime(self) }
return try body(UnsafeMutableBufferPointer(
start: firstElementAddressIfContiguous, count: count))
}
/// An object that keeps the elements stored in this buffer alive.
internal var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative
}
/// An object that keeps the elements stored in this buffer alive.
///
/// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.
internal var nativeOwner: AnyObject {
_sanityCheck(_isNative, "Expect a native array")
return _native._storage
}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
internal var identity: UnsafeRawPointer {
if _isNative {
return _native.identity
}
else {
return UnsafeRawPointer(Unmanaged.passUnretained(_nonNative).toOpaque())
}
}
//===--- Collection conformance -------------------------------------===//
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
internal var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
internal var endIndex: Int {
return count
}
internal typealias Indices = CountableRange<Int>
//===--- private --------------------------------------------------------===//
internal typealias Storage = _ContiguousArrayStorage<Element>
internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>
@_versioned
internal var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isNative
}
}
/// `true`, if the array is native and does not need a deferred type check.
internal var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask)
}
}
/// Our native representation.
///
/// - Precondition: `_isNative`.
@_versioned
internal var _native: NativeBuffer {
return NativeBuffer(
_isClassOrObjCExistential(Element.self)
? _storage.nativeInstance : _storage.nativeInstance_noSpareBits)
}
/// Fast access to the native representation.
///
/// - Precondition: `_isNativeTypeChecked`.
@_versioned
internal var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.nativeInstance_noSpareBits)
}
@_versioned
internal var _nonNative: _NSArrayCore {
@inline(__always)
get {
_sanityCheck(_isClassOrObjCExistential(Element.self))
return _storage.objCInstance
}
}
}
#endif
| apache-2.0 | cdd63ffb604d31968e26f91c4c99bb03 | 31.971209 | 80 | 0.669112 | 4.873191 | false | false | false | false |
wangyuanou/Coastline | Coastline/System/Device+Type.swift | 1 | 3196 | //
// Device+Type.swift
// Coastline
//
// Created by 王渊鸥 on 2017/6/25.
// Copyright © 2017年 王渊鸥. All rights reserved.
//
import Foundation
import UIKit
public extension UIDevice {
public var isiPad:Bool {
return UI_USER_INTERFACE_IDIOM() == .pad
}
public var isiPhone:Bool {
return UI_USER_INTERFACE_IDIOM() == .phone
}
public var isTV:Bool {
if #available(iOS 9.0, *) {
return UI_USER_INTERFACE_IDIOM() == .tv
} else {
return false
}
}
public var isEmulater:Bool {
#if TARGET_IPHONE_SIMULATOR
return true
#else
return false
#endif
}
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)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad6,11", "iPad6,12": return "iPad 5"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch"
case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch"
case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation"
case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
}
| mit | 2c25bbddb621ecae1ba02fbff85dc404 | 38.7625 | 91 | 0.522792 | 3.289555 | false | false | false | false |
drewcrawford/Caroline | caroline-static-tool/StringPlus.swift | 1 | 1315 | // Copyright (c) 2016 Drew Crawford.
//
// 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.
extension String {
func hasSuffix(_ str: String) -> Bool {
let view = self.utf8[self.utf8.index(self.utf8.startIndex, offsetBy: self.utf8.count - str.utf8.count)..<self.utf8.endIndex]
var strIndex = str.utf8.startIndex
for char in view {
if char != str.utf8[strIndex] { return false }
strIndex = str.utf8.index(after: strIndex)
}
return true
}
}
extension String.UTF8View {
func substring(from: String.UTF8View.Index) -> String {
return String(describing: self[from..<self.endIndex])
}
func substring(from: Int) -> String {
let index = self.index(startIndex, offsetBy: from)
return substring(from: index)
}
} | apache-2.0 | 66049932035f3f7d0f5629c8d144cef8 | 36.6 | 132 | 0.676806 | 3.879056 | false | false | false | false |
na4lapy/na4lapy-ios | Na4Łapy/Model/APIObject.swift | 1 | 1488 | //
// APIObject.swift
// Na4Łapy
//
// Created by Andrzej Butkiewicz on 20.06.2016.
// Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved.
//
import Foundation
class APIObject: ListingProtocol {
fileprivate(set) var id: Int
fileprivate(set) var name: String
//
// MARK: inicjalizacja obiektu za pomocą struktury JSON (id oraz name)
//
required init?(dictionary: [String:AnyObject]) {
guard
let id = dictionary[JsonAttr.id] as? Int,
let name = dictionary[JsonAttr.name] as? String
else {
log.error(Err.noIdOrName.desc())
return nil
}
self.id = id
self.name = name
}
/**
Tworzenie obiektów na podstawie JSON
- Parameter json: Struktura JSON
- Returns: Tablica obiektów Animal
*/
class func jsonToObj(_ obj: [AnyObject]) -> [AnyObject] {
var animals = [AnyObject]()
if let obj = obj as? [[String: AnyObject]] {
for item in obj {
if let animal = self.init(dictionary: item) {
animals.append(animal)
}
}
}
return animals
}
/**
Metoda nadpisywana w obiektach potomnych, wymagana przez protokół ListingProtocol
*/
class func get(_ page: Int, size: Int, preferences: UserPreferences?, success: @escaping ([AnyObject], Int) -> Void, failure: @escaping (NSError) -> Void) {}
}
| apache-2.0 | 07ff52cdd9b34b32bcd0262bb9a84596 | 25.909091 | 161 | 0.577027 | 3.72796 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/AppearancePaneController.swift | 1 | 27696 | //
// AppearancePaneController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2014-04-18.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2022 1024jp
//
// 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
//
// https://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 Combine
import Cocoa
import AudioToolbox
import UniformTypeIdentifiers
final class AppearancePaneController: NSViewController, NSMenuItemValidation, NSTableViewDelegate, NSTableViewDataSource, NSFilePromiseProviderDelegate, NSTextFieldDelegate, NSMenuDelegate, ThemeViewControllerDelegate {
// MARK: Private Properties
private var themeNames: [String] = []
private var themeViewController: ThemeViewController?
@objc private dynamic var isBundled = false
private var fontObserver: AnyCancellable?
private var themeManagerObservers: Set<AnyCancellable> = []
private lazy var filePromiseQueue = OperationQueue()
@IBOutlet private weak var fontField: AntialiasingTextField?
@IBOutlet private weak var lineHeightField: NSTextField?
@IBOutlet private weak var barCursorButton: NSButton?
@IBOutlet private weak var thickBarCursorButton: NSButton?
@IBOutlet private weak var blockCursorButton: NSButton?
@IBOutlet private weak var defaultAppearanceButton: NSButton?
@IBOutlet private weak var lightAppearanceButton: NSButton?
@IBOutlet private weak var darkAppearanceButton: NSButton?
@IBOutlet private weak var themeTableView: NSTableView?
@IBOutlet private var themeTableMenu: NSMenu?
// MARK: -
// MARK: View Controller Methods
/// setup UI
override func viewDidLoad() {
super.viewDidLoad()
// register drag & drop types
let receiverTypes = NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) }
self.themeTableView?.registerForDraggedTypes([.fileURL] + receiverTypes)
self.themeTableView?.setDraggingSourceOperationMask(.copy, forLocal: false)
// set initial value as field's placeholder
self.lineHeightField?.bindNullPlaceholderToUserDefaults()
self.themeNames = ThemeManager.shared.settingNames
}
/// apply current settings to UI
override func viewWillAppear() {
super.viewWillAppear()
self.fontObserver = UserDefaults.standard.publisher(for: .fontSize, initial: true)
.sink { [weak self] _ in self?.setupFontFamilyNameAndSize() }
// select one of cursor type radio buttons
switch UserDefaults.standard[.cursorType] {
case .bar:
self.barCursorButton?.state = .on
case .thickBar:
self.thickBarCursorButton?.state = .on
case .block:
self.blockCursorButton?.state = .on
}
// select one of appearance radio buttons
switch UserDefaults.standard[.documentAppearance] {
case .default:
self.defaultAppearanceButton?.state = .on
case .light:
self.lightAppearanceButton?.state = .on
case .dark:
self.darkAppearanceButton?.state = .on
}
// sync theme list change
self.themeManagerObservers.removeAll()
ThemeManager.shared.$settingNames
.receive(on: RunLoop.main)
.sink { [weak self] _ in self?.updateThemeList() }
.store(in: &self.themeManagerObservers)
ThemeManager.shared.didUpdateSetting
.sink { [weak self] _ in
guard
let self = self,
let latestTheme = ThemeManager.shared.setting(name: self.selectedThemeName),
latestTheme.name == self.themeViewController?.theme?.name
else { return }
self.themeViewController?.theme = latestTheme
}
.store(in: &self.themeManagerObservers)
self.themeTableView?.scrollToBeginningOfDocument(nil)
}
/// stop observations for UI update
override func viewDidDisappear() {
super.viewDidDisappear()
self.fontObserver = nil
self.themeManagerObservers.removeAll()
}
/// set delegate to ThemeViewController
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let destinationController = segue.destinationController as? ThemeViewController {
self.themeViewController = destinationController
destinationController.delegate = self
}
}
// MARK: User Interface Validation
/// apply current state to menu items
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
let isContextualMenu = (menuItem.menu == self.themeTableMenu)
let representedSettingName = self.representedSettingName(for: menuItem.menu)
menuItem.representedObject = representedSettingName
let itemSelected = (representedSettingName != nil)
let isBundled: Bool
let isCustomized: Bool
if let representedSettingName = representedSettingName {
isBundled = ThemeManager.shared.isBundledSetting(name: representedSettingName)
isCustomized = ThemeManager.shared.isCustomizedSetting(name: representedSettingName)
} else {
(isBundled, isCustomized) = (false, false)
}
// append target setting name to menu titles
switch menuItem.action {
case #selector(addTheme), #selector(importTheme(_:)):
menuItem.isHidden = (isContextualMenu && itemSelected)
case #selector(renameTheme(_:)):
if let name = representedSettingName, !isContextualMenu {
menuItem.title = String(format: "Rename “%@”".localized, name)
}
menuItem.isHidden = !itemSelected
return !isBundled
case #selector(duplicateTheme(_:)):
if let name = representedSettingName, !isContextualMenu {
menuItem.title = String(format: "Duplicate “%@”".localized, name)
}
menuItem.isHidden = !itemSelected
case #selector(deleteTheme(_:)):
menuItem.isHidden = (isBundled || !itemSelected)
case #selector(restoreTheme(_:)):
if let name = representedSettingName, !isContextualMenu {
menuItem.title = String(format: "Restore “%@”".localized, name)
}
menuItem.isHidden = (!isBundled || !itemSelected)
return isBundled && isCustomized
case #selector(exportTheme(_:)):
if let name = representedSettingName, !isContextualMenu {
menuItem.title = String(format: "Export “%@”…".localized, name)
}
menuItem.isHidden = !itemSelected
return isCustomized
case #selector(revealThemeInFinder(_:)):
if let name = representedSettingName, !isContextualMenu {
menuItem.title = String(format: "Reveal “%@” in Finder".localized, name)
}
return isCustomized
case nil:
return false
default:
break
}
return true
}
// MARK: Data Source
/// number of themes
func numberOfRows(in tableView: NSTableView) -> Int {
return self.themeNames.count
}
/// content of table cell
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return self.themeNames[safe: row]
}
/// validate when dragged items come to tableView
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
guard
info.draggingSource as? NSTableView != tableView, // avoid self D&D
let count = info.filePromiseReceivers(with: .cotTheme, for: tableView)?.count
?? info.fileURLs(with: .cotTheme, for: tableView)?.count
else { return [] }
// highlight table view itself
tableView.setDropRow(-1, dropOperation: .on)
// show number of acceptable files
info.numberOfValidItemsForDrop = count
return .copy
}
/// check acceptability of dropped items and insert them to table
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
if let receivers = info.filePromiseReceivers(with: .cotTheme, for: tableView) {
let dropDirectoryURL = FileManager.default.createTemporaryDirectory()
for receiver in receivers {
receiver.receivePromisedFiles(atDestination: dropDirectoryURL, operationQueue: .main) { [weak self] (fileURL, error) in
if let error = error {
self?.presentError(error)
return
}
self?.importTheme(fileURL: fileURL)
}
}
} else if let fileURLs = info.fileURLs(with: .cotTheme, for: tableView) {
for fileURL in fileURLs {
self.importTheme(fileURL: fileURL)
}
} else {
return false
}
AudioServicesPlaySystemSound(.volumeMount)
return true
}
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
let provider = NSFilePromiseProvider(fileType: UTType.cotTheme.identifier, delegate: self)
provider.userInfo = self.themeNames[row]
return provider
}
// MARK: File Promise Provider Delegate
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
(filePromiseProvider.userInfo as! String) + "." + UTType.cotTheme.preferredFilenameExtension!
}
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL) async throws {
guard
let settingName = filePromiseProvider.userInfo as? String,
let sourceURL = ThemeManager.shared.urlForUserSetting(name: settingName)
else { return }
try FileManager.default.copyItem(at: sourceURL, to: url)
}
func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
self.filePromiseQueue
}
// MARK: Delegate
// ThemeViewControllerDelegate
/// theme did update
func didUpdate(theme: Theme) {
do {
try ThemeManager.shared.save(setting: theme, name: self.selectedThemeName)
} catch {
print(error.localizedDescription)
}
}
// NSTableViewDelegate < themeTableView
/// selection of theme table did change
func tableViewSelectionDidChange(_ notification: Notification) {
guard notification.object as? NSTableView == self.themeTableView else { return }
self.setTheme(name: self.selectedThemeName)
}
/// set if table cell is editable
func tableView(_ tableView: NSTableView, didAdd rowView: NSTableRowView, forRow row: Int) {
guard let view = tableView.view(atColumn: 0, row: row, makeIfNecessary: false) as? NSTableCellView else { return }
let themeName = self.themeNames[row]
let isBundled = ThemeManager.shared.isBundledSetting(name: themeName)
view.textField?.isSelectable = false
view.textField?.isEditable = !isBundled
}
/// set action on swiping theme name
func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] {
guard edge == .trailing else { return [] }
// get swiped theme
let themeName = self.themeNames[row]
// do nothing on undeletable theme
guard ThemeManager.shared.isCustomizedSetting(name: themeName) else { return [] }
if ThemeManager.shared.isBundledSetting(name: themeName) {
// Restore
return [NSTableViewRowAction(style: .regular,
title: "Restore".localized,
handler: { [weak self] (_, _) in
self?.restoreTheme(name: themeName)
// finish swiped mode anyway
tableView.rowActionsVisible = false
})]
} else {
// Delete
return [NSTableViewRowAction(style: .destructive,
title: "Delete".localized,
handler: { [weak self] (_, _) in
self?.deleteTheme(name: themeName)
})]
}
}
// NSTextFieldDelegate
/// theme name was edited
func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
let newName = fieldEditor.string
// finish if empty (The original name will be restored automatically)
guard !newName.isEmpty else { return true }
let oldName = self.selectedThemeName
do {
try ThemeManager.shared.renameSetting(name: oldName, to: newName)
} catch {
// revert name
fieldEditor.string = oldName
// show alert
NSAlert(error: error).beginSheetModal(for: self.view.window!)
return false
}
if UserDefaults.standard[.theme] == oldName {
UserDefaults.standard[.theme] = newName
}
return true
}
// NSMenuDelegate
func menuWillOpen(_ menu: NSMenu) {
// create share menu dynamically
if let shareMenuItem = menu.items.compactMap({ $0 as? ShareMenuItem }).first {
let settingName = self.representedSettingName(for: menu) ?? self.selectedThemeName
shareMenuItem.sharingItems = ThemeManager.shared.urlForUserSetting(name: settingName).flatMap { [$0] }
}
}
// MARK: Action Messages
/// A radio button of documentConflictOption was clicked
@IBAction func updateCursorTypeSetting(_ sender: NSButton) {
UserDefaults.standard[.cursorType] = CursorType(rawValue: sender.tag)!
}
/// A radio button of documentAppearance was clicked
@IBAction func updateAppearanceSetting(_ sender: NSButton) {
UserDefaults.standard[.documentAppearance] = AppearanceMode(rawValue: sender.tag)!
let themeName = ThemeManager.shared.userDefaultSettingName
let row = self.themeNames.firstIndex(of: themeName) ?? 0
self.themeTableView?.selectRowIndexes([row], byExtendingSelection: false)
}
/// add theme
@IBAction func addTheme(_ sender: Any?) {
let settingName: String
do {
settingName = try ThemeManager.shared.createUntitledSetting()
} catch {
self.presentError(error)
return
}
self.updateThemeList(bySelecting: settingName)
}
/// duplicate selected theme
@IBAction func duplicateTheme(_ sender: Any?) {
let baseName = self.targetThemeName(for: sender)
let settingName: String
do {
settingName = try ThemeManager.shared.duplicateSetting(name: baseName)
} catch {
self.presentError(error)
return
}
self.updateThemeList(bySelecting: settingName)
}
/// start renaming theme
@IBAction func renameTheme(_ sender: Any?) {
let themeName = self.targetThemeName(for: sender)
let row = self.themeNames.firstIndex(of: themeName) ?? 0
self.themeTableView?.editColumn(0, row: row, with: nil, select: false)
}
/// delete selected theme
@IBAction func deleteTheme(_ sender: Any?) {
let themeName = self.targetThemeName(for: sender)
self.deleteTheme(name: themeName)
}
/// restore selected theme to original bundled one
@IBAction func restoreTheme(_ sender: Any?) {
let themeName = self.targetThemeName(for: sender)
self.restoreTheme(name: themeName)
}
/// export selected theme
@IBAction @MainActor func exportTheme(_ sender: Any?) {
let settingName = self.targetThemeName(for: sender)
let savePanel = NSSavePanel()
savePanel.canCreateDirectories = true
savePanel.canSelectHiddenExtension = true
savePanel.isExtensionHidden = true
savePanel.nameFieldLabel = "Export As:".localized
savePanel.nameFieldStringValue = settingName
savePanel.allowedContentTypes = [ThemeManager.shared.fileType]
Task {
guard await savePanel.beginSheetModal(for: self.view.window!) == .OK else { return }
do {
try ThemeManager.shared.exportSetting(name: settingName, to: savePanel.url!, hidesExtension: savePanel.isExtensionHidden)
} catch {
self.presentError(error)
}
}
}
/// import theme file via open panel
@IBAction @MainActor func importTheme(_ sender: Any?) {
let openPanel = NSOpenPanel()
openPanel.prompt = "Import".localized
openPanel.resolvesAliases = true
openPanel.allowsMultipleSelection = true
openPanel.canChooseDirectories = false
openPanel.allowedContentTypes = [ThemeManager.shared.fileType]
Task {
guard await openPanel.beginSheetModal(for: self.view.window!) == .OK else { return }
for url in openPanel.urls {
self.importTheme(fileURL: url)
}
}
}
/// open directory in Application Support in Finder where the selected theme exists
@IBAction func revealThemeInFinder(_ sender: Any?) {
let themeName = self.targetThemeName(for: sender)
guard let url = ThemeManager.shared.urlForUserSetting(name: themeName) else { return }
NSWorkspace.shared.activateFileViewerSelecting([url])
}
@IBAction func reloadAllThemes(_ sender: Any?) {
ThemeManager.shared.reloadCache()
}
// MARK: Private Methods
/// return theme name which is currently selected in the list table
private var selectedThemeName: String {
guard let tableView = self.themeTableView, tableView.selectedRow >= 0 else {
return ThemeManager.shared.userDefaultSettingName
}
return self.themeNames[tableView.selectedRow]
}
/// return representedObject if sender is menu item, otherwise selection in the list table
private func targetThemeName(for sender: Any?) -> String {
if let menuItem = sender as? NSMenuItem {
return menuItem.representedObject as! String
}
return self.selectedThemeName
}
private func representedSettingName(for menu: NSMenu?) -> String? {
guard self.themeTableView?.menu == menu else {
return self.selectedThemeName
}
guard let clickedRow = self.themeTableView?.clickedRow, clickedRow != -1 else { return nil } // clicked blank area
return self.themeNames[safe: clickedRow]
}
/// set given theme
private func setTheme(name: String) {
let theme = ThemeManager.shared.setting(name: name)
let isBundled = ThemeManager.shared.isBundledSetting(name: name)
// update default theme setting
let isDarkTheme = ThemeManager.shared.isDark(name: name)
let usesDarkAppearance = ThemeManager.shared.usesDarkAppearance
UserDefaults.standard[.pinsThemeAppearance] = (isDarkTheme != usesDarkAppearance)
UserDefaults.standard[.theme] = name
self.themeViewController?.theme = theme
self.themeViewController?.isBundled = isBundled
self.themeViewController?.view.setAccessibilityLabel(name)
self.isBundled = isBundled
}
/// try to delete given theme
private func deleteTheme(name: String) {
let alert = NSAlert()
alert.messageText = String(format: "Are you sure you want to delete “%@” theme?".localized, name)
alert.informativeText = "This action cannot be undone.".localized
alert.addButton(withTitle: "Cancel".localized)
alert.addButton(withTitle: "Delete".localized)
alert.buttons.last?.hasDestructiveAction = true
let window = self.view.window!
Task {
let returnCode = await alert.beginSheetModal(for: window)
guard returnCode == .alertSecondButtonReturn else { // cancelled
// flush swipe action for in case if this deletion was invoked by swiping the theme name
self.themeTableView?.rowActionsVisible = false
return
}
do {
try ThemeManager.shared.removeSetting(name: name)
} catch {
alert.window.orderOut(nil)
NSSound.beep()
await NSAlert(error: error).beginSheetModal(for: window)
return
}
AudioServicesPlaySystemSound(.moveToTrash)
}
}
/// try to restore given theme
private func restoreTheme(name: String) {
do {
try ThemeManager.shared.restoreSetting(name: name)
} catch {
self.presentError(error)
}
}
/// try to import theme file at given URL
private func importTheme(fileURL: URL) {
do {
try ThemeManager.shared.importSetting(fileURL: fileURL)
} catch {
// ask for overwriting if a setting with the same name already exists
self.presentError(error)
}
}
/// update theme list
private func updateThemeList(bySelecting selectingName: String? = nil) {
let themeName = selectingName ?? ThemeManager.shared.userDefaultSettingName
self.themeNames = ThemeManager.shared.settingNames
guard let tableView = self.themeTableView else { return }
tableView.reloadData()
let row = self.themeNames.firstIndex(of: themeName) ?? 0
tableView.selectRowIndexes([row], byExtendingSelection: false)
if selectingName != nil {
tableView.scrollRowToVisible(row)
}
}
/// update selection of theme table
private func updateThemeSelection() {
let themeName = ThemeManager.shared.userDefaultSettingName
let row = self.themeNames.firstIndex(of: themeName) ?? 0
self.themeTableView?.selectRowIndexes([row], byExtendingSelection: false)
}
}
// MARK: - Font Setting
extension AppearancePaneController: NSFontChanging {
// MARK: View Controller Methods
override func viewWillDisappear() {
super.viewWillDisappear()
// detach a possible font panel's target set in `showFonts()`
if NSFontManager.shared.target === self {
NSFontManager.shared.target = nil
}
}
// MARK: Font Changing Methods
/// restrict items in the font panel toolbar
func validModesForFontPanel(_ fontPanel: NSFontPanel) -> NSFontPanel.ModeMask {
return [.collection, .face, .size]
}
// MARK: Action Messages
/// show font panel
@IBAction func showFonts(_ sender: Any?) {
let name = UserDefaults.standard[.fontName]
let size = UserDefaults.standard[.fontSize]
let font = NSFont(name: name, size: size) ?? NSFont.userFont(ofSize: size)!
NSFontManager.shared.setSelectedFont(font, isMultiple: false)
NSFontManager.shared.orderFrontFontPanel(sender)
NSFontManager.shared.target = self
}
/// font in font panel did update
@IBAction func changeFont(_ sender: NSFontManager?) {
guard let sender = sender else { return assertionFailure() }
let newFont = sender.convert(.systemFont(ofSize: 0))
UserDefaults.standard[.fontName] = newFont.fontName
UserDefaults.standard[.fontSize] = newFont.pointSize
self.setupFontFamilyNameAndSize()
}
/// update font name field with new setting
@IBAction func updateFontField(_ sender: Any?) {
self.setupFontFamilyNameAndSize()
}
// MARK: Private Methods
/// display font name and size in the font field
private func setupFontFamilyNameAndSize() {
let name = UserDefaults.standard[.fontName]
let size = UserDefaults.standard[.fontSize]
let shouldAntiailias = UserDefaults.standard[.shouldAntialias]
let maxDisplaySize = NSFont.systemFontSize(for: .regular)
guard
let font = NSFont(name: name, size: size),
let displayFont = NSFont(name: name, size: min(size, maxDisplaySize)),
let fontField = self.fontField
else { return }
let displayName = font.displayName ?? font.fontName
fontField.stringValue = displayName + " " + String(format: "%g", locale: .current, size)
fontField.font = displayFont
fontField.disablesAntialiasing = !shouldAntiailias
}
}
| apache-2.0 | a5b67675de0cb0f0857587a59cb2bf96 | 32.700365 | 219 | 0.590682 | 5.436825 | false | false | false | false |
nathawes/swift | test/SILGen/struct_resilience.swift | 20 | 13518 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-emit-silgen -I %t -enable-library-evolution %s | %FileCheck %s
import resilient_struct
// Resilient structs from outside our resilience domain are always address-only
// CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience26functionWithResilientTypes_1f010resilient_A04SizeVAF_A2FXEtF : $@convention(thin) (@in_guaranteed Size, @noescape @callee_guaranteed (@in_guaranteed Size) -> @out Size) -> @out Size
// CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@noescape @callee_guaranteed (@in_guaranteed Size) -> @out Size):
func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
// Stored properties of resilient structs from outside our resilience
// domain are accessed through accessors
// CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size
var s2 = s
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[GETTER:%.*]] = function_ref @$s16resilient_struct4SizeV1wSivg : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[GETTER]]([[SIZE_BOX]])
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[OTHER_SIZE_BOX]] : $*Size
// CHECK: [[SETTER:%.*]] = function_ref @$s16resilient_struct4SizeV1wSivs : $@convention(method) (Int, @inout Size) -> ()
// CHECK: apply [[SETTER]]([[RESULT]], [[WRITE]])
s2.w = s.w
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @$s16resilient_struct4SizeV1hSivg : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
_ = s.h
// CHECK: apply %2(%0, %1)
// CHECK-NOT: destroy_value %2
// CHECK: return
return f(s)
}
// Use modify for inout access of properties in resilient structs
// from a different resilience domain
public func inoutFunc(_ x: inout Int) {}
// CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience18resilientInOutTestyy0c1_A04SizeVzF : $@convention(thin) (@inout Size) -> ()
func resilientInOutTest(_ s: inout Size) {
// CHECK: function_ref @$s16resilient_struct4SizeV1wSivM
// CHECK: function_ref @$s17struct_resilience9inoutFuncyySizF
inoutFunc(&s.w)
// CHECK: return
}
// Fixed-layout structs may be trivial or loadable
// CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience28functionWithFixedLayoutTypes_1f010resilient_A05PointVAF_A2FXEtF : $@convention(thin) (Point, @noescape @callee_guaranteed (Point) -> Point) -> Point
// CHECK: bb0(%0 : $Point, %1 : $@noescape @callee_guaranteed (Point) -> Point):
func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point {
// Stored properties of fixed layout structs are accessed directly
var p2 = p
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x
// CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x
// CHECK: assign [[RESULT]] to [[DEST]] : $*Int
p2.x = p.x
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y
_ = p.y
// CHECK: [[NEW_POINT:%.*]] = apply %1(%0)
// CHECK: return [[NEW_POINT]]
return f(p)
}
// Fixed-layout struct with resilient stored properties is still address-only
// CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience39functionWithFixedLayoutOfResilientTypes_1f010resilient_A09RectangleVAF_A2FXEtF : $@convention(thin) (@in_guaranteed Rectangle, @noescape @callee_guaranteed (@in_guaranteed Rectangle) -> @out Rectangle) -> @out Rectangle
// CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@noescape @callee_guaranteed (@in_guaranteed Rectangle) -> @out Rectangle):
func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle {
return f(r)
}
// Make sure we generate getters and setters for stored properties of
// resilient structs
public struct MySize {
// Static computed property
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivgZ : $@convention(method) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivsZ : $@convention(method) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivMZ : $@yield_once @convention(method) (@thin MySize.Type) -> @yields @inout Int
public static var expiration: Int {
get { return copyright + 70 }
set { copyright = newValue - 70 }
}
// Instance computed property
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivg : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivs : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivM : $@yield_once @convention(method) (@inout MySize) -> @yields @inout Int
public var d: Int {
get { return 0 }
set { }
}
// Instance stored property
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivs : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivM : $@yield_once @convention(method) (@inout MySize) -> @yields @inout Int
public var w: Int
// Read-only instance stored property
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1hSivg : $@convention(method) (@in_guaranteed MySize) -> Int
public let h: Int
// Weak property
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1iyXlSgvg : $@convention(method) (@in_guaranteed MySize) -> @owned Optional<AnyObject>
public weak var i: AnyObject?
// Static stored property
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivgZ : $@convention(method) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivsZ : $@convention(method) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivMZ : $@yield_once @convention(method) (@thin MySize.Type) -> @yields @inout Int
public static var copyright: Int = 0
}
// CHECK-LABEL: sil [ossa] @$s17struct_resilience28functionWithMyResilientTypes_1fAA0E4SizeVAE_A2EXEtF : $@convention(thin) (@in_guaranteed MySize, @noescape @callee_guaranteed (@in_guaranteed MySize) -> @out MySize) -> @out MySize
public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
// Stored properties of resilient structs from inside our resilience
// domain are accessed directly
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize
var s2 = s
// CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w
// CHECK: [[SRC:%.*]] = load [trivial] [[SRC_ADDR]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[SIZE_BOX]] : $*MySize
// CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MySize, #MySize.w
// CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int
s2.w = s.w
// CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h
// CHECK: [[RESULT:%.*]] = load [trivial] [[RESULT_ADDR]] : $*Int
_ = s.h
// CHECK: apply %2(%0, %1)
// CHECK-NOT: destroy_value %2
// CHECK: return
return f(s)
}
// CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience25publicTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int
@_transparent public func publicTransparentFunction(_ s: MySize) -> Int {
// Since the body of a public transparent function might be inlined into
// other resilience domains, we have to use accessors
// CHECK: [[SELF:%.*]] = alloc_stack $MySize
// CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @$s17struct_resilience6MySizeV1wSivg
// CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]])
// CHECK-NEXT: destroy_addr [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> @owned @callee_guaranteed () -> Int
@_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int {
// CHECK-LABEL: sil shared [serialized] [ossa] @$s17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVFSiycfU_ : $@convention(thin) (@in_guaranteed MySize) -> Int
// CHECK: function_ref @$s17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK: return {{.*}} : $Int
return { s.w }
}
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17struct_resilience27internalTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int
// CHECK: bb0([[ARG:%.*]] : $*MySize):
@_transparent func internalTransparentFunction(_ s: MySize) -> Int {
// The body of an internal transparent function will not be inlined into
// other resilience domains, so we can access storage directly
// CHECK: [[W_ADDR:%.*]] = struct_element_addr [[ARG]] : $*MySize, #MySize.w
// CHECK-NEXT: [[RESULT:%.*]] = load [trivial] [[W_ADDR]] : $*Int
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience23publicInlinableFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int
@inlinable public func publicInlinableFunction(_ s: MySize) -> Int {
// Since the body of a public transparent function might be inlined into
// other resilience domains, we have to use accessors
// CHECK: [[SELF:%.*]] = alloc_stack $MySize
// CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @$s17struct_resilience6MySizeV1wSivg
// CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]])
// CHECK-NEXT: destroy_addr [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// Make sure that @usableFromInline entities can be resilient
@usableFromInline struct VersionedResilientStruct {
@usableFromInline let x: Int
@usableFromInline let y: Int
@usableFromInline init(x: Int, y: Int) {
self.x = x
self.y = y
}
// Non-inlinable initializer, assigns to self -- treated as a root initializer
// CHECK-LABEL: sil [ossa] @$s17struct_resilience24VersionedResilientStructV5otherA2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct }
// CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]]
// CHECK: return
@usableFromInline init(other: VersionedResilientStruct) {
self = other
}
// Inlinable initializer, assigns to self -- treated as a delegating initializer
// CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience24VersionedResilientStructV6other2A2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct }
// CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: return
@usableFromInline @inlinable init(other2: VersionedResilientStruct) {
self = other2
}
}
// CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience27useVersionedResilientStructyAA0deF0VADF : $@convention(thin) (@in_guaranteed VersionedResilientStruct) -> @out VersionedResilientStruct
@usableFromInline
@_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct)
-> VersionedResilientStruct {
// CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1ySivg
// CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1xSivg
// CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1x1yACSi_SitcfC
return VersionedResilientStruct(x: s.y, y: s.x)
// CHECK: return
}
// CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience18inlinableInoutTestyyAA6MySizeVzF : $@convention(thin) (@inout MySize) -> ()
@inlinable public func inlinableInoutTest(_ s: inout MySize) {
// Inlinable functions can be inlined in other resiliene domains.
//
// Make sure we use modify for an inout access of a resilient struct
// property inside an inlinable function.
// CHECK: function_ref @$s17struct_resilience6MySizeV1wSivM
inoutFunc(&s.w)
// CHECK: return
}
// Initializers for resilient structs
extension Size {
// CHECK-LABEL: sil hidden [ossa] @$s16resilient_struct4SizeV0B11_resilienceE5otherA2C_tcfC : $@convention(method) (@in Size, @thin Size.Type) -> @out Size
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Size }
// CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var Size }
// CHECK: return
init(other: Size) {
self = other
}
}
| apache-2.0 | 37e5093067f692903499962588b087ae | 45.9375 | 277 | 0.67939 | 3.635826 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/EKAlertMessageView.swift | 3 | 3201 | //
// EKAlertMessageView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 5/5/18.
//
import UIKit
public class EKAlertMessageView: EKSimpleMessageView, EntryAppearanceDescriptor {
// MARK: Props
var buttonBarView: EKButtonBarView!
private var buttonsBarCompressedConstraint: NSLayoutConstraint!
private var buttonsBarExpandedConstraint: NSLayoutConstraint!
// MARK: EntryAppearenceDescriptor
var bottomCornerRadius: CGFloat = 0 {
didSet {
buttonBarView.bottomCornerRadius = bottomCornerRadius
}
}
// MARK: Setup
public init(with message: EKAlertMessage) {
super.init(with: message.simpleMessage)
setupButtonBarView(with: message.buttonBarContent)
layoutContent(with: message)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupButtonBarView(with content: EKProperty.ButtonBarContent) {
buttonBarView = EKButtonBarView(with: content)
buttonBarView.clipsToBounds = true
addSubview(buttonBarView)
}
func layoutContent(with message: EKAlertMessage) {
switch message.imagePosition {
case .top:
messageContentView.verticalMargins = 16
messageContentView.horizontalMargins = 16
messageContentView.labelsOffset = 5
if let thumbImageView = thumbImageView {
thumbImageView.layoutToSuperview(.top, offset: 20)
thumbImageView.layoutToSuperview(.centerX)
messageContentView.layout(.top, to: .bottom, of: thumbImageView)
} else {
messageContentView.layoutToSuperview(.top)
}
messageContentView.layoutToSuperview(axis: .horizontally)
buttonBarView.layout(.top, to: .bottom, of: messageContentView)
case .left:
messageContentView.verticalMargins = 0
messageContentView.horizontalMargins = 0
messageContentView.labelsOffset = 5
if let thumbImageView = thumbImageView {
thumbImageView.layoutToSuperview(.top, .left, offset: 16)
messageContentView.layout(.left, to: .right, of: thumbImageView, offset: 12)
messageContentView.layout(to: .top, of: thumbImageView, offset: 2)
} else {
messageContentView.layoutToSuperview(.left, .top, offset: 16)
}
messageContentView.layoutToSuperview(.right, offset: -16)
buttonBarView.layout(.top, to: .bottom, of: messageContentView, offset: 10)
}
buttonBarView.layoutToSuperview(axis: .horizontally)
buttonBarView.layoutToSuperview(.bottom)
buttonBarView.alpha = 0
if !message.buttonBarContent.content.isEmpty {
if message.buttonBarContent.expandAnimatedly {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.buttonBarView.expand()
}
} else {
buttonBarView.expand()
}
}
}
}
| apache-2.0 | dfeacdf81889c0cb6894fae65afed523 | 34.566667 | 92 | 0.626367 | 5.299669 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCap/BlueCap.playground/section-1.swift | 1 | 445 | // Playground - noun: a place where people can play
import UIKit
let a = [1,2,3,4]
a[0]
a[1...a.count-1]
a[a.count..<a.count]
func f(pred:@autoclosure()-> Bool) {
if pred() {
println("TRUE")
} else {
println("FALSE")
}
}
f(2==3)
f(3 > 2)
f(2 > 3)
let z : Int! = nil
func x(b:Int?) {
if let b = b {
println(b)
} else {
println("It is nil")
}
}
x(z)
let h = ["name":1]
h.keys.first
| mit | 10c223e999d252e1ed021feb0a60a1e7 | 11.361111 | 51 | 0.494382 | 2.458564 | false | false | false | false |
soapyigu/LeetCode_Swift | Sort/TopKFrequentElements.swift | 1 | 759 | /**
* Question Link: https://leetcode.com/problems/top-k-frequent-elements/
* Primary idea: Use a map to track frenquency of each number, then sort keys based on values
*
* Time Complexity: O(nlogn), Space Complexity: O(n)
*
*/
class TopKFrequentElements {
func topKFrequent(nums: [Int], _ k: Int) -> [Int] {
var map = [Int: Int]()
for num in nums {
guard let times = map[num] else {
map[num] = 1
continue
}
map[num] = times + 1
}
var keys = Array(map.keys)
keys.sortInPlace() {
let value1 = map[$0]
let value2 = map[$1]
return value1 > value2
}
return Array(keys[0..<k])
}
} | mit | f8d45a7a41abc0ae161b2980c806677a | 24.333333 | 93 | 0.512516 | 3.720588 | false | false | false | false |
anzfactory/TwitterClientCLI | Sources/TwitterClientCore/Shell.swift | 1 | 562 | //
// Shell.swift
// TwitterClientCLI
//
// Created by shingo asato on 2017/09/10.
//
//
import Foundation
struct Shell {
static func run(path: String, args: [String]?) -> String? {
let process = Process()
process.launchPath = path
if let args = args {
process.arguments = args
}
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
process.waitUntilExit()
return String(data: Data(pipe.fileHandleForReading.readDataToEndOfFile()), encoding: .utf8)
}
}
| mit | a41ceb4ac17cdf25e1be76522a5a9521 | 22.416667 | 99 | 0.599644 | 4.162963 | false | false | false | false |
wuyezhiguhun/DDMusicFM | DDMusicFM/DDTabBarController/Controller/DDTabBarController.swift | 1 | 2017 | //
// DDTabBarController.swift
// DDMusicFM
//
// Created by 王允顶 on 17/8/29.
// Copyright © 2017年 王允顶. All rights reserved.
//
import UIKit
class DDTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.addChildViewController(DDFoundViewController(), "tabbar_find_n", "tabbar_find_h", "发现")
self.addChildViewController(DDSoundViewController(), "tabbar_sound_n", "tabbar_sound_h", "订阅听")
self.addChildViewController(DDDownloadViewController(), "tabbar_download_n", "tabbar_download_h", "下载听")
self.addChildViewController(DDMeViewController(), "tabbar_me_n", "tabbar_me_h", "我的")
// Do any additional setup after loading the view.
}
func addChildViewController(_ childController: UIViewController, _ imageName: String, _ selectedImageName: String, _ title: String) {
childController.navigationItem.title = title
childController.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
childController.tabBarItem.selectedImage = UIImage(named: selectedImageName)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
childController.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0)
let nav = DDNavigationController(rootViewController: childController)
self.addChildViewController(nav);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 461e95160c990a07ec5cb51b67a0bf53 | 41.170213 | 140 | 0.709384 | 4.893827 | false | false | false | false |
fgengine/quickly | Quickly/ViewControllers/Dialog/Animation/QDialogViewControllerAnimation.swift | 1 | 3724 | //
// Quickly
//
public final class QDialogViewControllerPresentAnimation : IQDialogViewControllerFixedAnimation {
public var duration: TimeInterval
public var verticalOffset: CGFloat
public init(duration: TimeInterval = 0.2, verticalOffset: CGFloat = 50) {
self.duration = duration
self.verticalOffset = verticalOffset
}
public func animate(
viewController: IQDialogViewController,
animated: Bool,
complete: @escaping () -> Void
) {
if animated == true {
let originalVerticalAlignment = viewController.verticalAlignment
let originalAlpha = viewController.view.alpha
viewController.willPresent(animated: animated)
switch originalVerticalAlignment {
case .top(let offset): viewController.verticalAlignment = .top(offset: offset - self.verticalOffset)
case .center(let offset): viewController.verticalAlignment = .center(offset: offset - self.verticalOffset)
case .bottom(let offset): viewController.verticalAlignment = .bottom(offset: offset - self.verticalOffset)
}
viewController.layoutIfNeeded()
viewController.view.alpha = 0
UIView.animate(withDuration: self.duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
viewController.verticalAlignment = originalVerticalAlignment
viewController.view.alpha = originalAlpha
viewController.view.layoutIfNeeded()
}, completion: { (completed: Bool) in
viewController.didPresent(animated: animated)
complete()
})
} else {
viewController.willPresent(animated: animated)
viewController.didPresent(animated: animated)
complete()
}
}
}
public final class QDialogViewControllerDismissAnimation : IQDialogViewControllerFixedAnimation {
public var duration: TimeInterval
public var verticalOffset: CGFloat
public init(duration: TimeInterval = 0.2, verticalOffset: CGFloat = 200) {
self.duration = duration
self.verticalOffset = verticalOffset
}
public func animate(
viewController: IQDialogViewController,
animated: Bool,
complete: @escaping () -> Void
) {
if animated == true {
let originalVerticalAlignment = viewController.verticalAlignment
let originalAlpha = viewController.view.alpha
viewController.willDismiss(animated: animated)
UIView.animate(withDuration: self.duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
switch originalVerticalAlignment {
case .top(let offset): viewController.verticalAlignment = .top(offset: offset - self.verticalOffset)
case .center(let offset): viewController.verticalAlignment = .center(offset: offset - self.verticalOffset)
case .bottom(let offset): viewController.verticalAlignment = .bottom(offset: offset - self.verticalOffset)
}
viewController.view.alpha = 0
viewController.layoutIfNeeded()
}, completion: { (completed: Bool) in
viewController.verticalAlignment = originalVerticalAlignment
viewController.view.alpha = originalAlpha
viewController.didDismiss(animated: animated)
complete()
})
} else {
viewController.willDismiss(animated: animated)
viewController.didDismiss(animated: animated)
complete()
}
}
}
| mit | 71d3d66c24c61cdeb0356a1bcd1be943 | 41.318182 | 133 | 0.645005 | 5.809672 | false | false | false | false |
dduan/swift | benchmark/single-source/DictTest3.swift | 1 | 2370 | //===--- DictTest3.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_Dictionary3(N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
var hash1 = [String:Int]()
var hash2 = [String:Int]()
var res = ""
for _ in 1...N {
hash1 = [:]
for i in 0..<size1 {
hash1["foo_" + String(i)] = i
}
hash2 = hash1
for _ in 1..<reps {
for (k, v) in hash1 {
hash2[k] = hash2[k]! + v
}
}
res = (String(hash1["foo_1"]!) + " " + String(hash1["foo_99"]!) + " " +
String(hash2["foo_1"]!) + " " + String(hash2["foo_99"]!))
if res != ref_result {
break
}
}
CheckResults(res == ref_result, "Incorrect results in Dictionary3: \(res) != \(ref_result)")
}
class Box<T : Hashable where T : Equatable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue : Int {
return value.hashValue
}
}
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_Dictionary3OfObjects(N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
var hash1 : [ Box<String> : Box<Int> ] = [:]
var hash2 : [ Box<String> : Box<Int> ] = [:]
var res = ""
for _ in 1...N {
hash1 = [:]
for i in 0..<size1 {
hash1[Box("foo_" + String(i))] = Box(i)
}
hash2 = hash1
for _ in 1..<reps {
for (k, v) in hash1 {
hash2[k] = Box(hash2[k]!.value + v.value)
}
}
res = (String(hash1[Box("foo_1")]!.value) + " " + String(hash1[Box("foo_99")]!.value) + " " +
String(hash2[Box("foo_1")]!.value) + " " + String(hash2[Box("foo_99")]!.value))
if res != ref_result {
break
}
}
CheckResults(res == ref_result, "Incorrect results in Dictionary3OfObject: \(res) != \(ref_result)")
}
| apache-2.0 | 675588410dfa6d6392b4c9350acd7ffd | 23.6875 | 102 | 0.528692 | 3.237705 | false | false | false | false |
doctorn/hac-website | Sources/HaCWebsiteLib/ViewModels/PostCard.swift | 1 | 1178 | import HaCTML
struct PostCard {
enum PostCategory: String {
case workshop = "Workshop"
case video = "Video"
case hackathon = "Hackathon"
case general = "General Event"
}
let title: String
let category: PostCategory
let description: String
let backgroundColor: String?
let imageURL: String?
var node: Node {
return El.Div[Attr.className => "PostCard", Attr.style => ["background-color": backgroundColor]].containing(
El.Div[
Attr.className => "PostCard__photoBackground",
Attr.style => ["background-image": imageURL.map { "url('\($0)')" }]
],
El.Div[Attr.className => "PostCard__content"].containing(
El.Span[Attr.className => "PostCard__categoryLabel"].containing(category.rawValue),
El.Div[Attr.className => "PostCard__title"].containing(title),
El.Div[Attr.className => "PostCard__description"].containing(description)
),
El.Div[Attr.className => "PostCard__footer"].containing(
El.Div[Attr.className => "PostCard__bottomAction"].containing("Find out more")
)
)
}
}
protocol PostCardRepresentable {
var postCardRepresentation : PostCard {get}
} | mit | af45631dbd6daa149e46714123dadec3 | 30.864865 | 112 | 0.658744 | 4.020478 | false | false | false | false |
JakeLin/IBAnimatable | IBAnimatableApp/IBAnimatableApp/Playground/ActivityIndicators/ActivityIndicatorCollectionViewController.swift | 2 | 1770 | //
// ActivityIndicatorCollectionViewController.swift
// IBAnimatableApp
//
// Created by phimage on 02/05/2018.
// Copyright © 2018 IBAnimatable. All rights reserved.
//
import UIKit
import IBAnimatable
final class ActivityIndicatorCollectionViewController: UICollectionViewController {
// MARK: Properties
fileprivate var activityIndicatorsType: [ActivityIndicatorType] {
var types = [ActivityIndicatorType]()
iterateEnum(ActivityIndicatorType.self).forEach {
types.append($0)
}
if types.count % 2 != 0, let index = types.firstIndex(of: .none) {
types.remove(at: index)
}
return types
}
// MARK: UICollectionViewController
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return activityIndicatorsType.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if let activityCell = cell as? ActivityIndicatorCollectionViewCell {
activityCell.type = activityIndicatorsType[indexPath.row]
}
return cell
}
}
@IBDesignable
final class ActivityIndicatorCollectionViewCell: AnimatableCollectionViewCell {
// swiftlint:disable:next private_outlet
@IBOutlet weak var activityIndicatorView: AnimatableActivityIndicatorView!
// swiftlint:disable:next private_outlet
@IBOutlet weak var nameLabel: UILabel!
var type: ActivityIndicatorType = .none {
didSet {
activityIndicatorView.stopAnimating()
activityIndicatorView.animationType = type
activityIndicatorView.startAnimating()
nameLabel.text = type.rawValue
}
}
}
| mit | c51a9b256f00c7ba4a6b66fa1cc7f348 | 30.589286 | 128 | 0.754664 | 5.296407 | false | false | false | false |
nua-schroers/mvvm-frp | 41_MVVM_FRP-App_ExplicitSignals/MatchGame/MatchGame/ViewModel/SettingsViewModel.swift | 2 | 2162 | //
// SettingsViewModel.swift
// MatchGame
//
// Created by Dr. Wolfram Schroers on 5/27/16.
// Copyright © 2016 Wolfram Schroers. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
/// View model corresponding to the "Settings" screen.
class SettingsViewModel: NSObject, CanSupplyDataContext {
// MARK: VM -> Controller communication (state of the view and signals)
/// The text shown for initial matches.
var initialMatchSetting = MutableProperty("")
/// The text shown for maximum matches to remove.
var removeMaxSetting = MutableProperty("")
/// Request to handle the "Done" button.
var doneSignal: Signal<Void, Never>
// MARK: CanSupplyDataContext, VM -> VM communication
var initialMatchSliderValue = MutableProperty<Float>(18.0)
var removeMaxSliderValue = MutableProperty<Float>(3.0)
var strategyIndex = MutableProperty(0)
// MARK: Controller -> VM communication
/// Tap on the "Done" button.
var doneAction: CocoaAction<Any>!
// MARK: Declarative init
/// Designated initializer.
override init() {
// Set up the capability for requests to close the settings screen.
let (signalForDone, observerForDone) = Signal<Void, Never>.pipe()
self.doneSignal = signalForDone
self.doneObserver = observerForDone
super.init()
// Establish data bindings for updating the labels.
self.initialMatchSetting <~ self.initialMatchSliderValue.producer.map {
NSLocalizedString("Initial number of matches: \(Int($0))", comment: "")
}
self.removeMaxSetting <~ self.removeMaxSliderValue.producer.map {
NSLocalizedString("Maximum number to remove: \(Int($0))", comment: "")
}
// Set up the action to handle taps on the "Done" button.
let doneRACAction = Action<Void, Void, Never> {
self.doneObserver.send(value: Void())
return SignalProducer.empty
}
self.doneAction = CocoaAction(doneRACAction, input: ())
}
// MARK: Private
fileprivate var doneObserver: Signal<Void, Never>.Observer
}
| mit | 6539a3129609837d1172677bc6b75e57 | 30.779412 | 83 | 0.669597 | 4.637339 | false | false | false | false |
MrAlek/JSQDataSourcesKit | Example/Example/Extensions.swift | 1 | 3486 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import CoreData
import Foundation
import UIKit
extension UIAlertController {
class func showActionAlert(presenter: UIViewController,
addNewAction: () -> Void,
deleteAction: () -> Void,
changeNameAction: () -> Void,
changeColorAction: () -> Void,
changeAllAction: () -> Void) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
alert.addAction(UIAlertAction(title: "Add new", style: .Default) { action in
addNewAction()
})
alert.addAction(UIAlertAction(title: "Delete selected", style: .Default) { action in
deleteAction()
})
alert.addAction(UIAlertAction(title: "Change name selected", style: .Default) { action in
changeNameAction()
})
alert.addAction(UIAlertAction(title: "Change color selected", style: .Default) { action in
changeColorAction()
})
alert.addAction(UIAlertAction(title: "Change all selected", style: .Default) { action in
changeAllAction()
})
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presenter.presentViewController(alert, animated: true, completion: nil)
}
}
extension UITableView {
func deselectAllRows() {
if let indexPaths = indexPathsForSelectedRows {
for i in indexPaths {
deselectRowAtIndexPath(i, animated: true)
}
}
}
}
extension UICollectionView {
func deselectAllItems() {
if let indexPaths = indexPathsForSelectedItems() {
for i in indexPaths {
deselectItemAtIndexPath(i, animated: true)
}
}
}
}
extension NSFetchedResultsController {
func deleteThingsAtIndexPaths(indexPaths: [NSIndexPath]?) {
guard let indexPaths = indexPaths else {
return
}
for i in indexPaths {
let thingToDelete = objectAtIndexPath(i) as! Thing
managedObjectContext.deleteObject(thingToDelete)
}
}
func changeThingNamesAtIndexPaths(indexPaths: [NSIndexPath]?) {
guard let indexPaths = indexPaths else {
return
}
for i in indexPaths {
let thingToChange = objectAtIndexPath(i) as! Thing
thingToChange.changeNameRandomly()
}
}
func changeThingColorsAtIndexPaths(indexPaths: [NSIndexPath]?) {
guard let indexPaths = indexPaths else {
return
}
for i in indexPaths {
let thingToChange = objectAtIndexPath(i) as! Thing
thingToChange.changeColorRandomly()
}
}
func changeThingsAtIndexPaths(indexPaths: [NSIndexPath]?) {
guard let indexPaths = indexPaths else {
return
}
for i in indexPaths {
let thingToChange = objectAtIndexPath(i) as! Thing
thingToChange.changeRandomly()
}
}
}
| mit | 6ffb21a5794bfdf133f86b580ffe8571 | 25.807692 | 98 | 0.588235 | 5.170623 | false | false | false | false |
benlangmuir/swift | SwiftCompilerSources/Sources/SIL/Builder.swift | 4 | 7153 | //===--- Builder.swift - Building and modifying SIL ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
/// A utility to create new instructions at a given insertion point.
public struct Builder {
public enum InsertionPoint {
case before(Instruction)
case atEndOf(BasicBlock)
}
let insertAt: InsertionPoint
let location: Location
private let passContext: BridgedPassContext
private var bridged: BridgedBuilder {
switch insertAt {
case .before(let inst):
return BridgedBuilder(insertBefore: inst.bridged.optional,
insertAtEnd: OptionalBridgedBasicBlock.none,
loc: location.bridged)
case .atEndOf(let block):
return BridgedBuilder(insertBefore: OptionalBridgedInstruction.none,
insertAtEnd: block.bridged.optional,
loc: location.bridged)
}
}
private func notifyInstructionsChanged() {
PassContext_notifyChanges(passContext, instructionsChanged)
}
private func notifyCallsChanged() {
PassContext_notifyChanges(passContext, callsChanged)
}
private func notifyBranchesChanged() {
PassContext_notifyChanges(passContext, branchesChanged)
}
public init(insertAt: InsertionPoint, location: Location,
passContext: BridgedPassContext) {
self.insertAt = insertAt
self.location = location;
self.passContext = passContext
}
public func createBuiltinBinaryFunction(name: String,
operandType: Type, resultType: Type, arguments: [Value]) -> BuiltinInst {
notifyInstructionsChanged()
return arguments.withBridgedValues { valuesRef in
return name._withStringRef { nameStr in
let bi = SILBuilder_createBuiltinBinaryFunction(
bridged, nameStr, operandType.bridged, resultType.bridged, valuesRef)
return bi.getAs(BuiltinInst.self)
}
}
}
public func createCondFail(condition: Value, message: String) -> CondFailInst {
notifyInstructionsChanged()
return message._withStringRef { messageStr in
let cf = SILBuilder_createCondFail(bridged, condition.bridged, messageStr)
return cf.getAs(CondFailInst.self)
}
}
public func createIntegerLiteral(_ value: Int, type: Type) -> IntegerLiteralInst {
notifyInstructionsChanged()
let literal = SILBuilder_createIntegerLiteral(bridged, type.bridged, value)
return literal.getAs(IntegerLiteralInst.self)
}
public func createAllocStack(_ type: Type, hasDynamicLifetime: Bool = false,
isLexical: Bool = false, wasMoved: Bool = false) -> AllocStackInst {
notifyInstructionsChanged()
let dr = SILBuilder_createAllocStack(bridged, type.bridged, hasDynamicLifetime ? 1 : 0,
isLexical ? 1 : 0, wasMoved ? 1 : 0)
return dr.getAs(AllocStackInst.self)
}
@discardableResult
public func createDeallocStack(_ operand: Value) -> DeallocStackInst {
notifyInstructionsChanged()
let dr = SILBuilder_createDeallocStack(bridged, operand.bridged)
return dr.getAs(DeallocStackInst.self)
}
@discardableResult
public func createDeallocStackRef(_ operand: Value) -> DeallocStackRefInst {
notifyInstructionsChanged()
let dr = SILBuilder_createDeallocStackRef(bridged, operand.bridged)
return dr.getAs(DeallocStackRefInst.self)
}
public func createUncheckedRefCast(object: Value, type: Type) -> UncheckedRefCastInst {
notifyInstructionsChanged()
let object = SILBuilder_createUncheckedRefCast(bridged, object.bridged, type.bridged)
return object.getAs(UncheckedRefCastInst.self)
}
@discardableResult
public func createSetDeallocating(operand: Value, isAtomic: Bool) -> SetDeallocatingInst {
notifyInstructionsChanged()
let setDeallocating = SILBuilder_createSetDeallocating(bridged, operand.bridged, isAtomic)
return setDeallocating.getAs(SetDeallocatingInst.self)
}
public func createFunctionRef(_ function: Function) -> FunctionRefInst {
notifyInstructionsChanged()
let functionRef = SILBuilder_createFunctionRef(bridged, function.bridged)
return functionRef.getAs(FunctionRefInst.self)
}
public func createCopyValue(operand: Value) -> CopyValueInst {
notifyInstructionsChanged()
return SILBuilder_createCopyValue(bridged, operand.bridged).getAs(CopyValueInst.self)
}
@discardableResult
public func createCopyAddr(from fromAddr: Value, to toAddr: Value,
takeSource: Bool = false, initializeDest: Bool = false) -> CopyAddrInst {
notifyInstructionsChanged()
return SILBuilder_createCopyAddr(bridged, fromAddr.bridged, toAddr.bridged,
takeSource ? 1 : 0, initializeDest ? 1 : 0).getAs(CopyAddrInst.self)
}
@discardableResult
public func createDestroyValue(operand: Value) -> DestroyValueInst {
notifyInstructionsChanged()
return SILBuilder_createDestroyValue(bridged, operand.bridged).getAs(DestroyValueInst.self)
}
@discardableResult
public func createApply(
function: Value,
_ substitutionMap: SubstitutionMap,
arguments: [Value]
) -> ApplyInst {
notifyInstructionsChanged()
notifyCallsChanged()
let apply = arguments.withBridgedValues { valuesRef in
SILBuilder_createApply(bridged, function.bridged, substitutionMap.bridged, valuesRef)
}
return apply.getAs(ApplyInst.self)
}
public func createUncheckedEnumData(enum enumVal: Value,
caseIndex: Int,
resultType: Type) -> UncheckedEnumDataInst {
notifyInstructionsChanged()
let ued = SILBuilder_createUncheckedEnumData(bridged, enumVal.bridged, caseIndex, resultType.bridged)
return ued.getAs(UncheckedEnumDataInst.self)
}
@discardableResult
public func createSwitchEnum(enum enumVal: Value,
cases: [(Int, BasicBlock)],
defaultBlock: BasicBlock? = nil) -> SwitchEnumInst {
notifyInstructionsChanged()
notifyBranchesChanged()
let se = cases.withUnsafeBufferPointer { caseBuffer in
SILBuilder_createSwitchEnumInst(
bridged, enumVal.bridged, defaultBlock.bridged, caseBuffer.baseAddress, caseBuffer.count)
}
return se.getAs(SwitchEnumInst.self)
}
@discardableResult
public func createBranch(to destBlock: BasicBlock, arguments: [Value] = []) -> BranchInst {
notifyInstructionsChanged()
notifyBranchesChanged()
return arguments.withBridgedValues { valuesRef in
let bi = SILBuilder_createBranch(bridged, destBlock.bridged, valuesRef)
return bi.getAs(BranchInst.self)
}
}
}
| apache-2.0 | 7b0103d3d77f7d8b4ffcdd364d9cf441 | 36.647368 | 105 | 0.697889 | 4.724571 | false | false | false | false |
alexzatsepin/omim | iphone/Maps/Bookmarks/Catalog/DownloadedBookmarksDataSource.swift | 2 | 905 | class DownloadedBookmarksDataSource {
private var categories: [MWMCategory] = []
var categoriesCount: NSInteger {
get {
return categories.count
}
}
var allCategoriesHidden: Bool {
get {
var result = true
categories.forEach { if $0.isVisible { result = false } }
return result
}
set {
MWMBookmarksManager.shared().setCatalogCategoriesVisible(!newValue)
}
}
init() {
reloadData()
}
func category(at index: Int) -> MWMCategory {
return categories[index]
}
func reloadData() {
categories = MWMBookmarksManager.shared().categoriesFromCatalog()
}
func setCategory(visible: Bool, at index: Int) {
let category = categories[index]
category.isVisible = visible
}
func deleteCategory(at index: Int) {
MWMBookmarksManager.shared().deleteCategory(category(at: index).categoryId)
reloadData()
}
}
| apache-2.0 | d9b9f01517a6f98f27e0ea474ef68950 | 20.547619 | 79 | 0.661878 | 4.248826 | false | false | false | false |
akesson/LogCentral | Tests/ActivityTests.swift | 1 | 2502 | //
// ActivityTests.swift
// LogCentralTests
//
// Created by Henrik Akesson on 15/02/2018.
// Copyright © 2018 Henrik Akesson. All rights reserved.
//
import XCTest
@testable import LogCentral
class ActivityTests: XCTestCase {
/// THESE TESTS NEEDS TO BE MANUALLY VERIFIED IN THE CONSOLE
var infoLogger = TestLogger([.info])
override func setUp() {
infoLogger = TestLogger([.info])
loggers = [infoLogger]
}
func testInternalActivity() {
let myActivity = Activity("first internal root activity", parent: .none)
myActivity.active {
log.info(in: .model, "inside first internal root activity")
let mySecondActivity = Activity("nested internal activity")
var scope2 = mySecondActivity.enter()
log.info(in: .model, "inside nested internal activity")
scope2.leave()
}
}
func testRootAndNestedActivity() {
log.info(in: .model, "before root activity")
log.rootActivity("root activity") {
log.info(in: .view, "inside root activity")
log.activity("nested activity", {
log.info(in: .model, "inside nested activity")
})
}
}
func testActivityWithReturn() {
XCTAssertTrue(activityWithReturn())
}
func activityWithReturn() -> Bool {
return log.activity("root activity") {
return true
}
}
func testDualRootActivity() {
log.info(in: .model, "before root activity")
log.rootActivity("root activity") {
log.info(in: .view, "inside root activity")
log.rootActivity("second root activity", {
log.info(in: .model, "inside second root activity")
})
}
}
func testRootActivityError() {
log.info(in: .model, "before root activity")
var caught = false
do {
try log.rootActivity("root activity") {
log.info(in: .view, "before root activity error")
try throwser()
log.info(in: .view, "after root activity error")
}
} catch TestError.test {
caught = true
} catch {
XCTFail()
}
XCTAssert(caught)
}
func throwser() throws {
throw TestError.test
}
}
| mit | c1d3b287ca776e31067d6dbe53476bfd | 25.052083 | 80 | 0.534986 | 4.622921 | false | true | false | false |
CalebeEmerick/RandomNotification | Source/RandomNotification/ImageDownloader.swift | 1 | 1997 | //
// ImageDownloader.swift
// RandomNotification
//
// Created by Calebe Emerick on 23/12/16.
// Copyright © 2016 CalebeEmerick. All rights reserved.
//
import UIKit
final class ImageDownloader {
private init() { }
static let shared = ImageDownloader()
fileprivate let cache = NSCache<AnyObject, AnyObject>()
func download(from url: String, completion: @escaping (UIImage?) -> Void) {
if isCached(url) {
let cachedImage = retrieveCachedImage(from: url)
completion(cachedImage)
}
else {
downloadImage(from: url) { [weak self] image in
DispatchQueue.main.async {
completion(image)
self?.makeCache(for: url, image: image)
}
}
}
}
}
extension ImageDownloader {
fileprivate func downloadImage(from url: String, completion: @escaping (UIImage?) -> Void) {
Just.get(url) { result in
DispatchQueue.main.async {
guard let data = result.content else {
completion(nil)
return
}
let image = UIImage(data: data)
completion(image)
}
}
}
fileprivate func makeCache(for url: String, image: UIImage?) {
let item = CacheItem(url: url, image: image)
cache.setObject(item, forKey: item.urlObject)
}
fileprivate func retrieveCachedImage(from url: String) -> UIImage? {
let urlObject = url as AnyObject
guard let item = cache.object(forKey: urlObject) as? CacheItem else { return nil }
return item.image
}
fileprivate func isCached(_ url: String) -> Bool {
let urlObject = url as AnyObject
return cache.object(forKey: urlObject) != nil
}
}
| mit | 37b498eef1ce7cfad59956358e71d573 | 25.613333 | 96 | 0.529058 | 5.091837 | false | false | false | false |
Nyx0uf/MPDRemote | src/common/misc/CoreImageUtilities.swift | 1 | 1857 | // CoreImageUtilities.swift
// Copyright (c) 2017 Nyx0uf
//
// 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 CoreImage
final class CoreImageUtilities
{
// MARK: - Public properties
// Singletion instance
static let shared = CoreImageUtilities()
// Software context
private(set) lazy var swContext: CIContext = {
let swContext = CIContext(options: [kCIContextUseSoftwareRenderer : true])
return swContext
}()
// Hardware context
private(set) lazy var hwContext: CIContext = {
let hwContext = CIContext(options: [kCIContextUseSoftwareRenderer : false])
return hwContext
}()
//
private(set) lazy var isHeicCapable: Bool = {
if #available(iOS 11.0, *)
{
let types = CGImageDestinationCopyTypeIdentifiers() as! [String]
return types.contains("public.heic")
}
else
{
return false
}
}()
}
| mit | 420f56f41b0d9cefec91812bee77bfd8 | 34.037736 | 80 | 0.745288 | 4.090308 | false | false | false | false |
RemyDCF/tpg-offline | tpg offline/Disruptions/DisruptionsTableViewController.swift | 1 | 8341 | //
// DisruptionsTableViewController.swift
// tpgoffline
//
// Created by Rémy Da Costa Faro on 18/06/2017.
// Copyright © 2018 Rémy Da Costa Faro DA COSTA FARO. All rights reserved.
//
import UIKit
import Alamofire
import Crashlytics
class DisruptionsTableViewController: UITableViewController {
@IBOutlet weak var disruptionsCenteredView: DisruptionsCenteredView!
var disruptions: DisruptionsGroup? {
didSet {
guard let disruptions = self.disruptions else { return }
self.keys = disruptions.disruptions.keys.sorted(by: {
if let a = Int($0), let b = Int($1) {
return a < b
} else { return $0 < $1 }})
}
}
var requestStatus: RequestStatus = .loading {
didSet {
if requestStatus == .error {
self.disruptionsCenteredView.imageView.image = #imageLiteral(resourceName: "errorHighRes").maskWith(color:
App.textColor)
self.disruptionsCenteredView.titleLabel.textColor = App.textColor
self.disruptionsCenteredView.titleLabel.text = Text.error
self.disruptionsCenteredView.subtitleLabel.text = Text.errorNoInternet
self.disruptionsCenteredView.subtitleLabel.textColor = App.textColor
self.disruptionsCenteredView.isHidden = false
self.tableView.separatorStyle = .none
} else if requestStatus == .noResults {
self.disruptionsCenteredView.imageView.image = #imageLiteral(resourceName: "sunHighRes").maskWith(color:
App.textColor)
self.disruptionsCenteredView.titleLabel.text = Text.noDisruptions
self.disruptionsCenteredView.titleLabel.textColor = App.textColor
self.disruptionsCenteredView.subtitleLabel.text = Text.noDisruptionsSubtitle
self.disruptionsCenteredView.subtitleLabel.textColor = App.textColor
self.disruptionsCenteredView.isHidden = false
self.tableView.separatorStyle = .none
} else {
self.disruptionsCenteredView.isHidden = true
self.tableView.separatorStyle = .singleLine
}
}
}
var keys: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
App.logEvent("Show disruptions", attributes: [:])
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 140
tableView.allowsSelection = false
//disruptionsCenteredView.center = tableView.center
disruptionsCenteredView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(disruptionsCenteredView)
NSLayoutConstraint.activate([
disruptionsCenteredView.leadingAnchor.constraint(equalTo: view.leadingAnchor,
constant: 16),
disruptionsCenteredView.trailingAnchor.constraint(equalTo: view.trailingAnchor,
constant: 16)
])
disruptionsCenteredView.centerXAnchor
.constraint(equalTo: self.tableView.centerXAnchor).isActive = true
disruptionsCenteredView.centerYAnchor
.constraint(equalTo: self.tableView.centerYAnchor).isActive = true
disruptionsCenteredView.isHidden = true
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.largeTitleTextAttributes =
[NSAttributedString.Key.foregroundColor: App.textColor]
}
navigationController?.navigationBar.titleTextAttributes =
[NSAttributedString.Key.foregroundColor: App.textColor]
self.refreshDisruptions()
refreshControl = UIRefreshControl()
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl!)
}
refreshControl?.addTarget(self,
action: #selector(refreshDisruptions),
for: .valueChanged)
refreshControl?.tintColor = #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1)
navigationItem.rightBarButtonItems = [
UIBarButtonItem(image: #imageLiteral(resourceName: "reloadNavBar"),
style: UIBarButtonItem.Style.plain,
target: self,
action: #selector(self.refreshDisruptions),
accessbilityLabel: Text.reloadDepartures)
]
if App.darkMode {
self.navigationController?.navigationBar.barStyle = .black
self.tableView.backgroundColor = .black
self.tableView.separatorColor = App.separatorColor
}
self.tableView.sectionIndexBackgroundColor = App.darkMode ?
App.cellBackgroundColor : .white
ColorModeManager.shared.addColorModeDelegate(self)
}
override func colorModeDidUpdated() {
super.colorModeDidUpdated()
self.disruptionsCenteredView.titleLabel.textColor = App.textColor
self.disruptionsCenteredView.subtitleLabel.textColor = App.textColor
self.disruptionsCenteredView.imageView.image =
self.disruptionsCenteredView.imageView.image?.maskWith(color: App.textColor)
}
@objc func refreshDisruptions() {
self.requestStatus = .loading
self.tableView.reloadData()
Alamofire.request(URL.disruptions,
method: .get,
parameters: ["key": API.tpg])
.responseData { (response) in
if let data = response.result.value {
let jsonDecoder = JSONDecoder()
let json = try? jsonDecoder.decode(DisruptionsGroup.self,
from: data)
self.disruptions = json
self.requestStatus =
(json?.disruptions.count ?? 0 == 0) ? .noResults : .ok
self.tableView.reloadData()
} else {
self.requestStatus = .error
self.tableView.reloadData()
}
self.refreshControl?.endRefreshing()
// Warning: Ugly code ahead
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.05, execute: {
self.tableView.reloadData()
})
// End of warning
}
}
deinit {
ColorModeManager.shared.removeColorModeDelegate(self)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
if requestStatus == .loading {
return 1
} else if requestStatus == .noResults {
return 0
} else {
return (disruptions?.disruptions.count ?? 0)
}
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
#if swift(>=4.1)
return self.keys.compactMap({ $0.count > 4 ? "/" : $0 })
#else
return self.keys.flatMap({ $0.count > 4 ? "/" : $0 })
#endif
}
override func tableView(_ tableView: UITableView,
sectionForSectionIndexTitle title: String,
at index: Int) -> Int {
return index
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
if requestStatus == .loading {
return 3
} else {
return disruptions?.disruptions[self.keys[section]]?.count ?? 0
}
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(
withIdentifier: "disruptionsCell",
for: indexPath) as? DisruptionTableViewCell else {
return UITableViewCell()
}
if requestStatus == .ok {
let key = self.keys[indexPath.section]
cell.disruption = disruptions?.disruptions[key]?[indexPath.row]
cell.lines = self.keys[indexPath.section] == Text.wholeTpgNetwork ?
["tpg"] : self.keys[indexPath.section].components(separatedBy: " / ")
} else {
cell.disruption = nil
}
return cell
}
override func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator) {
// swiftlint:disable:previous line_length
// Warning: Ugly code ahead
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.05, execute: {
self.tableView.reloadData()
})
// End of warning
}
}
class DisruptionsCenteredView: UIView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
}
| mit | c381de36e542061d7a0e0052582e9768 | 34.632479 | 114 | 0.662149 | 4.68427 | false | false | false | false |
mgcm/CloudVisionKit | Pod/Classes/GCVApiManager.swift | 1 | 2765 | //
// GCVApiManager.swift
// CloudVisionKit
//
// Copyright (c) 2016 Milton Moura <[email protected]>
//
// The MIT License (MIT)
//
// 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 Alamofire
import Unbox
internal class GCVApiManager {
fileprivate static let apiVersion = "v1"
fileprivate static let baseURL = "https://vision.googleapis.com/" + GCVApiManager.apiVersion + "/images:annotate"
fileprivate var apiKey: String?
init(apiKey: String) {
self.apiKey = apiKey
}
fileprivate func buildQueryURL() -> URL? {
if var components = URLComponents(string: GCVApiManager.baseURL) {
components.queryItems = [URLQueryItem(name: "key", value: self.apiKey)]
return components.url
}
return nil
}
fileprivate func requestHeaders() -> [String: String] {
return ["Content-Type": "application/json"];
}
internal func performRequest(_ payload: [String: AnyObject]?, closure: @escaping (GCVResponse) -> Void) throws -> Void {
let request = Alamofire.request(self.buildQueryURL()!, method: .post, parameters: payload, encoding: JSONEncoding.default)
if let urlRequest = request.request {
if let httpBody = urlRequest.httpBody {
if httpBody.count > 8000000 {
throw GCVApiError.requestSizeExceeded
}
}
}
request.responseJSON { (response) -> Void in
if let JSON = response.result.value {
let resp = JSON as! Dictionary<String, AnyObject>
let r: GCVResponse = try! unbox(dictionary: resp)
closure(r)
}
}
}
}
| mit | 884f602727f2fba299c28337176ebc75 | 37.402778 | 130 | 0.669078 | 4.416933 | false | false | false | false |
nostramap/nostra-sdk-sample-ios | AddressSearchSample/Swift/AddressSearchSample/AddressSearchKeywordViewController.swift | 1 | 694 | //
// AddressSearchKeywordViewController.swift
// AddressSearchSample
//
// Copyright © 2559 Globtech. All rights reserved.
//
import UIKit
import NOSTRASDK
class AddressSearchKeywordViewController: UIViewController {
@IBOutlet weak var txtKeyword: UITextField!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "resultSegue" {
let resultViewController = segue.destination as? AddressSearchResultViewController;
let param = NTAddressSearchParameter(keyword: txtKeyword.text!);
resultViewController?.addressSearchParam = param;
}
}
}
| apache-2.0 | 3bd1c035946bc2d51166cf6a5ef0e91a | 25.653846 | 95 | 0.669553 | 5.171642 | false | false | false | false |
ZhangMingNan/MNMeiTuan | 15-MeiTuan/15-MeiTuan/UIViewExtensions.swift | 1 | 1727 | //
// UIViewExtensions.swift
// 15-MeiTuan
//
// Created by 张明楠 on 15/8/16.
// Copyright (c) 2015年 张明楠. All rights reserved.
//
import UIKit
extension UIView {
func setX(x:CGFloat){
var frame = self.frame
frame.origin.x = x
self.frame = frame
}
func setY(y:CGFloat){
var frame = self.frame
frame.origin.y = y
self.frame = frame
}
func x()->CGFloat{
return self.frame.origin.x
}
func y()->CGFloat{
return self.frame.origin.y
}
func setCenterX(centerX:CGFloat){
var center = self.center
center.x = centerX
self.center = center
}
func centerX()->CGFloat{
return self.center.x
}
func setCenterY(centerY:CGFloat){
var center = self.center
center.y = centerY
self.center = center
}
func centerY()->CGFloat{
return self.center.y
}
func setWidth(width:CGFloat){
var frame = self.frame
frame.size.width = width
self.frame = frame
}
func width()->CGFloat{
return self.frame.size.width
}
func setHeight(height:CGFloat){
var frame = self.frame
frame.size.height = height
self.frame = frame
}
func height()->CGFloat{
return self.frame.size.height
}
func setSize(size:CGSize){
var frame = self.frame
frame.size = size
self.frame = frame
}
func size()->CGSize{
return self.frame.size
}
func setOrigin(origin:CGPoint){
var frame = self.frame
frame.origin = origin
self.frame = frame
}
func origin()->CGPoint{
return self.frame.origin
}
} | apache-2.0 | a40a4c89f89f501ac636f76a2eb69f9f | 20.974359 | 49 | 0.563923 | 3.919908 | false | false | false | false |
nissivm/DemoShopPayPal | DemoShop-PayPal/View Controllers/Products_VC.swift | 1 | 12355 | //
// Products_VC.swift
// DemoShop-PayPal
//
// Copyright © 2016 Nissi Vieira Miranda. All rights reserved.
//
import UIKit
class Products_VC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, ItemForSaleCellDelegate, ShoppingCart_VC_Delegate
{
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var shoppingCartButton: UIButton!
@IBOutlet weak var authenticationContainerView: UIView!
@IBOutlet weak var shopName: UILabel!
@IBOutlet weak var headerHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var shoppingCartButtonHeightConstraint: NSLayoutConstraint!
var allItemsForSale = [ItemForSale]()
var itemsForSale = [ItemForSale]()
var shoppingCartItems = [ShoppingCartItem]()
var multiplier: CGFloat = 1
override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionStarted",
name: "SessionStarted", object: nil)
if Device.IS_IPHONE_6
{
multiplier = Constants.multiplier6
adjustForBiggerScreen()
}
else if Device.IS_IPHONE_6_PLUS
{
multiplier = Constants.multiplier6plus
adjustForBiggerScreen()
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return UIStatusBarStyle.LightContent
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//-------------------------------------------------------------------------//
// MARK: Notifications
//-------------------------------------------------------------------------//
func sessionStarted()
{
authenticationContainerView.hidden = true
retrieveProducts()
}
//-------------------------------------------------------------------------//
// MARK: IBActions
//-------------------------------------------------------------------------//
@IBAction func shoppingCartButtonTapped(sender: UIButton)
{
if shoppingCartButton.enabled
{
performSegueWithIdentifier("ToShoppingCart", sender: self)
}
}
//-------------------------------------------------------------------------//
// MARK: Retrieve products
//-------------------------------------------------------------------------//
var minimum = 0
var maximum = 5
func retrieveProducts()
{
Auxiliar.showLoadingHUDWithText("Retrieving products...", forView: self.view)
guard Reachability.connectedToNetwork() else
{
Auxiliar.hideLoadingHUDInView(self.view)
return
}
let ref = Firebase(url: Constants.baseURL + "ItemsForSale")
ref.observeEventType(.Value, withBlock:
{
[unowned self](snapshot) in
if let response = snapshot.value as? [[NSObject : AnyObject]]
{
for responseItem in response
{
let item = ItemForSale()
item.position = responseItem["position"] as! Int
item.itemId = responseItem["itemId"] as! String
item.itemName = responseItem["itemName"] as! String
item.itemPrice = responseItem["itemPrice"] as! CGFloat
item.imageAddr = responseItem["imageAddr"] as! String
self.allItemsForSale.append(item)
}
self.allItemsForSale.sortInPlace
{
item1, item2 in
return item1.position < item2.position
}
var firstItemsForSale = [ItemForSale]()
for (index, item) in self.allItemsForSale.enumerate()
{
firstItemsForSale.append(item)
if index == 5
{
break
}
}
self.incorporateItems(firstItemsForSale)
}
})
}
//-------------------------------------------------------------------------//
// MARK: UIScrollViewDelegate
//-------------------------------------------------------------------------//
var hasMoreToShow = true
func scrollViewDidScroll(scrollView: UIScrollView)
{
if collectionView.contentOffset.y >= (collectionView.contentSize.height - collectionView.bounds.size.height)
{
if hasMoreToShow
{
hasMoreToShow = false
Auxiliar.showLoadingHUDWithText("Retrieving products...", forView: self.view)
var counter = 6
var newItemsForSale = [ItemForSale]()
while counter <= 11
{
newItemsForSale.append(allItemsForSale[counter])
counter++
}
incorporateItems(newItemsForSale)
}
}
}
//-------------------------------------------------------------------------//
// MARK: Incorporate new search items
//-------------------------------------------------------------------------//
func incorporateItems(items : [ItemForSale])
{
var indexPath : NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
var counter = collectionView.numberOfItemsInSection(0)
var newItems = [NSIndexPath]()
for item in items
{
indexPath = NSIndexPath(forItem: counter, inSection: 0)
newItems.append(indexPath)
let imageURL : NSURL = NSURL(string: item.imageAddr)!
item.itemImage = UIImage(data: NSData(contentsOfURL: imageURL)!)
itemsForSale.append(item)
counter++
}
collectionView.performBatchUpdates({
[unowned self]() -> Void in
self.collectionView.insertItemsAtIndexPaths(newItems)
}){
completed in
Auxiliar.hideLoadingHUDInView(self.view)
}
}
//-------------------------------------------------------------------------//
// MARK: UICollectionViewDataSource
//-------------------------------------------------------------------------//
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return itemsForSale.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ItemForSaleCell",
forIndexPath: indexPath) as! ItemForSaleCell
cell.index = indexPath.item
cell.delegate = self
cell.setupCellWithItem(itemsForSale[indexPath.item])
return cell
}
//-------------------------------------------------------------------------//
// MARK: UICollectionViewDelegateFlowLayout
//-------------------------------------------------------------------------//
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
let cellWidth = self.view.frame.size.width/2
return CGSizeMake(cellWidth, 190 * multiplier)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat
{
return 0
}
//-------------------------------------------------------------------------//
// MARK: ItemForSaleCellDelegate
//-------------------------------------------------------------------------//
func addThisItemToShoppingCart(clickedItemIndex: Int)
{
let item = itemsForSale[clickedItemIndex]
var found = false
var message = "\(item.itemName) was added to shopping cart."
if shoppingCartItems.count > 0
{
for (index, cartItem) in shoppingCartItems.enumerate()
{
if cartItem.itemForSale.itemId == item.itemId
{
found = true
cartItem.amount++
shoppingCartItems[index] = cartItem
let lastLetterIdx = item.itemName.characters.count - 1
let lastLetter = NSString(string: item.itemName).substringFromIndex(lastLetterIdx)
if lastLetter != "s"
{
message = "You have \(cartItem.amount) \(item.itemName)s in your shopping cart."
}
else
{
message = "You have \(cartItem.amount) \(item.itemName) in your shopping cart."
}
break
}
}
}
else
{
shoppingCartButton.enabled = true
}
if found == false
{
let cartItem = ShoppingCartItem()
cartItem.itemForSale = item
shoppingCartItems.append(cartItem)
}
Auxiliar.presentAlertControllerWithTitle("Item added!",
andMessage: message, forViewController: self)
}
//-------------------------------------------------------------------------//
// MARK: ShoppingCart_VC_Delegate
//-------------------------------------------------------------------------//
func shoppingCartItemsListChanged(cartItems: [ShoppingCartItem])
{
shoppingCartItems = cartItems
if shoppingCartItems.count == 0
{
shoppingCartButton.enabled = false
}
}
//-------------------------------------------------------------------------//
// MARK: Ajust for bigger screen
//-------------------------------------------------------------------------//
func adjustForBiggerScreen()
{
for constraint in shopName.constraints
{
constraint.constant *= multiplier
}
headerHeightConstraint.constant *= multiplier
shoppingCartButtonHeightConstraint.constant *= multiplier
var fontSize = 25.0 * multiplier
shopName.font = UIFont(name: "HelveticaNeue-Light", size: fontSize)
fontSize = 17.0 * multiplier
shoppingCartButton.imageEdgeInsets = UIEdgeInsetsMake(5 * multiplier, 144 * multiplier,
5 * multiplier, 144 * multiplier)
}
//-------------------------------------------------------------------------//
// MARK: Navigation
//-------------------------------------------------------------------------//
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier != nil) && (segue.identifier == "ToShoppingCart")
{
let vc = segue.destinationViewController as! ShoppingCart_VC
vc.shoppingCartItems = shoppingCartItems
vc.delegate = self
}
}
//-------------------------------------------------------------------------//
// MARK: Memory Warning
//-------------------------------------------------------------------------//
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 9a094955b670718ee9cb43fa74b44821 | 34.398281 | 172 | 0.457342 | 7.174216 | false | false | false | false |
ahoppen/swift | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-4distinct_use.swift | 14 | 5111 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueVys5UInt8VGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sBi8_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVys5UInt8VGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$ss5UInt8VN",
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySSGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSSN", i32 0{{(, \[4 x i8\] zeroinitializer)?}}, i64 3 }>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySdGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sBi64_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySdGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSdN",
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0),
// CHECk-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
struct Value<First> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySdGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySSGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVys5UInt8VGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13) )
consume( Value(first: 13.0) )
consume( Value(first: "13") )
consume( Value(first: 13 as UInt8) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), [[INT]]* @"$s4main5ValueVMz") #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 122767b731daee31cc15cfd732cdb030 | 55.788889 | 338 | 0.610252 | 3.064149 | false | false | false | false |
dreamsxin/swift | validation-test/compiler_crashers_fixed/27628-swift-abstractclosureexpr-setparams.swift | 11 | 2181 | // 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
{
let a {
{
{
{{
{{{
typea
{
}typealias e:A<T:T {{{{
typealias B }
{struct A {()a{struct A
{let t:d
{
enum A { typealias B }}
class d
{
{-> : A{{{
}}
{
case,
{
{{
func c{{struct B? = Int }
var:a{
class A
class C<D: d
case,
{{
{
{{
class d
{
func c{{
}
{struct B? = nil
{
class d where h:e
func crash<T>:a{
}}typealias e{
{
^
let i}
{
{{
{
{
}}}}}}}}}}}
"
struct A {{
{e a{
{
{struct Q{
{
{{
{{struct B<H , f=1
class A<D: A
{{{
class A{{
{
}}typealias B }
{
}
"
{e a{func e{
{{
{let g{{{
^
{
for h:A
class A {
protocol d
{{
{
{()a{{
func a{{
class A {class a: D: C<H , f=1
{
{{
{
}protocol d
{
}}
enum A {struct A {{
func crash<d {let t:T {T> : C{
{
{{{
typea
}
var b{
{{
{{
typea
{{{{{
func c{
var d{
let a {ypealias F=i}
{
{{
protocol A c{
{
enum S{
let h:A<ere d
class A<T> : A {{g=1
func c{func a{A<T {
let h:e{{
case,
{{
{
{let a{{
{class a
{{
class a{ typealias e:a
{
{
{
func crash<T {
{
{
{{
{ypealias F=0A.c
{}}}}
{{
var b{{{
func c{
{{{let g{
{{
var f
typealias e
}
struct A
enum A { :{struct c:{
enum S<D.c{
struct A
protocol A { :a{
{
{func e:a{
{
{{
}
{
}
var b{
var b{struct B:A {{
{
{
enum A {A
}
{{
{
{ypealias F=0A.c:a{->:{
( "
{
{{
}}}}
{
{() ->{
class a {
{
{
class A {
{-> Bool {{
func crash<T {{{{{
{d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
{{g=i{}class C>{
{
{{struct A<T> Bool {
protocol A { typealias e{{
{
class A
class a {let h=i}}class a {let:a{
struct A<D: D.B? = Int }}}
{class A{
var:d
typea
s :A {
{
typea
class A{{
{
{
{
for}
{{let a {
class A{{
{
let<T al c:a{
{let a {
{
{()a{{()a
{{
class A
func c
{}
{
{
struct B<T:A {
{{
{
{{class a{T> Bool {ypealias F=c:d{{class A{class
{
let h:A{
var b{{{
func a{let c{{
{let<T
{
{{{let g=1
{
{
{{
func b {
protocol a{
class C>() ->:a{
class A{
typealias B }}}class a {{let h:a{{{
{
typealias d
{
| apache-2.0 | 2c111875ab85f265a0a15887b45c84cd | 8.693333 | 78 | 0.546538 | 2.146654 | false | false | false | false |
Connorrr/ParticleAlarm | IOS/Alarm/GlobalParams.swift | 1 | 423 | //
// GlobalParams.swift
// Alarm-ios8-swift
//
// Created by longyutao on 16/1/27.
// Copyright (c) 2016年 LongGames. All rights reserved.
//
import Foundation
class Global
{
static var indexOfCell = -1
static var isEditMode: Bool = false
static var label: String = "Alarm"
static var weekdays: [Int] = [Int]()
static var mediaLabel: String = "bell"
static var snoozeEnabled: Bool = false
}
| mit | 3c7ad85304e97d3f60948f3eff25e334 | 21.157895 | 55 | 0.667458 | 3.45082 | false | false | false | false |
parkera/swift | test/Concurrency/actor_call_implicitly_async.swift | 1 | 21310 | // RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency
// REQUIRES: concurrency
// some utilities
func thrower() throws {}
func asyncer() async {}
func rethrower(_ f : @autoclosure () throws -> Any) rethrows -> Any {
return try f()
}
func asAutoclosure(_ f : @autoclosure () -> Any) -> Any { return f() }
// not a concurrency-safe type
class Box {
var counter : Int = 0
}
actor BankAccount {
private var curBalance : Int
private var accountHolder : String = "unknown"
// expected-note@+1 {{mutation of this property is only permitted within the actor}}
var owner : String {
get { accountHolder }
set { accountHolder = newValue }
}
init(initialDeposit : Int) {
curBalance = initialDeposit
}
func balance() -> Int { return curBalance }
// expected-note@+1 {{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}}
func deposit(_ amount : Int) -> Int {
guard amount >= 0 else { return 0 }
curBalance = curBalance + amount
return curBalance
}
func canWithdraw(_ amount : Int) -> Bool {
// call 'balance' from sync through self
return self.balance() >= amount
}
func testSelfBalance() async {
_ = await balance() // expected-warning {{no 'async' operations occur within 'await' expression}}
}
// returns the amount actually withdrawn
func withdraw(_ amount : Int) -> Int {
guard canWithdraw(amount) else { return 0 }
curBalance = curBalance - amount
return amount
}
// returns the balance of this account following the transfer
func transferAll(from : BankAccount) async -> Int {
// call sync methods on another actor
let amountTaken = await from.withdraw(from.balance())
return deposit(amountTaken)
}
func greaterThan(other : BankAccount) async -> Bool {
return await balance() > other.balance()
}
func testTransactions() {
_ = deposit(withdraw(deposit(withdraw(balance()))))
}
func testThrowing() throws {}
var effPropA : Box {
get async {
await asyncer()
return Box()
}
}
var effPropT : Box {
get throws {
try thrower()
return Box()
}
}
var effPropAT : Int {
get async throws {
await asyncer()
try thrower()
return 0
}
}
// expected-note@+1 2 {{add 'async' to function 'effPropertiesFromInsideActorInstance()' to make it asynchronous}}
func effPropertiesFromInsideActorInstance() throws {
// expected-error@+1{{'async' property access in a function that does not support concurrency}}
_ = effPropA
// expected-note@+4{{did you mean to handle error as optional value?}}
// expected-note@+3{{did you mean to use 'try'?}}
// expected-note@+2{{did you mean to disable error propagation?}}
// expected-error@+1{{property access can throw but is not marked with 'try'}}
_ = effPropT
_ = try effPropT
// expected-note@+6 {{did you mean to handle error as optional value?}}
// expected-note@+5 {{did you mean to use 'try'?}}
// expected-note@+4 {{did you mean to disable error propagation?}}
// expected-error@+3 {{property access can throw but is not marked with 'try'}}
// expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}}
// expected-error@+1 {{call can throw but is not marked with 'try'}}
_ = rethrower(effPropT)
// expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}}
// expected-error@+1 {{call can throw but is not marked with 'try'}}
_ = rethrower(try effPropT)
_ = try rethrower(effPropT)
_ = try rethrower(thrower())
_ = try rethrower(try effPropT)
_ = try rethrower(try thrower())
_ = rethrower(effPropA) // expected-error{{'async' property access in an autoclosure that does not support concurrency}}
_ = asAutoclosure(effPropT) // expected-error{{property access can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}}
// expected-note@+5{{did you mean to handle error as optional value?}}
// expected-note@+4{{did you mean to use 'try'?}}
// expected-note@+3{{did you mean to disable error propagation?}}
// expected-error@+2{{property access can throw but is not marked with 'try'}}
// expected-error@+1{{'async' property access in a function that does not support concurrency}}
_ = effPropAT
}
} // end actor
func someAsyncFunc() async {
let deposit1 = 120, deposit2 = 45
let a = BankAccount(initialDeposit: 0)
let b = BankAccount(initialDeposit: deposit2)
let _ = await a.deposit(deposit1)
let afterXfer = await a.transferAll(from: b)
let reportedBal = await a.balance()
// check on account A
guard afterXfer == (deposit1 + deposit2) && afterXfer == reportedBal else {
print("BUG 1!")
return
}
// check on account B
guard await b.balance() == 0 else {
print("BUG 2!")
return
}
_ = await a.deposit(b.withdraw(a.deposit(b.withdraw(b.balance()))))
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{3-3=await }} expected-note@+1 {{call is 'async'}}
a.testSelfBalance()
await a.testThrowing() // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}}
////////////
// effectful properties from outside the actor instance
// expected-warning@+2 {{cannot use property 'effPropA' with a non-sendable type 'Box' across actors}}
// expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}}
_ = a.effPropA
// expected-warning@+3 {{cannot use property 'effPropT' with a non-sendable type 'Box' across actors}}
// expected-error@+2{{property access can throw, but it is not marked with 'try' and the error is not handled}}
// expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}}
_ = a.effPropT
// expected-error@+2{{property access can throw, but it is not marked with 'try' and the error is not handled}}
// expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}}
_ = a.effPropAT
// (mostly) corrected ones
_ = await a.effPropA // expected-warning {{cannot use property 'effPropA' with a non-sendable type 'Box' across actors}}
_ = try! await a.effPropT // expected-warning {{cannot use property 'effPropT' with a non-sendable type 'Box' across actors}}
_ = try? await a.effPropAT
print("ok!")
}
//////////////////
// check for appropriate error messages
//////////////////
extension BankAccount {
func totalBalance(including other: BankAccount) async -> Int {
//expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{12-12=await }}
return balance()
+ other.balance() // expected-note{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}}
}
func breakAccounts(other: BankAccount) async {
// expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
_ = other.deposit( // expected-note{{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}}
other.withdraw( // expected-note{{calls to instance method 'withdraw' from outside of its actor context are implicitly asynchronous}}
self.deposit(
other.withdraw( // expected-note{{calls to instance method 'withdraw' from outside of its actor context are implicitly asynchronous}}
other.balance())))) // expected-note{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}}
}
}
func anotherAsyncFunc() async {
let a = BankAccount(initialDeposit: 34)
let b = BankAccount(initialDeposit: 35)
// expected-error@+2{{expression is 'async' but is not marked with 'await'}} {{7-7=await }}
// expected-note@+1{{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}}
_ = a.deposit(1)
// expected-error@+2{{expression is 'async' but is not marked with 'await'}} {{7-7=await }}
// expected-note@+1{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}}
_ = b.balance()
_ = b.balance // expected-error {{actor-isolated instance method 'balance()' can not be partially applied}}
a.owner = "cat" // expected-error{{actor-isolated property 'owner' can not be mutated from a non-isolated context}}
// expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}}
_ = b.owner
_ = await b.owner == "cat"
}
func regularFunc() {
let a = BankAccount(initialDeposit: 34)
_ = a.deposit //expected-error{{actor-isolated instance method 'deposit' can not be partially applied}}
_ = a.deposit(1) // expected-error{{actor-isolated instance method 'deposit' can not be referenced from a non-isolated context}}
}
actor TestActor {}
@globalActor
struct BananaActor {
static var shared: TestActor { TestActor() }
}
@globalActor
struct OrangeActor {
static var shared: TestActor { TestActor() }
}
func blender(_ peeler : () -> Void) {
peeler()
}
// expected-note@+2 {{var declared here}}
// expected-note@+1 2 {{mutation of this var is only permitted within the actor}}
@BananaActor var dollarsInBananaStand : Int = 250000
@BananaActor func wisk(_ something : Any) { }
@BananaActor func peelBanana() { }
@BananaActor func takeInout(_ x : inout Int) {}
@OrangeActor func makeSmoothie() async {
var money = await dollarsInBananaStand
money -= 1200
dollarsInBananaStand = money // expected-error{{var 'dollarsInBananaStand' isolated to global actor 'BananaActor' can not be mutated from different global actor 'OrangeActor'}}
// FIXME: these two errors seem a bit redundant.
// expected-error@+2 {{actor-isolated var 'dollarsInBananaStand' cannot be passed 'inout' to implicitly 'async' function call}}
// expected-error@+1 {{var 'dollarsInBananaStand' isolated to global actor 'BananaActor' can not be used 'inout' from different global actor 'OrangeActor'}}
await takeInout(&dollarsInBananaStand)
_ = wisk
await wisk({})
// expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}}
await wisk(1)
// expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}}
await (peelBanana)()
await (((((peelBanana)))))()
await (((wisk)))((wisk)((wisk)(1)))
// expected-warning@-1 3{{cannot pass argument of non-sendable type 'Any' across actors}}
blender((peelBanana))
// expected-error@-1{{converting function value of type '@BananaActor () -> ()' to '() -> Void' loses global actor 'BananaActor'}}
await wisk(peelBanana)
// expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}}
await wisk(wisk)
// expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}}
await (((wisk)))(((wisk)))
// expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}}
// expected-warning@+1 {{cannot pass argument of non-sendable type 'Any' across actors}}
await {wisk}()(1)
// expected-warning@+1 {{cannot pass argument of non-sendable type 'Any' across actors}}
await (true ? wisk : {n in return})(1)
}
actor Chain {
var next : Chain?
}
func walkChain(chain : Chain) async {
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 4 {{property access is 'async'}}
_ = chain.next?.next?.next?.next
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 3 {{property access is 'async'}}
_ = (await chain.next)?.next?.next?.next
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 2 {{property access is 'async'}}
_ = (await chain.next?.next)?.next?.next
}
// want to make sure there is no note about implicitly async on this func.
@BananaActor func rice() async {}
@OrangeActor func quinoa() async {
// expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }} expected-note@+1 {{call is 'async'}}
rice()
}
///////////
// check various curried applications to ensure we mark the right expression.
actor Calculator {
func addCurried(_ x : Int) -> ((Int) -> Int) {
return { (_ y : Int) in x + y }
}
func add(_ x : Int, _ y : Int) -> Int {
return x + y
}
}
@BananaActor func bananaAdd(_ x : Int) -> ((Int) -> Int) {
return { (_ y : Int) in x + y }
}
@OrangeActor func doSomething() async {
let _ = (await bananaAdd(1))(2)
// expected-warning@-1{{cannot call function returning non-sendable type}}
let _ = await (await bananaAdd(1))(2) // expected-warning{{no 'async' operations occur within 'await' expression}}
// expected-warning@-1{{cannot call function returning non-sendable type}}
let calc = Calculator()
let _ = (await calc.addCurried(1))(2)
// expected-warning@-1{{cannot call function returning non-sendable type}}
let _ = await (await calc.addCurried(1))(2) // expected-warning{{no 'async' operations occur within 'await' expression}}
// expected-warning@-1{{cannot call function returning non-sendable type}}
let plusOne = await calc.addCurried(await calc.add(0, 1))
// expected-warning@-1{{cannot call function returning non-sendable type}}
let _ = plusOne(2)
}
///////
// Effectful properties isolated to a global actor
@BananaActor
var effPropA : Int {
get async {
await asyncer()
try thrower() // expected-error{{errors thrown from here are not handled}}
return 0
}
}
@BananaActor
var effPropT : Int { // expected-note{{var declared here}}
get throws {
await asyncer() // expected-error{{'async' call in a function that does not support concurrency}}
try thrower()
return 0
}
}
@BananaActor
var effPropAT : Int {
get async throws {
await asyncer()
try thrower()
return 0
}
}
// expected-note@+1 2 {{add 'async' to function 'tryEffPropsFromBanana()' to make it asynchronous}}
@BananaActor func tryEffPropsFromBanana() throws {
// expected-error@+1{{'async' property access in a function that does not support concurrency}}
_ = effPropA
// expected-note@+4{{did you mean to handle error as optional value?}}
// expected-note@+3{{did you mean to use 'try'?}}
// expected-note@+2{{did you mean to disable error propagation?}}
// expected-error@+1{{property access can throw but is not marked with 'try'}}
_ = effPropT
_ = try effPropT
// expected-note@+6 {{did you mean to handle error as optional value?}}
// expected-note@+5 {{did you mean to use 'try'?}}
// expected-note@+4 {{did you mean to disable error propagation?}}
// expected-error@+3 {{property access can throw but is not marked with 'try'}}
// expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}}
// expected-error@+1 {{call can throw but is not marked with 'try'}}
_ = rethrower(effPropT)
// expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}}
// expected-error@+1 {{call can throw but is not marked with 'try'}}
_ = rethrower(try effPropT)
_ = try rethrower(effPropT)
_ = try rethrower(thrower())
_ = try rethrower(try effPropT)
_ = try rethrower(try thrower())
_ = rethrower(effPropA) // expected-error{{'async' property access in an autoclosure that does not support concurrency}}
_ = asAutoclosure(effPropT) // expected-error{{property access can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}}
// expected-note@+5{{did you mean to handle error as optional value?}}
// expected-note@+4{{did you mean to use 'try'?}}
// expected-note@+3{{did you mean to disable error propagation?}}
// expected-error@+2{{property access can throw but is not marked with 'try'}}
// expected-error@+1{{'async' property access in a function that does not support concurrency}}
_ = effPropAT
}
// expected-note@+2 {{add '@BananaActor' to make global function 'tryEffPropsFromSync()' part of global actor 'BananaActor'}}
// expected-note@+1 2 {{add 'async' to function 'tryEffPropsFromSync()' to make it asynchronous}}
func tryEffPropsFromSync() {
_ = effPropA // expected-error{{'async' property access in a function that does not support concurrency}}
// expected-error@+1 {{property access can throw, but it is not marked with 'try' and the error is not handled}}
_ = effPropT // expected-error{{var 'effPropT' isolated to global actor 'BananaActor' can not be referenced from this synchronous context}}
// NOTE: that we don't complain about async access on `effPropT` because it's not declared async, and we're not in an async context!
// expected-error@+1 {{property access can throw, but it is not marked with 'try' and the error is not handled}}
_ = effPropAT // expected-error{{'async' property access in a function that does not support concurrency}}
}
@OrangeActor func tryEffPropertiesFromGlobalActor() async throws {
// expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}}
_ = effPropA
// expected-note@+5{{did you mean to handle error as optional value?}}
// expected-note@+4{{did you mean to use 'try'?}}
// expected-note@+3{{did you mean to disable error propagation?}}
// expected-error@+2{{property access can throw but is not marked with 'try'}}
// expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}}
_ = effPropT
// expected-note@+5{{did you mean to handle error as optional value?}}
// expected-note@+4{{did you mean to use 'try'?}}
// expected-note@+3{{did you mean to disable error propagation?}}
// expected-error@+2{{property access can throw but is not marked with 'try'}}
// expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}}
_ = effPropAT
_ = await effPropA
_ = try? await effPropT
_ = try! await effPropAT
}
/////////////
// check subscripts in actors
actor SubscriptA {
subscript(_ i : Int) -> Int {
get async {
try thrower() // expected-error{{errors thrown from here are not handled}}
await asyncer()
return 0
}
}
func f() async {
// expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{9-9=await }} expected-note@+1{{subscript access is 'async'}}
_ = self[0]
}
}
actor SubscriptT {
subscript(_ i : Int) -> Int {
get throws {
try thrower()
await asyncer() // expected-error{{'async' call in a function that does not support concurrency}}
return 0
}
}
func f() throws {
_ = try self[0]
// expected-note@+6 {{did you mean to handle error as optional value?}}
// expected-note@+5 {{did you mean to use 'try'?}}
// expected-note@+4 {{did you mean to disable error propagation?}}
// expected-error@+3 {{subscript access can throw but is not marked with 'try'}}
// expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}}
// expected-error@+1 {{call can throw but is not marked with 'try'}}
_ = rethrower(self[1])
// expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}}
// expected-error@+1 {{call can throw but is not marked with 'try'}}
_ = rethrower(try self[1])
_ = try rethrower(self[1])
_ = try rethrower(try self[1])
}
}
actor SubscriptAT {
subscript(_ i : Int) -> Int {
get async throws {
try thrower()
await asyncer()
return 0
}
}
func f() async throws {
_ = try await self[0]
}
}
func tryTheActorSubscripts(a : SubscriptA, t : SubscriptT, at : SubscriptAT) async throws {
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}}
_ = a[0]
_ = await a[0]
// expected-note@+5{{did you mean to handle error as optional value?}}
// expected-note@+4{{did you mean to use 'try'?}}
// expected-note@+3{{did you mean to disable error propagation?}}
// expected-error@+2{{subscript access can throw but is not marked with 'try'}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}}
_ = t[0]
_ = try await t[0]
_ = try! await t[0]
_ = try? await t[0]
// expected-note@+5{{did you mean to handle error as optional value?}}
// expected-note@+4{{did you mean to use 'try'?}}
// expected-note@+3{{did you mean to disable error propagation?}}
// expected-error@+2{{subscript access can throw but is not marked with 'try'}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}}
_ = at[0]
_ = try await at[0]
}
| apache-2.0 | 756efa47772b801fb9ee6d598d5e3a01 | 36.125436 | 178 | 0.670249 | 3.955085 | false | false | false | false |
robertherdzik/RHPlaygroundFreestyle | ThunkExample/RHThunk.playground/Contents.swift | 1 | 1349 | import UIKit
import PlaygroundSupport
// See: https://milen.me/writings/swift-generic-protocols/
protocol GenericProtocol {
associatedtype AbstractType
func content() -> AbstractType
}
struct GenericProtocolThunk<T> : GenericProtocol {
private let _content : () -> T
init<P : GenericProtocol>(_ dep : P) where P.AbstractType == T {
_content = dep.content
}
func content() -> T {
return _content()
}
}
struct StringMagic : GenericProtocol {
typealias AbstractType = String
func content() -> String {
return "String content 🎉"
}
}
struct IntMagic : GenericProtocol {
typealias AbstractType = Int
func content() -> Int {
return 3
}
}
class RequestBuilder<ResponseType> {
let parser: GenericProtocolThunk<ResponseType>
init(parser: GenericProtocolThunk<ResponseType>) {
self.parser = parser
}
func parse() -> ResponseType {
return parser.content()
}
}
var thunkString: GenericProtocolThunk<String> = GenericProtocolThunk(StringMagic())
var requestString = RequestBuilder<String>(parser: thunkString)
requestString.parse()
var thunkInt: GenericProtocolThunk<Int> = GenericProtocolThunk(IntMagic())
let requestInt = RequestBuilder<Int>(parser: thunkInt)
requestInt.parse()
| mit | 8633028922d20229a0d68189e8082cd2 | 20.709677 | 83 | 0.666419 | 4.547297 | false | false | false | false |
piersadrian/switch | Flow/Sources/DispatchSource.swift | 1 | 2179 | //
// DispatchSource.swift
// Switch
//
// Created by Piers Mainwaring on 12/24/15.
// Copyright © 2016 Playfair, LLC. All rights reserved.
//
import Foundation
struct DispatchSource {
enum Status {
case Running, Paused, Cancelled
}
// MARK: - Internal Properties
let source: dispatch_source_t
var status: Status
// MARK: - Lifecycle
init(fd: CFSocketNativeHandle, type: dispatch_source_type_t, queue: dispatch_queue_t, handler: dispatch_block_t) {
self.status = .Paused
guard let source = dispatch_source_create(type, UInt(fd), 0, queue) else {
fatalError("couldn't create dispatch_source")
}
self.source = source
dispatch_source_set_event_handler(self.source, handler)
}
// MARK: - Public API
func data() -> UInt {
return dispatch_source_get_data(self.source)
}
mutating func run() {
guard self.status != .Cancelled else {
fatalError("DispatchSource is cancelled and cannot be run")
}
guard self.status != .Running else {
fatalError("DispatchSource is already running")
}
self.status = .Running
dispatch_resume(self.source)
}
mutating func pause() {
guard self.status != .Cancelled else {
fatalError("DispatchSource is cancelled and cannot be paused")
}
guard self.status != .Paused else {
fatalError("DispatchSource is already paused")
}
self.status = .Paused
dispatch_suspend(self.source)
}
mutating func cancel() {
guard self.status != .Cancelled else {
fatalError("DispatchSource is cancelled and cannot be cancelled again")
}
let wasPaused = (status == .Paused)
self.status = .Cancelled
dispatch_source_cancel(self.source)
// A paused dispatch source will never recognize that it's been cancelled
// so its cancel handler won't run. This resumes the source so it can process
// its cancellation. Weird but true.
if wasPaused {
dispatch_resume(self.source)
}
}
}
| mit | 85c748e3150a591588a76c9affd6dcb7 | 24.928571 | 118 | 0.607897 | 4.509317 | false | false | false | false |
richardtin/ios-swift-practices | 003.LocalNotification/003.LocalNotification/ReminderTableViewController.swift | 1 | 5268 | //
// ReminderTableViewController.swift
// 003.LocalNotification
//
// Created by Richard Ting on 2/24/16.
// Copyright © 2016 Richard Ting. All rights reserved.
//
import UIKit
class ReminderTableViewController: UITableViewController {
private let cellReuseIdentifier = "ReminderItemCell"
private let reminderItemKey = "ReminderItems"
private var reminderItems = [Reminder]()
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.
title = "Reminder"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(ReminderTableViewController.addReminder))
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reminderItems = allItems()
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addReminder() {
self.navigationController?.pushViewController(AddReminderViewController(), animated: true)
}
func allItems() -> [Reminder] {
let reminderDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(reminderItemKey) ?? [:]
let items = Array(reminderDictionary.values)
return items.map({Reminder(deadline: $0["deadline"] as! NSDate, UUID: $0["UUID"] as! String!)})
.sort({ $0.deadline.compare($1.deadline) == .OrderedDescending })
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reminderItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier, forIndexPath: indexPath)
// Configure the cell...
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZ"
dateFormatter.timeZone = NSTimeZone.systemTimeZone()
cell.textLabel?.text = "\(dateFormatter.stringFromDate(reminderItems[indexPath.row].deadline))"
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
let item = reminderItems.removeAtIndex(indexPath.row)
// Cancel LocalNotification
for notification in UIApplication.sharedApplication().scheduledLocalNotifications! {
if notification.userInfo!["UUID"] as! String == item.UUID {
UIApplication.sharedApplication().cancelLocalNotification(notification)
break
}
}
// Remove item from NSUserDefaults
if var reminderDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(reminderItemKey) {
reminderDictionary.removeValueForKey(item.UUID)
NSUserDefaults.standardUserDefaults().setValue(reminderDictionary, forKey: reminderItemKey)
}
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 89a26d9f0c0fac146c7b0aefe934355f | 39.829457 | 186 | 0.693374 | 5.657358 | false | false | false | false |
LeoTuring/iOS_Learning | iOS_Learning/Traveler/Traveler/AppDelegate.swift | 1 | 4896 | //
// AppDelegate.swift
// Traveler
//
// Created by 李冬阳 on 2017/6/3.
// Copyright © 2017年 lidongyang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// 国际化配置
LocalizedRemoteConfig.shareInstance.setUp()
self.window = UIWindow.init(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
self.window?.rootViewController = self.setUp()
self.window?.makeKeyAndVisible()
return true
}
func setUp() -> UITabBarController {
/** 设置字体颜色*/
var textAttributes: [String : Any] = [:]
textAttributes[NSForegroundColorAttributeName] = UIColor.gray
var selectedAttributes: [String : Any] = [:]
selectedAttributes[NSForegroundColorAttributeName] = UIColor.init(colorLiteralRed: 0.29, green: 0.74, blue: 0.79, alpha: 1)
/** 推荐*/
let recommend = RecommendViewController()
let recommendNav = UINavigationController.init(rootViewController: recommend)
recommendNav.tabBarItem = UITabBarItem.init(title: LocalizedRemoteConfig.localize(forkey: "Lable_recommend"), image: UIImage.init(named: "icon1")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage.init(named: "icon11")?.withRenderingMode(.alwaysOriginal))
recommendNav.tabBarItem.setTitleTextAttributes(textAttributes, for: .normal)
recommendNav.tabBarItem.setTitleTextAttributes(selectedAttributes, for: .selected)
/** 目的地*/
let destination = DestinationViewController()
let destinationNav = UINavigationController.init(rootViewController: destination)
destinationNav.tabBarItem = UITabBarItem.init(title: LocalizedRemoteConfig.localize(forkey: "Lable_destination"), image: UIImage.init(named: "icon2")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage.init(named: "icon22")?.withRenderingMode(.alwaysOriginal))
destinationNav.tabBarItem.setTitleTextAttributes(textAttributes, for: .normal)
destinationNav.tabBarItem.setTitleTextAttributes(selectedAttributes, for: .selected)
/** 个人信息*/
let userInfo = UserInfoViewController()
let userInfoNav = UINavigationController.init(rootViewController: userInfo)
userInfoNav.tabBarItem = UITabBarItem.init(title: LocalizedRemoteConfig.localize(forkey: "Lable_userInfo"), image: UIImage.init(named: "icon4")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage.init(named: "icon44")?.withRenderingMode(.alwaysOriginal))
userInfoNav.tabBarItem.setTitleTextAttributes(textAttributes, for: .normal)
userInfoNav.tabBarItem.setTitleTextAttributes(selectedAttributes, for: .selected)
// Todo:
/** TabBarController */
let tabBarController = UITabBarController()
tabBarController.viewControllers = [recommendNav, destinationNav, userInfoNav]
tabBarController.tabBar.barTintColor = UIColor.init(colorLiteralRed: 0.85, green: 0.84, blue: 0.76, alpha: 1)
tabBarController.tabBar.tintColor = UIColor.white
return tabBarController
}
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active 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:.
}
}
| mit | c63d77ab1745e397bda68f3250e3e652 | 52.855556 | 281 | 0.768517 | 5.156383 | false | false | false | false |
megha14/Lets-Code-Them-Up | Learning-Swift/Learning Swift - Control Flow [Switch].playground/Contents.swift | 1 | 1359 | /* Copyright (C) {2016} {Megha Rastogi}
You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
*/
//if and else-if
/*var marksOfStudents = 85
if(marksOfStudents >= 75 && marksOfStudents<=100){
print("First Division")
} else if(marksOfStudents > 30 && marksOfStudents < 75){
print("Second Division")
}else{
print("Student Fails")
}*/
/*
switch conditionalValue {
case value 1:
//execute this block
case value 2:
//execute this block
case value 3, value 4:
//execute this block
case value5...value6:
//execute this block
default:
otherwise, do something else
}
*/
var marksOfStudents = 75
switch marksOfStudents {
case 75...100:
print("First Division")
case 31...75:
print("Second Division")
case 0...30:
print("Student Fails")
default:
print("Out of range")
}
//Counting vowels and spaces in a sentance
var sentence = "I am learning swift"
var countVowels = 0
var countSpaces = 0
for letter in sentence.characters{
switch letter {
case "a","A","e","E","i","I","o","O","u","U":
countVowels += 1
case " ":
countSpaces += 1
default:
countVowels += 0
}
}
print("Number of vowels = \(countVowels)")
print("Number of spaces = \(countSpaces)")
| gpl-3.0 | 880061aa42b54a4837d13eac60c35ac5 | 21.278689 | 133 | 0.631347 | 3.692935 | false | false | false | false |
iPantry/iPantry-iOS | Pantry/Helpers/KeyboardHandler.swift | 1 | 1473 | //
// KeyboardHandler.swift
// Pantry
//
// Created by Justin Oroz on 3/12/17.
// Copyright © 2017 Justin Oroz. All rights reserved.
//
import UIKit
class KeyboardHandler {
var layoutSetup: ((_ isHiding: Bool, _ keyBoardHeight: CGFloat) -> Void)?
var animations: ((_ isHiding: Bool, _ keyBoardHeight: CGFloat) -> Void)?
var completion: ((_ completed: Bool) -> Void)?
func animateWithKeyboardWillChange(on notification: NSNotification, in view: UIView) {
let userInfo = notification.userInfo!
guard let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
let convertedKeyboardEndFrame = view.convert(keyboardEndFrame, from: view.window)
guard var rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uint32Value else {
return
}
rawAnimationCurve = rawAnimationCurve << 16
let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve))
let isHiding = (notification.name == .UIKeyboardWillHide)
let keyboardHeight = view.bounds.maxY - convertedKeyboardEndFrame.minY
layoutSetup?(isHiding, keyboardHeight)
UIView.animate(withDuration: animationDuration, delay: 0.0, options: [.beginFromCurrentState, animationCurve], animations: {
self.animations?(isHiding, keyboardHeight)
}, completion: completion)
}
}
| agpl-3.0 | 11ba14381ebfa0b7f9015313d2a87f3a | 32.454545 | 126 | 0.757473 | 4.42042 | false | false | false | false |
Candyroot/HanekeSwift | Haneke/UIView+Haneke.swift | 1 | 1595 | //
// UIView+Haneke.swift
// Haneke
//
// Created by Joan Romano on 15/10/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public extension HanekeGlobals {
public struct UIKit {
public static func formatWithSize(size : CGSize, scaleMode : ImageResizer.ScaleMode, allowUpscaling: Bool = true) -> Format<UIImage> {
let name = "auto-\(size.width)x\(size.height)-\(scaleMode.rawValue)"
let cache = Shared.imageCache
if let (format,_,_) = cache.formats[name] {
return format
}
var format = Format<UIImage>(name: name,
diskCapacity: HanekeGlobals.UIKit.DefaultFormat.DiskCapacity) {
let resizer = ImageResizer(size:size,
scaleMode: scaleMode,
allowUpscaling: allowUpscaling,
compressionQuality: HanekeGlobals.UIKit.DefaultFormat.CompressionQuality)
return resizer.resizeImage($0)
}
format.convertToData = {(image : UIImage) -> NSData in
image.hnk_data(HanekeGlobals.UIKit.DefaultFormat.CompressionQuality)
}
return format
}
public struct DefaultFormat {
public static let DiskCapacity : UInt64 = 10 * 1024 * 1024
public static let CompressionQuality : Float = 0.75
}
static var SetImageFetcherKey = 0
static var SetBackgroundImageFetcherKey = 1
}
}
| apache-2.0 | c4ae52967805f26d357e2a466a507bf5 | 32.93617 | 142 | 0.563636 | 5.316667 | false | false | false | false |
liuxuan30/SwiftCharts | Examples/Examples/Examples/TrackerExample.swift | 5 | 3050 | //
// TrackerExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class TrackerExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let chartPoints = [(2, 2), (4, 4), (7, 1), (8, 11), (12, 3)].map{ChartPoint(x: ChartAxisValueFloat(CGFloat($0.0), labelSettings: labelSettings), y: ChartAxisValueFloat(CGFloat($0.1)))}
let xValues = chartPoints.map{$0.x}
let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueFloat($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), animDuration: 1, animDelay: 0)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel])
let trackerLayerSettings = ChartPointsLineTrackerLayerSettings(thumbSize: Env.iPad ? 30 : 20, thumbCornerRadius: Env.iPad ? 16 : 10, thumbBorderWidth: Env.iPad ? 4 : 2, infoViewFont: ExamplesDefaults.fontWithSize(Env.iPad ? 26 : 16), infoViewSize: CGSizeMake(Env.iPad ? 400 : 160, Env.iPad ? 70 : 40), infoViewCornerRadius: Env.iPad ? 30 : 15)
let chartPointsTrackerLayer = ChartPointsLineTrackerLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, lineColor: UIColor.blackColor(), animDuration: 1, animDelay: 2, settings: trackerLayerSettings)
var settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
chartPointsLineLayer,
chartPointsTrackerLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| apache-2.0 | 1c7a652b2a3ee7e652cd8c67f5766ffb | 52.508772 | 351 | 0.696393 | 5.169492 | false | false | false | false |
lauraskelton/GPUImage | examples/iOS/FilterShowcaseSwift/FilterShowcaseSwift/FilterListViewController.swift | 1 | 1264 | import UIKit
class FilterListViewController: UITableViewController {
var filterDisplayViewController: FilterDisplayViewController? = nil
var objects = NSMutableArray()
// #pragma mark - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
let filterInList = filterOperations[indexPath.row]
(segue.destinationViewController as FilterDisplayViewController).filterOperation = filterInList
}
}
// #pragma mark - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filterOperations.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let filterInList:FilterOperation = filterOperations[indexPath.row]
cell.textLabel.text = filterInList.listName
return cell
}
}
| bsd-3-clause | b1c63aafa1c308556ec15e42a2cba2f4 | 34.111111 | 118 | 0.721519 | 5.906542 | false | false | false | false |
yasuoza/graphPON | graphPON iOS/ViewControllers/HddServiceListTableViewController.swift | 1 | 2945 | import UIKit
import GraphPONDataKit
class HddServiceListTableViewController: UITableViewController {
var selectedService: String = ""
var mode: BaseChartViewController.Mode = .Summary
weak var delegate: HddServiceListTableViewControllerDelegate?
private var serviceCodes: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
switch self.mode {
case .Summary, .Ratio, .Availability:
self.serviceCodes = PacketInfoManager.sharedManager.hddServiceCodes
case .Daily:
self.serviceCodes = PacketInfoManager.sharedManager.hdoServiceNumbers
}
}
// MARK: - IBActions
@IBAction func closeViewController() {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if self.mode == .Daily {
return PacketInfoManager.sharedManager.hddServiceCodes.count ?? 0
}
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch self.mode {
case .Summary, .Ratio, .Availability:
return PacketInfoManager.sharedManager.hddServiceCodes.count
case .Daily:
return PacketInfoManager.sharedManager.hddServices[section].hdoServices?.count ?? 0
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if self.mode == .Daily {
return PacketInfoManager.sharedManager.hddServices[section].nickName
}
return nil
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("HddServiceCell", forIndexPath: indexPath) as! UITableViewCell
switch self.mode {
case .Summary, .Ratio, .Availability:
cell.textLabel?.text = PacketInfoManager.sharedManager.hddServices[indexPath.row].nickName
case .Daily:
cell.textLabel?.text = PacketInfoManager.sharedManager.hddServices[indexPath.section].hdoServices?[indexPath.row].nickName
}
let serviceCode = self.serviceCodes[indexPath.row]
if serviceCode == self.selectedService {
cell.selected = true
cell.accessoryType = .Checkmark
cell.textLabel?.textColor = GlobalTintColor
} else {
cell.selected = false
cell.accessoryType = .None
cell.textLabel?.textColor = UIColor.blackColor()
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
dismissViewControllerAnimated(true, completion: nil)
delegate?.serviceDidSelectedSection(indexPath.section, row: indexPath.row)
}
}
| mit | e5c39676fdc9672c54eb0e9785bde16b | 34.914634 | 134 | 0.678098 | 5.221631 | false | false | false | false |
iankunneke/TIY-Assignmnts | CoreList/CoreList/AppDelegate.swift | 1 | 6120 | //
// AppDelegate.swift
// CoreList
//
// Created by ian kunneke on 7/29/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tiy.CoreList" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CoreList", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreList.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| cc0-1.0 | 1f3ae0735941a1825653af43006cc313 | 54.135135 | 290 | 0.715033 | 5.730337 | false | false | false | false |
bparish628/iFarm-Health | iOS/iFarm-Health/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift | 4 | 13151 | //
// YAxisRenderer.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
@objc(ChartYAxisRenderer)
open class YAxisRenderer: AxisRendererBase
{
@objc public init(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, transformer: Transformer?)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer, axis: yAxis)
}
/// draws the y-axis labels to the screen
open override func renderAxisLabels(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler
else { return }
if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled
{
return
}
let xoffset = yAxis.xOffset
let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset
let dependency = yAxis.axisDependency
let labelPosition = yAxis.labelPosition
var xPos = CGFloat(0.0)
var textAlign: NSTextAlignment
if dependency == .left
{
if labelPosition == .outsideChart
{
textAlign = .right
xPos = viewPortHandler.offsetLeft - xoffset
}
else
{
textAlign = .left
xPos = viewPortHandler.offsetLeft + xoffset
}
}
else
{
if labelPosition == .outsideChart
{
textAlign = .left
xPos = viewPortHandler.contentRight + xoffset
}
else
{
textAlign = .right
xPos = viewPortHandler.contentRight - xoffset
}
}
drawYLabels(
context: context,
fixedPosition: xPos,
positions: transformedPositions(),
offset: yoffset - yAxis.labelFont.lineHeight,
textAlign: textAlign)
}
open override func renderAxisLine(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler
else { return }
if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(yAxis.axisLineColor.cgColor)
context.setLineWidth(yAxis.axisLineWidth)
if yAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if yAxis.axisDependency == .left
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
else
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
context.restoreGState()
}
/// draws the y-labels on the specified x-position
@objc internal func drawYLabels(
context: CGContext,
fixedPosition: CGFloat,
positions: [CGPoint],
offset: CGFloat,
textAlign: NSTextAlignment)
{
guard
let yAxis = self.axis as? YAxis
else { return }
let labelFont = yAxis.labelFont
let labelTextColor = yAxis.labelTextColor
let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1
let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1)
for i in stride(from: from, to: to, by: 1)
{
let text = yAxis.getFormattedLabel(i)
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(x: fixedPosition, y: positions[i].y + offset),
align: textAlign,
attributes: [NSAttributedStringKey.font: labelFont, NSAttributedStringKey.foregroundColor: labelTextColor])
}
}
open override func renderGridLines(context: CGContext)
{
guard let
yAxis = self.axis as? YAxis
else { return }
if !yAxis.isEnabled
{
return
}
if yAxis.drawGridLinesEnabled
{
let positions = transformedPositions()
context.saveGState()
defer { context.restoreGState() }
context.clip(to: self.gridClippingRect)
context.setShouldAntialias(yAxis.gridAntialiasEnabled)
context.setStrokeColor(yAxis.gridColor.cgColor)
context.setLineWidth(yAxis.gridLineWidth)
context.setLineCap(yAxis.gridLineCap)
if yAxis.gridLineDashLengths != nil
{
context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
// draw the grid
for i in 0 ..< positions.count
{
drawGridLine(context: context, position: positions[i])
}
}
if yAxis.drawZeroLineEnabled
{
// draw zero line
drawZeroLine(context: context)
}
}
@objc open var gridClippingRect: CGRect
{
var contentRect = viewPortHandler?.contentRect ?? CGRect.zero
let dy = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
@objc open func drawGridLine(
context: CGContext,
position: CGPoint)
{
guard
let viewPortHandler = self.viewPortHandler
else { return }
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.strokePath()
}
@objc open func transformedPositions() -> [CGPoint]
{
guard
let yAxis = self.axis as? YAxis,
let transformer = self.transformer
else { return [CGPoint]() }
var positions = [CGPoint]()
positions.reserveCapacity(yAxis.entryCount)
let entries = yAxis.entries
for i in stride(from: 0, to: yAxis.entryCount, by: 1)
{
positions.append(CGPoint(x: 0.0, y: entries[i]))
}
transformer.pointValuesToPixel(&positions)
return positions
}
/// Draws the zero line at the specified position.
@objc open func drawZeroLine(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler,
let transformer = self.transformer,
let zeroLineColor = yAxis.zeroLineColor
else { return }
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= yAxis.zeroLineWidth / 2.0
clippingRect.size.height += yAxis.zeroLineWidth
context.clip(to: clippingRect)
context.setStrokeColor(zeroLineColor.cgColor)
context.setLineWidth(yAxis.zeroLineWidth)
let pos = transformer.pixelForValues(x: 0.0, y: 0.0)
if yAxis.zeroLineDashLengths != nil
{
context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: pos.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: pos.y))
context.drawPath(using: CGPathDrawingMode.stroke)
}
open override func renderLimitLines(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler,
let transformer = self.transformer
else { return }
var limitLines = yAxis.limitLines
if limitLines.count == 0
{
return
}
context.saveGState()
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled && label.characters.count > 0
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
if l.labelPosition == .rightTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .right,
attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .rightBottom
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .right,
attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .leftTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .left,
attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .left,
attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
}
}
}
context.restoreGState()
}
}
| apache-2.0 | 33a57caa33beb7f43a0bca648048935d | 31.55198 | 135 | 0.53053 | 5.656344 | false | false | false | false |
theScud/Lunch | lunchPlanner/das-Quadart/Endpoints/Events.swift | 2 | 1572 | //
// Events.swift
// Quadrat
//
// Created by Constantine Fry on 06/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
open class Events: Endpoint {
override var endpoint: String {
return "events"
}
/** https://developer.foursquare.com/docs/events/events */
open func get(_ eventId: String, completionHandler: ResponseClosure? = nil) -> Task {
return self.getWithPath(eventId, parameters: nil, completionHandler: completionHandler)
}
// MARK: - General
/** https://developer.foursquare.com/docs/events/categories */
open func categories(_ completionHandler: ResponseClosure? = nil) -> Task {
let path = "categories"
return self.getWithPath(path, parameters: nil, completionHandler: completionHandler)
}
/** https://developer.foursquare.com/docs/events/search */
open func search(_ domain: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = "search"
var allParameters = [Parameter.domain: domain]
allParameters += parameters
return self.getWithPath(path, parameters: allParameters, completionHandler: completionHandler)
}
// MARK: - Actions
/** https://developer.foursquare.com/docs/events/add */
open func add(_ parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = "add"
return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
}
| apache-2.0 | 0c8c8bf82ee0c24b89d8441e5f1052a6 | 33.933333 | 116 | 0.666667 | 4.650888 | false | false | false | false |
TonyJin99/SinaWeibo | SinaWeibo/SinaWeibo/TJNewFeatureViewController.swift | 1 | 4248 | //
// TJNewFeatureViewController.swift
// SinaWeibo
//
// Created by Tony.Jin on 7/31/16.
// Copyright © 2016 Innovatis Tech. All rights reserved.
//
import UIKit
import SnapKit
class TJNewFeatureViewController: UIViewController {
var count = 4
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension TJNewFeatureViewController: UICollectionViewDelegate{
func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
let index = collectionView.indexPathsForVisibleItems().last
let currentCell = collectionView.cellForItemAtIndexPath(index!) as! TJNewFeatureCell
if index?.item == count - 1{
currentCell.startAnimation()
}
}
}
extension TJNewFeatureViewController: UICollectionViewDataSource{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 4
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("tony", forIndexPath: indexPath) as! TJNewFeatureCell
cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.redColor() : UIColor.purpleColor()
cell.index = indexPath.item
return cell
}
}
//MARK: 自定义cell
class TJNewFeatureCell: UICollectionViewCell{
var index: Int = 0{
didSet{
let name = "new_feature_\(index + 1)"
iconImage.image = UIImage(named: name)
startButton.hidden = true
if index == 3 {
startButton.hidden = false
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView.addSubview(iconImage)
contentView.addSubview(startButton)
iconImage.snp_makeConstraints { (make) in
make.edges.equalTo(0)
}
startButton.snp_makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.bottom.equalTo(contentView).offset(-150)
}
}
private lazy var iconImage = UIImageView()
private lazy var startButton: UIButton = {
let btn = UIButton(imageName: nil, backgroundImageName: "new_feature_button")
btn.addTarget(self, action: #selector(self.startButtonAction), forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
func startButtonAction(){
let view = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
UIApplication.sharedApplication().keyWindow?.rootViewController = view
}
func startAnimation(){
startButton.transform = CGAffineTransformMakeScale(0.0, 0.0)
startButton.userInteractionEnabled = false
UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
self.startButton.transform = CGAffineTransformIdentity
}, completion: { (_) -> Void in
self.startButton.userInteractionEnabled = true
})
}
}
//MARK: 自定义布局
class TJNewFeatureLayOut: UICollectionViewFlowLayout{
override func prepareLayout() {
itemSize = UIScreen.mainScreen().bounds.size //1 设置每个cell的尺寸
minimumLineSpacing = 0 //2 设置cell之间的间隙
minimumInteritemSpacing = 0 //2 设置cell之间的间隙
scrollDirection = UICollectionViewScrollDirection.Horizontal //3 设置滚动方向
collectionView?.pagingEnabled = true //4 设置分页
collectionView?.bounces = false //5 禁止回弹
collectionView?.showsVerticalScrollIndicator = false //6 去除滚动条
collectionView?.showsHorizontalScrollIndicator = false //6 去除滚动条
}
}
| apache-2.0 | 24c67cb51b4e1d67327b38f066ef0482 | 30.853846 | 181 | 0.657812 | 5.420157 | false | false | false | false |
Allow2CEO/browser-ios | Client/Frontend/Settings/SettingsTableViewController.swift | 1 | 18028 | /* 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 UIKit
import XCGLogger
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting : NSObject {
fileprivate var _title: NSAttributedString?
weak var delegate: SettingsDelegate?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: URL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
var accessibilityIdentifier: String? { return nil }
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .subtitle }
var accessoryType: UITableViewCellAccessoryType { return .none }
var textAlignment: NSTextAlignment { return .left }
fileprivate(set) var enabled: Bool = true
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(_ cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.detailTextLabel?.numberOfLines = 1
cell.detailTextLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.attributedText = title
cell.textLabel?.textAlignment = textAlignment
cell.textLabel?.numberOfLines = 0
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.selectionStyle = enabled ? .default : .none
cell.accessibilityIdentifier = accessibilityIdentifier
if let title = title?.string {
let detail = cell.detailTextLabel?.text ?? status?.string
cell.accessibilityLabel = title + (detail != nil ? ", \(detail!)" : "")
}
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.indentationWidth = 0
cell.layoutMargins = UIEdgeInsets.zero
// So that the separator line goes all the way to the left edge.
cell.separatorInset = UIEdgeInsets.zero
}
// Called when the pref is tapped.
func onClick(_ navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(_ navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self._title = title
self.delegate = delegate
self.enabled = enabled ?? true
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection : Setting {
fileprivate let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
return children.filter { !$0.hidden }.count
}
subscript(val: Int) -> Setting? {
let settings = children.filter { !$0.hidden }
return 0..<settings.count ~= val ? settings[val] : nil
}
}
private class PaddedSwitch: UIView {
fileprivate static let Padding: CGFloat = 8
init(switchView: UISwitch) {
super.init(frame: CGRect.zero)
addSubview(switchView)
frame.size = CGSize(width: switchView.frame.width + PaddedSwitch.Padding, height: switchView.frame.height)
switchView.frame.origin = CGPoint(x: PaddedSwitch.Padding, y: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
let prefKey: String
fileprivate let prefs: Prefs
fileprivate let defaultValue: Bool
fileprivate let settingDidChange: ((Bool) -> Void)?
fileprivate let statusText: NSAttributedString?
init(prefs: Prefs, prefKey: String, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = attributedStatusText
super.init(title: attributedTitleText)
}
convenience init(prefs: Prefs, prefKey: String, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
var statusTextAttributedString: NSAttributedString?
if let statusTextString = statusText {
statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor])
}
self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange)
}
override var status: NSAttributedString? {
return statusText
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: #selector(BoolSetting.switchValueChanged(_:)), for: UIControlEvents.valueChanged)
control.isOn = prefs.boolForKey(prefKey) ?? defaultValue
if let title = title {
if let status = status {
control.accessibilityLabel = "\(title.string), \(status.string)"
} else {
control.accessibilityLabel = title.string
}
}
cell.accessoryView = PaddedSwitch(switchView: control)
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ control: UISwitch) {
prefs.setBool(control.isOn, forKey: prefKey)
settingDidChange?(control.isOn)
}
}
@objc
protocol SettingsDelegate: class {
func settingsOpenURLInNewTab(_ url: URL)
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection]
fileprivate let Identifier = "CellIdentifier"
fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var settings = [SettingSection]()
weak var settingsDelegate: SettingsDelegate?
var profile: Profile!
/// Used to calculate cell heights.
fileprivate lazy var dummyToggleCell: UITableViewCell = {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell")
cell.accessoryView = UISwitch()
return cell
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = UIView()
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
tableView.estimatedRowHeight = 44
tableView.estimatedSectionHeaderHeight = 44
settings = generateSettings()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidStartSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidFinishSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELfirefoxAccountDidChange), name: NotificationFirefoxAccountChanged, object: nil)
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NotificationProfileDidStartSyncing, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
// Override to provide settings in subclasses
func generateSettings() -> [SettingSection] {
return []
}
@objc fileprivate func SELsyncDidChangeState() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
@objc fileprivate func SELrefresh() {
self.tableView.reloadData()
}
@objc func SELfirefoxAccountDidChange() {
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let _ = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = UITableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return settings.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle
}
headerView.showTopBorder = false
return headerView
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = settings[indexPath.section]
// Workaround for calculating the height of default UITableViewCell cells with a subtitle under
// the title text label.
if let setting = section[indexPath.row], setting is BoolSetting && setting.status != nil {
return calculateStatusCellHeightForSetting(setting)
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = settings[indexPath.section]
if let setting = section[indexPath.row], setting.enabled {
setting.onClick(navigationController)
}
}
fileprivate func calculateStatusCellHeightForSetting(_ setting: Setting) -> CGFloat {
let topBottomMargin: CGFloat = 10
let tableWidth = tableView.frame.width
let accessoryWidth = dummyToggleCell.accessoryView!.frame.width
let insetsWidth = 2 * tableView.separatorInset.left
let width = tableWidth - accessoryWidth - insetsWidth
return
heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) +
heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) +
2 * topBottomMargin
}
fileprivate func heightForLabel(_ label: UILabel, width: CGFloat, text: String?) -> CGFloat {
guard let text = text else { return 0 }
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let attrs = [NSFontAttributeName: label.font]
let boundingRect = NSString(string: text).boundingRect(with: size,
options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil)
return boundingRect.height
}
}
class SettingsTableFooterView: UIView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.center
image.accessibilityIdentifier = "SettingsTableFooterView.logo"
return image
}()
fileprivate lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.cgColor
return topBorder
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIConstants.TableViewHeaderBackgroundColor
layer.addSublayer(topBorder)
addSubview(logo)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
topBorder.frame = CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: 0.5)
logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
}
}
struct SettingsTableSectionHeaderFooterViewUX {
static let titleHorizontalPadding: CGFloat = 15
static let titleVerticalPadding: CGFloat = 6
static let titleVerticalLongPadding: CGFloat = 20
}
class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView {
enum TitleAlignment {
case top
case bottom
}
var titleAlignment: TitleAlignment = .bottom {
didSet {
remakeTitleAlignmentConstraints()
}
}
var showTopBorder: Bool = false {
didSet {
topBorder.isHidden = !showTopBorder
}
}
var showBottomBorder: Bool = false {
didSet {
bottomBorder.isHidden = !showBottomBorder
}
}
lazy var titleLabel: UILabel = {
var headerLabel = UILabel()
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFont(ofSize: 12.0, weight: UIFontWeightRegular)
headerLabel.numberOfLines = 0
return headerLabel
}()
fileprivate lazy var topBorder: UIView = {
let topBorder = UIView()
topBorder.backgroundColor = UIConstants.SeparatorColor
return topBorder
}()
fileprivate lazy var bottomBorder: UIView = {
let bottomBorder = UIView()
bottomBorder.backgroundColor = UIConstants.SeparatorColor
return bottomBorder
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
addSubview(topBorder)
addSubview(bottomBorder)
setupInitialConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupInitialConstraints() {
bottomBorder.snp.makeConstraints { make in
make.bottom.left.right.equalTo(self)
make.height.equalTo(0.5)
}
topBorder.snp.makeConstraints { make in
make.top.left.right.equalTo(self)
make.height.equalTo(0.5)
}
remakeTitleAlignmentConstraints()
}
override func prepareForReuse() {
super.prepareForReuse()
showTopBorder = false
showBottomBorder = false
titleLabel.text = nil
titleAlignment = .bottom
}
fileprivate func remakeTitleAlignmentConstraints() {
switch titleAlignment {
case .top:
titleLabel.snp.remakeConstraints { make in
make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding)
make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding)
make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding)
}
case .bottom:
titleLabel.snp.remakeConstraints { make in
make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding)
make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding)
make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding)
}
}
}
}
| mpl-2.0 | 116aa44dbd4c604c0afbce0aa2f5e677 | 37.439232 | 304 | 0.685822 | 5.476306 | false | false | false | false |
dnseitz/YAPI | YAPI/YAPI/Shared/YelpCoordinate.swift | 1 | 844 | //
// YelpCoordinate.swift
// YAPI
//
// Created by Daniel Seitz on 11/11/17.
// Copyright © 2017 Daniel Seitz. All rights reserved.
//
import Foundation
import CoreLocation
public struct YelpCoordinate {
private enum Params {
static let latitude = "latitude"
static let longitude = "longitude"
}
public let coordinate: CLLocationCoordinate2D
public var latitude: CLLocationDegrees {
return coordinate.latitude
}
public var longitude: CLLocationDegrees {
return coordinate.longitude
}
public init(withDict dict: [String: AnyObject]) throws {
let latitude: CLLocationDegrees = try dict.parseParam(key: Params.latitude)
let longitude: CLLocationDegrees = try dict.parseParam(key: Params.longitude)
self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
| mit | 2cb589aa5806cfa25bc9f69af6f11e0f | 26.193548 | 86 | 0.734282 | 4.413613 | false | false | false | false |
inacioferrarini/OMDBSpy | OMDBSpy/Foundation/ViewController/BaseTableViewController.swift | 1 | 2937 | import UIKit
class BaseTableViewController: BaseDataBasedViewController {
// MARK: - Properties
var refreshControl:UIRefreshControl?
@IBOutlet weak var tableView: UITableView?
var dataSource:UITableViewDataSource?
var delegate:UITableViewDelegate?
private var tableViewBGView:UIView?
// MARK: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
if let tableView = self.tableView {
self.setupTableView()
self.tableViewBGView = tableView.backgroundView
if let selfAsDataSource = self as? UITableViewDataSource {
tableView.dataSource = selfAsDataSource
} else {
self.dataSource = self.createDataSource()
tableView.dataSource = self.dataSource
}
if let selfAsDelegate = self as? UITableViewDelegate {
tableView.delegate = selfAsDelegate
} else {
self.delegate = self.createDelegate()
tableView.delegate = self.delegate
}
self.refreshControl = UIRefreshControl()
if let refreshControl = self.refreshControl {
refreshControl.backgroundColor = UIColor.blackColor()
refreshControl.tintColor = UIColor.whiteColor()
refreshControl.addTarget(self, action: Selector("performDataSync"), forControlEvents: .ValueChanged)
tableView.addSubview(refreshControl)
tableView.reloadData()
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.performDataSyncIfNeeded()
}
override func viewWillDisappear(animated: Bool) {
if let tableView = self.tableView,
let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.deselectRowAtIndexPath(selectedIndexPath, animated: true)
}
super.viewWillDisappear(animated)
}
// MARK: - Data Syncrhonization
override func performDataSync() {
dataSyncCompleted()
}
override func dataSyncCompleted() {
if let refreshControl = self.refreshControl {
refreshControl.endRefreshing()
}
super.dataSyncCompleted()
}
// MARK: - TableView Appearance
func defaultEmptyResultsBackgroundView() -> UIView? {
return tableViewBGView
}
func defaultNonEmptyResultsBackgroundView() -> UIView? {
return tableViewBGView
}
// MARK: - Child classes are expected to override these methods
func setupTableView() {}
func createDataSource() -> UITableViewDataSource? { return nil }
func createDelegate() -> UITableViewDelegate? { return nil }
}
| mit | 8b64a65e03047d23edf0e58d9a75b8df | 28.079208 | 116 | 0.602996 | 6.196203 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.SwingMode.swift | 1 | 2019 | import Foundation
public extension AnyCharacteristic {
static func swingMode(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Swing Mode",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.swingMode(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func swingMode(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Swing Mode",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt8> {
GenericCharacteristic<UInt8>(
type: .swingMode,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 7b6e602393cab94516d0a8632278ef65 | 32.098361 | 75 | 0.569589 | 5.203608 | false | false | false | false |
vkedwardli/SignalR-Swift | SignalR-Swift/Transports/HttpTransport.swift | 1 | 4633 | //
// HttpTransport.swift
// SignalR-Swift
//
//
// Copyright © 2017 Jordan Camara. All rights reserved.
//
import Foundation
import Alamofire
public class HttpTransport: ClientTransportProtocol {
public var name: String? {
return ""
}
public var supportsKeepAlive: Bool {
return false
}
var startedAbort: Bool = false
public func negotiate(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((NegotiationResponse?, Error?) -> ())?) {
let url = connection.url.appending("negotiate")
let parameters = self.getConnectionParameters(connection: connection, connectionData: connectionData)
let encodedRequest = connection.getRequest(url: url, httpMethod: .get, encoding: URLEncoding.default, parameters: parameters, timeout: 30.0)
encodedRequest.validate().responseJSON { (response: DataResponse<Any>) in
switch response.result {
case .success(let result):
if let json = result as? [String: Any] {
completionHandler?(NegotiationResponse(jsonObject: json), nil)
}
else {
completionHandler?(nil, AFError.responseSerializationFailed(reason: .inputDataNil))
}
case .failure(let error):
completionHandler?(nil, error)
}
}
}
public func start(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
}
public func send(connection: ConnectionProtocol, data: Any, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
let url = connection.url.appending("send")
let parameters = self.getConnectionParameters(connection: connection, connectionData: connectionData)
let encodedRequest = connection.sessionManager.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil)
var requestParams = [String: Any]()
if let dataString = data as? String {
requestParams["data"] = dataString
} else if let dataDict = data as? [String: Any] {
requestParams = dataDict
}
let request = connection.getRequest(url: encodedRequest.request!.url!.absoluteString, httpMethod: .post, encoding: URLEncoding.httpBody, parameters: requestParams)
request.validate().responseJSON { (response: DataResponse<Any>) in
switch response.result {
case .success(let result):
connection.didReceiveData(data: result)
if let handler = completionHandler {
handler(result, nil)
}
case .failure(let error):
connection.didReceiveError(error: error)
if let handler = completionHandler {
handler(nil, error)
}
}
}
}
func completeAbort() {
self.startedAbort = true
}
func tryCompleteAbort() -> Bool {
return startedAbort
}
public func lostConnection(connection: ConnectionProtocol) {
}
public func abort(connection: ConnectionProtocol, timeout: Double, connectionData: String?) {
guard timeout > 0, !self.startedAbort else { return }
self.startedAbort = true
let url = connection.url.appending("abort")
let parameters = self.getConnectionParameters(connection: connection, connectionData: connectionData)
let encodedRequest = connection.getRequest(url: url, httpMethod: .get, encoding: URLEncoding.default, parameters: parameters, timeout: 2.0)
let request = connection.getRequest(url: encodedRequest.request!.url!.absoluteString, httpMethod: .post, encoding: URLEncoding.httpBody, parameters: nil)
request.validate().response { response in
if response.error != nil {
self.completeAbort()
}
}
}
func getConnectionParameters(connection: ConnectionProtocol, connectionData: String?) -> [String: Any] {
var parameters: [String: Any] = [
"clientProtocol": connection.version.description,
"transport": self.name ?? "",
"connectionData": connectionData ?? "",
"connectionToken": connection.connectionToken ?? "",
]
if let queryString = connection.queryString {
for (key, value) in queryString {
parameters[key] = value
}
}
return parameters
}
}
| mit | 1a7ea814af084d178cba8a95c25f120a | 34.358779 | 171 | 0.61658 | 5.216216 | false | false | false | false |
sarvex/Stormy | Current.swift | 1 | 2068 | //
// Current.swift
// Stormy
//
// Created by Sarvex Jatasra on 12/04/2015.
// Copyright (c) 2015 Sarvex Jatasra. All rights reserved.
//
import Foundation
import UIKit
struct Current {
var currentTime: String?
var temperature: Int
var humidity: Double
var precipitationProbability: Double
var summary: String
var icon: UIImage?
init(weatherDictionary: NSDictionary) {
let currentWeather = weatherDictionary["currently"] as! NSDictionary
temperature = currentWeather["temperature"] as! Int
humidity = currentWeather["humidity"] as! Double
precipitationProbability = currentWeather["precipProbability"] as! Double
summary = currentWeather["summary"] as! String
currentTime = dateStringFromUnixTime(currentWeather["time"] as! Int)
icon = weatherIconFromString(currentWeather["icon"] as! String)
}
func dateStringFromUnixTime(unixTime: Int) -> String {
let timeInSeconds = NSTimeInterval(unixTime)
let weatherDate = NSDate(timeIntervalSince1970: timeInSeconds)
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
return dateFormatter.stringFromDate(weatherDate)
}
func weatherIconFromString(stringIcon: String) -> UIImage {
var imageName: String
switch stringIcon {
case "clear-day":
imageName = "clear-day"
case "clear-night":
imageName = "clear-night"
case "rain":
imageName = "rain"
case "snow":
imageName = "snow"
case "sleet":
imageName = "sleet"
case "wind":
imageName = "wind"
case "fog":
imageName = "fog"
case "cloudy":
imageName = "cloudy"
case "partly-cloudy-day":
imageName = "partly-cloudy"
case "partly-cloudy-night":
imageName = "cloudy-night"
default:
imageName = "default"
}
return UIImage(named: imageName)!
}
}
| isc | 9af647f6977c66cfc6992a9c47615dde | 27.328767 | 81 | 0.615571 | 4.809302 | false | false | false | false |
lhc70000/iina | iina/PlaySliderCell.swift | 1 | 7789 | //
// PlaySlider.swift
// iina
//
// Created by lhc on 25/7/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
// These colors are for 10.13- only
@available(macOS, obsoleted: 10.14)
fileprivate extension NSColor {
static let darkKnobColor = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 0.5)
static let lightKnobColor = NSColor(calibratedRed: 0.3, green: 0.3, blue: 0.3, alpha: 1)
static let darkBarColorLeft = NSColor(calibratedWhite: 1, alpha: 0.3)
static let darkBarColorRight = NSColor(calibratedWhite: 1, alpha: 0.1)
static let lightBarColorLeft = NSColor(calibratedRed: 0.239, green: 0.569, blue: 0.969, alpha: 1)
static let lightBarColorRight = NSColor(calibratedWhite: 0.5, alpha: 0.5)
static let lightChapterStrokeColor = NSColor(calibratedWhite: 0.4, alpha: 1)
static let darkChapterStrokeColor = NSColor(calibratedWhite: 0.2, alpha: 1)
}
class PlaySliderCell: NSSliderCell {
lazy var playerCore: PlayerCore = {
return (self.controlView!.window!.windowController as! MainWindowController).player
}()
override var knobThickness: CGFloat {
return knobWidth
}
let knobWidth: CGFloat = 3
let knobHeight: CGFloat = 15
let knobRadius: CGFloat = 1
let barRadius: CGFloat = 1.5
var isInDarkTheme: Bool = true {
didSet {
if #available(macOS 10.14, *) {} else {
self.knobColor = isInDarkTheme ? .darkKnobColor : .lightKnobColor
self.knobActiveColor = isInDarkTheme ? .darkKnobColor : .lightKnobColor
self.barColorLeft = isInDarkTheme ? .darkBarColorLeft : .lightBarColorLeft
self.barColorRight = isInDarkTheme ? .darkBarColorRight : .lightBarColorRight
self.chapterStrokeColor = isInDarkTheme ? .darkChapterStrokeColor : .lightChapterStrokeColor
}
}
}
private var knobColor: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderKnob)!
} else {
return .darkKnobColor
}
}()
private var knobActiveColor: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderKnobActive)!
} else {
return .darkKnobColor
}
}()
private var barColorLeft: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderBarLeft)!
} else {
return .darkBarColorLeft
}
}()
private var barColorRight: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderBarRight)!
} else {
return .darkBarColorRight
}
}()
private var chapterStrokeColor: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderBarChapterStroke)!
} else {
return .darkChapterStrokeColor
}
}()
var drawChapters = Preference.bool(for: .showChapterPos)
var isPausedBeforeSeeking = false
override func awakeFromNib() {
minValue = 0
maxValue = 100
}
override func drawKnob(_ knobRect: NSRect) {
// Round the X position for cleaner drawing
let rect = NSMakeRect(round(knobRect.origin.x),
knobRect.origin.y + 0.5 * (knobRect.height - knobHeight),
knobRect.width,
knobHeight)
let isLightTheme = !controlView!.window!.effectiveAppearance.isDark
if #available(macOS 10.14, *), isLightTheme {
NSGraphicsContext.saveGraphicsState()
let shadow = NSShadow()
shadow.shadowBlurRadius = 1
shadow.shadowColor = .controlShadowColor
shadow.shadowOffset = NSSize(width: 0, height: -0.5)
shadow.set()
}
let path = NSBezierPath(roundedRect: rect, xRadius: knobRadius, yRadius: knobRadius)
(isHighlighted ? knobActiveColor : knobColor).setFill()
path.fill()
if #available(macOS 10.14, *), isLightTheme {
path.lineWidth = 0.4
NSColor.controlShadowColor.setStroke()
path.stroke()
NSGraphicsContext.restoreGraphicsState()
}
}
override func knobRect(flipped: Bool) -> NSRect {
let slider = self.controlView as! NSSlider
let bounds = super.barRect(flipped: flipped)
let percentage = slider.doubleValue / (slider.maxValue - slider.minValue)
let pos = min(CGFloat(percentage) * bounds.width, bounds.width - 1);
let rect = super.knobRect(flipped: flipped)
let flippedMultiplier = flipped ? CGFloat(-1) : CGFloat(1)
return NSMakeRect(pos - flippedMultiplier * 0.5 * knobWidth, rect.origin.y, knobWidth, rect.height)
}
override func drawBar(inside rect: NSRect, flipped: Bool) {
let info = playerCore.info
let slider = self.controlView as! NSSlider
/// The position of the knob, rounded for cleaner drawing
let knobPos : CGFloat = round(knobRect(flipped: flipped).origin.x);
/// How far progressed the current video is, used for drawing the bar background
var progress : CGFloat = 0;
if info.isNetworkResource,
info.cacheTime != 0,
let duration = info.videoDuration,
duration.second != 0 {
let pos = Double(info.cacheTime) / Double(duration.second) * 100
progress = round(rect.width * CGFloat(pos / (slider.maxValue - slider.minValue))) + 2;
} else {
progress = knobPos;
}
let rect = NSMakeRect(rect.origin.x, rect.origin.y + 1, rect.width, rect.height - 2)
let path = NSBezierPath(roundedRect: rect, xRadius: barRadius, yRadius: barRadius)
// draw left
let pathLeftRect : NSRect = NSMakeRect(rect.origin.x, rect.origin.y, progress, rect.height)
NSBezierPath(rect: pathLeftRect).addClip();
if #available(macOS 10.14, *), !controlView!.window!.effectiveAppearance.isDark {
// Draw knob shadow in 10.14+ light theme
} else {
// Clip 1px around the knob
path.append(NSBezierPath(rect: NSRect(x: knobPos - 1, y: rect.origin.y, width: knobWidth + 2, height: rect.height)).reversed);
}
barColorLeft.setFill()
path.fill()
NSGraphicsContext.restoreGraphicsState()
// draw right
NSGraphicsContext.saveGraphicsState()
let pathRight = NSMakeRect(rect.origin.x + progress, rect.origin.y, rect.width - progress, rect.height)
NSBezierPath(rect: pathRight).setClip()
barColorRight.setFill()
path.fill()
NSGraphicsContext.restoreGraphicsState()
// draw chapters
NSGraphicsContext.saveGraphicsState()
if drawChapters {
if let totalSec = info.videoDuration?.second {
chapterStrokeColor.setStroke()
var chapters = info.chapters
if chapters.count > 0 {
chapters.remove(at: 0)
chapters.forEach { chapt in
let chapPos = CGFloat(chapt.time.second) / CGFloat(totalSec) * rect.width
let linePath = NSBezierPath()
linePath.move(to: NSPoint(x: chapPos, y: rect.origin.y))
linePath.line(to: NSPoint(x: chapPos, y: rect.origin.y + rect.height))
linePath.stroke()
}
}
}
}
NSGraphicsContext.restoreGraphicsState()
}
override func barRect(flipped: Bool) -> NSRect {
let rect = super.barRect(flipped: flipped)
return NSMakeRect(0, rect.origin.y, rect.width + rect.origin.x * 2, rect.height)
}
override func startTracking(at startPoint: NSPoint, in controlView: NSView) -> Bool {
isPausedBeforeSeeking = playerCore.info.isPaused
let result = super.startTracking(at: startPoint, in: controlView)
if result {
playerCore.togglePause(true)
playerCore.mainWindow.thumbnailPeekView.isHidden = true
}
return result
}
override func stopTracking(last lastPoint: NSPoint, current stopPoint: NSPoint, in controlView: NSView, mouseIsUp flag: Bool) {
if !isPausedBeforeSeeking {
playerCore.togglePause(false)
}
super.stopTracking(last: lastPoint, current: stopPoint, in: controlView, mouseIsUp: flag)
}
}
| gpl-3.0 | b604867e2fdb27a0e0331af5fd473ff6 | 33.460177 | 132 | 0.673729 | 4.155816 | false | false | false | false |
JuweTakeheshi/ajuda | Ajuda/Helpers/UI/UIViewController+ajuda.swift | 1 | 1995 | //
// UIViewController+ajuda.swift
// Ajuda
//
// Created by sp4rt4n_0 on 9/25/17.
// Copyright © 2017 Juwe Takeheshi. All rights reserved.
//
import UIKit
extension UIViewController {
// MARK: - standard alerts
func displayErrorAlert(title: String, message: String) {
displayOKAlert(title: title, message: message)
}
func displayOKAlert(title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Aceptar", style: .default, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
func displayHandlAlert(title: String, message: String, completion: @escaping (UIAlertAction) -> Void ){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Aceptar", style: .default, handler: completion)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
func displayConfirmHandlAlert(title: String, message: String, completion: @escaping (UIAlertAction) -> Void ){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Aceptar", style: .default, handler: completion)
let actionCancel = UIAlertAction(title:"Cancelar",style:.destructive)
alertController.addAction(actionCancel)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
func customizeNavigationBarColors() {
navigationController?.navigationBar.barTintColor = UIColor(red:1.00, green:0.37, blue:0.05, alpha:1.0)
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
}
}
| mit | 445a9b89119931d82c738d2874f108be | 45.372093 | 120 | 0.713139 | 4.501129 | false | false | false | false |
MadAppGang/SmartLog | iOS/Pods/Charts/Source/Charts/Utils/Platform.swift | 31 | 16493 | import Foundation
/** This file provides a thin abstraction layer atop of UIKit (iOS, tvOS) and Cocoa (OS X). The two APIs are very much
alike, and for the chart library's usage of the APIs it is often sufficient to typealias one to the other. The NSUI*
types are aliased to either their UI* implementation (on iOS) or their NS* implementation (on OS X). */
#if os(iOS) || os(tvOS)
import UIKit
public typealias NSUIFont = UIFont
public typealias NSUIColor = UIColor
public typealias NSUIEvent = UIEvent
public typealias NSUITouch = UITouch
public typealias NSUIImage = UIImage
public typealias NSUIScrollView = UIScrollView
public typealias NSUIGestureRecognizer = UIGestureRecognizer
public typealias NSUIGestureRecognizerState = UIGestureRecognizerState
public typealias NSUIGestureRecognizerDelegate = UIGestureRecognizerDelegate
public typealias NSUITapGestureRecognizer = UITapGestureRecognizer
public typealias NSUIPanGestureRecognizer = UIPanGestureRecognizer
#if !os(tvOS)
public typealias NSUIPinchGestureRecognizer = UIPinchGestureRecognizer
public typealias NSUIRotationGestureRecognizer = UIRotationGestureRecognizer
#endif
public typealias NSUIScreen = UIScreen
public typealias NSUIDisplayLink = CADisplayLink
extension NSUITapGestureRecognizer
{
final func nsuiNumberOfTouches() -> Int
{
return numberOfTouches
}
final var nsuiNumberOfTapsRequired: Int
{
get
{
return self.numberOfTapsRequired
}
set
{
self.numberOfTapsRequired = newValue
}
}
}
extension NSUIPanGestureRecognizer
{
final func nsuiNumberOfTouches() -> Int
{
return numberOfTouches
}
final func nsuiLocationOfTouch(_ touch: Int, inView: UIView?) -> CGPoint
{
return super.location(ofTouch: touch, in: inView)
}
}
#if !os(tvOS)
extension NSUIRotationGestureRecognizer
{
final var nsuiRotation: CGFloat
{
get { return rotation }
set { rotation = newValue }
}
}
#endif
#if !os(tvOS)
extension NSUIPinchGestureRecognizer
{
final var nsuiScale: CGFloat
{
get
{
return scale
}
set
{
scale = newValue
}
}
final func nsuiLocationOfTouch(_ touch: Int, inView: UIView?) -> CGPoint
{
return super.location(ofTouch: touch, in: inView)
}
}
#endif
open class NSUIView: UIView
{
public final override func touchesBegan(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesBegan(touches, withEvent: event)
}
public final override func touchesMoved(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesMoved(touches, withEvent: event)
}
public final override func touchesEnded(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesEnded(touches, withEvent: event)
}
public final override func touchesCancelled(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesCancelled(touches, withEvent: event)
}
open func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesBegan(touches, with: event!)
}
open func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesMoved(touches, with: event!)
}
open func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesEnded(touches, with: event!)
}
open func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
super.touchesCancelled(touches!, with: event!)
}
var nsuiLayer: CALayer?
{
return self.layer
}
}
extension UIView
{
final var nsuiGestureRecognizers: [NSUIGestureRecognizer]?
{
return self.gestureRecognizers
}
}
extension UIScrollView
{
var nsuiIsScrollEnabled: Bool
{
get { return isScrollEnabled }
set { isScrollEnabled = newValue }
}
}
extension UIScreen
{
final var nsuiScale: CGFloat
{
return self.scale
}
}
func NSUIGraphicsGetCurrentContext() -> CGContext?
{
return UIGraphicsGetCurrentContext()
}
func NSUIGraphicsGetImageFromCurrentImageContext() -> NSUIImage!
{
return UIGraphicsGetImageFromCurrentImageContext()
}
func NSUIGraphicsPushContext(_ context: CGContext)
{
UIGraphicsPushContext(context)
}
func NSUIGraphicsPopContext()
{
UIGraphicsPopContext()
}
func NSUIGraphicsEndImageContext()
{
UIGraphicsEndImageContext()
}
func NSUIImagePNGRepresentation(_ image: NSUIImage) -> Data?
{
return UIImagePNGRepresentation(image)
}
func NSUIImageJPEGRepresentation(_ image: NSUIImage, _ quality: CGFloat = 0.8) -> Data?
{
return UIImageJPEGRepresentation(image, quality)
}
func NSUIMainScreen() -> NSUIScreen?
{
return NSUIScreen.main
}
func NSUIGraphicsBeginImageContextWithOptions(_ size: CGSize, _ opaque: Bool, _ scale: CGFloat)
{
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
}
#endif
#if os(OSX)
import Cocoa
import Quartz
public typealias NSUIFont = NSFont
public typealias NSUIColor = NSColor
public typealias NSUIEvent = NSEvent
public typealias NSUITouch = NSTouch
public typealias NSUIImage = NSImage
public typealias NSUIScrollView = NSScrollView
public typealias NSUIGestureRecognizer = NSGestureRecognizer
public typealias NSUIGestureRecognizerState = NSGestureRecognizerState
public typealias NSUIGestureRecognizerDelegate = NSGestureRecognizerDelegate
public typealias NSUITapGestureRecognizer = NSClickGestureRecognizer
public typealias NSUIPanGestureRecognizer = NSPanGestureRecognizer
public typealias NSUIPinchGestureRecognizer = NSMagnificationGestureRecognizer
public typealias NSUIRotationGestureRecognizer = NSRotationGestureRecognizer
public typealias NSUIScreen = NSScreen
/** On OS X there is no CADisplayLink. Use a 60 fps timer to render the animations. */
public class NSUIDisplayLink
{
private var timer: Timer?
private var displayLink: CVDisplayLink?
private var _timestamp: CFTimeInterval = 0.0
private weak var _target: AnyObject?
private var _selector: Selector
public var timestamp: CFTimeInterval
{
return _timestamp
}
init(target: AnyObject, selector: Selector)
{
_target = target
_selector = selector
if CVDisplayLinkCreateWithActiveCGDisplays(&displayLink) == kCVReturnSuccess
{
CVDisplayLinkSetOutputCallback(displayLink!, { (displayLink, inNow, inOutputTime, flagsIn, flagsOut, userData) -> CVReturn in
let _self = unsafeBitCast(userData, to: NSUIDisplayLink.self)
_self._timestamp = CFAbsoluteTimeGetCurrent()
_self._target?.performSelector(onMainThread: _self._selector, with: _self, waitUntilDone: false)
return kCVReturnSuccess
}, Unmanaged.passUnretained(self).toOpaque())
}
else
{
timer = Timer(timeInterval: 1.0 / 60.0, target: target, selector: selector, userInfo: nil, repeats: true)
}
}
deinit
{
stop()
}
open func add(to runloop: RunLoop, forMode mode: RunLoopMode)
{
if displayLink != nil
{
CVDisplayLinkStart(displayLink!)
}
else if timer != nil
{
runloop.add(timer!, forMode: mode)
}
}
open func remove(from: RunLoop, forMode: RunLoopMode)
{
stop()
}
private func stop()
{
if displayLink != nil
{
CVDisplayLinkStop(displayLink!)
}
if timer != nil
{
timer?.invalidate()
}
}
}
/** The 'tap' gesture is mapped to clicks. */
extension NSUITapGestureRecognizer
{
final func nsuiNumberOfTouches() -> Int
{
return 1
}
final var nsuiNumberOfTapsRequired: Int
{
get
{
return self.numberOfClicksRequired
}
set
{
self.numberOfClicksRequired = newValue
}
}
}
extension NSUIPanGestureRecognizer
{
final func nsuiNumberOfTouches() -> Int
{
return 1
}
/// FIXME: Currently there are no more than 1 touch in OSX gestures, and not way to create custom touch gestures.
final func nsuiLocationOfTouch(_ touch: Int, inView: NSView?) -> NSPoint
{
return super.location(in: inView)
}
}
extension NSUIRotationGestureRecognizer
{
/// FIXME: Currently there are no velocities in OSX gestures, and not way to create custom touch gestures.
final var velocity: CGFloat
{
return 0.1
}
final var nsuiRotation: CGFloat
{
get { return -rotation }
set { rotation = -newValue }
}
}
extension NSUIPinchGestureRecognizer
{
final var nsuiScale: CGFloat
{
get
{
return magnification + 1.0
}
set
{
magnification = newValue - 1.0
}
}
/// FIXME: Currently there are no more than 1 touch in OSX gestures, and not way to create custom touch gestures.
final func nsuiLocationOfTouch(_ touch: Int, inView view: NSView?) -> NSPoint
{
return super.location(in: view)
}
}
extension NSView
{
final var nsuiGestureRecognizers: [NSGestureRecognizer]?
{
return self.gestureRecognizers
}
}
extension NSScrollView
{
var nsuiIsScrollEnabled: Bool
{
get { return scrollEnabled }
set { scrollEnabled = newValue }
}
}
open class NSUIView: NSView
{
public final override var isFlipped: Bool
{
return true
}
func setNeedsDisplay()
{
self.setNeedsDisplay(self.bounds)
}
public final override func touchesBegan(with event: NSEvent)
{
self.nsuiTouchesBegan(event.touches(matching: .any, in: self), withEvent: event)
}
public final override func touchesEnded(with event: NSEvent)
{
self.nsuiTouchesEnded(event.touches(matching: .any, in: self), withEvent: event)
}
public final override func touchesMoved(with event: NSEvent)
{
self.nsuiTouchesMoved(event.touches(matching: .any, in: self), withEvent: event)
}
open override func touchesCancelled(with event: NSEvent)
{
self.nsuiTouchesCancelled(event.touches(matching: .any, in: self), withEvent: event)
}
open func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesBegan(with: event!)
}
open func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesMoved(with: event!)
}
open func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesEnded(with: event!)
}
open func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
super.touchesCancelled(with: event!)
}
open var backgroundColor: NSUIColor?
{
get
{
return self.layer?.backgroundColor == nil
? nil
: NSColor(cgColor: self.layer!.backgroundColor!)
}
set
{
self.wantsLayer = true
self.layer?.backgroundColor = newValue == nil ? nil : newValue!.cgColor
}
}
final var nsuiLayer: CALayer?
{
return self.layer
}
}
extension NSFont
{
var lineHeight: CGFloat
{
// Not sure if this is right, but it looks okay
return self.boundingRectForFont.size.height
}
}
extension NSScreen
{
final var nsuiScale: CGFloat
{
return self.backingScaleFactor
}
}
extension NSImage
{
var cgImage: CGImage?
{
return self.cgImage(forProposedRect: nil, context: nil, hints: nil)
}
}
extension NSTouch
{
/** Touch locations on OS X are relative to the trackpad, whereas on iOS they are actually *on* the view. */
func locationInView(view: NSView) -> NSPoint
{
let n = self.normalizedPosition
let b = view.bounds
return NSPoint(x: b.origin.x + b.size.width * n.x, y: b.origin.y + b.size.height * n.y)
}
}
extension NSScrollView
{
var scrollEnabled: Bool
{
get
{
return true
}
set
{
// FIXME: We can't disable scrolling it on OSX
}
}
}
extension NSString
{
// iOS: size(attributes: ...), OSX: size(withAttributes: ...)
// Both are translated into sizeWithAttributes: on ObjC. So conflict...
@nonobjc
func size(attributes attrs: [String : Any]? = nil) -> NSSize
{
return size(withAttributes: attrs)
}
}
func NSUIGraphicsGetCurrentContext() -> CGContext?
{
return NSGraphicsContext.current()?.cgContext
}
func NSUIGraphicsPushContext(_ context: CGContext)
{
let cx = NSGraphicsContext(cgContext: context, flipped: true)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.setCurrent(cx)
}
func NSUIGraphicsPopContext()
{
NSGraphicsContext.restoreGraphicsState()
}
func NSUIImagePNGRepresentation(_ image: NSUIImage) -> Data?
{
image.lockFocus()
let rep = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height))
image.unlockFocus()
return rep?.representation(using: NSPNGFileType, properties: [:])
}
func NSUIImageJPEGRepresentation(_ image: NSUIImage, _ quality: CGFloat = 0.9) -> Data?
{
image.lockFocus()
let rep = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height))
image.unlockFocus()
return rep?.representation(using: NSJPEGFileType, properties: [NSImageCompressionFactor: quality])
}
private var imageContextStack: [CGFloat] = []
func NSUIGraphicsBeginImageContextWithOptions(_ size: CGSize, _ opaque: Bool, _ scale: CGFloat)
{
var scale = scale
if scale == 0.0
{
scale = NSScreen.main()?.backingScaleFactor ?? 1.0
}
let width = Int(size.width * scale)
let height = Int(size.height * scale)
if width > 0 && height > 0
{
imageContextStack.append(scale)
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4*width, space: colorSpace, bitmapInfo: (opaque ? CGImageAlphaInfo.noneSkipFirst.rawValue : CGImageAlphaInfo.premultipliedFirst.rawValue))
else { return }
ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(height)))
ctx.scaleBy(x: scale, y: scale)
NSUIGraphicsPushContext(ctx)
}
}
func NSUIGraphicsGetImageFromCurrentImageContext() -> NSUIImage?
{
if !imageContextStack.isEmpty
{
guard let ctx = NSUIGraphicsGetCurrentContext()
else { return nil }
let scale = imageContextStack.last!
if let theCGImage = ctx.makeImage()
{
let size = CGSize(width: CGFloat(ctx.width) / scale, height: CGFloat(ctx.height) / scale)
let image = NSImage(cgImage: theCGImage, size: size)
return image
}
}
return nil
}
func NSUIGraphicsEndImageContext()
{
if imageContextStack.last != nil
{
imageContextStack.removeLast()
NSUIGraphicsPopContext()
}
}
func NSUIMainScreen() -> NSUIScreen?
{
return NSUIScreen.main()
}
#endif
| mit | 41e42c4212074834ecbf3fbc88eca880 | 25.43109 | 243 | 0.625174 | 4.753026 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/View/Recent/VRecentBar.swift | 1 | 3866 | import UIKit
class VRecentBar:UIView
{
private weak var controller:CRecent!
private let kBorderHeight:CGFloat = 1
private let kImageWidth:CGFloat = 50
private let kLabelWidth:CGFloat = 100
private let kCornerRadius:CGFloat = 5
private let kCancelMarginVertical:CGFloat = 14
private let kCancelRight:CGFloat = -10
private let kCancelWidth:CGFloat = 100
init(controller:CRecent)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.white
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.3))
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.image = #imageLiteral(resourceName: "assetGenericRecent")
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.font = UIFont.regular(size:16)
label.textColor = UIColor.black
label.text = NSLocalizedString("VRecentBar_label", comment:"")
let buttonCancel:UIButton = UIButton()
buttonCancel.translatesAutoresizingMaskIntoConstraints = false
buttonCancel.clipsToBounds = true
buttonCancel.backgroundColor = UIColor.hyperOrange
buttonCancel.layer.cornerRadius = kCornerRadius
buttonCancel.setTitle(
NSLocalizedString("VRecentBar_buttonCancel", comment:""),
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonCancel.addTarget(
self,
action:#selector(actionCancel(sender:)),
for:UIControlEvents.touchUpInside)
buttonCancel.titleLabel!.font = UIFont.bold(size:14)
addSubview(border)
addSubview(imageView)
addSubview(label)
addSubview(buttonCancel)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
NSLayoutConstraint.equalsVertical(
view:imageView,
toView:self)
NSLayoutConstraint.leftToLeft(
view:imageView,
toView:self)
NSLayoutConstraint.width(
view:imageView,
constant:kImageWidth)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.leftToRight(
view:label,
toView:imageView)
NSLayoutConstraint.width(
view:label,
constant:kLabelWidth)
NSLayoutConstraint.equalsVertical(
view:buttonCancel,
toView:self,
margin:kCancelMarginVertical)
NSLayoutConstraint.rightToRight(
view:buttonCancel,
toView:self,
constant:kCancelRight)
NSLayoutConstraint.width(
view:buttonCancel,
constant:kCancelWidth)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionCancel(sender button:UIButton)
{
controller.viewRecent.animateHide()
}
}
| mit | bc00767495148683998a413ffb13da3f | 31.762712 | 75 | 0.627522 | 5.752976 | false | false | false | false |
pietro82/TransitApp | TransitApp/ChooseDirectionsViewController.swift | 1 | 5956 | //
// ChooseDirectionsViewController.swift
// TransitApp
//
// Created by Pietro Santececca on 24/01/17.
// Copyright © 2017 Tecnojam. All rights reserved.
//
import UIKit
import MapKit
class ChooseDirectionsViewController: UIViewController {
// MARK: - Variables
var chooseViewModelController: ChooseViewModelController?
var selectedMode: String? {
get {
guard let chooseVMC = chooseViewModelController,
let indexArray = modeCollectionView.indexPathsForSelectedItems,
indexArray.count > 0 else {
return nil
}
return chooseVMC.modeViewModel(at: indexArray[0].row)
}
}
var selectedOption: DirectionsOptionViewModel? {
get {
guard let chooseVMC = chooseViewModelController,
let index = optionsTableView.indexPathForSelectedRow,
let mode = selectedMode else {
return nil
}
return chooseVMC.optionViewModel(mode: mode, index: index.row)
}
}
// MARK: - Outlets
@IBOutlet weak var modeCollectionView: UICollectionView!
@IBOutlet weak var optionsTableView: UITableView!
@IBOutlet weak var originAddressLabel: UILabel!
@IBOutlet weak var arrivalAddressLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
// MARK: - Life cycle methods
override func viewDidLoad() {
super.viewDidLoad()
// Set user input on the view
originAddressLabel.text = chooseViewModelController?.searchDirectionsInput.originAddress
arrivalAddressLabel.text = chooseViewModelController?.searchDirectionsInput.arrivalAddress
timeLabel.text = chooseViewModelController?.searchDirectionsInput.getTimeAsString()
// Retrive directions
guard let chooseVMC = chooseViewModelController else { return }
chooseVMC.retrieveDirections() {
// Set first mode ad default one
modeCollectionView.selectItem(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .left)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let showDirectionsVC = segue.destination as? ShowDirectionsViewController, var option = selectedOption else { return }
option.startingAddress = chooseViewModelController?.searchDirectionsInput.originAddress
option.arrivalAddress = chooseViewModelController?.searchDirectionsInput.arrivalAddress
let showMVC = ShowViewModelController(directionsOption: option)
showDirectionsVC.showViewModelController = showMVC
}
}
// MARK: - Table view data source
extension ChooseDirectionsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let chooseVMC = chooseViewModelController, let mode = selectedMode else { return 0 }
return chooseVMC.optionsCount(mode: mode)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderDirectionsTableViewCell", for: indexPath) as? HeaderDirectionsTableViewCell
guard let chooseVMC = chooseViewModelController, let optionsCell = cell, let mode = selectedMode else {
return UITableViewCell()
}
optionsCell.cellModel = chooseVMC.optionViewModel(mode: mode, index: (indexPath as NSIndexPath).row)
optionsCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
return optionsCell
}
}
// MARK: - Table view delegate
extension ChooseDirectionsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "fromChooseToShow", sender: nil)
}
}
// MARK: - Collcetion view delegate
extension ChooseDirectionsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
optionsTableView.reloadData()
}
}
// MARK: - Collection view data source
extension ChooseDirectionsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let chooseVMC = chooseViewModelController else { return 0 }
if collectionView == modeCollectionView {
return chooseVMC.modesCount
}
else {
guard let mode = selectedMode else { return 0 }
return chooseVMC.directionsCount(mode: mode, row: collectionView.tag)
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == modeCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChooseModeCollectionViewCell", for: indexPath) as? ChooseModeCollectionViewCell
guard let chooseVMC = chooseViewModelController, let modesCell = cell else { return UICollectionViewCell() }
modesCell.cellModel = chooseVMC.modeViewModel(at: (indexPath as NSIndexPath).row)
return modesCell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderDirectionsCollectionViewCell", for: indexPath) as? HeaderDirectionsCollectionViewCell
guard let chooseVMC = chooseViewModelController, let modesCell = cell, let mode = selectedMode else { return UICollectionViewCell() }
modesCell.cellModel = chooseVMC.directionViewModel(mode: mode, row: collectionView.tag, index: (indexPath as NSIndexPath).row)
return modesCell
}
}
}
| mit | b375982e79720a18d68d5f448c603cf9 | 37.419355 | 171 | 0.693367 | 5.374549 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Extensions/Colors and Styles/MurielColor.swift | 1 | 2283 | /// Generates the names of the named colors in the ColorPalette.xcasset
enum MurielColorName: String, CustomStringConvertible {
// MARK: - Base colors
case wordPressBlue
case blue
case celadon
case gray
case green
case orange
case pink
case purple
case red
case yellow
case jetpackGreen
var description: String {
// can't use .capitalized because it lowercases the P and B in "wordPressBlue"
return rawValue.prefix(1).uppercased() + rawValue.dropFirst()
}
}
/// Value of a Muriel color's shade
///
/// Note: There are a finite number of acceptable values. Not just any Int works.
/// Also, enum cases cannot begin with a number, thus the `shade` prefix.
enum MurielColorShade: Int, CustomStringConvertible {
case shade0 = 0
case shade5 = 5
case shade10 = 10
case shade20 = 20
case shade30 = 30
case shade40 = 40
case shade50 = 50
case shade60 = 60
case shade70 = 70
case shade80 = 80
case shade90 = 90
case shade100 = 100
var description: String {
return "\(rawValue)"
}
}
/// A specific color and shade from the muriel palette's asset file
struct MurielColor {
let name: MurielColorName
let shade: MurielColorShade
init(name: MurielColorName, shade: MurielColorShade = .shade50) {
self.name = name
self.shade = shade
}
init(from identifier: MurielColor, shade: MurielColorShade) {
self.name = identifier.name
self.shade = shade
}
// MARK: - Muriel's semantic colors
static let accent = AppStyleGuide.accent
static let brand = AppStyleGuide.brand
static let divider = AppStyleGuide.divider
static let error = AppStyleGuide.error
static let gray = AppStyleGuide.gray
static let primary = AppStyleGuide.primary
static let success = AppStyleGuide.success
static let text = AppStyleGuide.text
static let textSubtle = AppStyleGuide.textSubtle
static let warning = AppStyleGuide.warning
static let jetpackGreen = AppStyleGuide.jetpackGreen
static let editorPrimary = AppStyleGuide.editorPrimary
/// The full name of the color, with required shade value
func assetName() -> String {
return "\(name)\(shade)"
}
}
| gpl-2.0 | 2c192d8ae9ec5382bba28e4416dba764 | 28.269231 | 86 | 0.679807 | 4.348571 | false | false | false | false |
Cleverlance/Pyramid | Sources/Common/Device Storage/Resource/DeviceRepositoryImpl.swift | 1 | 1146 | //
// Copyright © 2018 Cleverlance. All rights reserved.
//
open class DeviceRepositoryImpl<Params: DeviceStoreParams, Model, Dto: Codable>: Repository<Model> {
private let store: DeviceStore
private let externalConverter: Converter<Model, Dto>
private let domainConverter: Converter<Dto, Model>
public init(
store: DeviceStore,
externalConverter: Converter<Model, Dto>,
domainConverter: Converter<Dto, Model>
) {
self.domainConverter = domainConverter
self.externalConverter = externalConverter
self.store = store
}
open override func save(_ model: Model) throws {
let dto = try externalConverter.convert(model)
try store.save(value: PropertyListEncoder().encode(dto), key: Params.key)
}
open override func load() throws -> Model? {
if let data = try store.get(key: Params.key) {
return try domainConverter.convert(PropertyListDecoder().decode(Dto.self, from: data))
} else {
return nil
}
}
open override func deleteAll() throws {
try store.remove(key: Params.key)
}
}
| mit | edc528109aa998cc595f5177852ab1a3 | 29.945946 | 100 | 0.653275 | 4.320755 | false | false | false | false |
grint/Sum-41-Tour-Updates | EventsAPI.swift | 1 | 9247 | //
// EventsAPI.swift
// Sum41Tour
//
// Copyright © 2017 Anastasia Grineva.
//
import Foundation
struct Event: CustomStringConvertible {
var country: String
var city: String
var date: String
var isNew: Bool
var description: String {
return "\(country), \(city), \(date)"
}
func match(string:String) -> Bool {
return country.contains(string)
}
init() {
self.city = ""
self.country = ""
self.date = ""
self.isNew = false
}
init(city: String, country: String, date: String) {
self.city = city
self.country = country
self.date = date
self.isNew = false
}
}
enum SerializationError: Error {
case missing(String)
case invalid(String, Any)
}
var allEvents = [Event]()
var noOfUKevents : Int = 0
var noOfNewEvents : Int = 0
let file = ".Sum41events" // Used to store previously loaded events
class EventsAPI {
let BASE_URL = "https://rest.bandsintown.com/artists/"
let BAND_NAME = "Sum 41"
func fetchEvents(_ resetNewEvents: Bool, success: @escaping ([Event]) -> Void) {
let session = URLSession.shared
// url-escape the band name string
let escapedBandName = BAND_NAME.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string: "\(BASE_URL)\(escapedBandName)/events?app_id=\(escapedBandName)")
let task = session.dataTask(with: url!) { data, response, err in
// check for a hard error
if let error = err {
NSLog("Events api error: \(error)")
}
// check the response code
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 200:
// all good!
if let events = self.eventsFromJSONData(data!, resetNewEvents: resetNewEvents) {
success(events)
}
default:
NSLog("Events api returned response: %d %@", httpResponse.statusCode, HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode))
}
}
}
task.resume()
}
func eventsFromJSONData(_ data: Data, resetNewEvents: Bool) -> [Event]? {
do {
allEvents.removeAll()
noOfUKevents = 0
noOfNewEvents = 0
// Filter out countries that the user cannot visit
let notValidCountries = ["Japan","Canada", "United States"]
var validEvents = [[String:Any]]()
// Parse JSON and save only valid countries for the further actions
if let jsonObject = try JSONSerialization.jsonObject(with:data, options: []) as? [[String:Any]] {
for item in jsonObject {
if let venue = item["venue"] as? [String: Any] {
if let country = venue["country"] as? String {
// Filter entries by comparing countries
if(!notValidCountries.contains(country)) {
if(country == "United Kingdom") {
noOfUKevents += 1
}
else {
validEvents.append(item)
}
}
}
}
}
}
let eventsCount = validEvents.count
// Starting reading & writing log of events
let fileManager = FileManager.default
var fileContentToWrite : String = ""
// The log file will be saved to the user's documents directory
if let dir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent(file)
// Check if file with saved events exists
if fileManager.fileExists(atPath: path.path) {
}
else {
// Create an empty file
print("File not found")
try "".write(to: path, atomically: false, encoding: String.Encoding.utf8)
}
do {
// Read the file contents
var savedEvents = [[String]]()
do {
let fileContent = try String(contentsOf: path, encoding: String.Encoding.utf8)
for line in fileContent.components(separatedBy: "\n") {
var entry = line.components(separatedBy: ", ")
savedEvents.append([entry[2], entry[3]])
}
}
catch let error as NSError {
print("Failed reading from URL: \(file), Error: " + error.localizedDescription)
}
let savedEventsCount = savedEvents.count
// Get only necessary information and save entries as "Event" objects
for event in validEvents {
guard let venue = event["venue"] as? [String: Any] else {
NSLog("Venue parsing error"); throw SerializationError.missing("venue")}
guard let country = venue["country"] as? String else {
NSLog("Country parsing error"); throw SerializationError.missing("country")}
guard let city = venue["city"] as? String else {
NSLog("City parsing error"); throw SerializationError.missing("city")}
guard let datetime = event["datetime"] as? String else {
NSLog("Datetime parsing error"); throw SerializationError.missing("datetime")}
// format date to "06 Jun"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = dateFormatter.date(from: datetime)!
dateFormatter.dateFormat = "dd MMM"
let dateString = dateFormatter.string(from:date)
// save parsed data to a new Event object
var parsedEvent = Event(city: city, country: country, date: dateString)
if(eventsCount > savedEventsCount) {
// Events-API sent more events than saved, so, there are new events
if(!savedEvents.contains {$0.contains(dateString)}) {
// check if the current event is new by comparing dates from the events log
noOfNewEvents += 1
parsedEvent.isNew = true
}
}
else {
if(!resetNewEvents) {
// Auto-update called -
// we don't want to mark the event as old,
// even if it's already saved to log
// overwise the user can miss this info
if(savedEvents.contains {$0 == [dateString, "true"]}) {
noOfNewEvents += 1
parsedEvent.isNew = true
}
}
}
// Prepare log data
fileContentToWrite += "\(country), \(city), \(dateString), \(parsedEvent.isNew)\n"
// add the prepared event to the return array
allEvents.append(parsedEvent)
}
// Remove last "\n" and update log with events
fileContentToWrite = String(fileContentToWrite.characters.dropLast(1))
do {
try fileContentToWrite.write(to: path, atomically: false, encoding: String.Encoding.utf8)
}
catch let error as NSError {
print("Failed writing to URL: \(path), Error: " + error.localizedDescription)
}
}
catch {
print("Error in reading file: \(error)")
return nil
}
}
}
catch {
print("JSON parsing failed: \(error)")
return nil
}
return allEvents
}
}
| mit | c79fff89d59cb6a7f7ad9ec25e460932 | 40.648649 | 162 | 0.457387 | 5.949807 | false | false | false | false |
planvine/Line-Up-iOS-SDK | Pod/Classes/MainTableViewController/Line-Up_TicketsManager.swift | 1 | 15074 | /**
* Copyright (c) 2016 Line-Up
*
* 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 PassKit
/**
* TicketsManager is in charge of creating a TicketsTableView and a TicketsToolbar and implement all their delegate methods
*/
@objc public class TicketsManager : NSObject, PKAddPassesViewControllerDelegate, LineUpTicketsToolbarDelegate {
//MARK: Variables
/**
* ticketsTableView is a TicketsTableView object (UITableView). It will display the list of tickets available for the performance
*/
public var ticketsTableView: TicketsTableView!
/**
* ticketsToolbar is a TicketsToolbar object. It has a public method getToolbar() which returns a UIToolbar with a UIBarButtonItem ('Get Tickets'). When it is pressed getTicketsBtnPressed() is called and TicketsManager implements the LineUpTicketsToolbarDelegate delegate
*/
var ticketsToolbar: TicketsToolbar?
/**
* Its the user Email address
*/
public var userEmail: String?
/**
* It is the user LineUp token
*/
public var userToken: String?
/**
* It is the current performance id
*/
public var performanceId: NSNumber!
var viewControllerToPresent: UIViewController? = nil
/**
* Array of PVTicket. It will contain all the tickets for the performance with id performanceId
*/
public var listOfTickets: [PVTicket] = Array()
/**
* Array of PVTicket. It will contain all the tickets selected by the user in the ticketsTableView
*/
public var selectedTickets: [PVTicket] = Array()
//MARK: General Functions
/**
* - Parameters:
* - performanceId: is the current performance Id
* - viewController: is the viewController in which TicketsManager is instantiated. If it is provided, the payment flow will be presented on viewController after that 'Get Tickets' button is pressed
* - setToolbar: if set true, a toolbar with a button 'Get Tickets' is shown at the bottom of the page.
*/
required public init(performanceId: NSNumber, viewController: UIViewController? = nil, setToolbar: Bool? = true) {
super.init()
self.performanceId = performanceId
self.viewControllerToPresent = viewController
self.listOfTickets = LineUp.getListOfTicketsForPerformance(performanceId)
ticketsTableView = TicketsTableView(numberOfTickets: self.listOfTickets.count)
ticketsTableView.delegate = self
ticketsTableView.dataSource = self
if setToolbar != nil && setToolbar! == true {
ticketsToolbar = TicketsToolbar()
ticketsToolbar!.delegate = self
}
}
/**
* Returns a UIToolbar ('Get Tickets')
*/
public func getToolbar() -> UIToolbar {
guard let ticketsToolbar = ticketsToolbar else {
return UIToolbar()
}
return ticketsToolbar.getToolbar()
}
/**
* Returns the ticketsTableView height
*/
public func getViewHeight() -> CGFloat {
return ticketsTableView.frame.height
}
//MARK: LineUpGetTicketsToolbarDelegate
/**
* getTicketsBtnPressed is called when 'Get Tickets' button on the toolbar is pressed
* - It calls the delegate from LineUpDelegate
* - It highlights the cells of the ticketsTableView if no tickets are selected
* - If tickets are selected in the ticketsTableView, it calls getTicketsPressed() that is in charge of making the reservation of the tickets calling LineUp.getTicketsPressed and present the PaymentViewController
*/
public func getTicketsBtnPressed() {
if LineUp.delegate != nil && LineUp.delegate!.getTicketsBtnWasPressed != nil {
LineUp.delegate!.getTicketsBtnWasPressed!()
}
if getSelectedTickets().count > 0 {
getTicketsPressed()
} else {
ticketsTableView.highlightCells()
}
}
func getTicketsPressed() {
if viewControllerToPresent != nil {
if viewControllerToPresent!.view.window != nil {
PVHud.showCustomActivityIndicator(viewControllerToPresent!.view.window!)
}
LineUp.getTicketsPressed(getSelectedTickets(), userEmail: userEmail, userToken: userToken, viewController: viewControllerToPresent!, performanceId: performanceId, completion: { (reservation, error) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if error != nil || reservation == nil {
let alert : UIAlertController! = UIAlertController(title: "Error", message: LineUp.mapErrorMessage(error?.domain), preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction : UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in })
alert.addAction(cancelAction)
self.viewControllerToPresent!.presentViewController(alert, animated: true, completion: nil)
}
})
})
}
}
/**
* UserEmail and userToken have been updated. It updates these values in the class.
*/
public func userDetailsWereUpdated(email: String?, userToken: String?) {
if let userEmail = email {
self.userEmail = userEmail
}
if let token = userToken {
self.userToken = token
}
}
}
extension TicketsManager: UITableViewDataSource, UITableViewDelegate {
//MARK: TableView DataSource
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listOfTickets.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCellWithIdentifier(ticketsTableView.cellIdentifier, forIndexPath: indexPath)
if c.isKindOfClass(TicketsTableViewCell)
{
let cell: TicketsTableViewCell = c as! TicketsTableViewCell
cell.selectionStyle = .None
let ticket: PVTicket = listOfTickets[indexPath.row]
cell.typeLabel.text = ticket.kind?.capitalizedString
if ticket.price != nil && ticket.tax != nil && cell.numberOfTicketsLabel.text != nil {
cell.updatePriceLabelValue(ticket.price!.doubleValue, fee: ticket.tax!)
cell.insertSubview(cell.backgroundFlash, atIndex: 0)
}
if selectedTickets.count == 0 {
cell.showVerticalLine(false)
cell.numberOfTicketsLabel.hidden = true
cell.numberOfTicketsLabel.text = "x0"
}
var numberOfTickets : String? = nil
if cell.numberOfTicketsLabel.text != nil {
numberOfTickets = cell.numberOfTicketsLabel.text?.substringFromIndex(cell.numberOfTicketsLabel.text!.startIndex.advancedBy(1))
}
cell.setNoTickets(ticket, numberOfTickets: numberOfTickets)
return cell
}
return c
}
public func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
numberOfTicketsChanged(indexPath, delete: true)
tableView.reloadData()
}
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
numberOfTicketsChanged(indexPath, delete: false)
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return ticketsTableView.tableRowHeight
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: tableView.frame.origin.x, y:0, width: tableView.frame.width, height:1))
view.backgroundColor = PVColor.lightGrayLineColor
return view
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return ticketsTableView.tableRowHeight
}
public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y + tableView.frame.height, width: tableView.frame.width, height: ticketsTableView.tableRowHeight))
view.addSubview(ticketsTableView.totalLabel)
return view
}
//MARK: Number Of Tickets Changed
/**
* This method is called when a user select a row in ticketsTableView or it does a swipe gesture (for deleting the row -> emptying the list of selected tickets).
* - If the user select a row and there are tickets available, it adds the ticket to the selected tickets and increments the total number, otherwise if there are no more tickets available it shows the correct text
* - If the user does a swipe gesture and press delete, it empties the list of selected tickets for that type of ticket
*/
public func numberOfTicketsChanged (indexPath: NSIndexPath, delete:Bool) {
let cell : TicketsTableViewCell = ticketsTableView.cellForRowAtIndexPath(indexPath) as! TicketsTableViewCell
let ticket: PVTicket = listOfTickets[indexPath.row]
var maxValuePerTicket : NSNumber = PVConstant.maxNumberOfTicketsPerPerformance
if ticket.inventoryLeft != nil && ticket.inventoryLeft! < PVConstant.maxNumberOfTicketsPerPerformance {
maxValuePerTicket = ticket.inventoryLeft!
}
var numberOfTickets : String? = nil
if cell.numberOfTicketsLabel.text != nil {
numberOfTickets = cell.numberOfTicketsLabel.text?.substringFromIndex(cell.numberOfTicketsLabel.text!.startIndex.advancedBy(1))
}
cell.setNoTickets(ticket, numberOfTickets: numberOfTickets)
if (numberOfTickets != nil && numberOfTickets!.toNumber() < maxValuePerTicket) || (numberOfTickets != nil && numberOfTickets!.toNumber() >= maxValuePerTicket && delete == true) {
if !delete {
cell.showVerticalLine(true)
cell.numberOfTicketsLabel.hidden = false
cell.updateNumberOfTicketsLabelValue(true)
if ticket.id != nil {
if ticket.price != nil && ticket.tax != nil {
ticketsTableView.totalValue = ticketsTableView.totalValue + ticket.total!.doubleValue
ticketsTableView.setTotalLabelText()
}
selectedTickets.append(ticket)
}
} else {
if selectedTickets.count > 0 && ticket.id != nil {
for ticketToDelete in selectedTickets {
if ticketToDelete.id != nil && ticketToDelete.id! == ticket.id! {
if ticket.price != nil && ticket.tax != nil {
ticketsTableView.totalValue = ticketsTableView.totalValue - ticket.total!.doubleValue
if Int(ticketsTableView.totalValue) <= 0 {
ticketsTableView.totalValue = 0
}
ticketsTableView.setTotalLabelText()
}
selectedTickets.removeObject(ticketToDelete)
}
}
cell.showVerticalLine(false)
cell.numberOfTicketsLabel.hidden = true
cell.numberOfTicketsLabel.text = "x0"
}
}
} else if numberOfTickets != nil && numberOfTickets!.toNumber() >= maxValuePerTicket{
cell.numberOfTicketsLabel.text! = "x\(maxValuePerTicket)"
cell.backgroundFlash.hidden = false
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.15 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
cell.backgroundFlash.hidden = true
})
}
}
/**
* This method is called for resetting the ticketsTableView.
* - It resets the list of selected tickets (and as a consequence, the total amount)
* - It reloads the list of tickets
*/
public func resetTableViewValues(performanceId: NSNumber, viewToSetButtons: UIView?, resetSelectedTickets: Bool) {
self.performanceId = performanceId
if resetSelectedTickets {
selectedTickets = Array()
ticketsTableView.totalValue = 0
}
ticketsTableView.totalLabel.removeFromSuperview()
listOfTickets = LineUp.getListOfTicketsForPerformance(performanceId)
ticketsTableView.setupTableView()
ticketsTableView.setBottomView()
}
func getSelectedTickets() -> [PVTicket] {
return selectedTickets
}
//MARK: - LineUpPaymentDelegate
/**
* It resets the selected tickets array and the total amount.
*/
public func resetTickets() {
self.selectedTickets.removeAll()
ticketsTableView.totalValue = 0
ticketsTableView.setTotalLabelText()
for indexPath in ticketsTableView.indexPathsForRowsInRect(UIScreen.mainScreen().bounds)! {
if ticketsTableView.cellForRowAtIndexPath(indexPath)!.isKindOfClass(TicketsTableViewCell) {
(ticketsTableView.cellForRowAtIndexPath(indexPath) as! TicketsTableViewCell).setup()
}
}
}
}
| mit | 6df31852489d8135788518319e5d2704 | 43.997015 | 275 | 0.651453 | 5.214113 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Generators/Physical Models/Metal Bar/AKMetalBar.swift | 1 | 7537 | //
// AKMetalBar.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Metal Bar Physical Model
///
open class AKMetalBar: AKNode, AKComponent {
public typealias AKAudioUnitType = AKMetalBarAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(generator: "mbar")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var leftBoundaryConditionParameter: AUParameter?
fileprivate var rightBoundaryConditionParameter: AUParameter?
fileprivate var decayDurationParameter: AUParameter?
fileprivate var scanSpeedParameter: AUParameter?
fileprivate var positionParameter: AUParameter?
fileprivate var strikeVelocityParameter: AUParameter?
fileprivate var strikeWidthParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free
@objc open dynamic var leftBoundaryCondition: Double = 1 {
willSet {
if leftBoundaryCondition != newValue {
if let existingToken = token {
leftBoundaryConditionParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free
@objc open dynamic var rightBoundaryCondition: Double = 1 {
willSet {
if rightBoundaryCondition != newValue {
if let existingToken = token {
rightBoundaryConditionParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// 30db decay time (in seconds).
@objc open dynamic var decayDuration: Double = 3 {
willSet {
if decayDuration != newValue {
if let existingToken = token {
decayDurationParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Speed of scanning the output location.
@objc open dynamic var scanSpeed: Double = 0.25 {
willSet {
if scanSpeed != newValue {
if let existingToken = token {
scanSpeedParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Position along bar that strike occurs.
@objc open dynamic var position: Double = 0.2 {
willSet {
if position != newValue {
if let existingToken = token {
positionParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Normalized strike velocity
@objc open dynamic var strikeVelocity: Double = 500 {
willSet {
if strikeVelocity != newValue {
if let existingToken = token {
strikeVelocityParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Spatial width of strike.
@objc open dynamic var strikeWidth: Double = 0.05 {
willSet {
if strikeWidth != newValue {
if let existingToken = token {
strikeWidthParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize this Bar node
///
/// - Parameters:
/// - leftBoundaryCondition: Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - rightBoundaryCondition: Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - decayDuration: 30db decay time (in seconds).
/// - scanSpeed: Speed of scanning the output location.
/// - position: Position along bar that strike occurs.
/// - strikeVelocity: Normalized strike velocity
/// - strikeWidth: Spatial width of strike.
/// - stiffness: Dimensionless stiffness parameter
/// - highFrequencyDamping: High-frequency loss parameter. Keep this small
///
@objc public init(
leftBoundaryCondition: Double = 1,
rightBoundaryCondition: Double = 1,
decayDuration: Double = 3,
scanSpeed: Double = 0.25,
position: Double = 0.2,
strikeVelocity: Double = 500,
strikeWidth: Double = 0.05,
stiffness: Double = 3,
highFrequencyDamping: Double = 0.001) {
self.leftBoundaryCondition = leftBoundaryCondition
self.rightBoundaryCondition = rightBoundaryCondition
self.decayDuration = decayDuration
self.scanSpeed = scanSpeed
self.position = position
self.strikeVelocity = strikeVelocity
self.strikeWidth = strikeWidth
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
leftBoundaryConditionParameter = tree["leftBoundaryCondition"]
rightBoundaryConditionParameter = tree["rightBoundaryCondition"]
decayDurationParameter = tree["decayDuration"]
scanSpeedParameter = tree["scanSpeed"]
positionParameter = tree["position"]
strikeVelocityParameter = tree["strikeVelocity"]
strikeWidthParameter = tree["strikeWidth"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.leftBoundaryCondition = Float(leftBoundaryCondition)
internalAU?.rightBoundaryCondition = Float(rightBoundaryCondition)
internalAU?.decayDuration = Float(decayDuration)
internalAU?.scanSpeed = Float(scanSpeed)
internalAU?.position = Float(position)
internalAU?.strikeVelocity = Float(strikeVelocity)
internalAU?.strikeWidth = Float(strikeWidth)
}
// MARK: - Control
/// Trigger the sound with an optional set of parameters
///
open func trigger() {
internalAU?.start()
internalAU?.trigger()
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit | 63268e4cbaff38ac2447d8538a40fdb7 | 34.54717 | 111 | 0.617038 | 5.226075 | false | false | false | false |
daviwiki/Gourmet_Swift | Gourmet/GourmetModel/Interactors/StoreAccountObserver.swift | 1 | 1444 | //
// StoreAccountObserver.swift
// Gourmet
//
// Created by David Martinez on 11/12/2016.
// Copyright © 2016 Atenea. All rights reserved.
//
import Foundation
public protocol StoreAccountObserverListener : NSObjectProtocol {
func onChange(observer: StoreAccountObserver, account : Account?)
}
public class StoreAccountObserver : NSObject {
private weak var listener : StoreAccountObserverListener?
private var observer : NSObjectProtocol?
public func setListener (listener: StoreAccountObserverListener?) {
self.listener = listener
}
public func execute () {
let center = NotificationCenter.default
if (observer != nil) {
center.removeObserver(observer!)
}
observer = center.addObserver(
forName: .storedAccountUpdated,
object: nil,
queue: OperationQueue.main,
using: { (notification : Notification) in
let account = notification.userInfo?[StoreAccount.AccountKey] as? Account
self.onAccountChange(account: account)
}
)
}
deinit {
let center = NotificationCenter.default
if (observer != nil) {
center.removeObserver(observer!)
}
}
private func onAccountChange (account : Account?) {
self.listener?.onChange(observer: self, account: account)
}
}
| mit | ba9ab102f90d17e19d42c2e54abfd550 | 25.722222 | 89 | 0.620929 | 4.99308 | false | false | false | false |
larryhou/swift | PhotoPreview/PhotoPreview/PhotoPreviewController.swift | 1 | 5528 | //
// PhotoPreviewController.swift
// PhotoPreview
//
// Created by larryhou on 3/19/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import Foundation
import UIKit
class PhotoPreviewController: UIViewController, UIScrollViewDelegate {
private var background: UIImageView!
private var zoomView: UIImageView!
private var preview: UIScrollView!
var dirty: Bool = true
var dataIndex: Int = -1
var image: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
view.clipsToBounds = true
preview = UIScrollView()
preview.frame = UIScreen.mainScreen().applicationFrame
preview.contentSize = preview.frame.size
preview.minimumZoomScale = 0.01
preview.maximumZoomScale = 2.00
preview.delegate = self
view.addSubview(preview)
preview.pinchGestureRecognizer.addTarget(self, action: "pinchUpdated:")
setPreviewAutoLayout()
var tap = UITapGestureRecognizer()
tap.numberOfTapsRequired = 2
tap.addTarget(self, action: "doubleTapZoom:")
preview.addGestureRecognizer(tap)
}
func setPreviewAutoLayout() {
var views: [NSObject: AnyObject] = [:]
views.updateValue(preview, forKey: "preview")
preview.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[preview]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[preview]|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: views))
}
override func viewWillAppear(animated: Bool) {
if !dirty {
return
}
dirty = false
if zoomView != nil && zoomView.superview != nil {
zoomView.removeFromSuperview()
}
zoomView = UIImageView(image: image)
preview.addSubview(zoomView)
updateBackgroundImage()
preview.zoomScale = 0.01
repairImageZoom(useAnimation: true)
alignImageAtCenter()
}
func updateBackgroundImage() {
if background != nil && background.superview != nil {
background.removeFromSuperview()
}
background = UIImageView(image: createBackgroundImage(inputImage: image))
view.insertSubview(background, atIndex: 0)
var frame = background.frame
frame.origin.x = (view.frame.width - frame.width) / 2.0
frame.origin.y = (view.frame.height - frame.height) / 2.0
background.frame = frame
}
func createBackgroundImage(inputImage input: UIImage) -> UIImage? {
let bounds = UIScreen.mainScreen().bounds
let size = CGSize(width: bounds.width / 2.0, height: bounds.height / 2.0)
let scale = max(size.width / input.size.width, size.height / input.size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
CGContextScaleCTM(context, scale, scale)
let tx = (size.width / scale - input.size.width) / 2.0
let ty = (size.height / scale - input.size.height) / 2.0
CGContextTranslateCTM(context, tx, ty)
input.drawAtPoint(CGPoint(x: 0, y: 0))
var data: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
var filter = CIFilter(name: "CIGaussianBlur")
filter.setValue(CIImage(image: data), forKey: kCIInputImageKey)
filter.setValue(20.0, forKey: kCIInputRadiusKey)
return UIImage(CIImage: filter.outputImage)
}
func doubleTapZoom(gesture: UITapGestureRecognizer) {
let MAX_SIZE_W = zoomView.frame.width / preview.zoomScale
var scale: CGFloat
if zoomView.frame.width > preview.frame.width + 0.0001 {
scale = preview.frame.width / MAX_SIZE_W
} else {
scale = 1.0 / UIScreen.mainScreen().scale
}
preview.setZoomScale(scale, animated: true)
}
func pinchUpdated(gesture: UIPinchGestureRecognizer) {
switch gesture.state {
case .Began:
preview.panGestureRecognizer.enabled = false
case .Ended:
preview.panGestureRecognizer.enabled = true
repairImageZoom()
default:break
}
}
func setImage(image: UIImage, dataIndex index: Int) {
self.dirty = true
self.dataIndex = index
self.image = image
}
func restoreImageZoom() {
let MAX_SIZE_W = zoomView.frame.width / preview.zoomScale
preview.zoomScale = preview.frame.width / MAX_SIZE_W
}
func repairImageZoom(useAnimation flag: Bool = true) {
let MAX_SIZE_W = zoomView.frame.width / preview.zoomScale
var scale: CGFloat!
if zoomView.frame.width < view.frame.width {
scale = view.frame.width / MAX_SIZE_W
} else
if zoomView.frame.width > (MAX_SIZE_W / UIScreen.mainScreen().scale) {
scale = 1.0 / UIScreen.mainScreen().scale
}
if scale != nil {
if flag {
preview.setZoomScale(scale, animated: true)
} else {
preview.zoomScale = scale
}
}
}
func alignImageAtCenter() {
var inset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
if zoomView.frame.width < view.frame.width {
inset.left = (view.frame.width - zoomView.frame.width) / 2.0
} else {
inset.left = 0.0
}
if zoomView.frame.height < view.frame.height {
inset.top = (view.frame.height - zoomView.frame.height) / 2.0
} else {
inset.top = 0.0
}
preview.contentInset = inset
}
func scrollViewDidZoom(scrollView: UIScrollView) {
alignImageAtCenter()
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
updateBackgroundImage()
repairImageZoom()
alignImageAtCenter()
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return zoomView
}
deinit {
preview.pinchGestureRecognizer.removeObserver(self, forKeyPath: "pinchUpdated:")
}
}
| mit | 879ceaca42165820c382b0b3e87cb7e0 | 25.576923 | 162 | 0.729016 | 3.720054 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.