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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wireapp/wire-ios-data-model | Source/Model/User/PersonName.swift | 1 | 8015 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
@objcMembers public class PersonName: NSObject {
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? PersonName else { return false }
return self.components == other.components
}
enum NameOrder {
case givenNameFirst, givenNameLast, arabicGivenName
}
let components: [String]
let fullName: String
let rawFullName: String
let nameOrder: NameOrder
static let stringsToPersonNames = NSCache<NSString, PersonName>()
lazy var secondNameComponents: [String] = {
guard self.components.count < 2 else { return [] }
var startIndex = 0
var lastIndex = 0
switch self.nameOrder {
case .givenNameLast:
lastIndex = self.components.count - 2
case .givenNameFirst:
startIndex = 1
lastIndex = self.components.count - 1
case .arabicGivenName:
startIndex = 1
lastIndex = self.components.count - 1
guard self.components.count > 1 && self.components[1].zmIsGodName() else { break }
guard self.components.count > 2 else { return [] }
startIndex += 1
}
return Array(self.components[startIndex...lastIndex])
}()
lazy var givenName: String = {
guard let firstComponent = self.components.first else { return self.fullName }
var name = String()
switch self.nameOrder {
case .givenNameLast:
name += self.components.last!
case .givenNameFirst:
name += firstComponent
case .arabicGivenName:
name += firstComponent
guard self.components.count > 1 else { break }
let comp = self.components[1]
guard comp.zmIsGodName() else { break }
name = [name, comp].joined(separator: " ")
}
return name
}()
lazy public var initials: String = {
guard let firstComponent = self.components.first else { return "" }
var _initials = String()
switch self.nameOrder {
case .givenNameLast:
_initials += (firstComponent.zmFirstComposedCharacter() ?? "")
_initials += (firstComponent.zmSecondComposedCharacter() ?? "")
case .arabicGivenName, .givenNameFirst:
_initials += (firstComponent.zmFirstComposedCharacter() ?? "")
guard self.components.count > 1, let lastComponent = self.components.last else { break }
_initials += (lastComponent.zmFirstComposedCharacter() ?? "")
}
return _initials
}()
public static func person(withName name: String, schemeTagger: NSLinguisticTagger?) -> PersonName {
let tagger = schemeTagger ?? NSLinguisticTagger(tagSchemes: convertToNSLinguisticTagSchemeArray([convertFromNSLinguisticTagScheme(NSLinguisticTagScheme.script)]), options: 0)
if let cachedPersonName = stringsToPersonNames.object(forKey: name as NSString) {
return cachedPersonName
}
let cachedPersonName = PersonName(name: name, schemeTagger: tagger)
stringsToPersonNames.setObject(cachedPersonName, forKey: name as NSString)
return cachedPersonName
}
public init(name: String, schemeTagger: NSLinguisticTagger) {
// We're using -precomposedStringWithCanonicalMapping (Unicode Normalization Form C)
// since this allows us to use faster string comparison later.
self.rawFullName = name
self.fullName = name.precomposedStringWithCanonicalMapping
self.nameOrder = type(of: self).script(of: name, schemeTagger: schemeTagger)
self.components = type(of: self).splitNameComponents(fullName: fullName)
}
static func script(of string: String, schemeTagger: NSLinguisticTagger) -> NameOrder {
// We are checking the linguistic scheme in order to distinguisch between differences in the order of given and last name
// If the name contains latin scheme tag, it uses the first name as the given name
// If the name is in arab sript, we will check if the givenName consists of "servent of" + one of the names for god
schemeTagger.string = string
let tags = schemeTagger.tags(in: NSRange(location: 0, length: schemeTagger.string!.count), scheme: convertFromNSLinguisticTagScheme(NSLinguisticTagScheme.script), options: [.omitPunctuation, .omitWhitespace, .omitOther, .joinNames], tokenRanges: nil)
let nameOrder: NameOrder
if tags.contains("Arab") {
nameOrder = .arabicGivenName
}
else if tags.contains(where: {["Hani", "Jpan", "Deva", "Gurj"].contains($0)}) {
nameOrder = tags.contains("Latn") ? .givenNameFirst : .givenNameLast
}
else {
nameOrder = .givenNameFirst
}
return nameOrder
}
static func splitNameComponents(fullName: String) -> [String] {
let fullRange = Range<String.Index>(uncheckedBounds: (lower:fullName.startIndex, upper:fullName.endIndex))
var components = [String]()
var component: String?
var lastRange: Range<String.Index>?
// This is a bit more complicated because we don't want chinese names to be split up by their individual characters
let options: NSLinguisticTagger.Options = [.omitPunctuation, .omitWhitespace, .omitOther]
fullName.enumerateLinguisticTags(in: fullRange, scheme: convertFromNSLinguisticTagScheme(NSLinguisticTagScheme.tokenType), options: options, orthography: nil) { (tag, substringRange, _, _) in
guard tag == convertFromNSLinguisticTag(NSLinguisticTag.word) else { return }
let substring = fullName[substringRange]
if let aComponent = component {
if let lastRangeBound = lastRange?.upperBound, lastRangeBound == substringRange.lowerBound {
component = aComponent+substring
return
}
components.append(aComponent)
component = nil
}
if !substring.isEmpty {
component = String(substring)
lastRange = substringRange
} else {
lastRange = nil
}
}
if let aComponent = component {
components.append(aComponent)
}
return components
}
override public var hash: Int {
var hash = 0
components.forEach {hash ^= $0.hash}
return hash
}
func stringStarts(withUppercaseString string: String) -> Bool {
guard let scalar = string.unicodeScalars.first else { return false }
let uppercaseCharacterSet = NSCharacterSet.uppercaseLetters
return uppercaseCharacterSet.contains(scalar)
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToNSLinguisticTagSchemeArray(_ input: [String]) -> [NSLinguisticTagScheme] {
return input.map { key in NSLinguisticTagScheme(key) }
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSLinguisticTagScheme(_ input: NSLinguisticTagScheme) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSLinguisticTag(_ input: NSLinguisticTag) -> String {
return input.rawValue
}
| gpl-3.0 | 923c406185438b4e1d1e842689c99fd1 | 40.528497 | 258 | 0.656893 | 4.78222 | false | false | false | false |
kylef/Commander | Sources/Commander/AsyncGroup.swift | 1 | 2969 | #if compiler(>=5.5)
/// Represents a group of commands
open class AsyncGroup : AsyncCommandType {
struct AsyncSubCommand {
let name: String
let description: String?
let command: AsyncCommandType
init(name: String, description: String?, command: AsyncCommandType) {
self.name = name
self.description = description
self.command = command
}
}
var commands = [AsyncSubCommand]()
public var commandNames: [String] {
return commands.map { $0.name }
}
// When set, allows you to override the default unknown command behaviour
public var unknownCommand: ((_ name: String, _ parser: ArgumentParser) throws -> ())?
// When set, allows you to override the default no command behaviour
public var noAsyncCommand: ((_ path: String?, _ group: AsyncGroup, _ parser: ArgumentParser) throws -> ())?
/// Create a new group
@available(macOS 12, *)
public init() {}
/// Add a named sub-command to the group
@available(macOS 12, *)
public func addCommand(_ name: String, _ command: AsyncCommandType) {
commands.append(AsyncSubCommand(name: name, description: nil, command: command))
}
/// Add a named sub-command to the group with a description
@available(macOS 12, *)
public func addCommand(_ name: String, _ description: String?, _ command: AsyncCommandType) {
commands.append(AsyncSubCommand(name: name, description: description, command: command))
}
/// Run the group command
@available(macOS 12, *)
public func run(_ parser: ArgumentParser) async throws {
guard let name = parser.shift() else {
if let noAsyncCommand = noAsyncCommand {
return try noAsyncCommand(nil, self, parser)
} else {
throw GroupError.noAsyncCommand(nil, self)
}
}
guard let command = commands.first(where: { $0.name == name }) else {
if let unknownCommand = unknownCommand {
return try unknownCommand(name, parser)
} else {
throw GroupError.unknownCommand(name)
}
}
do {
try await command.command.run(parser)
} catch GroupError.unknownCommand(let childName) {
throw GroupError.unknownCommand("\(name) \(childName)")
} catch GroupError.noAsyncCommand(let path, let group) {
let path = (path == nil) ? name : "\(name) \(path!)"
if let noAsyncCommand = noAsyncCommand {
try noAsyncCommand(path, group, parser)
} else {
throw GroupError.noAsyncCommand(path, group)
}
} catch let error as Help {
throw error.reraise(name)
}
}
}
extension AsyncGroup {
@available(macOS 12, *)
public convenience init(closure: (AsyncGroup) async -> ()) async {
self.init()
await closure(self)
}
/// Add a sub-group using a closure
@available(macOS 12, *)
public func group(_ name: String, _ description: String? = nil, closure: (AsyncGroup) async -> ()) async {
addCommand(name, description, await AsyncGroup(closure: closure))
}
}
#endif | bsd-3-clause | e0a499dc9dc0a43947784838c741b010 | 30.595745 | 109 | 0.662513 | 4.078297 | false | false | false | false |
codeOfRobin/Components-Personal | Sources/DeletableTagNode.swift | 1 | 1673 | //
// DeletableTagNode.swift
// BuildingBlocks-iOS
//
// Created by Robin Malhotra on 13/10/17.
// Copyright © 2017 BuildingBlocks. All rights reserved.
//
import AsyncDisplayKit
protocol TagNodeDelegate: class {
func didTapDeleteButton(sender: ASCellNode)
}
class DeletableTagNode: ASCellNode {
let textNode = ASTextNode()
let deleteButton = ASButtonNode()
weak var delegate: TagNodeDelegate?
public init(text: String) {
textNode.attributedText = NSAttributedString(string: text, attributes: DefaultTextNode.textAttrs)
super.init()
textNode.style.flexShrink = 0.1
deleteButton.imageNode.image = FrameworkImage.delete
deleteButton.imageNode.contentMode = .scaleAspectFit
deleteButton.style.width = ASDimensionMake(16)
deleteButton.style.height = ASDimensionMake(16)
deleteButton.addTarget(self, action: #selector(deleteButtonTapped), forControlEvents: .touchUpInside)
deleteButton.hitTestSlop = UIEdgeInsets.init(top: -8, left: -8, bottom: -8, right: -8)
self.automaticallyManagesSubnodes = true
}
@objc func deleteButtonTapped() {
delegate?.didTapDeleteButton(sender: self)
}
override public func didLoad() {
self.layer.cornerRadius = 4.0
self.clipsToBounds = true
self.layer.borderColor = UIColor(red:0.75, green:0.77, blue:0.78, alpha:1.00).cgColor
self.layer.borderWidth = 1.0
}
override public func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let stack = ASStackLayoutSpec.init(direction: .horizontal, spacing: 6.0, justifyContent: .center, alignItems: .center, children: [textNode, deleteButton])
return ASInsetLayoutSpec(insets: UIEdgeInsetsMake(5, 9, 5, 9), child: stack)
}
}
| mit | c4e31147cf3a91f0b414091fe4953816 | 33.122449 | 156 | 0.759569 | 3.715556 | false | false | false | false |
vishw3/IOSChart-IOS-7.0-Support | VisChart/Classes/Renderers/ChartYAxisRendererRadarChart.swift | 2 | 5781 | //
// ChartYAxisRendererRadarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
public class ChartYAxisRendererRadarChart: ChartYAxisRenderer
{
private weak var _chart: RadarChartView!;
public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, chart: RadarChartView)
{
super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: nil);
_chart = chart;
}
public override func computeAxis(#yMin: Float, yMax: Float)
{
computeAxisValues(min: yMin, max: yMax);
}
internal override func computeAxisValues(min yMin: Float, max yMax: Float)
{
var labelCount = _yAxis.labelCount;
var range = abs(yMax - yMin);
if (labelCount == 0 || range <= 0)
{
_yAxis.entries = [Float]();
return;
}
var rawInterval = range / Float(labelCount);
var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval));
var intervalMagnitude = pow(10.0, round(log10(interval)));
var intervalSigDigit = Int(interval / intervalMagnitude);
if (intervalSigDigit > 5)
{
// Use one order of magnitude higher, to avoid intervals like 0.9 or
// 90
interval = floor(10 * intervalMagnitude);
}
// if the labels should only show min and max
if (_yAxis.isShowOnlyMinMaxEnabled)
{
_yAxis.entries = [Float]();
_yAxis.entries.append(yMin);
_yAxis.entries.append(yMax);
}
else
{
var first = ceil(Double(yMin) / interval) * interval;
var last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval);
var f: Double;
var i: Int;
var n = 0;
for (f = first; f <= last; f += interval)
{
++n;
}
if (isnan(_yAxis.customAxisMax))
{
n += 1;
}
if (_yAxis.entries.count < n)
{
// Ensure stops contains at least numStops elements.
_yAxis.entries = [Float](count: n, repeatedValue: 0.0);
}
for (f = first, i = 0; i < n; f += interval, ++i)
{
_yAxis.entries[i] = Float(f);
}
}
_yAxis.axisMaximum = _yAxis.entries[_yAxis.entryCount - 1];
_yAxis.axisRange = abs(_yAxis.axisMaximum - _yAxis.axisMinimum);
}
public override func renderAxisLabels(#context: CGContext)
{
if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled)
{
return;
}
var labelFont = _yAxis.labelFont;
var labelTextColor = _yAxis.labelTextColor;
var center = _chart.centerOffsets;
var factor = _chart.factor;
var labelCount = _yAxis.entryCount;
var labelLineHeight = _yAxis.labelFont.lineHeight;
for (var j = 0; j < labelCount; j++)
{
if (j == labelCount - 1 && _yAxis.isDrawTopYLabelEntryEnabled == false)
{
break;
}
var r = CGFloat(_yAxis.entries[j] - _yAxis.axisMinimum) * factor;
var p = ChartUtils.getPosition(center: center, dist: r, angle: _chart.rotationAngle);
var label = _yAxis.getFormattedLabel(j);
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: p.x + 10.0, y: p.y - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]);
}
}
public override func renderLimitLines(#context: CGContext)
{
var limitLines = _yAxis.limitLines;
if (limitLines.count == 0)
{
return;
}
var sliceangle = _chart.sliceAngle;
// calculate the factor that is needed for transforming the value to pixels
var factor = _chart.factor;
var center = _chart.centerOffsets;
for (var i = 0; i < limitLines.count; i++)
{
var l = limitLines[i];
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor);
CGContextSetLineWidth(context, l.lineWidth);
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var r = CGFloat(l.limit - _chart.chartYMin) * factor;
CGContextBeginPath(context);
for (var j = 0, count = _chart.data!.xValCount; j < count; j++)
{
var p = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(j) + _chart.rotationAngle);
if (j == 0)
{
CGContextMoveToPoint(context, p.x, p.y);
}
else
{
CGContextAddLineToPoint(context, p.x, p.y);
}
}
CGContextClosePath(context);
CGContextStrokePath(context);
}
}
} | mit | 9ab93f82104dd25a546f20b6c9b8af17 | 30.254054 | 228 | 0.518768 | 4.975043 | false | false | false | false |
duycao2506/SASCoffeeIOS | Pods/SwiftDate/Sources/SwiftDate/DateInRegion+Math.swift | 1 | 6049 | // SwiftDate
// Manage Date/Time & Timezone in Swift
//
// Created by: Daniele Margutti
// Email: <[email protected]>
// Web: <http://www.danielemargutti.com>
//
// Licensed under MIT License.
import Foundation
// MARK: - DateInRegion Private Extension
extension DateInRegion {
/// Return a `DateComponent` object from a given set of `Calendar.Component` object with associated values and a specific region
///
/// - parameter values: calendar components to set (with their values)
/// - parameter multipler: optional multipler (by default is nil; to make an inverse component value it should be multipled by -1)
/// - parameter region: optional region to set
///
/// - returns: a `DateComponents` object
internal static func componentsFrom(values: [Calendar.Component : Int], multipler: Int? = nil, setRegion region: Region? = nil) -> DateComponents {
var cmps = DateComponents()
if region != nil {
cmps.calendar = region!.calendar
cmps.calendar!.locale = region!.locale
cmps.timeZone = region!.timeZone
}
values.forEach { pair in
if pair.key != .timeZone && pair.key != .calendar {
cmps.setValue( (multipler == nil ? pair.value : pair.value * multipler!), for: pair.key)
}
}
return cmps
}
/// Create a new DateInRegion by adding specified DateComponents to self.
/// If fails it return `nil`o object.
///
/// - Parameter dateComponents: date components to add
/// - Returns: a new instance of DateInRegion expressed in same region
public func add(components dateComponents: DateComponents) -> DateInRegion? {
let newDate = self.region.calendar.date(byAdding: dateComponents, to: self.absoluteDate)
if newDate == nil { return nil }
return DateInRegion(absoluteDate: newDate!, in: self.region)
}
/// Enumerate dates between two intervals by adding specified time components and return an array of dates.
/// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically.
///
/// - Parameters:
/// - startDate: starting date
/// - endDate: ending date
/// - components: components to add
/// - normalize: normalize both start and end date at the start of the specified component (if nil, normalization is skipped)
/// - Returns: an array of DateInRegion objects
public static func dates(between startDate: DateInRegion, and endDate: DateInRegion, increment components: DateComponents) -> [DateInRegion]? {
guard startDate.region.calendar == endDate.region.calendar else {
return nil
}
var dates: [DateInRegion] = []
var currentDate = startDate
while (currentDate <= endDate) {
dates.append(currentDate)
guard let c_date = currentDate.add(components: components) else {
return nil
}
currentDate = c_date
}
return dates
}
/// Adjust time of the date by rounding to the next `value` interval.
/// Interval can be `seconds` or `minutes` and you can specify the type of rounding function to use.
///
/// - Parameters:
/// - value: value to round
/// - type: type of rounding
public func roundAt(_ value: IntervalType, type: IntervalRoundingType = .ceil) {
var roundedInterval: TimeInterval = 0
let rounded_abs_date = self.absoluteDate
let seconds = value.seconds
switch type {
case .round:
roundedInterval = (rounded_abs_date.timeIntervalSinceReferenceDate / seconds).rounded() * seconds
case .ceil:
roundedInterval = ceil(rounded_abs_date.timeIntervalSinceReferenceDate / seconds) * seconds
case .floor:
roundedInterval = floor(rounded_abs_date.timeIntervalSinceReferenceDate / seconds) * seconds
}
self.absoluteDate = Date(timeIntervalSinceReferenceDate: roundedInterval)
}
/// Return the difference between two dates expressed using passed time components.
///
/// - Parameters:
/// - components: time units to get
/// - refDate: reference date
/// - calendar: calendar to use, `nil` to user `Date.defaultRegion.calendar`
/// - Returns: components dictionary
// #NEW
public func components(_ components: [Calendar.Component], to refDate: DateInRegion) -> [Calendar.Component : Int] {
guard self.region.calendar == refDate.region.calendar else {
debugPrint("Date must have the same calendar")
return [:]
}
let cmps = self.region.calendar.dateComponents(componentsToSet(components), from: self.absoluteDate, to: refDate.absoluteDate)
return cmps.toComponentsDict()
}
/// Return the difference between two dates expressed in passed time unit.
/// This operation take care of the calendar in which dates are expressed (must be equal) differently
/// from the TimeInterval `in` function
///
/// - Parameters:
/// - component: component to get
/// - refDate: reference date
/// - Returns: difference expressed in given component
public func component(_ component: Calendar.Component, to refDate: DateInRegion) -> Int? {
return self.components([component], to: refDate)[component]
}
}
// MARK: - DateInRegion Support for math operation
// These functions allows us to make something like
// `let newDate = (date - 3.days + 3.months)`
// We can sum algebrically a `DateInRegion` object with a calendar component.
public func + (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion {
let nextDate = lhs.region.calendar.date(byAdding: rhs, to: lhs.absoluteDate)
return DateInRegion(absoluteDate: nextDate!, in: lhs.region)
}
public func - (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion {
return lhs + (-rhs)
}
public func + (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion {
let cmps = DateInRegion.componentsFrom(values: rhs)
return lhs + cmps
}
public func - (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion {
var invertedCmps: [Calendar.Component : Int] = [:]
rhs.forEach { invertedCmps[$0.key] = -$0.value }
return lhs + invertedCmps
}
public func - (lhs: DateInRegion, rhs: DateInRegion) -> TimeInterval {
return DateTimeInterval(start: rhs.absoluteDate, end: lhs.absoluteDate).duration
}
| gpl-3.0 | acc08bc2a08866537d9aa764441a202a | 36.333333 | 148 | 0.716435 | 3.963303 | false | false | false | false |
oscarqpe/machine-learning-algorithms | LNN/WriteData.swift | 1 | 933 | //
// WriteData.swift
// LSH Test
//
// Created by Andre Valdivia on 22/05/16.
// Copyright © 2016 Andre Valdivia. All rights reserved.
//
import Foundation
func writeData(text:String, nameFile:String){
let file = nameFile //this is the file. we will write to and read from it
// let text = text //just a text
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
// //reading
// do {
// let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
// }
// catch {/* error handling here */}
}
} | gpl-3.0 | 9b525e0fcdd9ac5f9399d39edbfcb95e | 30.1 | 146 | 0.641631 | 4.314815 | false | false | false | false |
eduardoeof/Gollum | Workspace/Gollum/GollumTests/GollumTests.swift | 1 | 8065 | //
// GollumTests.swift
// GollumTests
//
// Created by eduardo.ferreira on 5/28/16.
// Copyright © 2016 eduardoeof. All rights reserved.
//
import XCTest
@testable import Gollum
class GollumTests: XCTestCase {
var gollum: Gollum!
override func setUp() {
super.setUp()
gollum = Gollum()
}
override func tearDown() {
removeSelectedTestsFromStorage()
}
//MARK: - Test cases
func testInstanceProperty() {
XCTAssertNotNil(Gollum.instance)
XCTAssert(Gollum.instance === Gollum.instance)
}
func testRegisterVersions() {
do {
try gollum.registerVersions([GollumABTest.a, GollumABTest.b, GollumABTest.c])
let isA = try gollum.isVersionSelected(GollumABTest.a)
let isB = try gollum.isVersionSelected(GollumABTest.b)
let isC = try gollum.isVersionSelected(GollumABTest.c)
XCTAssert(isA || isB || isC)
} catch {
XCTFail()
}
}
func testRegisterVersionsWithVersionsAlreadySelected() {
do {
try gollum.registerVersions([GollumABTest.a, GollumABTest.b, GollumABTest.c])
let gollum2 = Gollum()
try gollum2.registerVersions([GollumABTest.a, GollumABTest.b, GollumABTest.c])
XCTAssertEqual(try gollum.isVersionSelected(GollumABTest.a), try gollum2.isVersionSelected(GollumABTest.a))
XCTAssertEqual(try gollum.isVersionSelected(GollumABTest.b), try gollum2.isVersionSelected(GollumABTest.b))
XCTAssertEqual(try gollum.isVersionSelected(GollumABTest.c), try gollum2.isVersionSelected(GollumABTest.c))
} catch {
XCTFail()
}
}
func testRegisterVersionsEmptyVersionArrayPassed() {
do {
let versions = [GollumABTest]()
try gollum.registerVersions(versions)
} catch GollumError.emptyVersionArrayPassed(let message) {
XCTAssertEqual(message, "A empty version array was passed to registered.")
} catch {
XCTFail()
}
}
func testRegisterVersionsProbabilitySumIncorrect() {
do {
try gollum.registerVersions([GollumABTestProbabilitySumIncorrect.a, GollumABTestProbabilitySumIncorrect.b])
} catch GollumError.probabilitySumIncorrect(let message) {
XCTAssertEqual(message, "Sum of GollumABTestProbabilitySumIncorrect's probability isn't 1.0")
} catch {
XCTFail()
}
}
func testIsVersionSelectedAlwaysA() {
do {
try gollum.registerVersions([GollumABTestAlwaysAVersion.a,
GollumABTestAlwaysAVersion.b,
GollumABTestAlwaysAVersion.c])
XCTAssertTrue(try gollum.isVersionSelected(GollumABTestAlwaysAVersion.a))
XCTAssertFalse(try gollum.isVersionSelected(GollumABTestAlwaysAVersion.b))
XCTAssertFalse(try gollum.isVersionSelected(GollumABTestAlwaysAVersion.c))
} catch {
XCTFail()
}
}
func testIsVersionSelectedAlwaysB() {
do {
try gollum.registerVersions([GollumABTestAlwaysBVersion.a,
GollumABTestAlwaysBVersion.b,
GollumABTestAlwaysBVersion.c])
XCTAssertTrue(try gollum.isVersionSelected(GollumABTestAlwaysBVersion.b))
XCTAssertFalse(try gollum.isVersionSelected(GollumABTestAlwaysBVersion.a))
XCTAssertFalse(try gollum.isVersionSelected(GollumABTestAlwaysBVersion.c))
} catch {
XCTFail()
}
}
func testIsVersionSelectedAlwaysC() {
do {
try gollum.registerVersions([GollumABTestAlwaysCVersion.a,
GollumABTestAlwaysCVersion.b,
GollumABTestAlwaysCVersion.c])
XCTAssertTrue(try gollum.isVersionSelected(GollumABTestAlwaysCVersion.c))
XCTAssertFalse(try gollum.isVersionSelected(GollumABTestAlwaysCVersion.a))
XCTAssertFalse(try gollum.isVersionSelected(GollumABTestAlwaysCVersion.b))
} catch {
XCTFail()
}
}
func testIsVersionSelectedErrorSelectedVersionNotFound() {
do {
_ = try gollum.isVersionSelected(GollumABTest.a)
} catch GollumError.selectedVersionNotFound(let message) {
XCTAssertEqual(message, "Test GollumABTest should have a selected version.")
} catch {
XCTFail()
}
}
func testLoadSelectedVersionsFromStorage() {
do {
try gollum.registerVersions([GollumABTest.a, GollumABTest.b, GollumABTest.c])
let gollumStorage = Gollum()
let isA = try gollumStorage.isVersionSelected(GollumABTest.a)
let isB = try gollumStorage.isVersionSelected(GollumABTest.b)
let isC = try gollumStorage.isVersionSelected(GollumABTest.c)
XCTAssert(isA || isB || isC)
} catch {
XCTFail()
}
}
func testGetSelectedVersionAlwayVersionA() {
do {
try gollum.registerVersions([GollumABTestAlwaysAVersion.a,
GollumABTestAlwaysAVersion.b,
GollumABTestAlwaysAVersion.c])
switch try gollum.getSelectedVersion(GollumABTestAlwaysAVersion.self) {
case .a:
XCTAssertTrue(true)
case .b:
XCTFail()
case .c:
XCTFail()
}
} catch {
XCTFail()
}
}
func testGetSelectedVersionAlwayVersionB() {
do {
try gollum.registerVersions([GollumABTestAlwaysBVersion.a,
GollumABTestAlwaysBVersion.b,
GollumABTestAlwaysBVersion.c])
switch try gollum.getSelectedVersion(GollumABTestAlwaysBVersion.self) {
case .a:
XCTFail()
case .b:
XCTAssertTrue(true)
case .c:
XCTFail()
}
} catch {
XCTFail()
}
}
func testGetSelectedVersionAlwayVersionC() {
do {
try gollum.registerVersions([GollumABTestAlwaysCVersion.a,
GollumABTestAlwaysCVersion.b,
GollumABTestAlwaysCVersion.c])
switch try gollum.getSelectedVersion(GollumABTestAlwaysCVersion.self) {
case .a:
XCTFail()
case .b:
XCTFail()
case .c:
XCTAssertTrue(true)
}
} catch {
XCTFail()
}
}
func testGetSelectedVersionErrorSelectedVersionNotFound() {
do {
_ = try gollum.getSelectedVersion(GollumABTestAlwaysAVersion.self)
} catch GollumError.selectedVersionNotFound(let message) {
XCTAssertEqual(message, "Test GollumABTestAlwaysAVersion should have a selected version.")
} catch {
XCTFail()
}
}
}
// MARK: - Extension
extension GollumTests: GollumUserDefaultHelper {}
// MARK: - Test enum
private enum GollumABTest: Version {
case a = "A:0.3"
case b = "B:0.3"
case c = "C:0.4"
}
private enum GollumABTestAlwaysAVersion: Version {
case a = "A:1.0"
case b = "B:0.0"
case c = "C:0.0"
}
private enum GollumABTestAlwaysBVersion: Version {
case a = "A:0.0"
case b = "B:1.0"
case c = "C:0.0"
}
private enum GollumABTestAlwaysCVersion: Version {
case a = "A:0.0"
case b = "B:0.0"
case c = "C:1.0"
}
private enum GollumABTestProbabilitySumIncorrect: Version {
case a = "A:0.3"
case b = "B:0.3"
}
| mit | 86c6d7844ca04bd278c84357fb07fc6e | 31.385542 | 119 | 0.577381 | 4.268925 | false | true | false | false |
CaiMiao/CGSSGuide | DereGuide/Common/CloudKitSync/EntityAndPredicate.swift | 1 | 1296 | //
// EntityAndPredicate.swift
// DereGuide
//
// Created by Daniel Eggert on 23/08/2015.
// Copyright © 2015 objc.io. All rights reserved.
//
import Foundation
import CoreData
final class EntityAndPredicate<A : NSManagedObject> {
let entity: NSEntityDescription
let predicate: NSPredicate
init(entity: NSEntityDescription, predicate: NSPredicate) {
self.entity = entity
self.predicate = predicate
}
}
extension EntityAndPredicate {
var fetchRequest: NSFetchRequest<A> {
let request = NSFetchRequest<A>()
request.entity = entity
request.predicate = predicate
return request
}
}
extension Sequence where Iterator.Element: NSManagedObject {
func filter(_ entityAndPredicate: EntityAndPredicate<Iterator.Element>) -> [Iterator.Element] {
typealias MO = Iterator.Element
let filtered = filter { (mo: Iterator.Element) -> Bool in
// guard mo.entity === entityAndPredicate.entity else { return false }
// return entityAndPredicate.predicate.evaluate(with: mo)
guard mo.entity.name == entityAndPredicate.entity.name else { return false }
return entityAndPredicate.predicate.evaluate(with: mo)
}
return Array(filtered)
}
}
| mit | 64879832cb87f4aa8d30d7bbcf3b0e1e | 26.553191 | 99 | 0.671042 | 4.709091 | false | false | false | false |
cottonBuddha/Qsic | Qsic/main.swift | 1 | 909 | //
// main.swift
// Qsic
//
// Created by cottonBuddha on 2017/7/7.
// Copyright © 2017年 cottonBuddha. All rights reserved.
//
import Foundation
let argCount = CommandLine.argc
let arguments = CommandLine.arguments
if 1 == argCount {
QSMusicController().start()
} else {
let cm = arguments[1]
if "-v" == cm || "--version" == cm {
print("v0.1.1")
} else if "-h" == cm || "--help" == cm {
let basicOperation =
"""
基本操作:
上下页请按: ←、→
上下项请按: ↑、↓
选中项请按:↵
返回上级菜单请按:/
登录请在首页按:d (仅支持手机号登录)
退出请按:q
更多操作请前往[首页-帮助]
"""
print(basicOperation)
} else {
print("I have no idea of this order! Try -h or -v")
}
}
| mit | fa1cc622019d1726d56bd7f5daf80c3c | 20.222222 | 59 | 0.5 | 3.031746 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-x | Source/Utils/Data+hex.swift | 2 | 2737 | //
// Copyright (C) 2015-2021 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
// MARK: - Data extension for hex encoding and decoding
public extension Data {
/// Encodes data in hex format
///
/// - Returns: Hex-encoded string
func hexEncodedString() -> String {
return self
.map { String(format: "%02hhx", $0) }
.joined()
}
/// Initializer
///
/// - Parameter hex: Hex-encoded string
init?(hexEncodedString hex: String) {
let length = hex.lengthOfBytes(using: .ascii)
guard length % 2 == 0 else {
return nil
}
var data = Data()
data.reserveCapacity(length / 2)
var lowerBound = hex.startIndex
while true {
guard let upperBound = hex.index(lowerBound, offsetBy: 2, limitedBy: hex.endIndex) else {
break
}
let substr = String(hex[Range(uncheckedBounds: (lowerBound, upperBound))])
let res = strtol(substr, nil, 16)
data.append(contentsOf: [UInt8(res)])
lowerBound = upperBound
}
self = data
}
}
| bsd-3-clause | c6872ed0ec3527d441eeaec16d8db047 | 33.64557 | 101 | 0.667154 | 4.607744 | false | false | false | false |
davidstump/SwiftPhoenixClient | Tests/Fakes/SocketSpy.swift | 1 | 1927 | // Copyright (c) 2021 David Stump <[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.
@testable import SwiftPhoenixClient
class SocketSpy: Socket {
private(set) var pushCalled: Bool?
private(set) var pushCallCount: Int = 0
private(set) var pushArgs: [Int: (topic: String, event: String, payload: Payload, ref: String?, joinRef: String?)] = [:]
override func push(topic: String,
event: String,
payload: Payload,
ref: String? = nil,
joinRef: String? = nil) {
self.pushCalled = true
self.pushCallCount += 1
self.pushArgs[pushCallCount] = (topic: topic, event: event, payload: payload, ref: ref, joinRef: joinRef)
super.push(topic: topic,
event: event,
payload: payload,
ref: ref,
joinRef: joinRef)
}
}
| mit | 5d5995489c583b6c6098174118908474 | 41.822222 | 122 | 0.683446 | 4.349887 | false | false | false | false |
for-meng/BuDeJie-Swift- | BSBuDeJie/BSBuDeJie/Classess/Main/Controller/BSTabBarViewController.swift | 1 | 4198 | //
// BSTabBarViewController.swift
// BSBuDeJie
//
// Created by mh on 16/4/19.
// Copyright © 2016年 BS. All rights reserved.
//
import UIKit
class BSTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
//添加所有控制器
addChildViewControllers()
//替换系统TabBar
replaceTabbar()
}
// MARK: - 初始化控件
private func replaceTabbar (){
let tabbar: BSTabBar = BSTabBar()
setValue(tabbar, forKey: "tabBar")
}
private func addChildViewControllers()
{
addChildViewController(BSEssenceController(), ti: "精华", Image: "tabBar_essence_icon", selectedImage: "tabBar_essence_click_icon")
addChildViewController(BSNewController(), ti: "新帖", Image: "tabBar_new_icon", selectedImage: "tabBar_new_click_icon")
addChildViewController(BSFriendViewController(), ti: "关注", Image: "tabBar_friendTrends_icon", selectedImage: "tabBar_friendTrends_click_icon")
addChildViewController(UIStoryboard.init(name: "BSMineTableViewController", bundle: nil).instantiateInitialViewController()!, ti: "我的", Image: "tabBar_me_icon", selectedImage: "tabBar_me_click_icon")
}
private func addChildViewController(Vc: UIViewController, ti: String ,Image: String, selectedImage: String) {
let nvC: BSNavgationController = BSNavgationController.init(rootViewController: Vc)
Vc.tabBarItem.image = UIImage(named: Image)?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
Vc.tabBarItem.selectedImage = UIImage(named: selectedImage)?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
Vc.title = ti
addChildViewController(nvC)
}
}
//自定义UITabBar
class BSTabBar: UITabBar {
//Swift中重写父类需要override关键字
override init(frame: CGRect) {
super.init(frame: frame)
backgroundImage = UIImage(named: "tabbar-light")
barTintColor = UIColor.grayColor()
addSubview(self.plusBtn)
self.plusBtn.addTarget(self, action: "plusBtnOnClick:", forControlEvents: UIControlEvents.TouchUpInside)
}
func plusBtnOnClick(btn:UIButton){
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(BSShareViewController(), animated: true, completion: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
self.plusBtn.sizeToFit()
self.plusBtn.center.x = self.bounds.width * 0.5
self.plusBtn.center.y = self.bounds.height * 0.5
var index:NSInteger = 0
var btnX : CGFloat = 0
let btnW : CGFloat = self.bounds.width / 5
//系统布局完之后再布局
for obj in self.subviews
{
if obj.isKindOfClass(NSClassFromString("UITabBarButton")!)
{
if index == 2
{
index++
}
btnX = CGFloat(index) * btnW
obj.frame.origin.x = btnX
index++
(obj as! UIControl).addTarget(self, action: "repeatClick:", forControlEvents: UIControlEvents.TouchUpInside)
}
}
}
var previousTabBarButton:UIControl?
func repeatClick(tabBarBtn : UIControl)
{
if previousTabBarButton != tabBarBtn{
previousTabBarButton = tabBarBtn
return
}
NSNotificationCenter.defaultCenter().postNotificationName(BSTabBarRepeatClickNotification, object: nil)
}
lazy var plusBtn: UIButton = {
let btn: UIButton = UIButton(type: UIButtonType.Custom)
btn.setBackgroundImage(UIImage(named: "tabBar_publish_icon"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabBar_publish_click_icon"), forState: UIControlState.Highlighted)
btn.bounds.size = (btn.currentBackgroundImage?.size)!
return btn
}()
//Swift只允许一种初始化方式,要么纯代码 要么XIB
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | apache-2.0 | 44cf06918eb5ed7737b6f41511b0ca11 | 37.358491 | 207 | 0.654859 | 4.65103 | false | false | false | false |
attackFromCat/LivingTVDemo | LivingTVDemo/LivingTVDemo/Classes/Home/Controller/FunnyViewController.swift | 1 | 1097 | //
// FunnyViewController.swift
// LivingTVDemo
//
// Created by 李翔 on 2017/1/9.
// Copyright © 2017年 Lee Xiang. All rights reserved.
//
import UIKit
fileprivate let kTopMargin : CGFloat = 8
class FunnyViewController: BaseAnchorViewController {
// MARK: 懒加载ViewModel对象
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
}
extension FunnyViewController {
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0)
}
}
extension FunnyViewController {
override func loadData() {
// 1.给父类中的ViewModel进行赋值
baseVM = funnyVM
// 2.请求数据
funnyVM.loadFunnyData {
// 2.1.刷新表格
self.collectionView.reloadData()
// 2.2.数据请求完成
self.loadDataFinished()
}
}
}
| mit | 8e61da25cf0fc3797821c2571913d1cd | 22.5 | 97 | 0.635397 | 4.809302 | false | false | false | false |
practicalswift/swift | test/IRGen/generic_metatypes.swift | 4 | 15707 |
// RUN: %swift -module-name generic_metatypes -target x86_64-apple-macosx10.9 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 -DINT=i64 %s
// RUN: %swift -module-name generic_metatypes -target i386-apple-ios7.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 -DINT=i32 %s
// RUN: %swift -module-name generic_metatypes -target x86_64-apple-ios7.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 -DINT=i64 %s
// RUN: %swift -module-name generic_metatypes -target x86_64-apple-tvos9.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 -DINT=i64 %s
// RUN: %swift -module-name generic_metatypes -target i386-apple-watchos2.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 -DINT=i32 %s
// RUN: %swift -module-name generic_metatypes -target x86_64-unknown-linux-gnu -disable-objc-interop -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 -DINT=i64 %s
// RUN: %swift -module-name generic_metatypes -target armv7-apple-ios7.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 -DINT=i32 %s
// RUN: %swift -module-name generic_metatypes -target arm64-apple-ios7.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 -DINT=i64 %s
// RUN: %swift -module-name generic_metatypes -target arm64-apple-tvos9.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 -DINT=i64 %s
// RUN: %swift -module-name generic_metatypes -target armv7k-apple-watchos2.0 -emit-ir -disable-legacy-type-info -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 -DINT=i32 %s
// REQUIRES: CODEGENERATOR=X86
// REQUIRES: CODEGENERATOR=ARM
enum Never {}
func never() -> Never { return never() }
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {
never()
}
// CHECK: define hidden swiftcc %swift.type* [[GENERIC_TYPEOF:@"\$s17generic_metatypes0A6TypeofyxmxlF"]](%swift.opaque* noalias nocapture, %swift.type* [[TYPE:%.*]])
func genericTypeof<T>(_ x: T) -> T.Type {
// CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* {{.*}}, %swift.type* [[TYPE]], i1 false)
// CHECK: ret %swift.type* [[METATYPE]]
return type(of: x)
}
struct Foo {}
class Bar {}
// CHECK-LABEL: define hidden swiftcc %swift.type* @"$s17generic_metatypes27remapToSubstitutedMetatypes{{.*}}"(%T17generic_metatypes3BarC*) {{.*}} {
func remapToSubstitutedMetatypes(_ x: Foo, y: Bar)
-> (Foo.Type, Bar.Type)
{
// CHECK: call swiftcc %swift.type* [[GENERIC_TYPEOF]](%swift.opaque* noalias nocapture undef, %swift.type* {{.*}} @"$s17generic_metatypes3FooVMf", {{.*}})
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s17generic_metatypes3BarCMa"([[INT]] 0)
// CHECK: [[BAR:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[BAR_META:%.*]] = call swiftcc %swift.type* [[GENERIC_TYPEOF]](%swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[BAR]])
// CHECK: ret %swift.type* [[BAR_META]]
return (genericTypeof(x), genericTypeof(y))
}
// CHECK-LABEL: define hidden swiftcc void @"$s17generic_metatypes23remapToGenericMetatypesyyF"()
func remapToGenericMetatypes() {
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s17generic_metatypes3BarCMa"([[INT]] 0)
// CHECK: [[BAR:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call swiftcc void @"$s17generic_metatypes0A9Metatypes{{.*}}"(%swift.type* {{.*}} @"$s17generic_metatypes3FooVMf", {{.*}} %swift.type* [[BAR]], %swift.type* {{.*}} @"$s17generic_metatypes3FooVMf", {{.*}} %swift.type* [[BAR]])
genericMetatypes(Foo.self, Bar.self)
}
func genericMetatypes<T, U>(_ t: T.Type, _ u: U.Type) {}
protocol Bas {}
// CHECK: define hidden swiftcc { %swift.type*, i8** } @"$s17generic_metatypes14protocolTypeof{{.*}}"(%T17generic_metatypes3BasP* noalias nocapture dereferenceable({{.*}}))
func protocolTypeof(_ x: Bas) -> Bas.Type {
// CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %T17generic_metatypes3BasP, %T17generic_metatypes3BasP* [[X:%.*]], i32 0, i32 1
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]]
// CHECK: [[BUFFER:%.*]] = getelementptr inbounds %T17generic_metatypes3BasP, %T17generic_metatypes3BasP* [[X]], i32 0, i32 0
// CHECK: [[VALUE_ADDR:%.*]] = call %swift.opaque* @__swift_project_boxed_opaque_existential_1({{.*}} [[BUFFER]], %swift.type* [[METADATA]])
// CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* [[VALUE_ADDR]], %swift.type* [[METADATA]], i1 true)
// CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %T17generic_metatypes3BasP, %T17generic_metatypes3BasP* %0, i32 0, i32 2
// CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]]
// CHECK-NOT: call void @__swift_destroy_boxed_opaque_existential_1(%T17generic_metatypes3BasP* %0)
// CHECK: [[T0:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* [[METATYPE]], 0
// CHECK: [[T1:%.*]] = insertvalue { %swift.type*, i8** } [[T0]], i8** [[WTABLE]], 1
// CHECK: ret { %swift.type*, i8** } [[T1]]
return type(of: x)
}
struct Zim : Bas {}
class Zang : Bas {}
// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @"$s17generic_metatypes15metatypeErasureyAA3Bas_pXpAA3ZimVmF"() #0
func metatypeErasure(_ z: Zim.Type) -> Bas.Type {
// CHECK: ret { %swift.type*, i8** } {{.*}} @"$s17generic_metatypes3ZimVMf", {{.*}} @"$s17generic_metatypes3ZimVAA3BasAAWP"
return z
}
// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @"$s17generic_metatypes15metatypeErasureyAA3Bas_pXpAA4ZangCmF"(%swift.type*) #0
func metatypeErasure(_ z: Zang.Type) -> Bas.Type {
// CHECK: [[RET:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* %0, 0
// CHECK: [[RET2:%.*]] = insertvalue { %swift.type*, i8** } [[RET]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s17generic_metatypes4ZangCAA3BasAAWP", i32 0, i32 0), 1
// CHECK: ret { %swift.type*, i8** } [[RET2]]
return z
}
struct OneArg<T> {}
struct TwoArgs<T, U> {}
struct ThreeArgs<T, U, V> {}
struct FourArgs<T, U, V, W> {}
struct FiveArgs<T, U, V, W, X> {}
func genericMetatype<A>(_ x: A.Type) {}
// CHECK-LABEL: define hidden swiftcc void @"$s17generic_metatypes20makeGenericMetatypesyyF"() {{.*}} {
func makeGenericMetatypes() {
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes6OneArgVyAA3FooVGMa"([[INT]] 0) [[NOUNWIND_READNONE:#[0-9]+]]
genericMetatype(OneArg<Foo>.self)
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMa"([[INT]] 0) [[NOUNWIND_READNONE]]
genericMetatype(TwoArgs<Foo, Bar>.self)
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMa"([[INT]] 0) [[NOUNWIND_READNONE]]
genericMetatype(ThreeArgs<Foo, Bar, Foo>.self)
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMa"([[INT]] 0) [[NOUNWIND_READNONE]]
genericMetatype(FourArgs<Foo, Bar, Foo, Bar>.self)
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMa"([[INT]] 0) [[NOUNWIND_READNONE]]
genericMetatype(FiveArgs<Foo, Bar, Foo, Bar, Foo>.self)
}
// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s17generic_metatypes6OneArgVyAA3FooVGMa"([[INT]]) [[NOUNWIND_READNONE_OPT:#[0-9]+]]
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes6OneArgVMa"([[INT]] %0, %swift.type* {{.*}} @"$s17generic_metatypes3FooVMf", {{.*}}) [[NOUNWIND_READNONE:#[0-9]+]]
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s17generic_metatypes6OneArgVMa"
// CHECK-SAME: ([[INT]], %swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type* }, { %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_getGenericMetadata([[INT]] %0, i8* [[BUFFER_PTR]], %swift.type_descriptor* {{.*}} @"$s17generic_metatypes6OneArgVMn" {{.*}})
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-LABEL: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s17generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMa"
// CHECK-SAME: ([[INT]]) [[NOUNWIND_READNONE_OPT]]
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s17generic_metatypes3BarCMa"([[INT]] 255)
// CHECK: [[BAR:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes7TwoArgsVMa"([[INT]] %0, %swift.type* {{.*}} @"$s17generic_metatypes3FooVMf", {{.*}}, %swift.type* [[BAR]])
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s17generic_metatypes7TwoArgsVMa"
// CHECK-SAME: ([[INT]], %swift.type*, %swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type* }, { %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type* }, { %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1
// CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_getGenericMetadata([[INT]] %0, i8* [[BUFFER_PTR]], %swift.type_descriptor* {{.*}} @"$s17generic_metatypes7TwoArgsVMn" {{.*}})
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-LABEL: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s17generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMa"
// CHECK-SAME: ([[INT]]) [[NOUNWIND_READNONE_OPT]]
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s17generic_metatypes3BarCMa"([[INT]] 255)
// CHECK: [[BAR:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes9ThreeArgsVMa"([[INT]] %0, %swift.type* {{.*}} @"$s17generic_metatypes3FooVMf", {{.*}}, %swift.type* [[BAR]], %swift.type* {{.*}} @"$s17generic_metatypes3FooVMf", {{.*}}) [[NOUNWIND_READNONE]]
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s17generic_metatypes9ThreeArgsVMa"
// CHECK-SAME: ({{i[0-9]+}}, %swift.type*, %swift.type*, %swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type*, %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1
// CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 2
// CHECK: store %swift.type* %3, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_getGenericMetadata([[INT]] %0, i8* [[BUFFER_PTR]], %swift.type_descriptor* {{.*}} @"$s17generic_metatypes9ThreeArgsVMn" {{.*}})
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-LABEL: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s17generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMa"
// CHECK-SAME: ([[INT]]) [[NOUNWIND_READNONE_OPT]]
// CHECK: [[BUFFER:%.*]] = alloca [4 x i8*]
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s17generic_metatypes3BarCMa"([[INT]] 255)
// CHECK: [[BAR:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call void @llvm.lifetime.start
// CHECK-NEXT: [[SLOT_0:%.*]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BUFFER]], i32 0, i32 0
// CHECK-NEXT: store {{.*}}@"$s17generic_metatypes3FooVMf"{{.*}}, i8** [[SLOT_0]]
// CHECK-NEXT: [[SLOT_1:%.*]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BUFFER]], i32 0, i32 1
// CHECK-NEXT: [[T0:%.*]] = bitcast %swift.type* [[BAR]] to i8*
// CHECK-NEXT: store i8* [[T0]], i8** [[SLOT_1]]
// CHECK-NEXT: [[SLOT_2:%.*]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BUFFER]], i32 0, i32 2
// CHECK-NEXT: store {{.*}}@"$s17generic_metatypes3FooVMf"{{.*}}, i8** [[SLOT_2]]
// CHECK-NEXT: [[SLOT_3:%.*]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BUFFER]], i32 0, i32 3
// CHECK-NEXT: [[T0:%.*]] = bitcast %swift.type* [[BAR]] to i8*
// CHECK-NEXT: store i8* [[T0]], i8** [[SLOT_3]]
// CHECK-NEXT: [[BUFFER_PTR:%.*]] = bitcast [4 x i8*]* [[BUFFER]] to i8**
// CHECK-NEXT: call swiftcc %swift.metadata_response @"$s17generic_metatypes8FourArgsVMa"([[INT]] %0, i8** [[BUFFER_PTR]]) [[NOUNWIND_ARGMEM:#[0-9]+]]
// CHECK: call void @llvm.lifetime.end.p0i8
// CHECK-LABEL: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s17generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMa"
// CHECK-SAME: ([[INT]]) [[NOUNWIND_READNONE_OPT]]
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s17generic_metatypes3BarCMa"([[INT]] 255)
// CHECK: [[BAR:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call swiftcc %swift.metadata_response @"$s17generic_metatypes8FiveArgsVMa"([[INT]] %0, i8**
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s17generic_metatypes8FiveArgsVMa"
// CHECK-SAME: ([[INT]], i8**) [[NOUNWIND_OPT:#[0-9]+]]
// CHECK-NOT: alloc
// CHECK: call swiftcc %swift.metadata_response @swift_getGenericMetadata([[INT]] %0, i8* {{.*}}, %swift.type_descriptor* {{.*}} @"$s17generic_metatypes8FiveArgsVMn" {{.*}})
// CHECK-NOT: call void @llvm.lifetime.end
// CHECK: ret %swift.metadata_response
// CHECK: attributes [[NOUNWIND_READNONE_OPT]] = { nounwind readnone "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "target-cpu"
// CHECK: attributes [[NOUNWIND_OPT]] = { nounwind "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "target-cpu"
// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
// CHECK: attributes [[NOUNWIND_ARGMEM]] = { inaccessiblemem_or_argmemonly nounwind }
| apache-2.0 | 649bc854b04dfc52fa3694514b38af0b | 73.795238 | 265 | 0.659897 | 3.162271 | false | false | false | false |
OHAKO-Inc/OHAKO-Prelude | PreludePlayground.playground/Pages/KeyboardNotificationReceiving.xcplaygroundpage/Contents.swift | 1 | 2121 | //: [Previous](@previous)
/*:
# KeyboardNotificationReceiving
*/
import UIKit
import XCPlayground
import PlaygroundSupport
import Prelude
let textFieldOriginalFrame = CGRect(x: 0.0, y: 667.0 - 50.0, width: 375.0, height: 50.0)
class ViewController: UIViewController {
lazy var textField: UITextField = {
let textField = UITextField(frame: textFieldOriginalFrame)
textField.borderStyle = .line
textField.placeholder = "Text Field"
return textField
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(textField)
let tapGesture = UITapGestureRecognizer(
target: self,
action: #selector(ViewController.viewTapped)
)
view.addGestureRecognizer(tapGesture)
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.keyboardWillShow(_:)),
name: .UIKeyboardWillShow,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.keyboardWillHide(_:)),
name: .UIKeyboardWillHide,
object: nil
)
}
@objc func viewTapped() {
view.endEditing(true)
}
@objc func keyboardWillShow(_ notification: Notification) {
handleKeyboardWillShow(notification)
}
@objc func keyboardWillHide(_ notification: Notification) {
handleKeyboardWillHide(notification)
}
}
extension ViewController: KeyboardNotificationReceiving {
func animationsWhenKeyboardWillMove(keyboardRect: CGRect, show: Bool) {
// add custom animation here
textField.frame = CGRect(
x: textFieldOriginalFrame.origin.x,
y: textFieldOriginalFrame.origin.y - (show ? keyboardRect.size.height : 0),
width: textFieldOriginalFrame.size.width,
height: textFieldOriginalFrame.size.height
)
}
}
let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
//: [Next](@next)
| mit | fafde5d0fef206a183f24142ad6d52c9 | 28.458333 | 88 | 0.652522 | 5.123188 | false | false | false | false |
sweetkk/SWMusic | SWMusic/Pods/ReactiveCocoa/ReactiveCocoa/NSObject+Association.swift | 6 | 4154 | import ReactiveSwift
internal struct AssociationKey<Value> {
fileprivate let address: UnsafeRawPointer
fileprivate let `default`: Value!
/// Create an ObjC association key.
///
/// - warning: The key must be uniqued.
///
/// - parameters:
/// - default: The default value, or `nil` to trap on undefined value. It is
/// ignored if `Value` is an optional.
init(default: Value? = nil) {
self.address = UnsafeRawPointer(UnsafeMutablePointer<UInt8>.allocate(capacity: 1))
self.default = `default`
}
/// Create an ObjC association key from a `StaticString`.
///
/// - precondition: `key` has a pointer representation.
///
/// - parameters:
/// - default: The default value, or `nil` to trap on undefined value. It is
/// ignored if `Value` is an optional.
init(_ key: StaticString, default: Value? = nil) {
assert(key.hasPointerRepresentation)
self.address = UnsafeRawPointer(key.utf8Start)
self.default = `default`
}
/// Create an ObjC association key from a `Selector`.
///
/// - parameters:
/// - default: The default value, or `nil` to trap on undefined value. It is
/// ignored if `Value` is an optional.
init(_ key: Selector, default: Value? = nil) {
self.address = UnsafeRawPointer(key.utf8Start)
self.default = `default`
}
}
internal struct Associations<Base: AnyObject> {
fileprivate let base: Base
init(_ base: Base) {
self.base = base
}
}
extension Reactive where Base: NSObject {
/// Retrieve the associated value for the specified key. If the value does not
/// exist, `initial` would be called and the returned value would be
/// associated subsequently.
///
/// - parameters:
/// - key: An optional key to differentiate different values.
/// - initial: The action that supples an initial value.
///
/// - returns:
/// The associated value for the specified key.
internal func associatedValue<T>(forKey key: StaticString = #function, initial: (Base) -> T) -> T {
let key = AssociationKey<T?>(key)
if let value = base.associations.value(forKey: key) {
return value
}
let value = initial(base)
base.associations.setValue(value, forKey: key)
return value
}
}
extension NSObject {
@nonobjc internal var associations: Associations<NSObject> {
return Associations(self)
}
}
extension Associations {
/// Retrieve the associated value for the specified key.
///
/// - parameters:
/// - key: The key.
///
/// - returns: The associated value, or the default value if no value has been
/// associated with the key.
internal func value<Value>(forKey key: AssociationKey<Value>) -> Value {
return (objc_getAssociatedObject(base, key.address) as! Value?) ?? key.default
}
/// Retrieve the associated value for the specified key.
///
/// - parameters:
/// - key: The key.
///
/// - returns: The associated value, or `nil` if no value is associated with
/// the key.
internal func value<Value>(forKey key: AssociationKey<Value?>) -> Value? {
return objc_getAssociatedObject(base, key.address) as! Value?
}
/// Set the associated value for the specified key.
///
/// - parameters:
/// - value: The value to be associated.
/// - key: The key.
internal func setValue<Value>(_ value: Value, forKey key: AssociationKey<Value>) {
objc_setAssociatedObject(base, key.address, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Set the associated value for the specified key.
///
/// - parameters:
/// - value: The value to be associated.
/// - key: The key.
internal func setValue<Value>(_ value: Value?, forKey key: AssociationKey<Value>) {
objc_setAssociatedObject(base, key.address, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Set the associated value for the specified key.
///
/// - parameters:
/// - value: The value to be associated.
/// - key: The key.
/// - address: The address of the object.
internal func unsafeSetAssociatedValue<Value>(_ value: Value?, forKey key: AssociationKey<Value>, forObjectAt address: UnsafeRawPointer) {
_rac_objc_setAssociatedObject(address, key.address, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
| mit | a66a313944e1a02553ce8ee1a73827e9 | 30.469697 | 138 | 0.678382 | 3.634296 | false | false | false | false |
ChernyshenkoTaras/TCPickerView | TCPickerView/Example/TCPickerView/DarkViewController.swift | 1 | 2714 | //
// CustomCellViewController.swift
// TCPickerViewExample
//
// Created by Taras Chernyshenko on 6/11/18.
// Copyright © 2018 Taras Chernyshenko. All rights reserved.
//
import UIKit
import TCPickerView
class DarkViewController: UIViewController, TCPickerViewOutput {
@IBOutlet private weak var avatarImageView: UIImageView!
private var filteredCars: [String] = []
private let theme = TCPickerViewDarkTheme()
@IBAction private func showButtonPressed(button: UIButton) {
let screenWidth: CGFloat = UIScreen.main.bounds.width
let width: CGFloat = screenWidth - 64
let height: CGFloat = 500
var picker: TCPickerViewInput = TCPickerView(size: CGSize(width: width, height: height))
picker.title = "Cars"
let cars = [
"Chevrolet Bolt EV",
"Subaru WRX",
"Porsche Panamera",
"BMW 330e",
"Chevrolet Volt",
"Ford C-Max Hybrid",
"Ford Focus"
]
filteredCars = cars
let values = cars.map { TCPickerView.Value(title: $0) }
picker.values = values
picker.theme = self.theme
picker.delegate = self
picker.selection = .multiply
picker.isSearchEnabled = true
picker.register(UINib(nibName: "ExampleTableViewCell", bundle: nil), forCellReuseIdentifier: "ExampleTableViewCell")
picker.completion = { [unowned self] selectedIndexes in
for i in selectedIndexes {
print(self.filteredCars[i])
}
}
picker.searchResult = { [unowned self] searchText in
self.filteredCars = cars.filter { $0.contains(searchText) }
let values = filteredCars.map { TCPickerView.Value(title: $0) }
picker.values = values
}
picker.show()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
//MARK: TCPickerViewDelegate methods
func pickerView(_ pickerView: TCPickerViewInput, didSelectRowAtIndex index: Int) {
print("User select row at index: \(index)")
}
func pickerView(_ pickerView: TCPickerViewInput,
cellForRowAt indexPath: IndexPath) -> (UITableViewCell & TCPickerCellType)? {
let cell = pickerView.dequeue(withIdentifier: "ExampleTableViewCell", for: indexPath) as! ExampleTableViewCell
cell.titleLabel?.textColor = self.theme.textColor
cell.checkmarkImageView?.image = UIImage(named: "checkmark_icon")?.withRenderingMode(.alwaysTemplate)
cell.checkmarkImageView?.tintColor = self.theme.textColor
cell.backgroundColor = self.theme.mainColor
return cell
}
}
| mit | bdd3465eda149300d94fe86cd5ef134c | 36.680556 | 124 | 0.647254 | 4.751313 | false | false | false | false |
jjb3rd/HttpBasicAuth | Sources/String+Extensions.swift | 1 | 2847 | //
// String+Extensions.swift
// HttpBasicAuth
//
// This source file is part of the HttpBasicAuth open source project
//
// Created by John Becker on 1/13/16.
// Copyright © 2016 Beckersoft. All rights reserved.
// Licensed under MIT License
//
// See LICENSE.txt for license information.
//
import Foundation
/// String extensions
internal extension String {
/**
Returns strings matching the regular expression pattern.
- Parameter pattern: The regular expression pattern.
- Returns: An array of matching strings.
*/
func regexMatches(pattern:String) -> [String] {
let regex = try! NSRegularExpression(pattern: pattern,
options:[.CaseInsensitive])
let textCheckingResults = regex.matchesInString(self,
options: [],
range: NSMakeRange(0, self.utf16.count))
var matches:[String] = []
for match in textCheckingResults {
for index in 0 ..< match.numberOfRanges {
if let range =
self.rangeFromNSRange(match.rangeAtIndex(index)) {
matches.append(self.substringWithRange(range))
}
}
}
return matches
}
/**
Converts NSRange to Range<String.Index>.
- Parameter nsRange: The NSRange in need of conversion.
- Returns: A Range<String.Index>? converted based on the string.
*/
func rangeFromNSRange(nsRange:NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location,
limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
/**
Base64 encodes strings using UTF8 string encoding by default.
- Parameter encoding: The encoding to be used. Defaults to UTF8.
- Returns: A base64 encoded string.
*/
func base64Encode(encoding:NSStringEncoding = NSUTF8StringEncoding)
-> String? {
if let encodedData = self.dataUsingEncoding(encoding) {
return encodedData.base64EncodedStringWithOptions([])
}
return nil
}
/**
Base64 decodes encoded strings using UTF8 string encoding by default.
- Parameter encoding: The encoding to be used. Defaults to UTF8.
- Returns: A regular string.
*/
func base64Decode(encoding:NSStringEncoding = NSUTF8StringEncoding)
-> String? {
if let data = NSData(base64EncodedString: self, options:[]) {
return String(data: data, encoding: encoding)
}
return nil
}
} | mit | 80f0590b89595c0e801b930436ffe1a1 | 28.968421 | 75 | 0.603654 | 4.791246 | false | false | false | false |
biohazardlover/ROer | Roer/MapRenderer.swift | 1 | 10643 |
import GLKit
import OpenGLES
import SDWebImage
import SwiftyJSON
extension GLKMatrix4 {
var mm: [GLfloat] {
return [m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33]
}
init(mm: [Float]) {
self.init(m: (mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8], mm[9], mm[10], mm[11], mm[12], mm[13], mm[14], mm[15]))
}
}
struct RSW {
var gt = [GLuint]()
var wt = [GLuint]()
var lightmap = GLuint()
var buffer = [[Float]]()
var water = [Float]()
var vertices = [Float]()
var indexes = [GLushort]()
var m = [RSM]()
}
struct RSM {
var m = M()
var p = [GLKMatrix4]()
var t = [GLuint]()
}
struct M {
var c = [M]()
var params = [(offset: Int, length: Int)]()
var r1 = GLKMatrix4()
var r2: GLKMatrix4?
var r3 = [GLKMatrix4]()
}
class MapRenderer: NSObject {
fileprivate var context: EAGLContext
fileprivate var size: CGSize
fileprivate var effect: MapEffect!
fileprivate var name: String!
weak var delegate: MapRendererDelegate?
init(context: EAGLContext, size: CGSize) {
self.context = context
self.size = size
super.init()
initGL()
}
// var now = Date.now
// ? function () { return Date.now(); }
// : function () { return +new Date; },
// filter = [].filter
// ? function (array, predicate) { return array.filter(predicate); }
// : function (array, predicate) { var result = []; for (var i = 0; i < array.length; i++) if (predicate(array[i])) result.push(array[i]); return result; };
//
// var raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
// setTimeout(callback, 1000 / 60);
// };
func xhr(_ name: String, _ onload: (JSON) -> Void) {
let path = documentDirectoryURL.appendingPathComponent("\(name)/\(name).txt")
let data = try! Data(contentsOf: path)
let json = JSON(data: data)
onload(json)
}
// function doat(count, action) {
// return function () {
// if (!--count)
// action();
// };
// }
func eachM(_ m: M, _ state: GLKMatrix4, _ function: (M, GLKMatrix4) -> GLKMatrix4) {
let state = function(m, state)
for i in m.c {
eachM(i, state, function)
}
}
//
// /** @type {{gt: !Array, m: !Array.<{m: !Array.<{v: !Array, f: !Array}>, t: !Array, p: !Array, a: !Array}>, t: !Array, p: !Array, wt: !Array, w: !number, h: !number, c: !Array, l: !number}} */
var rsw = RSW()
var isLoaded = false
var modelView = GLKMatrix4Identity
var fps: TimeInterval = 0
var lastFps: TimeInterval = 0
func drawRsw() {
if isLoaded == false {
return
}
let start = Date().timeIntervalSince1970
if (start < lastFps) {
fps = 1
} else {
fps += 1
}
lastFps = start
glClear(GLbitfield(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT))
glUniformMatrix4fv(effect.modelView, 1, GLboolean(GL_FALSE), modelView.mm)
for (i, buf) in rsw.buffer.enumerated() {
glBindTexture(GLenum(GL_TEXTURE_2D), rsw.gt[i])
glBufferData(GLenum(GL_ARRAY_BUFFER), buf.count * MemoryLayout<Float>.size, buf, GLenum(GL_STREAM_DRAW))
glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, GLsizei(buf.count / 7))
}
glBufferData(GLenum(GL_ARRAY_BUFFER), rsw.vertices.count * MemoryLayout<Float>.size, rsw.vertices, GLenum(GL_STATIC_DRAW))
glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), rsw.indexes.count * MemoryLayout<GLushort>.size, rsw.indexes, GLenum(GL_STATIC_DRAW))
for rsm in rsw.m {
eachM(rsm.m, GLKMatrix4Identity, { (mesh, matrix) -> GLKMatrix4 in
var matrix = matrix
if let r2 = mesh.r2 {
matrix = GLKMatrix4Multiply(matrix, r2)
} else if mesh.r3.count > 0 {
let exp = ~(~(mesh.r3.count * 1000 / 60))
let index = Int((start * 1000).truncatingRemainder(dividingBy: Double(exp)) / 1000 * 60) | 0
let r3 = mesh.r3[index]
matrix = GLKMatrix4Multiply(matrix, r3)
}
var transform = matrix
transform = GLKMatrix4Multiply(transform, mesh.r1);
glUniformMatrix4fv(self.effect.transform, 1, GLboolean(GL_FALSE), transform.mm)
for (k, param) in mesh.params.enumerated() {
glBindTexture(GLenum(GL_TEXTURE_2D), rsm.t[k])
for l in rsm.p {
glUniformMatrix4fv(self.effect.position, 1, GLboolean(GL_FALSE), l.mm)
glDrawElements(GLenum(GL_TRIANGLES), GLsizei(param.length), GLenum(GL_UNSIGNED_SHORT), self.bufferOffset(param.offset * MemoryLayout<GLushort>.size))
}
}
return matrix
})
}
glUniformMatrix4fv(effect.position, 1, GLboolean(GL_FALSE), GLKMatrix4Identity.mm)
glUniformMatrix4fv(effect.transform, 1, GLboolean(GL_FALSE), GLKMatrix4Identity.mm)
let step = Int((NSDate().timeIntervalSince1970 * 1000 / 100).truncatingRemainder(dividingBy: 32))
glUniform1f(effect.alpha, 0.85)
glUniform1i(effect.wavePhase, GLint(step * 20))
glEnable(GLenum(GL_BLEND))
glBindTexture(GLenum(GL_TEXTURE_2D), rsw.wt[step])
glBufferData(GLenum(GL_ARRAY_BUFFER), rsw.water.count * MemoryLayout<Float>.size, rsw.water, GLenum(GL_STREAM_DRAW))
glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, GLsizei(rsw.water.count / 7))
glDisable(GLenum(GL_BLEND))
glUniform1f(effect.alpha, 1.0)
glUniform1i(effect.wavePhase, -1)
}
func parseRsw(_ name: String, _ json: JSON) {
let parser = MapParser(mapName: name, json: json)
parser.parse()
rsw = parser.rsw
glActiveTexture(GLenum(GL_TEXTURE1))
glBindTexture(GLenum(GL_TEXTURE_2D), rsw.lightmap)
glActiveTexture(GLenum(GL_TEXTURE0))
isLoaded = true
}
var translation: (x: Float, y: Float) = (0, 0)
var angle: Float = 30
var rotate: Float = 0
var zoom: Float = 0.001
func updateModelView() {
modelView = GLKMatrix4Identity
modelView = GLKMatrix4Translate(modelView, translation.x, translation.y, -1)
modelView = GLKMatrix4RotateX(modelView, GLKMathDegreesToRadians(angle))
modelView = GLKMatrix4RotateY(modelView, GLKMathDegreesToRadians(rotate))
modelView = GLKMatrix4Scale(modelView, zoom, -zoom, -zoom)
}
func loadRsw(_ name: String) {
self.name = name
xhr(name) { (json) in
self.delegate?.mapRendererDidStartRendering(self)
self.parseRsw(name, json)
self.updateModelView()
self.delegate?.mapRendererDidFinishRendering(self)
}
}
var perspective = GLKMatrix4Identity
func initGL() {
effect = MapEffect()
effect.prepareToDraw()
var buffers: [GLuint] = [0, 0]
glGenBuffers(2, &buffers)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), buffers[0])
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), buffers[1])
glEnable(GLenum(GL_DEPTH_TEST))
glDepthFunc(GLenum(GL_LEQUAL))
glBlendFunc(GLenum(GL_SRC_ALPHA), GLenum(GL_ONE_MINUS_SRC_ALPHA))
glClearColor(0.0, 0.0, 0.0, 1.0)
glViewport(0, 0, GLsizei(size.width), GLsizei(size.height))
glActiveTexture(GLenum(GL_TEXTURE0))
perspective = GLKMatrix4MakePerspective(45, Float(size.width / size.height), 0.1, 100.0)
glUniformMatrix4fv(effect.perspective, 1, GLboolean(GL_FALSE), perspective.mm)
glUniformMatrix4fv(effect.position, 1, GLboolean(GL_FALSE), GLKMatrix4Identity.mm)
glUniformMatrix4fv(effect.transform, 1, GLboolean(GL_FALSE), GLKMatrix4Identity.mm)
glUniform1i(effect.sampler, 0)
glUniform1i(effect.lightmapSampler, 1)
glUniform1f(effect.alpha, 1.0)
glUniform1i(effect.wavePhase, -1)
}
func bufferOffset(_ offset: Int) -> UnsafeRawPointer {
let ptr: UnsafeRawPointer? = nil
return ptr! + offset
}
// var canvas, map, oncomplete = doat(2, function () {
// var lang = document.documentElement.lang == "ja" ? 1 : 2;
// loadRsw("hugel");
// var select = document.getElementById("select");
// map = filter(map, function (i) { return !!i[lang]; });
// map.sort(function (a, b) { return a[lang].localeCompare(b[lang]); });
// for (var i in map) {
// var option = document.createElement("option");
// option.value = map[i][0];
// option.innerHTML = map[i][lang];
// select.appendChild(option);
// }
// setupHandler(canvas, select);
// });
//
// xhr("romap/list.txt", function (result) {
// map = result;
// oncomplete();
// });
//
// document.addEventListener("DOMContentLoaded", function () {
// canvas = document.getElementById("canvas");
// initGL(canvas);
// oncomplete();
// }, false);
}
extension MapRenderer: GLKViewDelegate {
func glkView(_ view: GLKView, drawIn rect: CGRect) {
let positions = glGetAttribLocation(effect.programHandle, "positions")
glEnableVertexAttribArray(GLuint(positions))
glVertexAttribPointer(GLuint(positions), 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 28, bufferOffset(0))
let coords = glGetAttribLocation(effect.programHandle, "coords")
glEnableVertexAttribArray(GLuint(coords))
glVertexAttribPointer(GLuint(coords), 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 28, bufferOffset(12))
let lightmapCoords = glGetAttribLocation(effect.programHandle, "lightmapCoords")
glEnableVertexAttribArray(GLuint(lightmapCoords))
glVertexAttribPointer(GLuint(lightmapCoords), 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 28, bufferOffset(20))
drawRsw()
}
}
protocol MapRendererDelegate: NSObjectProtocol {
func mapRendererDidStartRendering(_ mapRenderer: MapRenderer)
func mapRendererDidFinishRendering(_ mapRenderer: MapRenderer)
}
| mit | 8f97c4b58d2892ca018865d3cae7154b | 35.954861 | 197 | 0.588744 | 3.730459 | false | false | false | false |
ytbryan/swiftknife | bin/swiftknife.swift | 1 | 32764 |
//
// Color.swift
// SwiftKnife
//
// Created by Bryan Lim on 6/23/14.
// Copyright (c) 2014 TADA. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
class func CGRGB(rgbValue:NSInteger) -> CGColorRef{
return UIColor(red: (CGFloat)((rgbValue & 0xFF0000) >> 16)/255.0,
green: (CGFloat)((rgbValue & 0xFF00) >> 8)/255.0,
blue: (CGFloat)((rgbValue & 0xFF))/255.0,
alpha: 1.0).CGColor
}
class func CGRGBA(rgbValue:NSInteger, alpha:CGFloat) -> CGColorRef{
return UIColor(red: (CGFloat)((rgbValue & 0xFF0000) >> 16)/255.0,
green: (CGFloat)((rgbValue & 0xFF00) >> 8)/255.0,
blue: (CGFloat)((rgbValue & 0xFF))/255.0,
alpha: ((alpha)/255.0)).CGColor
}
class func RGB(rgbValue:NSInteger) -> UIColor{
return UIColor(red: (CGFloat)((rgbValue & 0xFF0000) >> 16)/255.0,
green: (CGFloat)((rgbValue & 0xFF00) >> 8)/255.0,
blue: (CGFloat)((rgbValue & 0xFF))/255.0,
alpha: 1.0)
}
class func RGBA(rgbValue:NSInteger, alpha:CGFloat) -> UIColor{
return UIColor(red: (CGFloat)((rgbValue & 0xFF0000) >> 16)/255.0,
green: (CGFloat)((rgbValue & 0xFF00) >> 8)/255.0,
blue: (CGFloat)((rgbValue & 0xFF))/255.0,
alpha: ((alpha)/255.0))
}
//Additional colors
class var red: UIColor {
return RGB(0xE74C3C)
}
class var blue: UIColor {
return RGB(0x3498DB)
}
class var flatRed: UIColor{
return RGB(0xE74C3C)
}
class var flatDarkRed: UIColor{
return RGB(0xC0392B)
}
class var flatGreen: UIColor{
return RGB(0x2ECC71)
}
class var flatDarkGreen: UIColor{
return RGB(0x27AE60)
}
class var flatBlue: UIColor{
return RGB(0x3498DB)
}
class var flatDarkBlue: UIColor{
return RGB(0x2980B9)
}
class var flatTeal: UIColor{
return RGB(0x1ABC9C)
}
class var flatDarkTeal: UIColor{
return RGB(0x16A085)
}
class var flatPurple: UIColor{
return RGB(0x9B59B6)
}
class var flatDarkPurple: UIColor{
return RGB(0x8E44AD)
}
class var flatYellow: UIColor{
return RGB(0xF1C40F)
}
class var flatDarkYellow: UIColor{
return RGB(0xF39C12)
}
class var flatOrange: UIColor{
return RGB(0xE67E22)
}
class var flatDarkOrange: UIColor{
return RGB(0xD35400)
}
class var flatGray: UIColor{
return RGB(0x95A5A6)
}
class var flatDarkGray: UIColor{
return RGB(0x7F8C8D)
}
class var flatWhite: UIColor{
return RGB(0xECF0F1)
}
class var flatDarkWhite: UIColor{
return RGB(0xBDC3C7)
}
class var flatBlack: UIColor{
return RGB(0x34495E)
}
class var flatDarkBlack: UIColor{
return RGB(0x2C3E50)
}
//CGColor
class var CGRed: CGColorRef {
return RGB(0xE74C3C).CGColor
}
class var CGBlue: CGColorRef {
return RGB(0x3498DB).CGColor
}
class var CGFlatRed: CGColorRef{
return RGB(0xE74C3C).CGColor
}
class var CGFlatDarkRed: CGColorRef{
return RGB(0xC0392B).CGColor
}
class var CGFlatGreen: CGColorRef{
return RGB(0x2ECC71).CGColor
}
class var CGFlatDarkGreen: CGColorRef{
return RGB(0x27AE60).CGColor
}
class var CGFlatBlue: CGColorRef{
return RGB(0x3498DB).CGColor
}
class var CGFlatDarkBlue: CGColorRef{
return RGB(0x2980B9).CGColor
}
class var CGFlatTeal: CGColorRef{
return RGB(0x1ABC9C).CGColor
}
class var CGFlatDarkTeal: CGColorRef{
return RGB(0x16A085).CGColor
}
class var CGFlatPurple: CGColorRef{
return RGB(0x9B59B6).CGColor
}
class var CGFlatDarkPurple: CGColorRef{
return RGB(0x8E44AD).CGColor
}
class var CGFlatYellow: CGColorRef{
return RGB(0xF1C40F).CGColor
}
class var CGFlatDarkYellow: CGColorRef{
return RGB(0xF39C12).CGColor
}
class var CGFlatOrange: CGColorRef{
return RGB(0xE67E22).CGColor
}
class var CGFlatDarkOrange: CGColorRef{
return RGB(0xD35400).CGColor
}
class var CGFlatGray: CGColorRef{
return RGB(0x95A5A6).CGColor
}
class var CGFlatDarkGray: CGColorRef{
return RGB(0x7F8C8D).CGColor
}
class var CGFlatWhite: CGColorRef{
return RGB(0xECF0F1).CGColor
}
class var CGFlatDarkWhite: CGColorRef{
return RGB(0xBDC3C7).CGColor
}
class var CGFlatBlack: CGColorRef{
return RGB(0x34495E).CGColor
}
class var CGFlatDarkBlack: CGColorRef{
return RGB(0x2C3E50).CGColor
}
}
//
// MaterialColor.swift
// Colors
//
// Created by Bryan Lim on 10/5/14.
// Copyright (c) 2014 TADA. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
// Google's Material Design UI Color Palette:
// http://www.google.com/design/spec/style/color.html#color-ui-color- palette
//RED
class var red50: UIColor {
return RGB(0xfde0dc)
}
class var red100: UIColor {
return RGB(0xf9bdbb)
}
class var red200: UIColor {
return RGB(0xf69988)
}
class var red300: UIColor {
return RGB(0xf36c60)
}
class var red400: UIColor {
return RGB(0xe84e40)
}
class var red500: UIColor {
return RGB(0xe51c23)
}
class var red600: UIColor {
return RGB(0xdd191d)
}
class var red700: UIColor {
return RGB(0xd01716)
}
class var red800: UIColor {
return RGB(0xc41411)
}
class var red900: UIColor {
return RGB(0xb0120a)
}
class var redA100: UIColor {
return RGB(0xff7997)
}
class var redA200: UIColor {
return RGB(0xff5177)
}
class var redA400: UIColor {
return RGB(0xff2d6f)
}
class var redA700: UIColor {
return RGB(0xe00032)
}
class var CGRed50: CGColorRef {
return RGB(0xfde0dc).CGColor
}
class var CGRed100: CGColorRef {
return RGB(0xf9bdbb).CGColor
}
class var CGRed200: CGColorRef {
return RGB(0xf69988).CGColor
}
class var CGRed300: CGColorRef {
return RGB(0xf36c60).CGColor
}
class var CGRed400: CGColorRef {
return RGB(0xe84e40).CGColor
}
class var CGRed500: CGColorRef {
return RGB(0xe51c23).CGColor
}
class var CGRed600: CGColorRef {
return RGB(0xdd191d).CGColor
}
class var CGRed700: CGColorRef {
return RGB(0xd01716).CGColor
}
class var CGRed800: CGColorRef {
return RGB(0xc41411).CGColor
}
class var CGRed900: CGColorRef {
return RGB(0xb0120a).CGColor
}
class var CGRedA100: CGColorRef {
return RGB(0xff7997).CGColor
}
class var CGRedA200: CGColorRef {
return RGB(0xff5177).CGColor
}
class var CGRedA400: CGColorRef {
return RGB(0xff2d6f).CGColor
}
class var CGRedA700: CGColorRef {
return RGB(0xe00032).CGColor
}
//orange
class var pink50: UIColor {
return RGB(0xfce4ec)
}
class var pink100: UIColor {
return RGB(0xf8bbd0)
}
class var pink200: UIColor {
return RGB(0xf48fb1)
}
class var pink300: UIColor {
return RGB(0xf06292)
}
class var pink400: UIColor {
return RGB(0xec407a)
}
class var pink500: UIColor {
return RGB(0xe91e63)
}
class var pink600: UIColor {
return RGB(0xd81b60)
}
class var pink700: UIColor {
return RGB(0xc2185b)
}
class var pink800: UIColor {
return RGB(0xad1457)
}
class var pink900: UIColor {
return RGB(0x880e4f)
}
class var pinkA100: UIColor {
return RGB(0xff80ab)
}
class var pinkA200: UIColor {
return RGB(0xff4081)
}
class var pinkA400: UIColor {
return RGB(0xff2d6f)
}
class var pinkA700: UIColor {
return RGB(0xe00032)
}
//Purple
class var purple50: UIColor {
return RGB(0xfde0dc)
}
class var purple100: UIColor {
return RGB(0xf9bdbb)
}
class var purple200: UIColor {
return RGB(0xf69988)
}
class var purple300: UIColor {
return RGB(0xf36c60)
}
class var purple400: UIColor {
return RGB(0xe84e40)
}
class var purple500: UIColor {
return RGB(0xe51c23)
}
class var purple600: UIColor {
return RGB(0xdd191d)
}
class var purple700: UIColor {
return RGB(0xd01716)
}
class var purple800: UIColor {
return RGB(0xc41411)
}
class var purple900: UIColor {
return RGB(0xb0120a)
}
class var purpleA100: UIColor {
return RGB(0xff7997)
}
class var purpleA200: UIColor {
return RGB(0xff5177)
}
class var purpleA400: UIColor {
return RGB(0xff2d6f)
}
class var purpleA700: UIColor {
return RGB(0xe00032)
}
//Deep Purple
class var deepPurple50: UIColor {
return RGB(0xfde0dc)
}
class var deepPurple100: UIColor {
return RGB(0xf9bdbb)
}
class var deepPurple200: UIColor {
return RGB(0xf69988)
}
class var deepPurple300: UIColor {
return RGB(0xf36c60)
}
class var deepPurple400: UIColor {
return RGB(0xe84e40)
}
class var deepPurple500: UIColor {
return RGB(0xe51c23)
}
class var deepPurple600: UIColor {
return RGB(0xdd191d)
}
class var deepPurple700: UIColor {
return RGB(0xd01716)
}
class var deepPurple800: UIColor {
return RGB(0xc41411)
}
class var deepPurple900: UIColor {
return RGB(0xb0120a)
}
class var deepPurpleA100: UIColor {
return RGB(0xff7997)
}
class var deepPurpleA200: UIColor {
return RGB(0xff5177)
}
class var deepPurpleA400: UIColor {
return RGB(0xff2d6f)
}
class var deepPurpleA700: UIColor {
return RGB(0xe00032)
}
//Indigo
class var indigo50: UIColor {
return RGB(0xfde0dc)
}
class var indigo100: UIColor {
return RGB(0xf9bdbb)
}
class var indigo200: UIColor {
return RGB(0xf69988)
}
class var indigo300: UIColor {
return RGB(0xf36c60)
}
class var indigo400: UIColor {
return RGB(0xe84e40)
}
class var indigo500: UIColor {
return RGB(0xe51c23)
}
class var indigo600: UIColor {
return RGB(0xdd191d)
}
class var indigo700: UIColor {
return RGB(0xd01716)
}
class var indigo800: UIColor {
return RGB(0xc41411)
}
class var indigo900: UIColor {
return RGB(0xb0120a)
}
class var indigoA100: UIColor {
return RGB(0xff7997)
}
class var indigoA200: UIColor {
return RGB(0xff5177)
}
class var indigoA400: UIColor {
return RGB(0xff2d6f)
}
class var indigoA700: UIColor {
return RGB(0xe00032)
}
//Pink
class var blue50: UIColor {
return RGB(0xfde0dc)
}
class var blue100: UIColor {
return RGB(0xf9bdbb)
}
class var blue200: UIColor {
return RGB(0xf69988)
}
class var blue300: UIColor {
return RGB(0xf36c60)
}
class var blue400: UIColor {
return RGB(0xe84e40)
}
class var blue500: UIColor {
return RGB(0xe51c23)
}
class var blue600: UIColor {
return RGB(0xdd191d)
}
class var blue700: UIColor {
return RGB(0xd01716)
}
class var blue800: UIColor {
return RGB(0xc41411)
}
class var blue900: UIColor {
return RGB(0xb0120a)
}
class var blueA100: UIColor {
return RGB(0xff7997)
}
class var blueA200: UIColor {
return RGB(0xff5177)
}
class var blueA400: UIColor {
return RGB(0xff2d6f)
}
class var blueA700: UIColor {
return RGB(0xe00032)
}
//light blue
class var lightBlue50: UIColor {
return RGB(0xfde0dc)
}
class var lightBlue100: UIColor {
return RGB(0xf9bdbb)
}
class var lightBlue200: UIColor {
return RGB(0xf69988)
}
class var lightBlue300: UIColor {
return RGB(0xf36c60)
}
class var lightBlue400: UIColor {
return RGB(0xe84e40)
}
class var lightBlue500: UIColor {
return RGB(0xe51c23)
}
class var lightBlue600: UIColor {
return RGB(0xdd191d)
}
class var lightBlue700: UIColor {
return RGB(0xd01716)
}
class var lightBlue800: UIColor {
return RGB(0xc41411)
}
class var lightBlue900: UIColor {
return RGB(0xb0120a)
}
class var lightBlueA100: UIColor {
return RGB(0xff7997)
}
class var lightBlueA200: UIColor {
return RGB(0xff5177)
}
class var lightBlueA400: UIColor {
return RGB(0xff2d6f)
}
class var lightBlueA700: UIColor {
return RGB(0xe00032)
}
//cyan
class var cyan50: UIColor {
return RGB(0xfde0dc)
}
class var cyan100: UIColor {
return RGB(0xf9bdbb)
}
class var cyan200: UIColor {
return RGB(0xf69988)
}
class var cyan300: UIColor {
return RGB(0xf36c60)
}
class var cyan400: UIColor {
return RGB(0xe84e40)
}
class var cyan500: UIColor {
return RGB(0xe51c23)
}
class var cyan600: UIColor {
return RGB(0xdd191d)
}
class var cyan700: UIColor {
return RGB(0xd01716)
}
class var cyan800: UIColor {
return RGB(0xc41411)
}
class var cyan900: UIColor {
return RGB(0xb0120a)
}
class var cyanA100: UIColor {
return RGB(0xff7997)
}
class var cyanA200: UIColor {
return RGB(0xff5177)
}
class var cyanA400: UIColor {
return RGB(0xff2d6f)
}
class var cyanA700: UIColor {
return RGB(0xe00032)
}
//Teal
class var teal50: UIColor {
return RGB(0xfde0dc)
}
class var teal100: UIColor {
return RGB(0xf9bdbb)
}
class var teal200: UIColor {
return RGB(0xf69988)
}
class var teal300: UIColor {
return RGB(0xf36c60)
}
class var teal400: UIColor {
return RGB(0xe84e40)
}
class var teal500: UIColor {
return RGB(0xe51c23)
}
class var teal600: UIColor {
return RGB(0xdd191d)
}
class var teal700: UIColor {
return RGB(0xd01716)
}
class var teal800: UIColor {
return RGB(0xc41411)
}
class var teal900: UIColor {
return RGB(0xb0120a)
}
class var tealA100: UIColor {
return RGB(0xff7997)
}
class var tealA200: UIColor {
return RGB(0xff5177)
}
class var tealA400: UIColor {
return RGB(0xff2d6f)
}
class var tealA700: UIColor {
return RGB(0xe00032)
}
//Green
//Pink
class var green50: UIColor {
return RGB(0xfde0dc)
}
class var green100: UIColor {
return RGB(0xf9bdbb)
}
class var green200: UIColor {
return RGB(0xf69988)
}
class var green300: UIColor {
return RGB(0xf36c60)
}
class var green400: UIColor {
return RGB(0xe84e40)
}
class var green500: UIColor {
return RGB(0xe51c23)
}
class var green600: UIColor {
return RGB(0xdd191d)
}
class var green700: UIColor {
return RGB(0xd01716)
}
class var green800: UIColor {
return RGB(0xc41411)
}
class var green900: UIColor {
return RGB(0xb0120a)
}
class var greenA100: UIColor {
return RGB(0xff7997)
}
class var greenA200: UIColor {
return RGB(0xff5177)
}
class var greenA400: UIColor {
return RGB(0xff2d6f)
}
class var greenA700: UIColor {
return RGB(0xe00032)
}
//Pink
class var lightGreen50: UIColor {
return RGB(0xfde0dc)
}
class var lightGreen100: UIColor {
return RGB(0xf9bdbb)
}
class var lightGreen200: UIColor {
return RGB(0xf69988)
}
class var lightGreen300: UIColor {
return RGB(0xf36c60)
}
class var lightGreen400: UIColor {
return RGB(0xe84e40)
}
class var lightGreen500: UIColor {
return RGB(0xe51c23)
}
class var lightGreen600: UIColor {
return RGB(0xdd191d)
}
class var lightGreen700: UIColor {
return RGB(0xd01716)
}
class var lightGreen800: UIColor {
return RGB(0xc41411)
}
class var lightGreen900: UIColor {
return RGB(0xb0120a)
}
class var lightGreenA100: UIColor {
return RGB(0xff7997)
}
class var lightGreenA200: UIColor {
return RGB(0xff5177)
}
class var lightGreenA400: UIColor {
return RGB(0xff2d6f)
}
class var lightGreenA700: UIColor {
return RGB(0xe00032)
}
//lime
class var lime50: UIColor {
return RGB(0xfde0dc)
}
class var lime100: UIColor {
return RGB(0xf9bdbb)
}
class var lime200: UIColor {
return RGB(0xf69988)
}
class var lime300: UIColor {
return RGB(0xf36c60)
}
class var lime400: UIColor {
return RGB(0xe84e40)
}
class var lime500: UIColor {
return RGB(0xe51c23)
}
class var lime600: UIColor {
return RGB(0xdd191d)
}
class var lime700: UIColor {
return RGB(0xd01716)
}
class var lime800: UIColor {
return RGB(0xc41411)
}
class var lime900: UIColor {
return RGB(0xb0120a)
}
class var limeA100: UIColor {
return RGB(0xff7997)
}
class var limeA200: UIColor {
return RGB(0xff5177)
}
class var limeA400: UIColor {
return RGB(0xff2d6f)
}
class var limeA700: UIColor {
return RGB(0xe00032)
}
//yellow
class var yellow50: UIColor {
return RGB(0xfde0dc)
}
class var yellow100: UIColor {
return RGB(0xf9bdbb)
}
class var yellow200: UIColor {
return RGB(0xf69988)
}
class var yellow300: UIColor {
return RGB(0xf36c60)
}
class var yellow400: UIColor {
return RGB(0xe84e40)
}
class var yellow500: UIColor {
return RGB(0xe51c23)
}
class var yellow600: UIColor {
return RGB(0xdd191d)
}
class var yellow700: UIColor {
return RGB(0xd01716)
}
class var yellow800: UIColor {
return RGB(0xc41411)
}
class var yellow900: UIColor {
return RGB(0xb0120a)
}
class var yellowA100: UIColor {
return RGB(0xff7997)
}
class var yellowA200: UIColor {
return RGB(0xff5177)
}
class var yellowA400: UIColor {
return RGB(0xff2d6f)
}
class var yellowA700: UIColor {
return RGB(0xe00032)
}
//amber
class var amber50: UIColor {
return RGB(0xfde0dc)
}
class var amber100: UIColor {
return RGB(0xf9bdbb)
}
class var amber200: UIColor {
return RGB(0xf69988)
}
class var amber300: UIColor {
return RGB(0xf36c60)
}
class var amber400: UIColor {
return RGB(0xe84e40)
}
class var amber500: UIColor {
return RGB(0xe51c23)
}
class var amber600: UIColor {
return RGB(0xdd191d)
}
class var amber700: UIColor {
return RGB(0xd01716)
}
class var amber800: UIColor {
return RGB(0xc41411)
}
class var amber900: UIColor {
return RGB(0xb0120a)
}
class var amberA100: UIColor {
return RGB(0xff7997)
}
class var amberA200: UIColor {
return RGB(0xff5177)
}
class var amberA400: UIColor {
return RGB(0xff2d6f)
}
class var amberA700: UIColor {
return RGB(0xe00032)
}
//orange
class var orange50: UIColor {
return RGB(0xfde0dc)
}
class var orange100: UIColor {
return RGB(0xf9bdbb)
}
class var orange200: UIColor {
return RGB(0xf69988)
}
class var orange300: UIColor {
return RGB(0xf36c60)
}
class var orange400: UIColor {
return RGB(0xe84e40)
}
class var orange500: UIColor {
return RGB(0xe51c23)
}
class var orange600: UIColor {
return RGB(0xdd191d)
}
class var orange700: UIColor {
return RGB(0xd01716)
}
class var orange800: UIColor {
return RGB(0xc41411)
}
class var orange900: UIColor {
return RGB(0xb0120a)
}
class var orangeA100: UIColor {
return RGB(0xff7997)
}
class var orangeA200: UIColor {
return RGB(0xff5177)
}
class var orangeA400: UIColor {
return RGB(0xff2d6f)
}
class var orangeA700: UIColor {
return RGB(0xe00032)
}
//deepOrange
class var deepOrange50: UIColor {
return RGB(0xfde0dc)
}
class var deepOrange100: UIColor {
return RGB(0xf9bdbb)
}
class var deepOrange200: UIColor {
return RGB(0xf69988)
}
class var deepOrange300: UIColor {
return RGB(0xf36c60)
}
class var deepOrange400: UIColor {
return RGB(0xe84e40)
}
class var deepOrange500: UIColor {
return RGB(0xe51c23)
}
class var deepOrange600: UIColor {
return RGB(0xdd191d)
}
class var deepOrange700: UIColor {
return RGB(0xd01716)
}
class var deepOrange800: UIColor {
return RGB(0xc41411)
}
class var deepOrange900: UIColor {
return RGB(0xb0120a)
}
class var deepOrangeA100: UIColor {
return RGB(0xff7997)
}
class var deepOrangeA200: UIColor {
return RGB(0xff5177)
}
class var deepOrangeA400: UIColor {
return RGB(0xff2d6f)
}
class var deepOrangeA700: UIColor {
return RGB(0xe00032)
}
//brown
class var brown50: UIColor {
return RGB(0xfde0dc)
}
class var brown100: UIColor {
return RGB(0xf9bdbb)
}
class var brown200: UIColor {
return RGB(0xf69988)
}
class var brown300: UIColor {
return RGB(0xf36c60)
}
class var brown400: UIColor {
return RGB(0xe84e40)
}
class var brown500: UIColor {
return RGB(0xe51c23)
}
class var brown600: UIColor {
return RGB(0xdd191d)
}
class var brown700: UIColor {
return RGB(0xd01716)
}
class var brown800: UIColor {
return RGB(0xc41411)
}
class var brown900: UIColor {
return RGB(0xb0120a)
}
class var brownA100: UIColor {
return RGB(0xff7997)
}
class var brownA200: UIColor {
return RGB(0xff5177)
}
class var brownA400: UIColor {
return RGB(0xff2d6f)
}
class var brownA700: UIColor {
return RGB(0xe00032)
}
//grey
class var grey50: UIColor {
return RGB(0xfde0dc)
}
class var grey100: UIColor {
return RGB(0xf9bdbb)
}
class var grey200: UIColor {
return RGB(0xf69988)
}
class var grey300: UIColor {
return RGB(0xf36c60)
}
class var grey400: UIColor {
return RGB(0xe84e40)
}
class var grey500: UIColor {
return RGB(0xe51c23)
}
class var grey600: UIColor {
return RGB(0xdd191d)
}
class var grey700: UIColor {
return RGB(0xd01716)
}
class var grey800: UIColor {
return RGB(0xc41411)
}
class var grey900: UIColor {
return RGB(0xb0120a)
}
class var greyA100: UIColor {
return RGB(0xff7997)
}
class var greyA200: UIColor {
return RGB(0xff5177)
}
class var greyA400: UIColor {
return RGB(0xff2d6f)
}
class var greyA700: UIColor {
return RGB(0xe00032)
}
//blueGrey
class var blueGrey50: UIColor {
return RGB(0xfde0dc)
}
class var blueGrey100: UIColor {
return RGB(0xf9bdbb)
}
class var blueGrey200: UIColor {
return RGB(0xf69988)
}
class var blueGrey300: UIColor {
return RGB(0xf36c60)
}
class var blueGrey400: UIColor {
return RGB(0xe84e40)
}
class var blueGrey500: UIColor {
return RGB(0xe51c23)
}
class var blueGrey600: UIColor {
return RGB(0xdd191d)
}
class var blueGrey700: UIColor {
return RGB(0xd01716)
}
class var blueGrey800: UIColor {
return RGB(0xc41411)
}
class var blueGrey900: UIColor {
return RGB(0xb0120a)
}
class var blueGreyA100: UIColor {
return RGB(0xff7997)
}
class var blueGreyA200: UIColor {
return RGB(0xff5177)
}
class var blueGreyA400: UIColor {
return RGB(0xff2d6f)
}
class var blueGreyA700: UIColor {
return RGB(0xe00032)
}
}
//
// String.swift
// Swifeknife
//
// Created by Bryan Lim on 6/20/14.
// Copyright (c) 2014 TADA. All rights reserved.
//
import Foundation
extension String {
var array: [Character] {
get { return Array(self) }
}
var length: Int {
get { return countElements(self) }
}
var size: Int {
get { return countElements(self) }
}
func upper() -> String? {
if self.isEmpty { return nil }
return self.uppercaseString
}
func lower() -> String? {
if self.isEmpty { return nil }
return self.lowercaseString
}
func toArray() -> [Character] {
return Array(self)
}
//beta 5
// func substring(value:Int) -> String {
//
//
//
// return self.substringFromIndex(value)
//// return self.bridgeToObjectiveC().substringFromIndex(value)
// }
func print() {
for eachChar in self {
println(eachChar)
}
}
//beta 5
// func indexOf(index:String) -> NSRange {
// return self.rangeOfString(index, options: nil, range: nil, locale: nil)
//// return self.bridgeToObjectiveC().rangeOfString(index)
// }
func first() -> String? {
if(self.isEmpty) {return nil}
return String(Array(self)[0])
}
func last() -> String? {
if(self.isEmpty) {return nil}
return String(Array(self)[self.length-1])
}
subscript (i: Int) -> String?{
if(self.isEmpty) {return nil}
return String(Array(self)[i])
}
}
//
// swiftknife.swift
// swiftknife
//
// Created by ytbryan and Koh Poh Chiat on 6/10/14.
// Copyright (c) 2014 TADA. All rights reserved.
//
import Foundation
import UIKit
class swiftknife {
init(){
}
}
var _file = __FILE__
var _line = __LINE__
var _col = __COLUMN__
var _func = __FUNCTION__
extension CALayer {
class func mark(element:AnyObject, width:CGFloat, color: CGColorRef) -> AnyObject{
//element.layer.borderWidth
//element.layer.borderColor
element.layer.borderColor = color
element.layer.borderWidth = width
return element
}
}
//bring back yes and no
let NO = false
let YES = true
class S: swiftknife {
override init(){
}
class var sharedInstance: S {
struct Singleton {
static let instance = S()
}
return Singleton.instance
}
//root url for HTTPClient
// var root_url = ""
// var rootURL:String {
// get {return self.root_url}
// set(input) { self.root_url = input}
// }
}
class Device {
class var height:CGFloat{
return UIScreen.mainScreen().bounds.height
}
class var width:CGFloat {
return UIScreen.mainScreen().bounds.width
}
class func bottomBy(value:CGFloat)->CGFloat{
return UIScreen.mainScreen().bounds.height - value
}
class func rightBy(value:CGFloat)->CGFloat{
return UIScreen.mainScreen().bounds.width - value
}
class func centerIt(value:CGFloat) -> CGFloat {
puts(UIScreen.mainScreen().bounds.width/2)
return (UIScreen.mainScreen().bounds.width/2 - value/2)
}
}
extension Int {
func times(task: () -> ()) {
for i in 0..<self {
task()
}
}
}
extension UIDevice { }
extension UIScreen {
//access the current width and height of the screen
var info:CGRect{
get { return UIScreen.mainScreen().bounds }
}
//get phone orientation
class func getOrientation() {
}
}
extension S {
//according to https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIDevice_Class/index.html#//apple_ref/occ/instp/UIDevice/systemName
//commenting out because UIDevice is possibly not ready in this version of swift or xcode?
// var name: String {
// get {return UIDevice.name}
// }
//
// var system: String {
// get {return UIDevice.systemName}
// }
//
// var version: String {
// get {return UIDevice.systemVersion}
// }
//
// var model: String {
// get {return UIDevice.model}
// }
//
// var orientation: UIDeviceOrientation {
// get { return UIDevice.orientation }
// }
//
// var battery: UIDeviceOrientation {
// get { return UIDevice.batteryLevel }
// }
}
extension S {
class func inspect<T>(element: T, _ file:String=__FILE__, _ column:Int=__COLUMN__, line:Int=__LINE__, function:String=__FUNCTION__) -> T {
println("\(element) -- line:\(line),col:\(column), name:\(function) -- \(file)")
return element
}
class func p <T>(value: T){
println(value)
}
class func puts <T>(value: T){
println(value)
}
class func show() {
//show a toast
}
}
// testing extension
extension S {
class func assert(expression: @autoclosure () -> BooleanType, message: String, toAssert: Bool = true) {
// XCTAssertEquals(expression: expression, message: message)
}
}
func inspect<T>(element: T, _ file:String=__FILE__, _ column:Int=__COLUMN__, line:Int=__LINE__, function:String=__FUNCTION__) -> T {
println("\(element) -- line:\(line),col:\(column), name:\(function) -- \(file)")
return element
}
func p<T>(element: T) {
println(element)
}
func puts<T>(element: T) {
println(element)
}
func log<T>(element: T) {
println(element)
}
func rect(x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat) -> CGRect{
return CGRectMake(x, y, width, height)
}
func rect(x:CGFloat,y:CGFloat,square:CGFloat) -> CGRect {
return CGRectMake(x, y, square, square)
}
func rect(xy:CGFloat,square:CGFloat) -> CGRect {
return CGRectMake(xy, xy, square, square)
}
func mark(element:AnyObject, width:CGFloat, color: CGColorRef) -> AnyObject{
element.layer.borderColor = color
element.layer.borderWidth = width
return element
}
func dialog(t:String, msg:String, viewController: UIViewController) {
var alert = UIAlertController(title: t, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) in
println("Dismiss")
}))
viewController.presentViewController(alert, animated: true, completion: nil)
}
func show(t:String, msg:String, viewController: UIViewController) {
var alert = UIAlertController(title: t, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) in
println("OK")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
println("Dismiss")
}))
viewController.presentViewController(alert, animated: true, completion: nil)
}
func sheet<T:UIActionSheetDelegate>(t:String, cancel:String, destruct:String, other: String, vc: T, vc2:UIViewController, more: String...) {
let actionSheet = UIActionSheet(title: t,
delegate: vc,
cancelButtonTitle: cancel,
destructiveButtonTitle: destruct,
otherButtonTitles: other)
actionSheet.showInView(vc2.view)
}
| mit | 79112a46db3ceaedd784167ed029917d | 18.398461 | 167 | 0.591015 | 3.651399 | false | false | false | false |
seungprk/PenguinJump | PenguinJump/PenguinJump/SettingsScene.swift | 1 | 9430 | //
// SettingsScene.swift
// PenguinJump
//
// Created by Seung Park on 6/6/16.
// Copyright © 2016 De Anza. All rights reserved.
//
import SpriteKit
import CoreData
import AVFoundation
class SettingsScene: SKScene {
var managedObjectContext : NSManagedObjectContext!
var fetchRequest : NSFetchRequest!
var gameData : GameData!
var fetchedData = [GameData]()
var musicButton : SimpleButton!
var soundsButton : SimpleButton!
var backButton : SimpleButton!
var backgroundMusic: AVAudioPlayer?
var backgroundOcean: AVAudioPlayer?
override func didMoveToView(view: SKView) {
backgroundColor = SKColor(red: 220/255, green: 230/255, blue: 236/255, alpha: 1.0)
// Fetch Data
managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
fetchRequest = NSFetchRequest(entityName: "GameData")
do {
fetchedData = try managedObjectContext.executeFetchRequest(fetchRequest) as! [GameData]
} catch {
print(error)
}
gameData = fetchedData.first
// Build Interface
let logo = SKSpriteNode(texture: SKTexture(image: UIImage(named: "logo")!))
logo.name = "logo"
logo.alpha = 0.2
logo.position = CGPoint(x: size.width/2, y: size.height/2)
logo.zPosition = -100
addChild(logo)
let musicLabel = SKLabelNode(text: "Music")
musicLabel.fontName = "Helvetica Neue Condensed Black"
musicLabel.fontSize = 24
musicLabel.position = CGPoint(x: size.width * 0.5 - 45, y: size.height * 0.55)
musicLabel.fontColor = SKColor(red: 35/255, green: 134/255, blue: 221/255, alpha: 1.0)
musicLabel.zPosition = 100
addChild(musicLabel)
if gameData.musicOn == true {
musicButton = SimpleButton(text: "On")
} else {
musicButton = SimpleButton(text: "Off")
}
musicButton.name = "musicButton"
musicButton.position = musicLabel.position
musicButton.position.x += 100
addChild(musicButton)
let soundsLabel = SKLabelNode(text: "Sounds")
soundsLabel.fontName = "Helvetica Neue Condensed Black"
soundsLabel.fontSize = 24
soundsLabel.position = CGPoint(x: size.width * 0.5 - 45, y: size.height * 0.45)
soundsLabel.fontColor = SKColor(red: 35/255, green: 134/255, blue: 221/255, alpha: 1.0)
soundsLabel.zPosition = 100
addChild(soundsLabel)
if gameData.soundEffectsOn == true {
soundsButton = SimpleButton(text: "On")
} else {
soundsButton = SimpleButton(text: "Off")
}
soundsButton.name = "soundsButton"
soundsButton.position = soundsLabel.position
soundsButton.position.x += 100
addChild(soundsButton)
backButton = SimpleButton(text: "Back")
backButton.name = "backButton"
backButton.position = CGPoint(x: CGRectGetMidX(view.frame), y: CGRectGetMidY(view.frame))
backButton.position.y -= 200
addChild(backButton)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let positionInScene = touch.locationInNode(self)
let touchedNodes = self.nodesAtPoint(positionInScene)
for touchedNode in touchedNodes {
if touchedNode.name == "musicButton" {
musicButton.buttonPress(gameData.soundEffectsOn)
}
if touchedNode.name == "soundsButton" {
soundsButton.buttonPress(gameData.soundEffectsOn)
}
if touchedNode.name == "backButton" {
backButton.buttonPress(gameData.soundEffectsOn)
}
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let positionInScene = touch.locationInNode(self)
let touchedNodes = self.nodesAtPoint(positionInScene)
for touchedNode in touchedNodes {
if touchedNode.name == "musicButton" && musicButton.pressed == true {
if gameData.musicOn == true {
fadeMusic()
gameData.musicOn = false
gameData.musicPlaying = false
do { try managedObjectContext.save() } catch { print(error) }
musicButton.label.text = "Off"
} else if gameData.musicOn == false {
playMusic()
gameData.musicOn = true
gameData.musicPlaying = true
do { try managedObjectContext.save() } catch { print(error) }
musicButton.label.text = "On"
}
musicButton.buttonRelease()
}
if touchedNode.name == "soundsButton" && soundsButton.pressed == true {
if gameData.soundEffectsOn == true {
gameData.soundEffectsOn = false
soundsButton.label.text = "Off"
} else {
gameData.soundEffectsOn = true
soundsButton.label.text = "On"
}
soundsButton.buttonRelease()
}
if (touchedNode.name == "backButton" && backButton.pressed == true) {
backButton.buttonRelease()
saveSettings()
// Present Main Game Scene
let gameScene = GameScene(size: self.size)
gameScene.backgroundMusic = backgroundMusic
gameScene.musicInitialized = true
let transition = SKTransition.pushWithDirection(.Up, duration: 0.5)
gameScene.scaleMode = SKSceneScaleMode.AspectFill
self.scene!.view?.presentScene(gameScene, transition: transition)
}
}
}
musicButton.buttonRelease()
soundsButton.buttonRelease()
backButton.buttonRelease()
}
func saveSettings() {
if gameData != nil {
do {
try managedObjectContext.save()
} catch {
print(error)
}
}
}
func playMusic() {
if gameData.musicOn == false && gameData.musicPlaying == false {
if let backgroundMusic = backgroundMusic {
backgroundMusic.volume = 0.0
backgroundMusic.numberOfLoops = -1 // Negative integer to loop indefinitely
backgroundMusic.play()
fadeAudioPlayer(backgroundMusic, fadeTo: 0.5, duration: 1, completion: nil)
}
}
}
func fadeMusic() {
if gameData.musicOn == true {
fadeAudioPlayer(backgroundMusic!, fadeTo: 0.0, duration: 1.0, completion: {() in
self.backgroundMusic?.stop()
})
}
}
// MARK: - Audio
func audioPlayerWithFile(file: String, type: String) -> AVAudioPlayer? {
let path = NSBundle.mainBundle().pathForResource(file, ofType: type)
let url = NSURL.fileURLWithPath(path!)
var audioPlayer: AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Audio player not available")
}
return audioPlayer
}
func fadeVolumeDown(player: AVAudioPlayer) {
player.volume -= 0.01
if player.volume < 0.01 {
player.stop()
} else {
// Use afterDelay value to change duration.
performSelector("fadeVolumeDown:", withObject: player, afterDelay: 0.02)
}
}
func fadeVolumeUp(player: AVAudioPlayer ) {
player.volume += 0.01
if player.volume < 1.0 {
performSelector("fadeVolumeUp:", withObject: player, afterDelay: 0.02)
}
}
func fadeAudioPlayer(player: AVAudioPlayer, fadeTo: Float, duration: NSTimeInterval, completion block: (() -> ())? ) {
let amount:Float = 0.1
let incrementDelay = duration * Double(amount)// * amount)
if player.volume > fadeTo + amount {
player.volume -= amount
delay(incrementDelay) {
self.fadeAudioPlayer(player, fadeTo: fadeTo, duration: duration, completion: block)
}
} else if player.volume < fadeTo - amount {
player.volume += amount
delay(incrementDelay) {
self.fadeAudioPlayer(player, fadeTo: fadeTo, duration: duration, completion: block)
}
} else {
// Execute when desired volume reached.
block?()
}
}
// MARK: - Utilities
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
| bsd-2-clause | bfd2fb71b573fe7790d4d18801cd9498 | 35.832031 | 122 | 0.552232 | 5.007435 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Views/Common/Data Rows/Callouts/CalloutsNib.swift | 1 | 680 | //
// CalloutsNib.swift
// MEGameTracker
//
// Created by Emily Ivie on 6/9/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
@IBDesignable open class CalloutsNib: SimpleArrayDataRowNib {
override open class func loadNib(heading: String? = nil, cellNibs: [String] = []) -> CalloutsNib? {
let bundle = Bundle(for: CalloutsNib.self)
if let view = bundle.loadNibNamed("CalloutsNib", owner: self, options: nil)?.first as? CalloutsNib {
let bundle = Bundle(for: CalloutsNib.self)
for nib in cellNibs {
view.tableView?.register(UINib(nibName: nib, bundle: bundle), forCellReuseIdentifier: nib)
}
return view
}
return nil
}
}
| mit | 59ee69a4a7b22dd5c45fafd8db8fe2a3 | 27.291667 | 103 | 0.698085 | 3.378109 | false | false | false | false |
LuizZak/TaskMan | TaskMan/EditDateViewController.swift | 1 | 1248 | //
// EditDateViewController.swift
// TaskMan
//
// Created by Luiz Fernando Silva on 05/12/16.
// Copyright © 2016 Luiz Fernando Silva. All rights reserved.
//
import Cocoa
class EditDateViewController: NSViewController {
@IBOutlet weak var datePicker: NSDatePicker!
var date: Date {
get {
_ = view
return datePicker.dateValue
}
set {
_ = view
datePicker.dateValue = newValue
}
}
var didTapOkCallback: ((EditDateViewController) -> ())?
override func viewWillAppear() {
super.viewWillAppear()
// Centralize on screen
if let window = self.view.window {
if let screenSize = window.screen?.frame.size {
window.setFrameOrigin(NSPoint(x: (screenSize.width - window.frame.size.width) / 2, y: (screenSize.height - window.frame.size.height) / 2))
}
}
}
@IBAction func didTapOk(_ sender: NSButton) {
guard let callback = didTapOkCallback else {
dismiss(self)
return
}
callback(self)
}
@IBAction func didTapCancel(_ sender: NSButton) {
dismiss(self)
}
}
| mit | 639d2256353af2c1bcf0a5c8cd7b3bff | 22.980769 | 154 | 0.560545 | 4.618519 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/Component/CompositionalNewsComponentBuilderTests.swift | 1 | 5232 | import EurofurenceApplication
import XCTest
import XCTEurofurenceModel
class CompositionalNewsComponentBuilderTests: XCTestCase {
func testProducesSceneFromFactory() {
let refreshService = CapturingRefreshService()
let sceneFactory = FakeCompositionalNewsSceneFactory()
let builder = CompositionalNewsComponentBuilder(refreshService: refreshService)
.with(sceneFactory)
let delegate = CapturingNewsComponentDelegate()
let component = builder.build().makeNewsComponent(delegate)
XCTAssertIdentical(component, sceneFactory.scene)
}
func testInstallsWidgetsIntoSceneInDesignatedOrder() {
let refreshService = CapturingRefreshService()
let sceneFactory = FakeCompositionalNewsSceneFactory()
let (firstWidget, secondWidget) = (FakeNewsWidget(), FakeNewsWidget())
let builder = CompositionalNewsComponentBuilder(refreshService: refreshService)
.with(sceneFactory)
.with(firstWidget)
.with(secondWidget)
let delegate = CapturingNewsComponentDelegate()
_ = builder.build().makeNewsComponent(delegate)
sceneFactory.scene.simulateSceneReady()
let expected = [firstWidget.mediator, secondWidget.mediator]
let actual = sceneFactory.scene.installedDataSources
let installedWidgets = actual.elementsEqual(expected, by: { $0 === $1 })
XCTAssertTrue(installedWidgets, "Should install all widgets passed to builder in the order they are provided")
}
func testWaitsUntilSceneReadyBeforeInstallingWidgets() {
let refreshService = CapturingRefreshService()
let sceneFactory = FakeCompositionalNewsSceneFactory()
let widget = FakeNewsWidget()
let builder = CompositionalNewsComponentBuilder(refreshService: refreshService)
.with(sceneFactory)
.with(widget)
let delegate = CapturingNewsComponentDelegate()
_ = builder.build().makeNewsComponent(delegate)
let installedWidgets = sceneFactory.scene.installedDataSources.isEmpty
XCTAssertTrue(installedWidgets, "Should wait until scene ready before installing widgets")
}
func testTellRefreshServiceToBeginRefreshingWhenSceneRequestsIt() {
let refreshService = CapturingRefreshService()
let sceneFactory = FakeCompositionalNewsSceneFactory()
let builder = CompositionalNewsComponentBuilder(refreshService: refreshService)
.with(sceneFactory)
let delegate = CapturingNewsComponentDelegate()
_ = builder.build().makeNewsComponent(delegate)
sceneFactory.scene.simulateSceneReady()
XCTAssertFalse(refreshService.toldToRefresh, "Should not begin refreshing until scene requests it")
sceneFactory.scene.simulateRefreshRequested()
XCTAssertTrue(refreshService.toldToRefresh, "Should begin refreshing when the scene requests it")
}
func testTellDelegateToShowSettingsWhenSceneRequestsit() {
let refreshService = CapturingRefreshService()
let sceneFactory = FakeCompositionalNewsSceneFactory()
let builder = CompositionalNewsComponentBuilder(refreshService: refreshService)
.with(sceneFactory)
let delegate = CapturingNewsComponentDelegate()
_ = builder.build().makeNewsComponent(delegate)
sceneFactory.scene.simulateSceneReady()
let sender = "Opqaque sender"
sceneFactory.scene.simulateSettingsTapped(sender: sender)
XCTAssertEqual(sender, delegate.showSettingsSender as? String)
}
func testControlSceneRefreshIndicatorVisibilityDuringRefresh() {
let refreshService = CapturingRefreshService()
let sceneFactory = FakeCompositionalNewsSceneFactory()
let builder = CompositionalNewsComponentBuilder(refreshService: refreshService)
.with(sceneFactory)
let delegate = CapturingNewsComponentDelegate()
_ = builder.build().makeNewsComponent(delegate)
sceneFactory.scene.simulateSceneReady()
XCTAssertEqual(
.unknown,
sceneFactory.scene.loadingIndicatorState,
"Loading indicator should not be told to show or hide until the service propogates its state"
)
refreshService.simulateRefreshBegan()
XCTAssertEqual(
.visible,
sceneFactory.scene.loadingIndicatorState,
"Loading indicator should be visible while refresh is active"
)
refreshService.simulateRefreshFinished()
XCTAssertEqual(
.hidden,
sceneFactory.scene.loadingIndicatorState,
"Loading indicator should be hidden when refresh concludes"
)
}
private struct FakeNewsWidget: NewsWidget {
let mediator = FakeTableViewMediator()
func register(in environment: NewsWidgetEnvironment) {
environment.install(dataSource: mediator)
}
}
}
| mit | db69109263c2f340a76f10fa1b23c9f3 | 38.338346 | 118 | 0.677561 | 5.774834 | false | true | false | false |
deirinberg/MDCalendarSelector | Demo/MDCalendarSelector/ViewController.swift | 1 | 4464 | //
// ViewController.swift
// MDCalendarSelector
//
// Created by Dylan Eirinberg on 9/28/14.
// Copyright (c) 2014 Dylan Eirinberg. All rights reserved.
//
import UIKit
import PureLayout
import MDCalendarSelector
class ViewController: UIViewController, MDCalendarSelectorDelegate {
var containerView: UIView!
var calendarSelector: MDCalendarSelector!
var selectedDatesLabel: UILabel!
var selectedLengthLabel: UILabel!
var todayButton: UIButton!
var didSetupConstraints: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
containerView = UIView.newAutoLayoutView()
view.addSubview(containerView)
calendarSelector = MDCalendarSelector()
calendarSelector.delegate = self
calendarSelector.regularFontName = "Montserrat-Regular"
calendarSelector.boldFontName = "Montserrat-Bold"
containerView.addSubview(calendarSelector)
selectedDatesLabel = UILabel.newAutoLayoutView()
selectedDatesLabel.text = "No Selected Dates"
selectedDatesLabel.textColor = UIColor(white: 0.0, alpha: 0.5)
containerView.addSubview(selectedDatesLabel)
selectedLengthLabel = UILabel.newAutoLayoutView()
selectedLengthLabel.text = "(0 Days)"
selectedLengthLabel.textColor = UIColor(white: 0.0, alpha: 0.5)
containerView.addSubview(selectedLengthLabel)
todayButton = UIButton(type: .System)
todayButton.setTitle("Today", forState: .Normal)
todayButton.setTitleColor(UIColor.themeRedColor(), forState: .Normal)
todayButton.titleLabel?.font = UIFont.systemFontOfSize(15.0)
todayButton.addTarget(self, action: "todayButtonSelected", forControlEvents: .TouchUpInside)
containerView.addSubview(todayButton)
if #available(iOS 8.2, *) {
selectedDatesLabel.font = UIFont.systemFontOfSize(15.0, weight: UIFontWeightLight)
selectedLengthLabel.font = UIFont.systemFontOfSize(15.0, weight: UIFontWeightUltraLight)
} else {
selectedDatesLabel.font = UIFont(name: "HelveticaNeue-Light", size: 15.0)
selectedLengthLabel.font = UIFont(name: "HelveticaNeue-UltraLight", size: 15.0)
}
}
override func updateViewConstraints() {
if !didSetupConstraints {
containerView.autoCenterInSuperview()
calendarSelector.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Bottom)
selectedDatesLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: calendarSelector, withOffset: 25.0)
selectedDatesLabel
.autoAlignAxisToSuperviewAxis(.Vertical)
selectedLengthLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: selectedDatesLabel, withOffset: 10.0)
selectedLengthLabel
.autoAlignAxisToSuperviewAxis(.Vertical)
todayButton.autoPinEdge(.Top, toEdge: .Bottom, ofView: selectedLengthLabel, withOffset: 5)
todayButton.autoAlignAxisToSuperviewAxis(.Vertical)
todayButton.autoPinEdgeToSuperviewEdge(.Bottom)
didSetupConstraints = true
}
super.updateViewConstraints()
}
func calendarSelector(calendarSelector: MDCalendarSelector, startDateChanged startDate: NSDate) {
updateSelectedDateLabel(startDate, endDate: calendarSelector.endDate)
}
func calendarSelector(calendarSelector: MDCalendarSelector, endDateChanged endDate: NSDate) {
if let startDate = calendarSelector.startDate {
updateSelectedDateLabel(startDate, endDate: endDate)
}
}
func updateSelectedDateLabel(startDate: NSDate, endDate: NSDate?) {
if let lastDate = endDate where
startDate.dateString != lastDate.dateString {
selectedDatesLabel.text = "\(startDate.displayDateString) - \(lastDate.displayDateString)"
} else {
selectedDatesLabel.text = "\(startDate.displayDateString)"
}
let length: Int = calendarSelector.selectedLength
let daysText: String = length == 1 ? "Day" : "Days"
selectedLengthLabel.text = "(\(length) \(daysText))"
}
func todayButtonSelected() {
calendarSelector.goToToday()
}
}
| mit | 4e7145e14778fc32efaaeeb46c3b1c1d | 37.153846 | 112 | 0.663306 | 5.424058 | false | false | false | false |
manavgabhawala/swift | test/SILGen/nested_generics.swift | 1 | 14502 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null
// TODO:
// - test generated SIL -- mostly we're just testing mangling here
// - class_method calls
// - witness_method calls
// - inner generic parameters on protocol requirements
// - generic parameter list on method in nested type
// - types nested inside unconstrained extensions of generic types
protocol Pizza : class {
associatedtype Topping
}
protocol HotDog {
associatedtype Condiment
}
protocol CuredMeat {}
// Generic nested inside generic
struct Lunch<T : Pizza where T.Topping : CuredMeat> {
struct Dinner<U : HotDog where U.Condiment == Deli<Pepper>.Mustard> {
let firstCourse: T
let secondCourse: U?
var leftovers: T
var transformation: (T) -> U
func coolCombination(t: T.Topping, u: U.Condiment) {
func nestedGeneric<X, Y>(x: X, y: Y) -> (X, Y) {
return (x, y)
}
_ = nestedGeneric(x: t, y: u)
}
}
}
// CHECK-LABEL: // nested_generics.Lunch.Dinner.coolCombination (t : A.Topping, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> ()
// CHECK-LABEL: // nested_generics.Lunch.Dinner.(coolCombination (t : A.Topping, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()).(nestedGeneric #1) <A><A1><A2, B2 where A: nested_generics.Pizza, A1: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, A1.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard> (x : A2, y : B2) -> (A2, B2)
// CHECK-LABEL: sil shared @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF0A7GenericL_qd0___qd0_0_tqd0__1x_qd0_0_1ytAA5PizzaRzAA6HotDogRd__AA9CuredMeatAHRQAP9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in X, @in Y) -> (@out X, @out Y)
// CHECK-LABEL: // nested_generics.Lunch.Dinner.init (firstCourse : A, secondCourse : Swift.Optional<A1>, leftovers : A, transformation : (A) -> A1) -> nested_generics.Lunch<A>.Dinner<A1>
// CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerVAEyx_qd__Gx11firstCourse_qd__Sg06secondF0x9leftoversqd__xc14transformationtcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_owned (@owned T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U>
// Non-generic nested inside generic
class Deli<Spices> : CuredMeat {
class Pepperoni : CuredMeat {}
struct Sausage : CuredMeat {}
enum Mustard {
case Yellow
case Dijon
case DeliStyle(Spices)
}
}
// CHECK-LABEL: // nested_generics.Deli.Pepperoni.init () -> nested_generics.Deli<A>.Pepperoni
// CHECK-LABEL: sil hidden @_T015nested_generics4DeliC9PepperoniCAEyx_Gycfc : $@convention(method) <Spices> (@owned Deli<Spices>.Pepperoni) -> @owned Deli<Spices>.Pepperoni
// Typealiases referencing outer generic parameters
struct Pizzas<Spices> {
class NewYork : Pizza {
typealias Topping = Deli<Spices>.Pepperoni
}
class DeepDish : Pizza {
typealias Topping = Deli<Spices>.Sausage
}
}
class HotDogs {
struct Bratwurst : HotDog {
typealias Condiment = Deli<Pepper>.Mustard
}
struct American : HotDog {
typealias Condiment = Deli<Pepper>.Mustard
}
}
// Local type in extension of type in another module
extension String {
func foo() {
// CHECK-LABEL: // (extension in nested_generics):Swift.String.(foo () -> ()).(Cheese #1).init (material : A) -> (extension in nested_generics):Swift.String.(foo () -> ()).(Cheese #1)<A>
// CHECK-LABEL: sil shared @_T0SS15nested_genericsE3fooyyF6CheeseL_VADyxGx8material_tcfC
struct Cheese<Milk> {
let material: Milk
}
let r = Cheese(material: "cow")
}
}
// Local type in extension of type in same module
extension HotDogs {
func applyRelish() {
// CHECK-LABEL: // nested_generics.HotDogs.(applyRelish () -> ()).(Relish #1).init (material : A) -> nested_generics.HotDogs.(applyRelish () -> ()).(Relish #1)<A>
// CHECK-LABEL: sil shared @_T015nested_generics7HotDogsC11applyRelishyyF0F0L_VAFyxGx8material_tcfC
struct Relish<Material> {
let material: Material
}
let r = Relish(material: "pickles")
}
}
struct Pepper {}
struct ChiliFlakes {}
// CHECK-LABEL: // nested_generics.eatDinnerGeneric <A, B where A: nested_generics.Pizza, B: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, B.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard> (d : inout nested_generics.Lunch<A>.Dinner<B>, t : A.Topping, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @_T015nested_generics16eatDinnerGenericyAA5LunchV0D0Vyx_q_Gz1d_7ToppingQz1tAA4DeliC7MustardOyAA6PepperV_G1utAA5PizzaRzAA6HotDogR_AA9CuredMeatAJRQAR9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in T.Topping, Deli<Pepper>.Mustard) -> ()
func eatDinnerGeneric<T, U>(d: inout Lunch<T>.Dinner<U>, t: T.Topping, u: U.Condiment) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// Overloading concrete function with different bound generic arguments in parent type
// CHECK-LABEL: // nested_generics.eatDinnerConcrete (d : inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork>.Dinner<nested_generics.HotDogs.American>, t : nested_generics.Deli<nested_generics.ChiliFlakes>.Pepperoni, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAA6PepperV_G1utF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @owned Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> ()
func eatDinnerConcrete(d: inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>,
t: Deli<ChiliFlakes>.Pepperoni,
u: Deli<Pepper>.Mustard) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// CHECK-LABEL: // reabstraction thunk helper from @callee_owned (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@out nested_generics.HotDogs.American) to @callee_owned (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@unowned nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA11ChiliFlakesV_GAA7HotDogsC8AmericanVIxxr_AhLIxxd_TR : $@convention(thin) (@owned Pizzas<ChiliFlakes>.NewYork, @owned @callee_owned (@owned Pizzas<ChiliFlakes>.NewYork) -> @out HotDogs.American) -> HotDogs.American
// CHECK-LABEL: // nested_generics.eatDinnerConcrete (d : inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.Pepper>.NewYork>.Dinner<nested_generics.HotDogs.American>, t : nested_generics.Deli<nested_generics.Pepper>.Pepperoni, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAL_G1utF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @owned Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> ()
func eatDinnerConcrete(d: inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>,
t: Deli<Pepper>.Pepperoni,
u: Deli<Pepper>.Mustard) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// CHECK-LABEL: // reabstraction thunk helper from @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) to @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIxxr_AhLIxxd_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @owned @callee_owned (@owned Pizzas<Pepper>.NewYork) -> @out HotDogs.American) -> HotDogs.American
// CHECK-LABEL: // nested_generics.(calls () -> ()).(closure #1)
// CHECK-LABEL: sil shared @_T015nested_generics5callsyyFAA7HotDogsC8AmericanVAA6PizzasV7NewYorkCyAA6PepperV_GcfU_ : $@convention(thin) (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American
func calls() {
let firstCourse = Pizzas<Pepper>.NewYork()
let secondCourse = HotDogs.American()
var dinner = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>(
firstCourse: firstCourse,
secondCourse: secondCourse,
leftovers: firstCourse,
transformation: { _ in HotDogs.American() })
let topping = Deli<Pepper>.Pepperoni()
let condiment1 = Deli<Pepper>.Mustard.Dijon
let condiment2 = Deli<Pepper>.Mustard.DeliStyle(Pepper())
eatDinnerGeneric(d: &dinner, t: topping, u: condiment1)
eatDinnerConcrete(d: &dinner, t: topping, u: condiment2)
}
protocol ProtocolWithGenericRequirement {
associatedtype T
associatedtype U
func method<V>(t: T, u: U, v: V) -> (T, U, V)
}
class OuterRing<T> {
class InnerRing<U> : ProtocolWithGenericRequirement {
func method<V>(t: T, u: U, v: V) -> (T, U, V) {
return (t, u, v)
}
}
}
class SubclassOfInner<T, U> : OuterRing<T>.InnerRing<U> {
override func method<V>(t: T, u: U, v: V) -> (T, U, V) {
return super.method(t: t, u: u, v: v)
}
}
// CHECK-LABEL: // reabstraction thunk helper from @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) to @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIxxd_AhLIxxr_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @owned @callee_owned (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American) -> @out HotDogs.American
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementAAr__lAaGP6method1TQz_1UQzqd__tAK1t_AM1uqd__1vtlFTW : $@convention(witness_method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) {
// CHECK: bb0([[T:%[0-9]+]] : $*τ_0_0, [[U:%[0-9]+]] : $*τ_1_0, [[V:%[0-9]+]] : $*τ_2_0, [[TOut:%[0-9]+]] : $*τ_0_0, [[UOut:%[0-9]+]] : $*τ_1_0, [[VOut:%[0-9]+]] : $*τ_2_0, [[SELF:%[0-9]+]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>):
// CHECK: [[SELF_COPY:%[0-9]+]] = alloc_stack $OuterRing<τ_0_0>.InnerRing<τ_1_0>
// CHECK: copy_addr [[SELF]] to [initialization] [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>
// CHECK: [[SELF_COPY_VAL:%[0-9]+]] = load [take] [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>
// CHECK: [[BORROWED_SELF_COPY_VAL:%.*]] = begin_borrow [[SELF_COPY_VAL]]
// CHECK: [[METHOD:%[0-9]+]] = class_method [[BORROWED_SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>, #OuterRing.InnerRing.method!1 : <T><U><V> (OuterRing<T>.InnerRing<U>) -> (T, U, V) -> (T, U, V), $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0)
// CHECK: apply [[METHOD]]<τ_0_0, τ_1_0, τ_2_0>([[T]], [[U]], [[V]], [[TOut]], [[UOut]], [[VOut]], [[BORROWED_SELF_COPY_VAL]]) : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: end_borrow [[BORROWED_SELF_COPY_VAL]] from [[SELF_COPY_VAL]]
// CHECK: destroy_value [[SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>
// CHECK: dealloc_stack [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>
// CHECK: return [[RESULT]] : $()
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Pepperoni: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Sausage: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.NewYork: Pizza module nested_generics {
// CHECK: associated_type Topping: Deli<Spices>.Pepperoni
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.DeepDish: Pizza module nested_generics {
// CHECK: associated_type Topping: Deli<Spices>.Sausage
// CHECK: }
// CHECK: sil_witness_table hidden HotDogs.Bratwurst: HotDog module nested_generics {
// CHECK: associated_type Condiment: Deli<Pepper>.Mustard
// CHECK: }
// CHECK: sil_witness_table hidden HotDogs.American: HotDog module nested_generics {
// CHECK: associated_type Condiment: Deli<Pepper>.Mustard
// CHECK: }
| apache-2.0 | ee2372d7f8fa51a2825880688b077b76 | 53.513208 | 403 | 0.702132 | 3.221677 | false | false | false | false |
darina/omim | iphone/Maps/Classes/Components/RatingSummaryView/RatingSummaryView.swift | 5 | 8104 |
final class RatingSummaryView: UIView {
@IBInspectable var value: String = RatingSummaryViewSettings.Default.value {
didSet {
guard oldValue != value else { return }
update()
}
}
var type = UgcSummaryRatingType.none {
didSet {
guard oldValue != type else { return }
update()
}
}
@IBInspectable var topOffset: CGFloat {
get { return settings.topOffset }
set {
settings.topOffset = newValue
update()
}
}
@IBInspectable var bottomOffset: CGFloat {
get { return settings.bottomOffset }
set {
settings.bottomOffset = newValue
update()
}
}
@IBInspectable var leadingImageOffset: CGFloat {
get { return settings.leadingImageOffset }
set {
settings.leadingImageOffset = newValue
update()
}
}
@IBInspectable var margin: CGFloat {
get { return settings.margin }
set {
settings.margin = newValue
update()
}
}
@IBInspectable var trailingTextOffset: CGFloat {
get { return settings.trailingTextOffset }
set {
settings.trailingTextOffset = newValue
update()
}
}
var textFont: UIFont {
get { return settings.textFont }
set {
settings.textFont = newValue
update()
}
}
@IBInspectable var textSize: CGFloat {
get { return settings.textSize }
set {
settings.textSize = newValue
update()
}
}
@IBInspectable var backgroundOpacity: CGFloat {
get { return settings.backgroundOpacity }
set {
settings.backgroundOpacity = newValue
update()
}
}
@IBInspectable var noValueText: String {
get { return settings.noValueText }
set {
settings.noValueText = newValue
update()
}
}
@IBInspectable var noValueImage: UIImage? {
get { return settings.images[.none] }
set {
settings.images[.none] = newValue
update()
}
}
@IBInspectable var noValueColor: UIColor? {
get { return settings.colors[.none] }
set {
settings.colors[.none] = newValue
update()
}
}
@IBInspectable var horribleImage: UIImage? {
get { return settings.images[.horrible] }
set {
settings.images[.horrible] = newValue
update()
}
}
@IBInspectable var horribleColor: UIColor? {
get { return settings.colors[.horrible] }
set {
settings.colors[.horrible] = newValue
update()
}
}
@IBInspectable var badImage: UIImage? {
get { return settings.images[.bad] }
set {
settings.images[.bad] = newValue
update()
}
}
@IBInspectable var badColor: UIColor? {
get { return settings.colors[.bad] }
set {
settings.colors[.bad] = newValue
update()
}
}
@IBInspectable var normalImage: UIImage? {
get { return settings.images[.normal] }
set {
settings.images[.normal] = newValue
update()
}
}
@IBInspectable var normalColor: UIColor? {
get { return settings.colors[.normal] }
set {
settings.colors[.normal] = newValue
update()
}
}
@IBInspectable var goodImage: UIImage? {
get { return settings.images[.good] }
set {
settings.images[.good] = newValue
update()
}
}
@IBInspectable var goodColor: UIColor? {
get { return settings.colors[.good] }
set {
settings.colors[.good] = newValue
update()
}
}
@IBInspectable var excellentImage: UIImage? {
get { return settings.images[.excellent] }
set {
settings.images[.excellent] = newValue
update()
}
}
@IBInspectable var excellentColor: UIColor? {
get { return settings.colors[.excellent] }
set {
settings.colors[.excellent] = newValue
update()
}
}
private var scheduledUpdate: DispatchWorkItem?
var settings = RatingSummaryViewSettings() {
didSet {
update()
}
}
private var isRightToLeft = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft
public override func awakeFromNib() {
super.awakeFromNib()
setup()
update()
}
public convenience init() {
self.init(frame: CGRect())
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
update()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
update()
}
private func setup() {
layer.backgroundColor = UIColor.clear.cgColor
isOpaque = true
}
private var viewSize = CGSize()
func updateImpl() {
let sublayer = createLayer()
layer.sublayers = [sublayer]
viewSize = sublayer.bounds.size
invalidateIntrinsicContentSize()
frame.size = intrinsicContentSize
}
func update() {
scheduledUpdate?.cancel()
scheduledUpdate = DispatchWorkItem { [weak self] in self?.updateImpl() }
DispatchQueue.main.async(execute: scheduledUpdate!)
}
override var intrinsicContentSize: CGSize {
return viewSize
}
private func createLayer() -> CALayer {
let textLayer = createTextLayer()
return combineLayers(imageLayer: createImageLayer(textLayer.bounds.height),
textLayer: textLayer)
}
private func combineLayers(imageLayer: CALayer?, textLayer: CALayer) -> CALayer {
var x: CGFloat = 0
let height = textLayer.bounds.height + settings.topOffset + settings.bottomOffset
let containerLayer = createContainerLayer(height)
if let imageLayer = imageLayer {
x += settings.leadingImageOffset
containerLayer.addSublayer(imageLayer)
imageLayer.position = CGPoint(x: x, y: settings.topOffset)
x += imageLayer.bounds.width
containerLayer.backgroundColor = settings.colors[type]!.withAlphaComponent(settings.backgroundOpacity).cgColor
containerLayer.cornerRadius = height / 2
}
containerLayer.addSublayer(textLayer)
x += settings.margin
textLayer.position = CGPoint(x: x, y: settings.topOffset)
x += textLayer.bounds.width + settings.trailingTextOffset
containerLayer.bounds.size.width = x
if isRightToLeft {
let rotation = CATransform3DMakeRotation(CGFloat.pi, 0, 1, 0)
containerLayer.transform = CATransform3DTranslate(rotation, -containerLayer.bounds.size.width, 0, 0)
textLayer.transform = CATransform3DTranslate(rotation, -textLayer.bounds.size.width, 0, 0)
}
return containerLayer
}
private func createImageLayer(_ size: CGFloat) -> CALayer? {
guard let image = settings.images[type] else { return nil }
let imageLayer = createContainerLayer(size)
imageLayer.contents = image.cgImage
imageLayer.contentsGravity = CALayerContentsGravity.resizeAspect
let containerLayer = createContainerLayer(size)
if image.renderingMode == .alwaysTemplate {
containerLayer.mask = imageLayer
containerLayer.backgroundColor = settings.colors[type]!.cgColor
} else {
containerLayer.addSublayer(imageLayer)
}
return containerLayer
}
private func createTextLayer() -> CALayer {
let font = textFont.withSize(textSize)
let size = NSString(string: value).size(withAttributes: [NSAttributedString.Key.font: font])
let layer = CATextLayer()
layer.bounds = CGRect(origin: CGPoint(),
size: CGSize(width: ceil(size.width), height: ceil(size.height)))
layer.anchorPoint = CGPoint()
layer.string = value
layer.font = CGFont(font.fontName as CFString)
layer.fontSize = font.pointSize
layer.foregroundColor = settings.colors[type]!.cgColor
layer.contentsScale = UIScreen.main.scale
return layer
}
private func createContainerLayer(_ size: CGFloat) -> CALayer {
let layer = CALayer()
layer.bounds = CGRect(origin: CGPoint(), size: CGSize(width: size, height: size))
layer.anchorPoint = CGPoint()
layer.contentsGravity = CALayerContentsGravity.resizeAspect
layer.contentsScale = UIScreen.main.scale
layer.masksToBounds = true
layer.isOpaque = true
return layer
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
updateImpl()
}
}
| apache-2.0 | 4bce38eb037c72deb62421dce893fc32 | 23.935385 | 116 | 0.659921 | 4.565634 | false | false | false | false |
Kronusdark/SwiftExtensions | Extensions.swift | 1 | 3241 | //
// Extensions.swift
//
// Created by Weston Hanners on 1/8/15.
// Copyright (c) 2015 Hanners Software. All rights reserved.
//
import UIKit
extension UINavigationController {
func pushStoryboard(name: String, bundle: NSBundle?) {
pushStoryboard(name: name, bundle: bundle, transitionDelegate: nil)
}
func pushStoryboard(#name: String, bundle: NSBundle?, transitionDelegate: UINavigationControllerDelegate?) {
let storyboard = UIStoryboard(name: name, bundle: bundle)
let destination = storyboard.instantiateInitialViewController() as UIViewController
if let delegate = transitionDelegate {
self.delegate = delegate
}
pushViewController(destination, animated: true)
}
}
extension UIViewController {
func presentStoryboard(name: String, bundle: NSBundle?) {
presentStoryboard(name: name, bundle: bundle, transitionDelegate: nil)
}
func presentStoryboard(#name: String, bundle: NSBundle?, transitionDelegate: UIViewControllerTransitioningDelegate?) {
let storyboard = UIStoryboard(name: name, bundle: bundle)
let destination = storyboard.instantiateInitialViewController() as UIViewController
if let delegate = transitionDelegate {
destination.transitioningDelegate = transitionDelegate
}
presentViewController(destination, animated: true, completion: nil)
}
}
extension UINavigationBar {
func removeShadow() {
if let view = removeShadowFromView(self) {
view.removeFromSuperview()
}
}
func removeShadowFromView(view: UIView) -> UIImageView? {
if (view.isKindOfClass(UIImageView) && view.bounds.size.height <= 1) {
return view as? UIImageView
}
for subView in view.subviews {
if let imageView = removeShadowFromView(subView as UIView) {
return imageView
}
}
return nil
}
}
extension UIImage {
func tintedWith(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext() as CGContextRef
CGContextTranslateCTM(context, 0, self.size.height)
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeNormal)
let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
CGContextClipToMask(context, rect, self.CGImage)
color.setFill()
CGContextFillRect(context, rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return newImage
}
}
extension Array {
func firstObjectOfType(c: AnyClass) -> AnyObject? {
return filter({
let obj = $0 as NSObject
return obj.isKindOfClass(c)
}).first as NSObject
}
func contains<T : AnyObject>(obj: T) -> Bool {
return self.filter({$0 as? T === obj}).count > 0
}
} | mit | 6a3ea4658530ccbfab95b5dd1bc77d04 | 26.243697 | 122 | 0.622339 | 5.348185 | false | false | false | false |
simorgh3196/Twifter | Sources/Twifter/Networking/Request.swift | 1 | 2399 | //
// Request.swift
// Core
//
// Created by Tomoya Hayakawa on 2020/03/26.
// Copyright © 2020 simorgh3196. All rights reserved.
//
import Foundation
public protocol Request {
associatedtype Response
var baseURL: URL { get }
var path: String { get }
/// The HTTP request method of the receiver.
var method: HTTPMethod { get }
// MARK: Optional
var requestURL: URL { get }
/// A dictionary containing all the HTTP header fields of the receiver.
var headerFields: [String: String]? { get }
var queryParameters: [String: String]? { get }
var bodyParameters: [String: String]? { get }
/// The cache policy for the request.
var cachePolicy: URLRequest.CachePolicy { get }
/// The timeout interval for the request. See the commentary for the `timeoutInterval` for more information on timeout intervals.
var timeoutInterval: TimeInterval { get }
var acceptableStatusCodes: Range<Int> { get }
/// Creates a URLRequest with the properties.
func buildURLRequest() -> URLRequest
func decodeResponse(data: Data,
urlResponse: HTTPURLResponse,
completionHandler: @escaping ((Response) -> Void)) throws
}
public extension Request {
var requestURL: URL { baseURL.appendingPathComponent(path) }
var headerFields: [String: String]? { nil }
var queryParameters: [String: String]? { nil }
var bodyParameters: [String: String]? { nil }
var cachePolicy: URLRequest.CachePolicy { .useProtocolCachePolicy }
var timeoutInterval: TimeInterval { 60.0 }
var acceptableStatusCodes: Range<Int> { 200..<400 }
func buildURLRequest() -> URLRequest {
var components = URLComponents(url: requestURL, resolvingAgainstBaseURL: false)!
components.queryItems = queryParameters?.map { URLQueryItem(name: $0.key, value: $0.value) }
let url = components.url!
var request = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
request.httpMethod = method.value
request.allHTTPHeaderFields = headerFields
request.httpBody = bodyParameters?
.filter { !$0.key.contains("oauth_callback") }
.map { $0.key.urlEncoded + "=" + "\($0.value)".urlEncoded }
.joined(separator: "&")
.data(using: .utf8)
return request
}
}
| mit | be3c972f51c423cd7c366b8da0e66173 | 28.604938 | 133 | 0.654712 | 4.729783 | false | false | false | false |
ZwxWhite/V2EX | V2EX/V2EX/Class/View/Cell/UserHeaderCell.swift | 1 | 1300 | //
// UserHeaderCell.swift
// V2EX
//
// Created by wenxuan.zhang on 15/12/4.
// Copyright © 2015年 张文轩. All rights reserved.
//
import UIKit
class UserHeaderCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView! {
didSet{
avatarImageView.layer.cornerRadius = 3
avatarImageView.layer.masksToBounds = true
}
}
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
func reloadData() {
if let user = v2Realm.objects(V2UserModel).first {
usernameLabel.text = user.username
if let tagline = user.tagline where tagline.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 {
descriptionLabel.text = "简介: " + tagline
} else {
descriptionLabel.text = "这家伙很懒,什么都没留下"
}
if let avatarUrl = user.avatar_normal {
avatarImageView.kf_setImageWithURL(NSURL(string: v2exHttps(false) + avatarUrl)!, placeholderImage: UIImage(named: "avatar_default"))
}
} else {
usernameLabel.text = "未登录"
descriptionLabel.text = "简介: 暂无简介"
avatarImageView.image = nil
}
}
}
| mit | 829fe4b17d1be47493e21e1bd5b70eee | 30.974359 | 148 | 0.607859 | 4.36014 | false | false | false | false |
r-a-o/PineKit | Pod/Classes/PineMenuTransition.swift | 1 | 1822 | //
// KamaConfig.swift
// KamaUIKit
//
// Created by Prakash Raman on 13/02/16.
// Copyright © 2016 1985. All rights reserved.
//
import Foundation
import UIKit
open class PineMenuTransition : NSObject {
open var mainController: PineMenuViewController?
open var menuView: PineBaseMenuView?
open var x : CGFloat = 200
public override init(){
self.mainController = nil
}
// ONCE THE CONTROLLER IS SETUP THE MENU IS SETUP AS WELL
// START MENU POSITION IS VERY IMPORTANT
func setController(_ controller: PineMenuViewController){
self.mainController = controller
self.menuView = self.mainController!.menuView!
self.setup()
}
func setup(){
self.mainController!.menuView!.frame = self.mainController!.view.frame
}
func toggle(){
setup()
if self.isOpen() {
close()
} else {
open()
}
}
func isOpen() -> Bool {
let contentFrame = self.mainController!.contentNavigationController!.view.frame
let controllerFrame = self.mainController!.view.frame
return (controllerFrame != contentFrame) ? true : false
}
func open(){
UIView.animate(withDuration: PineConfig.Menu.transitionDuration, animations: { () -> Void in
var frame = (self.mainController?.contentNavigationController!.view.frame)! as CGRect
frame.origin.x = self.x
self.mainController?.contentNavigationController!.view.frame = frame
})
}
func close(){
UIView.animate(withDuration: PineConfig.Menu.transitionDuration, animations: { () -> Void in
self.mainController!.contentNavigationController!.view.frame = self.mainController!.view.frame
})
}
}
| mit | 03928222bbb04ca4fa609ef8ae578fd1 | 27.453125 | 106 | 0.629874 | 4.742188 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/AviasalesSource/SearchResults/Views/SearchResultsPriceCalendarView/SearchResultsPriceCalendarView.swift | 1 | 1417 | //
// SearchResultsPriceCalendarView.swift
// AviasalesSDKTemplate
//
// Created by Dim on 01.02.2018.
// Copyright © 2018 Go Travel Un Limited. All rights reserved.
//
import UIKit
class SearchResultsPriceCalendarView: UIView {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var chartContainerView: UIView!
@IBOutlet weak var overlayView: UIView!
var tapAction: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = JRColorScheme.mainBackgroundColor()
containerView.layer.cornerRadius = 6
titleLabel.text = NSLS("SEARCH_RESULTS_PRICE_CALENDAR_VIEW_TITLE").uppercased()
titleLabel.textColor = JRColorScheme.darkTextColor()
if let chartView = PriceCalendarChartView.loadFromNib() {
chartView.showPriceView = false
chartView.selectOnScroll = false
chartContainerView.addSubview(chartView)
chartView.translatesAutoresizingMaskIntoConstraints = false
chartContainerView.addConstraints(JRConstraintsMakeScaleToFill(chartView, chartContainerView))
chartView.reloadData()
overlayView.addGestureRecognizer(chartView.collectionView.panGestureRecognizer)
}
}
@IBAction func overlayTapped(_ sender: UITapGestureRecognizer) {
tapAction?()
}
}
| mit | ceeb746ac13a2e164f1e6014ad58ced0 | 29.12766 | 106 | 0.700565 | 5.303371 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/Common/Nodes/Mixing/Dry Wet Mixer/AKDryWetMixer.swift | 1 | 1715 | //
// AKDryWetMixer.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
import AVFoundation
/// Balanceable Mix between two signals, usually used for a dry signal and wet signal
///
/// - parameter dry: Dry Input (or just input 1)
/// - parameter wet: Wet Input (or just input 2)
/// - parameter balance: Balance Point (0 = all dry, 1 = all wet)
///
public class AKDryWetMixer: AKNode {
private let mixer = AKMixer()
/// Balance (Default 0.5)
public var balance: Double = 0.5 {
didSet {
if balance < 0 {
balance = 0
}
if balance > 1 {
balance = 1
}
dryGain?.volume = 1 - balance
wetGain?.volume = balance
}
}
private var lastKnownMix: Double = 100
private var dryGain: AKMixer?
private var wetGain: AKMixer?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted = true
/// Initialize this dry wet mixer node
///
/// - parameter dry: Dry Input (or just input 1)
/// - parameter wet: Wet Input (or just input 2)
/// - parameter balance: Balance Point (0 = all dry, 1 = all wet)
///
public init(_ dry: AKNode, _ wet: AKNode, balance: Double) {
self.balance = balance
super.init()
avAudioNode = mixer.avAudioNode
dryGain = AKMixer(dry)
dryGain!.volume = 1 - balance
mixer.connect(dryGain!)
wetGain = AKMixer(wet)
wetGain!.volume = balance
mixer.connect(wetGain!)
}
}
| mit | ffaa24286bfbd874f2f8b6609523e166 | 26.206349 | 85 | 0.57993 | 4.274314 | false | false | false | false |
DaiYue/HAMLeetcodeSwiftSolutions | solutions/12_Integer_to_Roman.playground/Contents.swift | 1 | 1999 | // #12 Integer to Roman https://leetcode.com/problems/integer-to-roman/
// 很简单的递归,没什么可说的。就是细心一点吧。
// 看到题解是把 1000、900、500 都存起来,这样确实快很多,因为不用考虑往左加的情况。另外非递归因为不用算 10 次幂可能略快一点。
// 时间复杂度:O(lgn) 空间复杂度:O(1)
class Solution {
func intToRoman(_ num: Int) -> String {
guard num > 0 else {
return ""
}
let lettersForOne = ["O", "I", "X", "C", "M"]
let lettersForFive = ["O", "V", "L", "D"]
var digits = 1
var numToCompare = 1
while numToCompare * 10 <= num {
numToCompare = numToCompare * 10
digits += 1
}
let highestDigit = num / numToCompare
var leftPart = "", middlePart = "", rightPart = ""
if highestDigit <= 3 {
for _ in 1...highestDigit {
middlePart.append(lettersForOne[digits])
}
} else if highestDigit <= 5 {
middlePart = lettersForFive[digits]
if highestDigit == 4 {
leftPart = lettersForOne[digits]
}
} else if highestDigit <= 8 {
middlePart = lettersForFive[digits]
for _ in 6...highestDigit {
rightPart.append(lettersForOne[digits])
}
} else { // highestDigit = 9
middlePart = lettersForOne[digits + 1]
leftPart = lettersForOne[digits]
}
rightPart += intToRoman(num - highestDigit * numToCompare)
return leftPart + middlePart + rightPart
}
}
Solution().intToRoman(3)
Solution().intToRoman(31)
Solution().intToRoman(5)
Solution().intToRoman(4)
Solution().intToRoman(41)
Solution().intToRoman(9)
Solution().intToRoman(99)
Solution().intToRoman(89)
Solution().intToRoman(10)
Solution().intToRoman(3999) | mit | 5ca48d688cd22f75c1191f531e872994 | 28.934426 | 72 | 0.547945 | 3.732106 | false | false | false | false |
Pretz/SwiftGraphics | Demos/SwiftGraphics_OSX_UITest/Sketch.swift | 2 | 1911 | //
// Sketch.swift
// Sketch
//
// Created by Jonathan Wight on 8/31/14.
// Copyright (c) 2014 schwa.io. All rights reserved.
//
import CoreGraphics
import SwiftGraphics
@objc public protocol Shape {
var frame : CGRect { get }
}
@objc public protocol Node : class {
weak var parent : Node? { get set }
}
@objc public protocol GroupNode : Node {
var children : [Node] { get set }
}
@objc public protocol GeometryNode : Node {
var frame : CGRect { get }
}
@objc public protocol Named {
var name : String? { get }
}
@objc public class GroupGeometryNode : GroupNode, GeometryNode {
public var parent : Node?
public var children : [Node] = []
public var name : String?
public var frame : CGRect {
let geometryChildren = children as! [GeometryNode]
let rects = geometryChildren.map {
(child: GeometryNode) -> CGRect in
return child.frame
}
return CGRect.unionOfRects(rects)
}
public init() {
}
}
@objc public class CircleNode : Shape, Node, GeometryNode {
public var frame : CGRect { return CGRect(center: center, radius: radius) }
public var center : CGPoint
public var radius : CGFloat
public var parent : Node?
public init(center: CGPoint, radius: CGFloat) {
self.center = center
self.radius = radius
}
}
@objc public class LineSegmentNode : Shape, Node, GeometryNode {
public var frame : CGRect { return CGRect(p1: start, p2: end) }
public var start : CGPoint
public var end : CGPoint
public var parent : Node?
public init(start: CGPoint, end: CGPoint) {
self.start = start
self.end = end
}
}
@objc public class RectangleNode : Shape, Node, GeometryNode {
public var frame : CGRect
public var parent : Node?
public init(frame: CGRect) {
self.frame = frame
}
}
| bsd-2-clause | dade65f7929232a2074f2f652c6e2962 | 20.965517 | 79 | 0.62742 | 3.972973 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/check-if-there-is-a-valid-path-in-a-grid.swift | 2 | 2429 | /**
* LeeCode 1391: Check if There is a Valid Path in a Grid
*
* Using BFS to visit all the possible cells from start point (0, 0)
*
* - Complexity: Time and Space: O(n * m),
* which is the number of rows and number of colums in the 2-dimension array.
*
* The key part is at each valid cell, try through all the possble next cell (xx, yy) based on the rules and current cell (x, y).
*
* When checking the validation of next cell, need to check
* If (xx, yy) is not out of current matrix.
* If (xx, yy) has not been visited before, otherwise, duplicates will be added, it would be unlimited cells to visit, which results exceeds time limit.
* If (xx, yy) is able to getting back to (x, y), otherwise, it's not valid, which means it should be connected well.
*/
class Solution {
func hasValidPath(_ grid: [[Int]]) -> Bool {
let n = grid.count
guard n > 0, let m = grid.first?.count, m > 0 else { return false}
// List of direction options.
let dirs = [(0, -1), (-1, 0), (0, 1), (1 ,0)] // Left, Up, Right, Down
// Map cell number to corresponding direction options.
let rules = [
[],
[0, 2],
[1, 3],
[0, 3],
[2, 3],
[0, 1],
[1, 2]
]
// Mark the cell if it has been visited.
var marked = Array(repeating: Array(repeating: false, count: m), count: n)
var queue = [(0, 0)]
marked[0][0] = true
while queue.isEmpty == false {
let (x, y) = queue.removeFirst()
// print("\(grid[x][y]) : \(x) - \(y)")
if x == n - 1, y == m - 1 { return true }
for ruleChoice in rules[grid[x][y]] {
let xx = x + dirs[ruleChoice].0
let yy = y + dirs[ruleChoice].1
// print("(xx, yy) : (\(xx), \(yy))")
// 1, check the validation of boundary
// 2, if it has not been visited
// 3, if it has the opposite direction of current (x, y)'s direction `ruleChoice`
if xx >= 0, xx < n, yy >= 0, yy < m, marked[xx][yy] == false, rules[grid[xx][yy]].contains((ruleChoice + 2) % dirs.count) {
marked[xx][yy] = true
queue.append((xx, yy))
}
}
}
return false
}
}
| mit | 66d8d55601b07d9c63c371ef6dc6271e | 38.177419 | 153 | 0.508028 | 3.783489 | false | false | false | false |
BluechipSystems/viper-module-generator | VIPERGenDemo/VIPERGenDemo/Libraries/Swifter/Swifter/SwifterSavedSearches.swift | 5 | 3850 | //
// SwifterSavedSearches.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
public extension Swifter {
/*
GET saved_searches/list
Returns the authenticated user's saved search queries.
*/
public func getSavedSearchesListWithSuccess(success: ((savedSearches: [JSONValue]?) -> Void)?, failure: FailureHandler?) {
let path = "saved_searches/list.json"
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(savedSearches: json.array)
return
}, failure: failure)
}
/*
GET saved_searches/show/:id
Retrieve the information for the saved search represented by the given id. The authenticating user must be the owner of saved search ID being requested.
*/
public func getSavedSearchesShowWithID(id: Int, success: ((savedSearch: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) {
let path = "saved_searches/show/\(id).json"
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(savedSearch: json.object)
return
}, failure: failure)
}
/*
POST saved_searches/create
Create a new saved search for the authenticated user. A user may only have 25 saved searches.
*/
public func postSavedSearchesCreateShowWithQuery(query: String, success: ((savedSearch: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) {
let path = "saved_searches/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["query"] = query
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(savedSearch: json.object)
return
}, failure: failure)
}
/*
POST saved_searches/destroy/:id
Destroys a saved search for the authenticating user. The authenticating user must be the owner of saved search id being destroyed.
*/
public func postSavedSearchesDestroyWithID(id: Int, success: ((savedSearch: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) {
let path = "saved_searches/destroy/\(id).json"
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(savedSearch: json.object)
return
}, failure: failure)
}
}
| mit | 8aa0773bc8ca3d778745f015ba5c75da | 37.118812 | 162 | 0.678442 | 4.695122 | false | false | false | false |
box/box-ios-sdk | Sources/Modules/UsersModule.swift | 1 | 28403 | //
// UsersModule.swift
// BoxSDK-iOS
//
// Copyright © 2019 Box. All rights reserved.
//
import Foundation
/// Defines user status.
public enum UserStatus: BoxEnum {
/// User is active
case active
/// User is inactive
case inactive
/// User cannot delete or edit content
case cannotDeleteOrEdit
/// User cannot delete, edit or upload content
case cannotDeleteEditOrUpload
/// A custom user status that is not yet implemented
case customValue(String)
/// Initializer.
///
/// - Parameter value: String representation of UserStatus.
public init(_ value: String) {
switch value {
case "active":
self = .active
case "inactive":
self = .inactive
case "cannot_delete_edit":
self = .cannotDeleteOrEdit
case "cannot_delete_edit_upload":
self = .cannotDeleteEditOrUpload
default:
self = .customValue(value)
}
}
/// Returns string representation of user status.
public var description: String {
switch self {
case .active:
return "active"
case .inactive:
return "inactive"
case .cannotDeleteOrEdit:
return "cannot_delete_edit"
case .cannotDeleteEditOrUpload:
return "cannot_delete_edit_upload"
case let .customValue(userValue):
return userValue
}
}
}
/// Defines user’s role within an enterprise
public enum UserRole: BoxEnum {
/// Coadmin role
case coadmin
/// Admin role
case admin
/// User role
case user
/// A custom role that is not yet implemented
case customValue(String)
/// Initializer.
///
/// - Parameter value: String representation of UserRole.
public init(_ value: String) {
switch value {
case "coadmin":
self = .coadmin
case "admin":
self = .admin
case "user":
self = .user
default:
self = .customValue(value)
}
}
/// Returns string representation of user's role.
public var description: String {
switch self {
case .admin:
return "admin"
case .coadmin:
return "coadmin"
case .user:
return "user"
case let .customValue(userValue):
return userValue
}
}
}
/// Provides [User](../Structs/User.html) management.
public class UsersModule {
/// Required for communicating with Box APIs.
weak var boxClient: BoxClient!
// swiftlint:disable:previous implicitly_unwrapped_optional
/// Initializer
///
/// - Parameter boxClient: Required for communicating with Box APIs.
init(boxClient: BoxClient) {
self.boxClient = boxClient
}
/// Get information about the user for which this client is authenticated.
///
/// - Parameters:
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard user object or an error.
public func getCurrent(
fields: [String]? = nil,
completion: @escaping Callback<User>
) {
get(userId: BoxSDK.Constants.currentUser, fields: fields, completion: completion)
}
/// Get information about a user in the enterprise. Requires enterprise administration
/// authorization.
///
/// - Parameters:
/// - userId: The ID of the user.
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard user object or an error.
public func get(
userId: String,
fields: [String]? = nil,
completion: @escaping Callback<User>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Upload avatar image to user account. Supported formats are JPG, JPEG and PNG.
/// Maximum allowed file size is 1MB and resolution 1024x1024 pixels.
///
/// - Parameters:
/// - userId: The ID of the user.
/// - data: The content of image file as binary data.
/// - name: File name of the avatar image. File name should also contains file extension (.jpg, .jpeg or .png).
/// - progress: Closure where upload progress will be reported
/// - completion: Returns an `UserAvatarUpload` object which contains avatar urls if successful otherwise a BoxSDKError.
/// - Returns: BoxUploadTask
@discardableResult
public func uploadAvatar(
userId: String,
data: Data,
name: String,
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<UserAvatarUpload>
) -> BoxUploadTask {
print(name)
var body = MultipartForm()
body.appendFilePart(
name: "pic",
contents: InputStream(data: data),
length: data.count,
fileName: name,
mimeType: MimeTypeProvider.getMimeTypeFrom(filename: name)
)
return boxClient.post(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)/avatar", configuration: boxClient.configuration),
multipartBody: body,
progress: progress,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Upload avatar image to user account. Supported formats are JPG, JPEG and PNG.
/// Maximum allowed file size is 1MB and resolution 1024x1024 pixels.
///
/// - Parameters:
/// - userId: The ID of the user.
/// - stream: An InputStream of an image for been uploaded.
/// - name: File name of the avatar image. File name should also contains file extension (.jpg, .jpeg or .png).
/// - progress: Closure where upload progress will be reported
/// - completion: Returns an `UserAvatarUpload` object which contains avatar urls if successful otherwise a BoxSDKError.
/// - Returns: BoxUploadTask
@discardableResult
public func streamUploadAvatar(
userId: String,
stream: InputStream,
name: String,
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<UserAvatarUpload>
) -> BoxUploadTask {
var body = MultipartForm()
body.appendFilePart(
name: "pic",
contents: stream,
length: 0,
fileName: name,
mimeType: MimeTypeProvider.getMimeTypeFrom(filename: name)
)
return boxClient.post(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)/avatar", configuration: boxClient.configuration),
multipartBody: body,
progress: progress,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Get image of a user's avatar
///
/// - Parameters:
/// - userId: The ID of the user.
/// - completion: Returns the data object of the avatar image of the user or an error.
public func getAvatar(
userId: String,
completion: @escaping Callback<Data>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)/avatar", configuration: boxClient.configuration),
completion: { (result: Result<BoxResponse, BoxSDKError>) in
let objectResult: Result<Data, BoxSDKError> = result.flatMap { response in
guard let data = response.body else {
return .failure(BoxAPIError(message: .notFound("No user avatar returned"), response: response))
}
return .success(data)
}
completion(objectResult)
}
)
}
/// Deletes a user's avatar image.
///
/// - Parameters:
/// - userId: The ID of the user.
/// - completion: Empty response in case of success or an error.
public func deleteAvatar(
userId: String,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)/avatar", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Create a new managed user in an enterprise. This method only works for Box admins.
///
/// - Parameters:
/// - login: The email address the user uses to login
/// - name: The name of the user
/// - role: The user’s enterprise role. Can be coadmin or user
/// - language: The language of the user. Input format follows a modified version of the ISO 639-1 language code format. https://developer.box.com/docs/api-language-codes
/// - isSyncEnabled: Whether the user can use Box Sync
/// - jobTitle: The user’s job title
/// - phone: The user’s phone number
/// - address: The user’s address
/// - spaceAmount: The user’s total available space amount in bytes
/// - trackingCodes: An array of key/value pairs set by the user’s admin
/// - canSeeManagedUsers: Whether the user can see other managed users
/// - timezone: The user's timezone. Input format follows tz database timezones. https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
/// - isExternalCollabRestricted: Whether the user is restricted from external collaboration
/// - isExemptFromDeviceLimits: Whether to exempt the user from Enterprise device limits
/// - isExemptFromLoginVerification: Whether the user must use two-factor authentication
/// - status: active, inactive, cannotDeleteOrEdit, or cannotDeleteEditOrupload
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard user object or an error.
public func create(
login: String,
name: String,
role: UserRole? = nil,
language: String? = nil,
isSyncEnabled: Bool? = nil,
jobTitle: String? = nil,
phone: String? = nil,
address: String? = nil,
spaceAmount: Int64? = nil,
trackingCodes: [User.TrackingCode]? = nil,
canSeeManagedUsers: Bool? = nil,
timezone: String? = nil,
isExternalCollabRestricted: Bool? = nil,
isExemptFromDeviceLimits: Bool? = nil,
isExemptFromLoginVerification: Bool? = nil,
status: UserStatus? = nil,
fields: [String]? = nil,
completion: @escaping Callback<User>
) {
var body: [String: Any] = ["login": login, "name": name]
body["role"] = role?.description
body["language"] = language
body["is_sync_enabled"] = isSyncEnabled
body["job_title"] = jobTitle
body["phone"] = phone
body["address"] = address
body["space_amount"] = spaceAmount
body["tracking_codes"] = trackingCodes
body["can_see_managed_users"] = canSeeManagedUsers
body["timezone"] = timezone
body["is_exempt_from_device_limits"] = isExemptFromDeviceLimits
body["is_exempt_from_login_verification"] = isExemptFromLoginVerification
body["is_external_collab_restricted"] = isExternalCollabRestricted
body["status"] = status?.description
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/users", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Update the information for a user.
///
/// - Parameters:
/// - userId: The ID of the user.
/// - login: The ID of the user.
/// - name: The name of the user
/// - role: The user’s enterprise role. Can be coadmin or user
/// - language: The language of the user. Input format follows a modified version of the ISO 639-1 language code format. https://developer.box.com/docs/api-language-codes
/// - isSyncEnabled: Whether the user can use Box Sync
/// - jobTitle: The user’s job title
/// - phone: The user’s phone number
/// - address: The user’s address
/// - spaceAmount: The user’s total available space amount in bytes
/// - trackingCodes: An array of key/value pairs set by the user’s admin
/// - canSeeManagedUsers: Whether the user can see other managed users
/// - timezone: The user's timezone. Input format follows tz database timezones. https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
/// - isExternalCollabRestricted: Whether the user is restricted from external collaboration
/// - isExemptFromDeviceLimits: Whether to exempt the user from Enterprise device limits
/// - isExemptFromLoginVerification: Whether the user must use two-factor authentication
/// - status: active, inactive, cannotDeleteOrEdit, or cannotDeleteEditOrupload
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard user object or an error.
public func update(
userId: String,
login: String? = nil,
name: String? = nil,
role: UserRole? = nil,
language: String? = nil,
isSyncEnabled: Bool? = nil,
jobTitle: String? = nil,
phone: String? = nil,
address: String? = nil,
spaceAmount: Int64? = nil,
trackingCodes: [User.TrackingCode]? = nil,
canSeeManagedUsers: Bool? = nil,
timezone: String? = nil,
isExternalCollabRestricted: Bool? = nil,
isExemptFromDeviceLimits: Bool? = nil,
isExemptFromLoginVerification: Bool? = nil,
status: UserStatus? = nil,
fields: [String]? = nil,
completion: @escaping Callback<User>
) {
var body: [String: Any] = [:]
body["login"] = login
body["name"] = name
body["role"] = role?.description
body["language"] = language
body["is_sync_enabled"] = isSyncEnabled
body["job_title"] = jobTitle
body["phone"] = phone
body["address"] = address
body["space_amount"] = spaceAmount
body["tracking_codes"] = trackingCodes?.compactMap { $0.bodyDict }
body["can_see_managed_users"] = canSeeManagedUsers
body["timezone"] = timezone
body["is_exempt_from_device_limits"] = isExemptFromDeviceLimits
body["is_exempt_from_login_verification"] = isExemptFromLoginVerification
body["is_external_collab_restricted"] = isExternalCollabRestricted
body["status"] = status?.description
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Create a new app user in an enterprise.
///
/// - Parameters:
/// - name: The name of the user. All special characters are acceptable except for <, >, and " ".
/// - language: The language of the user. Input format follows a modified version of the ISO 639-1 language code format. https://developer.box.com/v2.0/docs/api-language-codes
/// - jobTitle: The user's job title
/// - timezone: The user's timezone. Input format follows tz database timezones. https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
/// - phone: The user’s phone number
/// - address: The user’s address
/// - spaceAmount: The user’s total available space amount in bytes
/// - status: active, inactive, cannotDeleteOrEdit, or cannotDeleteEditOrupload
/// - isExternalCollabRestricted: Whether the user is restricted from external collaboration
/// - canSeeManagedUsers: Whether the user can see managed users
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard user object or an error.
public func createAppUser(
name: String,
language: String? = nil,
jobTitle: String? = nil,
timezone: String? = nil,
phone: String? = nil,
address: String? = nil,
spaceAmount: Int64? = nil,
status: UserStatus? = nil,
isExternalCollabRestricted: Bool? = nil,
canSeeManagedUsers: Bool? = nil,
fields: [String]? = nil,
completion: @escaping Callback<User>
) {
var body: [String: Any] = [:]
body["name"] = name
body["language"] = language
body["job_title"] = jobTitle
body["timezone"] = timezone
body["phone"] = phone
body["address"] = address
body["space_amount"] = spaceAmount
body["status"] = status?.description
body["is_external_collab_restricted"] = isExternalCollabRestricted
body["can_see_managed_users"] = canSeeManagedUsers
body["is_platform_access_only"] = true
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/users", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Delete a user.
///
/// - Parameters:
/// - userId: The ID of the user
/// - notify: Whether the destination user will receive email notification of the transfer
/// - force: Whether the user should be deleted even if this user still own files
/// - completion: An empty response will be returned upon successful deletion. An error is
/// thrown if the folder is not empty and the ‘recursive’ parameter is not included.
public func delete(
userId: String,
notify: Bool? = nil,
force: Bool? = nil,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)", configuration: boxClient.configuration),
queryParameters: ["force": force, "notify": notify],
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Returns all of the users for the Enterprise. Only available to admin accounts or service accounts.
///
/// - Parameters:
/// - filterTerm: Only return users whose name or login matches the filter_term. See notes below for details on the matching.
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - usemarker: This specifies whether you would like to use marker-based or offset-based
/// paging. You can only use one or the other. Marker-based paging is the preferred method
/// and is most performant. If not specified, this endpoint defaults to using offset-based
/// paging. This parameter is unique to Get Folder Items to retain backwards compatibility
/// for this endpoint. This parameter is required for both the first and subsequent calls to
/// use marked-based paging.
/// - marker: The position marker at which to begin the response. See [marker-based paging]
/// (https://developer.box.com/reference#section-marker-based-paging) for details. This
/// parameter cannot be used simultaneously with the 'offset' parameter.
/// - offset: The offset of the item at which to begin the response. See [offset-based paging]
/// (https://developer.box.com/reference#section-offset-based-paging) for details.
/// - limit: The maximum number of items to return.
/// - completion: Returns an iterator of users or a BoxSDKError
public func listForEnterprise(
filterTerm: String? = nil,
fields: [String]? = nil,
usemarker: Bool? = nil,
marker: String? = nil,
offset: Int? = nil,
limit: Int? = nil
) -> PagingIterator<User> {
var queryParams: QueryParameters = [
"filter_term": filterTerm,
"fields": FieldsQueryParam(fields),
"limit": limit
]
if usemarker ?? false {
queryParams["usemarker"] = true
queryParams["marker"] = marker
}
else {
queryParams["offset"] = offset
}
return .init(
client: boxClient,
url: URL.boxAPIEndpoint("/2.0/users", configuration: boxClient.configuration),
queryParameters: queryParams
)
}
/// Invite an existing user to join an Enterprise.
///
/// - Parameters:
/// - enterpriseId: The ID of the enterprise the user will be invited to
/// - login: The login of the user that will receive the invitation
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard Invite object or an error.
public func inviteToJoinEnterprise(
login: String,
enterpriseId: String,
fields: [String]? = nil,
completion: @escaping Callback<Invite>
) {
let body = ["enterprise": ["id": enterpriseId], "actionable_by": ["login": login]]
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/invites", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Move all of the items owned by a user into a new folder in another user’s account.
///
/// - Parameters:
/// - sourceUserID: The ID of the user whose owned content will be moved
/// - destinationUserID: The ID of the user who the folder will be transferred to
/// - notify: Whether the destination user should receive email notification of the transfer
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard Folder object or an error.
public func moveItemsOwnedByUser(
withID sourceUserID: String,
toUserWithID destinationUserID: String,
notify: Bool? = nil,
fields: [String]? = nil,
completion: @escaping Callback<Folder>
) {
let body = ["owned_by": ["id": destinationUserID]]
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/users/\(sourceUserID)/folders/0", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields), "notify": notify],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Used to convert one of the user’s confirmed email aliases into the user’s primary login.
///
/// - Parameters:
/// - userId: The ID of the user
/// - login: The email alias to become the primary email
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard User object or an error.
public func changeLogin(
userId: String,
login: String,
fields: [String]? = nil,
completion: @escaping Callback<User>
) {
update(userId: userId, login: login, fields: fields, completion: completion)
}
/// Retrieves all email aliases for this user.
///
/// - Parameters:
/// - userId: The ID of the user
/// - completion: Returns a collection of Email Aliases of the user or an error.
public func listEmailAliases(
userId: String,
completion: @escaping Callback<EntryContainer<EmailAlias>>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)/email_aliases", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Adds a new email alias to the given user’s account.
///
/// - Parameters:
/// - userId: The ID of the user
/// - email: The email address to add to the account as an alias
/// - completion: Returns a Email Aliases object or an error.
public func createEmailAlias(
userId: String,
email: String,
completion: @escaping Callback<EmailAlias>
) {
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)/email_aliases", configuration: boxClient.configuration),
json: ["email": email],
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Removes an email alias from a user.
///
/// - Parameters:
/// - userId: The ID of the user
/// - emailAliasId: The ID of the email alias
/// - completion: An empty response will be returned upon successful deletion. An error is
/// thrown if the user don't have permission to delete the email alias.
public func deleteEmailAlias(
userId: String,
emailAliasId: String,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)/email_aliases/\(emailAliasId)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Roll a user out of their enterprise (and convert them to a standalone free user)
///
/// - Parameters:
/// - userId: The ID of the user
/// - notify: Whether the user should receive an email when they are rolled out of an enterprise
/// - fields: List of [user object fields](https://developer.box.com/reference#user-object) to
/// include in the response. Only those fields will be populated on the resulting model object.
/// If not passed, a default set of fields will be returned.
/// - completion: Returns a standard User object of the updated user, or an error.
public func rollOutOfEnterprise(
userId: String,
notify: Bool? = nil,
fields: [String]? = nil,
completion: @escaping Callback<User>
) {
var body: [String: Any] = ["enterprise": NSNull()]
body["notify"] = notify
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/users/\(userId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
}
| apache-2.0 | 2ef68cceadec6b01b667d0694e409be2 | 41.074184 | 181 | 0.623986 | 4.50986 | false | false | false | false |
honghaoz/UW-Quest-iOS | UW Quest/Main/MainCollectionViewController/MainCollectionViewController.swift | 1 | 8890 | //
// MainCollectionViewController.swift
// UW Quest
//
// Created by Honghao on 9/21/14.
// Copyright (c) 2014 Honghao. All rights reserved.
//
// TODO: Slide out status bar when showing menu VC
// TODO: Don't show loading HUD, load all information once
// TODO: Different iPad cell size
import UIKit
protocol MainCollectionVCImplementation {
var title: String { get }
var mainCollectionVC: MainCollectionViewController! { get set }
var collectionView: ZHDynamicCollectionView! { get set }
func setUp(collectionVC: MainCollectionViewController)
// Data Source
func numberOfSectionsInCollectionView() -> Int
func numberOfItemsInSection(section: Int) -> Int
func cellForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewCell
func titleForHeaderAtIndexPath(indexPath: NSIndexPath) -> String
// FlowLayout
func sizeForItemAtIndexPath(indexPath: NSIndexPath, layout collectionViewLayout: UICollectionViewLayout) -> CGSize
// Actions
func headerViewTapped(headerView: UQCollectionReusableView)
}
class MainCollectionViewController: UIViewController {
var currentImplemention: MainCollectionVCImplementation!
var currentShowingSection: Int = -1
@IBOutlet weak var collectionView: ZHDynamicCollectionView!
init(implementation: MainCollectionVCImplementation) {
super.init()
self.setup(implementation)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup(implementation: MainCollectionVCImplementation) {
currentImplemention = implementation
}
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
self.navigationController?.title = currentImplemention.title
}
private func setupAnimation() {
// Default animation
self.navigationController?.view.addGestureRecognizer(self.slidingViewController().panGesture)
// // Dynamic transition
// var dynamicTransition = Locator.sharedLocator.dynamicTransition
// dynamicTransition.slidingViewController = self.slidingViewController()
// self.slidingViewController().delegate = dynamicTransition
//
// self.slidingViewController().topViewAnchoredGesture = ECSlidingViewControllerAnchoredGesture.Tapping | ECSlidingViewControllerAnchoredGesture.Custom
//
// var dynamicTransitionPanGesture = UIPanGestureRecognizer(target: dynamicTransition, action: "handlePanGesture:")
// self.slidingViewController().customAnchoredGestures = [dynamicTransitionPanGesture]
// self.navigationController?.view.addGestureRecognizer(dynamicTransitionPanGesture)
//
// // Zoom transition
// let zoomTransition = Locator.sharedLocator.zoomTransition
// self.slidingViewController().delegate = zoomTransition
// self.slidingViewController().topViewAnchoredGesture = ECSlidingViewControllerAnchoredGesture.Tapping | ECSlidingViewControllerAnchoredGesture.Panning
//
// self.navigationController?.view.addGestureRecognizer(self.slidingViewController().panGesture)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
setupAnimation()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
// MARK: Actions
@IBAction func menuButtonTapped(sender: AnyObject) {
self.slidingViewController().anchorTopViewToRightAnimated(true)
}
// MARK: - Header tap gesture action
func headerViewTapped(tapGesture: UITapGestureRecognizer) {
var headerView = tapGesture.view as! UQCollectionReusableView
currentShowingSection = currentShowingSection == headerView.indexPath.section ? -1 : headerView.indexPath.section
currentImplemention.headerViewTapped(headerView)
}
}
// MARK: CollectionView
extension MainCollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var kSectionHorizontalInsets: CGFloat { return 10.0 }
var kSectionVerticalInsets: CGFloat { return 10.0 }
var kHeaderViewReuseIdentifier: String { return "HeaderView" }
var kDescriptionCellResueIdentifier: String { return "DescriptionCell" }
private func setupCollectionView() {
currentImplemention = PersonalInfoImplementation()
currentImplemention.setUp(self)
collectionView.dataSource = self
collectionView.delegate = self
// Registeration
collectionView.registerClass(DescriptionCollectionViewCell.self, forCellWithReuseIdentifier: kDescriptionCellResueIdentifier)
}
// MARK: - UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return currentImplemention.numberOfSectionsInCollectionView()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return currentImplemention.numberOfItemsInSection(section)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return currentImplemention.cellForItemAtIndexPath(indexPath)
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
var headerView: UQCollectionReusableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kHeaderViewReuseIdentifier, forIndexPath: indexPath) as! UQCollectionReusableView
// First section header, hide topSeparator line
if (indexPath.section == 0) {
headerView.topSeparator.hidden = true
headerView.bottomSeparator.hidden = true
} else {
headerView.topSeparator.hidden = false
headerView.bottomSeparator.hidden = true
}
// For current showing section
if (indexPath.section == currentShowingSection) {
headerView.bottomSeparator.hidden = true
}
if (indexPath.section == currentShowingSection + 1) {
headerView.topSeparator.hidden = true
}
headerView.indexPath = indexPath
self.attachTapGestureForHeaderView(headerView)
headerView.titleLabel.text = currentImplemention.titleForHeaderAtIndexPath(indexPath)
return headerView
}
// MARK: - UICollectionViewDelegate
// MARK: - UICollectionViewFlowLayout Delegate
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return currentImplemention.sizeForItemAtIndexPath(indexPath, layout: collectionViewLayout)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
if section == currentShowingSection {
return UIEdgeInsetsMake(kSectionVerticalInsets, kSectionHorizontalInsets, kSectionVerticalInsets, kSectionHorizontalInsets)
} else {
return UIEdgeInsetsMake(0, kSectionHorizontalInsets, 0, kSectionHorizontalInsets)
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return kSectionHorizontalInsets
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return kSectionVerticalInsets
}
}
// MARK: Rotation
extension MainCollectionViewController {
// iOS7
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
collectionView.collectionViewLayout.invalidateLayout()
}
// iOS8
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: - Helper
func attachTapGestureForHeaderView(headerView: UICollectionReusableView) {
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "headerViewTapped:" as Selector)
tapGesture.numberOfTouchesRequired = 1
headerView.addGestureRecognizer(tapGesture)
}
}
| apache-2.0 | c2bbfd9ef7a805bed793a978c3a301d0 | 41.94686 | 213 | 0.735546 | 6.027119 | false | false | false | false |
NUKisZ/MyTools | MyTools/MyTools/Tools/PhoneField.swift | 1 | 6034 | //
// PhoneField.swift
// hangge_1610_2
//
// Created by hangge on 2017/7/6.
// Copyright © 2017年 hangge.com. All rights reserved.
//
import UIKit
class PhoneField: UITextField {
//保存上一次的文本内容
var _previousText:String!
//保持上一次的文本范围
var _previousRange:UITextRange!
private var digitsText:String!=""
public var phoneNumber:String!{
get{
return digitsText
}
}
override init(frame: CGRect) {
super.init(frame: frame)
//默认边框样式为圆角矩形
self.borderStyle = UITextBorderStyle.roundedRect
//使用数字键盘
self.keyboardType = UIKeyboardType.numberPad
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//当本视图的父类视图改变的时候
override func willMove(toSuperview newSuperview: UIView?) {
//监听值改变通知事件
if newSuperview != nil {
NotificationCenter.default.addObserver(self,
selector: #selector(phoneNumberFormat(_:)),
name: NSNotification.Name.UITextFieldTextDidChange,
object: nil)
}else{
NotificationCenter.default.removeObserver(self,
name: Notification.Name.UITextFieldTextDidChange,
object: nil)
}
}
//输入框内容改变时对其内容做格式化处理
func phoneNumberFormat(_ notification: Notification) {
let textField = notification.object as! UITextField
//输入的第一个数字必需为1
if textField.text != "" && (textField.text![0] as NSString).intValue != 1 {
//第1位输入非1数则使用原来值,且关闭停留在开始位置
textField.text = _previousText
let start = textField.beginningOfDocument
textField.selectedTextRange = textField.textRange(from: start, to: start)
return
}
//当前光标的位置(后面会对其做修改)
var cursorPostion = textField.offset(from: textField.beginningOfDocument,
to: textField.selectedTextRange!.start)
//过滤掉非数字字符,只保留数字
digitsText = getDigitsText(string: textField.text!,
cursorPosition: &cursorPostion)
//避免超过11位的输入
if digitsText.characters.count > 11 {
textField.text = _previousText
textField.selectedTextRange = _previousRange
return
}
//得到带有分隔符的字符串
let hyphenText = getHyphenText(string: digitsText, cursorPosition: &cursorPostion)
//将最终带有分隔符的字符串显示到textField上
textField.text = hyphenText
//让光标停留在正确位置
let targetPostion = textField.position(from: textField.beginningOfDocument,
offset: cursorPostion)!
textField.selectedTextRange = textField.textRange(from: targetPostion,
to: targetPostion)
//现在的值和选中范围,供下一次输入使用
_previousText = self.text!
_previousRange = self.selectedTextRange!
}
//除去非数字字符,同时确定光标正确位置
func getDigitsText(string:String, cursorPosition:inout Int) -> String{
//保存开始时光标的位置
let originalCursorPosition = cursorPosition
//处理后的结果字符串
var result = ""
var i = 0
//遍历每一个字符
for uni in string.unicodeScalars {
//如果是数字则添加到返回结果中
if CharacterSet.decimalDigits.contains(uni) {
//let str = string[i] as Character
result.append(string[i])
}
//非数字则跳过,如果这个非法字符在光标位置之前,则光标需要向前移动
else{
if i < originalCursorPosition {
cursorPosition = cursorPosition - 1
}
}
i = i + 1
}
return result
}
//将分隔符插入现在的string中,同时确定光标正确位置
func getHyphenText(string:String, cursorPosition:inout Int) -> String {
//保存开始时光标的位置
let originalCursorPosition = cursorPosition
//处理后的结果字符串
var result = ""
//遍历每一个字符
for i in 0 ..< string.characters.count {
//如果当前到了第4个、第8个数字,则先添加个分隔符
if i == 3 || i == 7 {
result.append("-")
//如果添加分隔符位置在光标前面,光标则需向后移动一位
if i < originalCursorPosition {
cursorPosition = cursorPosition + 1
}
}
//let str = string[i] as Character
result.append(string[i])
}
return result
}
}
//通过对String扩展,字符串增加下表索引功能
extension String
{
subscript(index:Int) -> String
{
get{
return String(self[self.index(self.startIndex, offsetBy: index)])
}
set{
let tmp = self
self = ""
for (idx, item) in tmp.characters.enumerated() {
if idx == index {
self += "\(newValue)"
}else{
self += "\(item)"
}
}
}
}
}
| mit | 47c6d9b51b01cb001bc991eae10ab916 | 29.331395 | 90 | 0.521564 | 4.716998 | false | false | false | false |
treejames/firefox-ios | Storage/SuggestedSites.swift | 5 | 1674 | /* 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 XCGLogger
import UIKit
import Shared
private let log = XCGLogger.defaultInstance()
public class SuggestedSite: Site {
public let wordmark: Favicon
public let backgroundColor: UIColor
let trackingId: Int
init(json: JSON) {
self.backgroundColor = UIColor(colorString: json["bgcolor"].asString!)
self.trackingId = json["trackingid"].asInt ?? 0
self.wordmark = Favicon(url: json["imageurl"].asString!, date: NSDate(), type: .Icon)
super.init(url: json["url"].asString!, title: json["title"].asString!)
self.icon = Favicon(url: json["faviconUrl"].asString!, date: NSDate(), type: .Icon)
}
}
public let SuggestedSites: SuggestedSitesData<SuggestedSite> = SuggestedSitesData<SuggestedSite>()
public class SuggestedSitesData<T>: ArrayCursor<SuggestedSite> {
private init() {
// TODO: Make this list localized. That should be as simple as making sure it's in the lproj directory.
var err: NSError? = nil
let path = NSBundle.mainBundle().pathForResource("suggestedsites", ofType: "json")
let data = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err)
let json = JSON.parse(data as! String)
var tiles = [SuggestedSite]()
for i in 0..<json.length {
let t = SuggestedSite(json: json[i])
tiles.append(t)
}
super.init(data: tiles, status: .Success, statusMessage: "Loaded")
}
}
| mpl-2.0 | 5ff4c37a0fbfa25e3feb4bcef62bf56b | 36.2 | 111 | 0.669056 | 4.174564 | false | false | false | false |
gaurav1981/HackingWithSwift | project29/Project29/BuildingNode.swift | 20 | 2728 | //
// BuildingNode.swift
// Project29
//
// Created by Hudzilla on 26/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import SpriteKit
import UIKit
class BuildingNode: SKSpriteNode {
var currentImage: UIImage!
func setup() {
name = "building"
currentImage = drawBuilding(size)
texture = SKTexture(image: currentImage)
configurePhysics()
}
func configurePhysics() {
physicsBody = SKPhysicsBody(texture: texture, size: size)
physicsBody!.dynamic = false
physicsBody!.categoryBitMask = CollisionTypes.Building.rawValue
physicsBody!.contactTestBitMask = CollisionTypes.Banana.rawValue
}
func drawBuilding(size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context = UIGraphicsGetCurrentContext()
// DRAW THE MAIN BUILDING BLOCK
let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height)
var color: UIColor
switch RandomInt(min: 0, max: 2) {
case 0:
color = UIColor(hue: 0.502, saturation: 0.98, brightness: 0.67, alpha: 1)
case 1:
color = UIColor(hue: 0.999, saturation: 0.99, brightness: 0.67, alpha: 1)
default:
color = UIColor(hue: 0, saturation: 0, brightness: 0.67, alpha: 1)
}
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextAddRect(context, rectangle)
CGContextDrawPath(context, kCGPathFill)
// DRAW WINDOWS
for var row: CGFloat = 10; row < size.height - 10; row += 40 {
for var col: CGFloat = 10; col < size.width - 10; col += 40 {
var lightOnColor = UIColor(hue: 0.190, saturation: 0.67, brightness: 0.99, alpha: 1)
var lightOffColor = UIColor(hue: 0, saturation: 0, brightness: 0.34, alpha: 1)
if RandomInt(min: 0, max: 1) == 0 {
CGContextSetFillColorWithColor(context, lightOnColor.CGColor)
} else {
CGContextSetFillColorWithColor(context, lightOffColor.CGColor)
}
CGContextFillRect(context, CGRect(x: col, y: row, width: 15, height: 20))
}
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
func hitAtPoint(point: CGPoint) {
var convertedPoint = CGPoint(x: point.x + size.width / 2.0, y: (size.height / 2.0) - point.y)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context = UIGraphicsGetCurrentContext()
currentImage.drawAtPoint(CGPoint(x: 0, y: 0))
CGContextAddEllipseInRect(context, CGRect(x: convertedPoint.x - 32, y: convertedPoint.y - 32, width: 64, height: 64))
CGContextSetBlendMode(context, kCGBlendModeClear)
CGContextDrawPath(context, kCGPathFill)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
texture = SKTexture(image: img)
currentImage = img
configurePhysics()
}
}
| unlicense | a1bdbdf2c80f574031b0cdb942f17571 | 28.021277 | 119 | 0.718109 | 3.580052 | false | false | false | false |
HongliYu/firefox-ios | XCUITests/HistoryTests.swift | 1 | 12083 | /* 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 XCTest
let webpage = ["url": "www.mozilla.org", "label": "Internet for people, not profit — Mozilla", "value": "mozilla.org"]
let oldHistoryEntries: [String] = ["Internet for people, not profit — Mozilla", "Twitter", "Home - YouTube"]
// This is part of the info the user will see in recent closed tabs once the default visited website (https://www.mozilla.org/en-US/book/) is closed
let closedWebPageLabel = "localhost:\(serverPort)/test-fixture/test-mozilla-book.html"
class HistoryTests: BaseTestCase {
let testWithDB = ["testOpenHistoryFromBrowserContextMenuOptions", "testClearHistoryFromSettings", "testClearRecentHistory"]
// This DDBB contains those 4 websites listed in the name
let historyDB = "browserYoutubeTwitterMozillaExample.db"
override func setUp() {
// Test name looks like: "[Class testFunc]", parse out the function name
let parts = name.replacingOccurrences(of: "]", with: "").split(separator: " ")
let key = String(parts[1])
if testWithDB.contains(key) {
// for the current test name, add the db fixture used
launchArguments = [LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew, LaunchArguments.LoadDatabasePrefix + historyDB]
}
super.setUp()
}
func testEmptyHistoryListFirstTime() {
// Go to History List from Top Sites and check it is empty
navigator.goto(HomePanel_History)
waitForExistence(app.tables.cells["HistoryPanel.recentlyClosedCell"])
XCTAssertTrue(app.tables.cells["HistoryPanel.recentlyClosedCell"].exists)
XCTAssertTrue(app.tables.cells["HistoryPanel.syncedDevicesCell"].exists)
}
func testOpenSyncDevices() {
navigator.goto(HomePanel_History)
app.tables.cells["HistoryPanel.syncedDevicesCell"].tap()
waitForExistence(app.tables.cells.staticTexts["Firefox Sync"])
XCTAssertTrue(app.tables.buttons["Sign in to Sync"].exists, "Sing in button does not appear")
}
func testClearHistoryFromSettings() {
// Browse to have an item in history list
navigator.goto(HomePanel_History)
waitForExistence(app.tables.cells["HistoryPanel.recentlyClosedCell"], timeout: 5)
XCTAssertTrue(app.tables.cells.staticTexts[webpage["label"]!].exists)
// Go to Clear Data
navigator.performAction(Action.AcceptClearPrivateData)
// Back on History panel view check that there is not any item
navigator.goto(HomePanel_History)
waitForExistence(app.tables.cells["HistoryPanel.recentlyClosedCell"])
XCTAssertFalse(app.tables.cells.staticTexts[webpage["label"]!].exists)
}
func testClearPrivateDataButtonDisabled() {
//Clear private data from settings and confirm
navigator.goto(ClearPrivateDataSettings)
app.tables.cells["ClearPrivateData"].tap()
app.alerts.buttons["OK"].tap()
//Wait for OK pop-up to disappear after confirming
waitForNoExistence(app.alerts.buttons["OK"], timeoutValue:5)
//Try to tap on the disabled Clear Private Data button
app.tables.cells["ClearPrivateData"].tap()
//If the button is disabled, the confirmation pop-up should not exist
XCTAssertEqual(app.alerts.buttons["OK"].exists, false)
}
func testRecentlyClosedOptionAvailable() {
navigator.goto(HistoryRecentlyClosed)
waitForNoExistence(app.tables["Recently Closed Tabs List"])
// Go to the default web site and check whether the option is enabled
navigator.nowAt(HomePanel_History)
navigator.goto(HomePanelsScreen)
userState.url = path(forTestPage: "test-mozilla-book.html")
navigator.goto(BrowserTab)
navigator.goto(BrowserTabMenu)
// Workaround to bug 1508368
navigator.goto(HomePanel_Bookmarks)
navigator.goto(HomePanel_History)
navigator.goto(HistoryRecentlyClosed)
waitForNoExistence(app.tables["Recently Closed Tabs List"])
navigator.nowAt(HomePanel_History)
navigator.goto(HomePanelsScreen)
// Now go back to default website close it and check whether the option is enabled
navigator.openURL(path(forTestPage: "test-mozilla-book.html"))
waitUntilPageLoad()
waitForTabsButton()
navigator.goto(TabTray)
navigator.performAction(Action.AcceptRemovingAllTabs)
navigator.nowAt(NewTabScreen)
navigator.goto(BrowserTabMenu)
navigator.goto(HistoryRecentlyClosed)
// The Closed Tabs list should contain the info of the website just closed
waitForExistence(app.tables["Recently Closed Tabs List"], timeout: 3)
XCTAssertTrue(app.tables.cells.staticTexts[closedWebPageLabel].exists)
navigator.goto(HomePanelsScreen)
// This option should be enabled on private mode too
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.performAction(Action.OpenNewTabFromTabTray)
navigator.nowAt(NewTabScreen)
navigator.goto(BrowserTabMenu)
navigator.goto(HistoryRecentlyClosed)
waitForExistence(app.tables["Recently Closed Tabs List"])
}
func testClearRecentlyClosedHistory() {
// Open the default website
userState.url = path(forTestPage: "test-mozilla-book.html")
navigator.goto(BrowserTab)
waitForTabsButton()
navigator.goto(TabTray)
navigator.performAction(Action.AcceptRemovingAllTabs)
navigator.nowAt(NewTabScreen)
navigator.goto(BrowserTabMenu)
navigator.goto(HistoryRecentlyClosed)
// Once the website is visited and closed it will appear in Recently Closed Tabs list
waitForExistence(app.tables["Recently Closed Tabs List"])
XCTAssertTrue(app.tables.cells.staticTexts[closedWebPageLabel].exists)
navigator.goto(HomePanelsScreen)
// Go to settings and clear private data
navigator.performAction(Action.AcceptClearPrivateData)
// Back on History panel view check that there is not any item
navigator.goto(HistoryRecentlyClosed)
waitForNoExistence(app.tables["Recently Closed Tabs List"])
}
func testLongTapOptionsRecentlyClosedItem() {
// Open the default website
userState.url = path(forTestPage: "test-mozilla-book.html")
navigator.goto(BrowserTab)
waitForTabsButton()
navigator.goto(TabTray)
navigator.performAction(Action.AcceptRemovingAllTabs)
navigator.nowAt(NewTabScreen)
navigator.goto(BrowserTabMenu)
navigator.goto(HistoryRecentlyClosed)
waitForExistence(app.tables["Recently Closed Tabs List"])
XCTAssertTrue(app.tables.cells.staticTexts[closedWebPageLabel].exists)
app.tables.cells.staticTexts[closedWebPageLabel].press(forDuration: 1)
waitForExistence(app.tables["Context Menu"])
XCTAssertTrue(app.tables.cells["quick_action_new_tab"].exists)
XCTAssertTrue(app.tables.cells["quick_action_new_private_tab"].exists)
}
func testOpenInNewTabRecentlyClosedItem() {
// Open the default website
userState.url = path(forTestPage: "test-mozilla-book.html")
navigator.goto(BrowserTab)
waitForTabsButton()
navigator.goto(TabTray)
navigator.performAction(Action.AcceptRemovingAllTabs)
navigator.nowAt(NewTabScreen)
navigator.goto(HistoryRecentlyClosed)
waitForExistence(app.tables["Recently Closed Tabs List"])
XCTAssertTrue(app.tables.cells.staticTexts[closedWebPageLabel].exists)
let numTabsOpen = userState.numTabs
XCTAssertEqual(numTabsOpen, 1)
app.tables.cells.staticTexts[closedWebPageLabel].press(forDuration: 1)
waitForExistence(app.tables["Context Menu"])
app.tables.cells["quick_action_new_tab"].tap()
navigator.goto(TabTray)
let numTabsOpen2 = userState.numTabs
XCTAssertEqual(numTabsOpen2, 2)
}
func testOpenInNewPrivateTabRecentlyClosedItem() {
// Open the default website
userState.url = path(forTestPage: "test-mozilla-book.html")
navigator.goto(BrowserTab)
waitForTabsButton()
navigator.goto(TabTray)
navigator.performAction(Action.AcceptRemovingAllTabs)
navigator.nowAt(NewTabScreen)
navigator.goto(HistoryRecentlyClosed)
waitForExistence(app.tables["Recently Closed Tabs List"])
XCTAssertTrue(app.tables.cells.staticTexts[closedWebPageLabel].exists)
app.tables.cells.staticTexts[closedWebPageLabel].press(forDuration: 1)
waitForExistence(app.tables["Context Menu"])
app.tables.cells["quick_action_new_private_tab"].tap()
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.goto(TabTray)
let numTabsOpen = userState.numTabs
XCTAssertEqual(numTabsOpen, 1)
}
func testPrivateClosedSiteDoesNotAppearOnRecentlyClosed() {
waitForTabsButton()
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
// Open the default website
userState.url = path(forTestPage: "test-mozilla-book.html")
navigator.goto(BrowserTab)
// It is necessary to open two sites so that when one is closed private mode is not closed
navigator.openNewURL(urlString: path(forTestPage: "test-mozilla-org.html"))
waitUntilPageLoad()
waitForTabsButton()
navigator.goto(TabTray)
waitForExistence(app.collectionViews.cells[webpage["label"]!])
// 'x' button to close the tab is not visible, so closing by swiping the tab
app.collectionViews.cells[webpage["label"]!].swipeRight()
navigator.performAction(Action.OpenNewTabFromTabTray)
navigator.goto(HomePanelsScreen)
navigator.goto(HomePanel_History)
XCTAssertFalse(app.cells.staticTexts["Recently Closed"].isSelected)
waitForNoExistence(app.tables["Recently Closed Tabs List"])
// Now verify that on regular mode the recently closed list is empty too
navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.goto(NewTabScreen)
navigator.goto(HomePanel_History)
XCTAssertFalse(app.cells.staticTexts["Recently Closed"].isSelected)
waitForNoExistence(app.tables["Recently Closed Tabs List"])
}
// Private function created to select desired option from the "Clear Recent History" list
// We used this aproch to avoid code duplication
private func tapOnClearRecentHistoryOption(optionSelected: String) {
app.sheets.buttons[optionSelected].tap()
}
func testClearRecentHistory() {
navigator.performAction(Action.ClearRecentHistory)
tapOnClearRecentHistoryOption(optionSelected: "The Last Hour")
// No data will be removed after Action.ClearRecentHistory since there is no recent history created.
for entry in oldHistoryEntries {
XCTAssertTrue(app.tables.cells.staticTexts[entry].exists)
}
// Go to 'goolge.com' to create a recent history entry.
navigator.openURL("google.com")
navigator.goto(HomePanel_History)
XCTAssertTrue(app.tables.cells.staticTexts["Google"].exists)
navigator.performAction(Action.ClearRecentHistory)
// Recent data will be removed after calling tapOnClearRecentHistoryOption(optionSelected: "Today").
// Older data will not be removed
tapOnClearRecentHistoryOption(optionSelected: "Today")
for entry in oldHistoryEntries {
XCTAssertTrue(app.tables.cells.staticTexts[entry].exists)
}
XCTAssertFalse(app.tables.cells.staticTexts["Google"].exists)
}
}
| mpl-2.0 | c3afeae4336f5430c82827a0317807d4 | 45.817829 | 148 | 0.702956 | 4.874496 | false | true | false | false |
MichaelRow/MusicPlayer | Sources/Manager/MusicPlayerManager.swift | 1 | 5375 | //
// MusicPlayerManager.swift
// MusicPlayer
//
// Created by Michael Row on 2017/9/3.
//
import Foundation
public class MusicPlayerManager {
public weak var delegate: MusicPlayerManagerDelegate?
public fileprivate(set) var musicPlayers = [MusicPlayer]()
public fileprivate(set) weak var currentPlayer: MusicPlayer?
public init() {}
}
// MARK: - Public Manager Methods
public extension MusicPlayerManager {
/// The player names that added to the manager.
public var allPlayerNames: [MusicPlayerName] {
var playerNames = [MusicPlayerName]()
for player in musicPlayers {
playerNames.append(player.name)
}
return playerNames
}
/// Return the player with selected name if exists.
public func existMusicPlayer(with name: MusicPlayerName) -> MusicPlayer? {
for player in musicPlayers {
if player.name == name {
return player
}
}
return nil
}
/// Add a music player to the manager.
///
/// - Parameter name: The name of the music player you wanna add.
public func add(musicPlayer name: MusicPlayerName) {
for player in musicPlayers {
guard player.name != name else { return }
}
guard let player = MusicPlayerFactory.musicPlayer(name: name) else { return }
player.delegate = self
player.startPlayerTracking()
musicPlayers.append(player)
selectMusicPlayer(with: player)
}
/// Add music players to the manager.
///
/// - Parameter names: The names of the music player you wanna add.
public func add(musicPlayers names: [MusicPlayerName]) {
for name in names {
add(musicPlayer: name)
}
}
/// Remove a music player from the manager.
///
/// - Parameter name: The name of the music player you wanna remove.
public func remove(musicPlayer name: MusicPlayerName) {
for index in 0 ..< musicPlayers.count {
let player = musicPlayers[index]
guard player.name == name else { continue }
player.stopPlayerTracking()
musicPlayers.remove(at: index)
// if the removal is the current player, we should select a new one.
if currentPlayer?.name == player.name {
currentPlayer = nil
selectMusicPlayerFromList()
}
return
}
}
/// Remove music players from the manager.
///
/// - Parameter names: The names of the music player you wanna remove.
public func remove(musicPlayers names: [MusicPlayerName]) {
for name in names {
remove(musicPlayer: name)
}
}
/// Remove all music players from the manager.
public func removeAllMusicPlayers() {
for player in musicPlayers {
player.stopPlayerTracking()
}
musicPlayers.removeAll()
currentPlayer = nil
}
}
// MARK: - MusicPlayerDelegate
extension MusicPlayerManager: MusicPlayerDelegate {
public func player(_ player: MusicPlayer, didChangeTrack track: MusicTrack, atPosition position: TimeInterval) {
selectMusicPlayer(with: player)
guard currentPlayer?.name == player.name else { return }
delegate?.manager(self, trackingPlayer: player, didChangeTrack: track, atPosition: position)
}
public func player(_ player: MusicPlayer, playbackStateChanged playbackState: MusicPlaybackState, atPosition postion: TimeInterval) {
selectMusicPlayer(with: player)
guard currentPlayer?.name == player.name else { return }
delegate?.manager(self, trackingPlayer: player, playbackStateChanged: playbackState, atPosition: postion)
if !playbackState.isActiveState {
selectMusicPlayerFromList()
}
}
public func playerDidQuit(_ player: MusicPlayer) {
guard currentPlayer != nil,
currentPlayer!.name == player.name
else { return }
currentPlayer = nil
delegate?.manager(self, trackingPlayerDidQuit: player)
selectMusicPlayerFromList()
}
fileprivate func selectMusicPlayerFromList() {
for player in musicPlayers {
selectMusicPlayer(with: player)
if let playerState = currentPlayer?.playbackState,
playerState.isActiveState {
return
}
}
}
fileprivate func selectMusicPlayer(with player: MusicPlayer) {
guard shouldChangePlayer(with: player) else { return }
currentPlayer = player
delegate?.manager(self, trackingPlayerDidChange: player)
}
fileprivate func shouldChangePlayer(with player: MusicPlayer) -> Bool {
// check wheter the new player and current one are the same player.
guard currentPlayer !== player else { return false }
// check the new player's playback state
guard player.playbackState.isActiveState else { return false }
// check current player's playback state
guard let playbackState = currentPlayer?.playbackState else { return true }
if playbackState.isActiveState {
return false
} else {
return true
}
}
}
| gpl-3.0 | 3c902501cf805f8d152348f89732d583 | 31.379518 | 137 | 0.622512 | 5.353586 | false | false | false | false |
johntmcintosh/BarricadeKit | DevelopmentApp/Pods/Sourcery/bin/Sourcery.app/Contents/Resources/SwiftTemplateRuntime/Typealias.swift | 1 | 2079 | import Foundation
// sourcery: skipJSExport
final class Typealias: NSObject, Typed, SourceryModel {
// New typealias name
let aliasName: String
// Target name
let typeName: TypeName
// sourcery: skipEquality, skipDescription
var type: Type?
// sourcery: skipEquality, skipDescription
var parent: Type? {
didSet {
parentName = parent?.name
}
}
private(set) var parentName: String?
var name: String {
if let parentName = parent?.name {
return "\(parentName).\(aliasName)"
} else {
return aliasName
}
}
init(aliasName: String = "", typeName: TypeName, parent: Type? = nil) {
self.aliasName = aliasName
self.typeName = typeName
self.parent = parent
self.parentName = parent?.name
}
// sourcery:inline:Typealias.AutoCoding
/// :nodoc:
required internal init?(coder aDecoder: NSCoder) {
guard let aliasName: String = aDecoder.decode(forKey: "aliasName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["aliasName"])); fatalError() }; self.aliasName = aliasName
guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName
self.type = aDecoder.decode(forKey: "type")
self.parent = aDecoder.decode(forKey: "parent")
self.parentName = aDecoder.decode(forKey: "parentName")
}
/// :nodoc:
internal func encode(with aCoder: NSCoder) {
aCoder.encode(self.aliasName, forKey: "aliasName")
aCoder.encode(self.typeName, forKey: "typeName")
aCoder.encode(self.type, forKey: "type")
aCoder.encode(self.parent, forKey: "parent")
aCoder.encode(self.parentName, forKey: "parentName")
}
// sourcery:end
}
| mit | 27efabf11c953efb61ec8dc539e8d142 | 35.473684 | 252 | 0.620972 | 4.62 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/TabContentsScripts/LocalRequestHelper.swift | 2 | 1499 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import WebKit
import Shared
class LocalRequestHelper: TabContentScript {
func scriptMessageHandlerName() -> String? {
return "localRequestHelper"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let requestUrl = message.frameInfo.request.url,
let internalUrl = InternalURL(requestUrl)
else { return }
let params = message.body as! [String: String]
guard let token = params["appIdToken"],
token == UserScriptManager.appIdToken
else {
print("Missing required appid token.")
return
}
if params["type"] == "reload" {
// If this is triggered by session restore pages, the url to reload is a nested url argument.
if let _url = internalUrl.extractedUrlParam, let nested = InternalURL(_url), let url = nested.extractedUrlParam {
message.webView?.replaceLocation(with: url)
} else {
_ = message.webView?.reload()
}
} else {
assertionFailure("Invalid message: \(message.body)")
}
}
class func name() -> String {
return "LocalRequestHelper"
}
}
| mpl-2.0 | e66286e0d68393b84e58b963c2cbd799 | 33.860465 | 132 | 0.631087 | 4.930921 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/UITestsFoundation/Screens/Me/ContactUsScreen.swift | 1 | 2281 | import ScreenObject
import XCTest
/// This screen object is for the Support section. In the app, it's a modal we can get to from Me
/// > Help & Support > Contact Support, or, when logged out, from Prologue > tap either continue button > Help > Contact Support.
public class ContactUsScreen: ScreenObject {
private let closeButtonGetter: (XCUIApplication) -> XCUIElement = {
$0.buttons["ZDKbackButton"]
}
private let sendButtonGetter: (XCUIApplication) -> XCUIElement = {
$0.buttons["ZDKsendButton"]
}
private let attachButtonGetter: (XCUIApplication) -> XCUIElement = {
$0.buttons["ZDKattachButton"]
}
private let deleteMessageButtonGetter: (XCUIApplication) -> XCUIElement = {
$0.buttons["Delete"]
}
var closeButton: XCUIElement { closeButtonGetter(app) }
var sendButton: XCUIElement { sendButtonGetter(app) }
var attachButton: XCUIElement { attachButtonGetter(app) }
var deleteMessageButton: XCUIElement { deleteMessageButtonGetter(app) }
public init(app: XCUIApplication = XCUIApplication()) throws {
// Notice we are not checking for the send button because it's visible but not enabled,
// and `ScreenObject` checks for enabled elements.
try super.init(
expectedElementGetters: [
closeButtonGetter,
attachButtonGetter,
],
app: app,
waitTimeout: 7
)
}
@discardableResult
public func assertCanNotSendEmptyMessage() -> ContactUsScreen {
XCTAssert(!sendButton.isEnabled)
return self
}
@discardableResult
public func assertCanSendMessage() -> ContactUsScreen {
XCTAssert(sendButton.isEnabled)
return self
}
public func enterText(_ text: String) -> ContactUsScreen {
app.typeText(text)
return self
}
public func dismiss() throws -> SupportScreen {
closeButton.tap()
discardMessageIfNeeded()
return try SupportScreen()
}
private func discardMessageIfNeeded() {
if deleteMessageButton.isHittable {
deleteMessageButton.tap()
}
}
static func isLoaded() -> Bool {
(try? SupportScreen().isLoaded) ?? false
}
}
| gpl-2.0 | 7c0002e65be56cd809a07790cc4e33a9 | 29.824324 | 129 | 0.647961 | 4.947939 | false | false | false | false |
sjchmiela/call-of-beacons | ios/CallOfBeacons/CallOfBeacons/COBBeaconView.swift | 1 | 7340 | //
// COBBeaconView.swift
// CallOfBeacons
//
// Created by Stanisław Chmiela on 04.06.2016.
// Copyright © 2016 Stanisław Chmiela, Rafał Żelazko. All rights reserved.
//
import UIKit
@IBDesignable
class COBBeaconView: UIView {
var shapeLayer: CAShapeLayer!
var pulseAnimationLayer: LFTPulseAnimation?
@IBInspectable var fillColor: UIColor? {
didSet {
shapeLayer.fillColor = fillColor?.CGColor
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
shapeLayer.strokeColor = borderColor?.CGColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
shapeLayerInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
shapeLayerInit()
}
convenience init(center: CGPoint) {
self.init(frame: CGRect(x: center.x - 17, y: center.y - 24, width: 34, height: 48))
}
func updateWithBeacon(beacon: COBBeacon?, andGamerState gamerState: COBGamerState?) {
if let beacon = beacon {
fillColor = UIColor(hexString: beacon.color) ?? UIColor.whiteColor()
if let behavior = beacon.behavior, let gamerState = gamerState where behavior.highlighted(beacon, forGamerState: gamerState) {
borderColor = UIColor.whiteColor()
} else {
borderColor = UIColor.blackColor()
}
if let proximity = beacon.proximity {
layer.opacity = proximity == .Unknown ? (layer.opacity == 0 ? 0 : 0.5) : 1
if let radius = beacon.behavior?.pulseRadius(beacon, forGamerState: gamerState), let shapeLayer = shapeLayer {
pulseAnimationLayer?.removeFromSuperlayer()
pulseAnimationLayer = LFTPulseAnimation(repeatCount: 1, radius: radius, position: bounds.center)
layer.insertSublayer(pulseAnimationLayer!, below: shapeLayer)
}
} else {
layer.opacity = 0
}
} else {
layer.opacity = 0
}
}
private func shapeLayerInit() {
shapeLayer = CAShapeLayer()
shapeLayer.path = drawing.CGPath
shapeLayer.fillColor = UIColor.whiteColor().CGColor
shapeLayer.strokeColor = UIColor.blackColor().CGColor
shapeLayer.lineWidth = 0.5
shapeLayer.position = CGPoint(x: 0, y: 0)
layer.addSublayer(shapeLayer)
}
let drawing: UIBezierPath = {
//// PaintCode Trial Version
//// www.paintcodeapp.com
//// layer1
//// path6017 Drawing
let path6017Path = UIBezierPath()
path6017Path.moveToPoint(CGPoint(x: 17.35, y: 8.63))
path6017Path.addLineToPoint(CGPoint(x: 17.35, y: 8.63))
path6017Path.addCurveToPoint(CGPoint(x: 16.55, y: 9.43), controlPoint1: CGPoint(x: 17.35, y: 9.07), controlPoint2: CGPoint(x: 16.99, y: 9.43))
path6017Path.addLineToPoint(CGPoint(x: 16.55, y: 9.43))
path6017Path.addCurveToPoint(CGPoint(x: 15.75, y: 8.63), controlPoint1: CGPoint(x: 16.11, y: 9.43), controlPoint2: CGPoint(x: 15.75, y: 9.07))
path6017Path.addLineToPoint(CGPoint(x: 15.75, y: 8.63))
path6017Path.addCurveToPoint(CGPoint(x: 16.55, y: 7.83), controlPoint1: CGPoint(x: 15.75, y: 8.18), controlPoint2: CGPoint(x: 16.11, y: 7.83))
path6017Path.addLineToPoint(CGPoint(x: 16.55, y: 7.83))
path6017Path.addCurveToPoint(CGPoint(x: 17.35, y: 8.63), controlPoint1: CGPoint(x: 16.99, y: 7.83), controlPoint2: CGPoint(x: 17.35, y: 8.18))
path6017Path.closePath()
path6017Path.moveToPoint(CGPoint(x: 23.18, y: 1.79))
path6017Path.addLineToPoint(CGPoint(x: 21.93, y: 3.31))
path6017Path.addLineToPoint(CGPoint(x: 8.21, y: 4.47))
path6017Path.addLineToPoint(CGPoint(x: 7.59, y: 5.71))
path6017Path.addLineToPoint(CGPoint(x: 9.46, y: 33.16))
path6017Path.addLineToPoint(CGPoint(x: 3.58, y: 36.37))
path6017Path.addLineToPoint(CGPoint(x: 1.53, y: 34.32))
path6017Path.addLineToPoint(CGPoint(x: 3.13, y: 40.11))
path6017Path.addLineToPoint(CGPoint(x: 5.63, y: 40.29))
path6017Path.addLineToPoint(CGPoint(x: 18.73, y: 45.99))
path6017Path.addLineToPoint(CGPoint(x: 20.24, y: 47.24))
path6017Path.addLineToPoint(CGPoint(x: 26.66, y: 45.37))
path6017Path.addLineToPoint(CGPoint(x: 27.99, y: 44.75))
path6017Path.addLineToPoint(CGPoint(x: 27.37, y: 43.14))
path6017Path.addLineToPoint(CGPoint(x: 20.33, y: 45.01))
path6017Path.addLineToPoint(CGPoint(x: 18.82, y: 45.91))
path6017Path.addLineToPoint(CGPoint(x: 5.45, y: 40.2))
path6017Path.addLineToPoint(CGPoint(x: 3.49, y: 36.37))
path6017Path.addLineToPoint(CGPoint(x: 9.37, y: 33.16))
path6017Path.addLineToPoint(CGPoint(x: 14, y: 34.85))
path6017Path.addLineToPoint(CGPoint(x: 20.42, y: 45.01))
path6017Path.addLineToPoint(CGPoint(x: 27.28, y: 43.05))
path6017Path.addLineToPoint(CGPoint(x: 32.09, y: 32.45))
path6017Path.addLineToPoint(CGPoint(x: 32.18, y: 29.6))
path6017Path.addLineToPoint(CGPoint(x: 28.35, y: 18.37))
path6017Path.addLineToPoint(CGPoint(x: 25.23, y: 5.18))
path6017Path.addLineToPoint(CGPoint(x: 25.5, y: 2.68))
path6017Path.addLineToPoint(CGPoint(x: 25.32, y: 5.09))
path6017Path.addLineToPoint(CGPoint(x: 22.02, y: 3.4))
path6017Path.addLineToPoint(CGPoint(x: 25.14, y: 5.18))
path6017Path.addLineToPoint(CGPoint(x: 28.44, y: 18.55))
path6017Path.addLineToPoint(CGPoint(x: 14, y: 34.68))
path6017Path.addLineToPoint(CGPoint(x: 9.28, y: 33.25))
path6017Path.addLineToPoint(CGPoint(x: 7.5, y: 6.07))
path6017Path.addLineToPoint(CGPoint(x: 8.39, y: 4.56))
path6017Path.addLineToPoint(CGPoint(x: 22.02, y: 3.31))
path6017Path.addLineToPoint(CGPoint(x: 25.32, y: 5.09))
path6017Path.addLineToPoint(CGPoint(x: 25.59, y: 2.68))
path6017Path.addLineToPoint(CGPoint(x: 23.18, y: 1.79))
path6017Path.closePath()
path6017Path.moveToPoint(CGPoint(x: 8.92, y: 2.95))
path6017Path.addLineToPoint(CGPoint(x: -0.34, y: 24.87))
path6017Path.addLineToPoint(CGPoint(x: 2.86, y: 40.02))
path6017Path.addLineToPoint(CGPoint(x: 4.56, y: 42.52))
path6017Path.addLineToPoint(CGPoint(x: 16.77, y: 47.86))
path6017Path.addLineToPoint(CGPoint(x: 20.24, y: 47.42))
path6017Path.addLineToPoint(CGPoint(x: 26.66, y: 45.46))
path6017Path.addLineToPoint(CGPoint(x: 31.56, y: 42.25))
path6017Path.addLineToPoint(CGPoint(x: 32.27, y: 31.47))
path6017Path.addLineToPoint(CGPoint(x: 31.29, y: 16.14))
path6017Path.addLineToPoint(CGPoint(x: 27.28, y: 4.29))
path6017Path.addLineToPoint(CGPoint(x: 25.77, y: 2.77))
path6017Path.addLineToPoint(CGPoint(x: 23.36, y: 1.79))
path6017Path.addLineToPoint(CGPoint(x: 16.77, y: 0.28))
path6017Path.addLineToPoint(CGPoint(x: 8.92, y: 2.95))
path6017Path.closePath()
path6017Path.miterLimit = 4;
path6017Path.lineCapStyle = .Round;
return path6017Path
}()
}
| mit | 26629475a873599324fb0dca87b1e2a4 | 46.62987 | 150 | 0.630402 | 3.416395 | false | false | false | false |
ralcr/Localizabler | Localizabler/LocalizationsPresenter.swift | 1 | 8824 | //
// AppPresenter.swift
// Localizabler
//
// Created by Cristian Baluta on 04/10/16.
// Copyright © 2016 Cristian Baluta. All rights reserved.
//
import Cocoa
protocol LocalizationsPresenterInput {
func setupDataSourceFor (termsTableView: NSTableView, translationsTableView: NSTableView)
func loadUrls (_ urls: [String: URL])
func insertNewTerm (afterIndex index: Int)
func removeTerm (atIndex index: Int)
func search (_ searchString: String)
func saveChanges()
func selectLanguageNamed (_ fileName: String)
}
protocol LocalizationsPresenterOutput: class {
func updatePlaceholders (message: String, hideTerms: Bool, hideTranslations: Bool)
func enableSaving()
func disableSaving()
func insertNewTerm (atIndex index: Int)
func removeTerm (atIndex index: Int)
func reloadTerm (atIndex index: Int)
func selectedTermRow() -> Int?
func showLanguagesPopup (_ languages: [String])
func selectLanguage (_ language: String)
func selectTerm (atRow row: Int)
func deselectActiveTerm()
func enableTermsEditingOptions (enabled: Bool)
}
class LocalizationsPresenter {
var interactor: LocalizationsInteractorInput?
weak var userInterface: LocalizationsPresenterOutput?
fileprivate var termsTableDataSource: TermsTableDataSource?
fileprivate var translationsTableDataSource: TranslationsTableDataSource?
fileprivate var lastSearchString = ""
fileprivate var lastHighlightedTermRow = -1
fileprivate func markFilesAsSaved() {
for i in 0..<self.termsTableDataSource!.data.count {
termsTableDataSource?.data[i].translationChanged = false
}
termsTableDataSource?.reloadData()
}
}
extension LocalizationsPresenter: LocalizationsPresenterInput {
func setupDataSourceFor (termsTableView: NSTableView, translationsTableView: NSTableView) {
termsTableDataSource = TermsTableDataSource(tableView: termsTableView)
translationsTableDataSource = TranslationsTableDataSource(tableView: translationsTableView)
termsTableDataSource?.onDidSelectRow = { [weak self] (rowNumber: Int, key: TermData) -> Void in
guard let wself = self else {
return
}
let translations = wself.interactor!.translationsForTerm(key.value)
wself.translationsTableDataSource?.data = translations
wself.translationsTableDataSource?.reloadData()
wself.updatePlaceholders(withMessage: "No selection")
}
termsTableDataSource?.termDidChange = { [weak self] (term: TermData) -> Void in
guard let wself = self else {
return
}
// A term was changed, update the value
if let newValue = term.newValue {
wself.interactor!.updateTerm(term.value, newTerm: newValue)
wself.userInterface!.enableSaving()
}
}
translationsTableDataSource?.translationDidChange = { [weak self] (translation: TranslationData) -> Void in
guard let wself = self else {
return
}
// A translation was changed, update the term object so it knows about the change
var selectedRow = wself.userInterface!.selectedTermRow()!
if selectedRow < 0 {
selectedRow = wself.lastHighlightedTermRow
}
guard selectedRow >= 0 else {
return
}
let termData = wself.termsTableDataSource?.data[selectedRow]
wself.termsTableDataSource?.data[selectedRow].translationChanged = true
// If there are changes in the translation
if let newValue = translation.newValue {
wself.interactor!.updateTranslation(newValue,
forTerm: termData!.value,
inLanguage: translation.languageCode)
}
wself.userInterface!.reloadTerm(atIndex: selectedRow)
wself.userInterface!.enableSaving()
}
translationsTableDataSource?.translationDidBecomeFirstResponder = { [weak self] (value: String) -> Void in
guard let wself = self else {
return
}
guard wself.lastSearchString != "" else {
return
}
if let line: Line = wself.interactor!.lineMatchingTranslation(value) {
guard line.term.characters.count > 0 else {
return
}
let displayedTerms: [TermData] = wself.termsTableDataSource!.data
var i = 0
var found = false
for term in displayedTerms {
if term.value == line.term {
found = true
break
}
i += 1
}
wself.lastHighlightedTermRow = i
wself.termsTableDataSource!.highlightedRow = i
if !found {
wself.termsTableDataSource?.data.append((value: line.term, newValue: nil, translationChanged: false) as TermData)
}
wself.termsTableDataSource?.reloadData()
}
}
}
func loadUrls (_ urls: [String: URL]) {
interactor!.loadUrls(urls)
let languages = interactor!.languages()
userInterface!.showLanguagesPopup(languages)
showBaseLanguage()
}
func insertNewTerm (afterIndex index: Int) {
let data = interactor!.insertNewTerm(afterIndex: index)
let termData: TermData = (value: data.line.term, newValue: nil, translationChanged: true)
termsTableDataSource!.data.insert(termData, at: data.row + 1)
termsTableDataSource!.reloadData()
userInterface!.selectTerm(atRow: data.row + 1)
userInterface!.enableSaving()
}
func removeTerm (atIndex index: Int) {
// Remove from files
let term: TermData = termsTableDataSource!.data[index]
interactor!.removeTerm(term)
// Remove from datasource
termsTableDataSource?.data.remove(at: index)
termsTableDataSource!.reloadData()
userInterface!.enableSaving()
}
fileprivate func clear() {
userInterface!.deselectActiveTerm()
translationsTableDataSource?.data = []
translationsTableDataSource?.reloadData()
}
func showTerms (_ terms: [String]) {
clear()
var termsData = [TermData]()
for term in terms {
termsData.append((value: term, newValue: nil, translationChanged: false) as TermData)
}
termsTableDataSource?.data = termsData
termsTableDataSource?.reloadData()
updatePlaceholders(withMessage: "No selection")
}
func search (_ searchString: String) {
lastSearchString = searchString
userInterface!.enableTermsEditingOptions(enabled: searchString == "")
userInterface!.deselectActiveTerm()
let results = interactor!.search(searchString)
//
termsTableDataSource?.data = results.terms
termsTableDataSource?.reloadData()
//
translationsTableDataSource?.data = results.translations
translationsTableDataSource?.reloadData()
// Add Placeholders if no matches found
updatePlaceholders(withMessage: "No matches")
}
func showBaseLanguage() {
let baseLanguage = interactor!.baseLanguage()
userInterface!.selectLanguage(baseLanguage)
selectLanguageNamed(baseLanguage)
}
func saveChanges() {
if interactor!.saveChanges() {
markFilesAsSaved()
userInterface!.disableSaving()
}
}
func selectLanguageNamed (_ fileName: String) {
let terms = interactor!.termsForLanguage(fileName)
showTerms(terms)
}
}
extension LocalizationsPresenter {
fileprivate func updatePlaceholders(withMessage message: String) {
userInterface!.updatePlaceholders(message: message,
hideTerms: translationsTableDataSource!.data.count > 0,
hideTranslations: termsTableDataSource!.data.count > 0)
}
}
extension LocalizationsPresenter: LocalizationsInteractorOutput {
}
| mit | 41bbc63cd81e143061f1f8b8fe00ea57 | 33.73622 | 133 | 0.597303 | 5.677606 | false | false | false | false |
hyperkit/KRProgressHUD | KRProgressHUD/Classes/KRActivityIndicatorView/KRActivityIndicatorViewStyle.swift | 1 | 5545 | //
// KRActivityIndicatorViewStyle.swift
// KRProgressIndicator
//
// Copyright © 2016年 Krimpedance. All rights reserved.
//
import UIKit
/**
KRActivityIndicatorView's style
- Normal size(20x20)
- **Black:** the color is a gradation to `.lightGrayColor()` from `.blackColor()`.
- **White:** the color is a gradation to `UIColor(white: 0.7, alpha:1)` from `.whiteColor()`.
- **Color(startColor, endColor):** the color is a gradation to `endColor` from `startColor`.
- Large size(50x50)
- **LargeBlack:** the color is same `.Black`.
- **LargeWhite:** the color is same `.White`.
- **LargeColor(startColor, endColor):** the color is same `.Color()`.
*/
public enum KRActivityIndicatorViewStyle {
case black, white, color(UIColor, UIColor?)
case largeBlack, largeWhite, largeColor(UIColor, UIColor?)
}
extension KRActivityIndicatorViewStyle {
mutating func sizeToLarge() {
switch self {
case .black: self = .largeBlack
case .white: self = .largeWhite
case let .color(sc, ec): self = .largeColor(sc, ec)
default: break
}
}
mutating func sizeToDefault() {
switch self {
case .largeBlack: self = .black
case .largeWhite: self = .white
case let .largeColor(sc, ec): self = .color(sc, ec)
default: break
}
}
var isLargeStyle: Bool {
switch self {
case .black, .white, .color(_, _): return false
case .largeBlack, .largeWhite, .largeColor(_, _): return true
}
}
var startColor: UIColor {
switch self {
case .black, .largeBlack: return UIColor.black
case .white, .largeWhite: return UIColor.white
case let .color(start, _): return start
case let .largeColor(start, _): return start
}
}
var endColor: UIColor {
switch self {
case .black, .largeBlack: return UIColor.lightGray
case .white, .largeWhite: return UIColor(white: 0.7, alpha: 1)
case let .color(start, end): return end ?? start
case let .largeColor(start, end): return end ?? start
}
}
func getGradientColors() -> [CGColor] {
let gradient = CAGradientLayer()
gradient.frame = CGRect(x: 0, y: 0, width: 1, height: 70)
gradient.colors = [startColor.cgColor, endColor.cgColor]
var colors: [CGColor] = [startColor.cgColor]
colors.append( // 中間色
contentsOf: (1..<7).map {
let point = CGPoint(x: 0, y: 10*CGFloat($0))
return gradient.colorOfPoint(point).cgColor
}
)
colors.append(endColor.cgColor)
return colors
}
func getPaths() -> [CGPath] {
if isLargeStyle {
return KRActivityIndicatorPath.largePaths
} else {
return KRActivityIndicatorPath.paths
}
}
}
/**
* KRActivityIndicator Path ---------
*/
private struct KRActivityIndicatorPath {
static let paths: [CGPath] = [
UIBezierPath(ovalIn: CGRect(x: 4.472, y: 0.209, width: 4.801, height: 4.801)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 0.407, y: 5.154, width: 4.321, height: 4.321)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 0.93, y: 11.765, width: 3.841, height: 3.841)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 5.874, y: 16.31, width: 3.361, height: 3.361)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 12.341, y: 16.126, width: 3.169, height: 3.169)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 16.912, y: 11.668, width: 2.641, height: 2.641)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 16.894, y: 5.573, width: 2.115, height: 2.115)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 12.293, y: 1.374, width: 1.901, height: 1.901)).cgPath,
]
static let largePaths: [CGPath] = [
UIBezierPath(ovalIn: CGRect(x: 12.013, y: 1.962, width: 8.336, height: 8.336)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 1.668, y: 14.14, width: 7.502, height: 7.502)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 2.792, y: 30.484, width: 6.668, height: 6.668)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 14.968, y: 41.665, width: 5.835, height: 5.835)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 31.311, y: 41.381, width: 5.001, height: 5.001)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 42.496, y: 30.041, width: 4.168, height: 4.168)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 42.209, y: 14.515, width: 3.338, height: 3.338)).cgPath,
UIBezierPath(ovalIn: CGRect(x: 30.857, y: 4.168, width: 2.501, height: 2.501)).cgPath,
]
}
/**
* CAGradientLayer Extension ------------------------------
*/
private extension CAGradientLayer {
func colorOfPoint(_ point: CGPoint) -> UIColor {
var pixel: [CUnsignedChar] = [0, 0, 0, 0]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmap = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmap.rawValue)
context?.translateBy(x: -point.x, y: -point.y)
render(in: context!)
let red: CGFloat = CGFloat(pixel[0])/255.0
let green: CGFloat = CGFloat(pixel[1])/255.0
let blue: CGFloat = CGFloat(pixel[2])/255.0
let alpha: CGFloat = CGFloat(pixel[3])/255.0
return UIColor(red:red, green: green, blue:blue, alpha:alpha)
}
}
| mit | 283b08c90c537f10fe96b7091160175a | 36.154362 | 151 | 0.604408 | 3.6833 | false | false | false | false |
michaelsabo/hammer | HammerTests/Services/GifServiceSpec.swift | 1 | 2011 | //
// GifServiceSpec.swift
// Hammer
//
// Created by Mike Sabo on 11/7/15.
// Copyright © 2015 FlyingDinosaurs. All rights reserved.
//
import Quick
import Nimble
import SwiftyJSON
import Hammer
class GifServiceSpec: QuickSpec {
override func spec() {
var gifService: GifService!
var gif: Gif!
beforeEach {
gifService = GifService()
gif = Gif(id: 10, url: "http://i.imgur.com/p5tJEpm.gif", thumbnailUrl: "http://i.imgur.com/p5tJEpmb.gif", index: 0)
}
describe("Gif Service") {
it("should return gifs in the response") {
var gifsResponse = [Gif]()
waitUntil(timeout: 15) { done in
gifService.getGifsResponse()
.on(next: {
gifsResponse = $0.gifs
done()
})
.start()
}
expect(gifsResponse.count).to(beGreaterThan(400))
}
it("should return gifs for a tag search") {
let gifsResponse = Gifs()
waitUntil(timeout: 15) { done in
gifService.getGifsForTagSearchResponse("no")
.on(next: {
gifsResponse.gifs = $0.gifs
done()
})
.start()
}
expect(gifsResponse.gifs.count).to(beGreaterThan(1))
}
it("should return an empty response for a bad search") {
let gifsResponse = Gifs()
waitUntil(timeout: 5) { done in
gifService.getGifsForTagSearchResponse("xxxxxoko")
.on(next: {
gifsResponse.gifs = $0.gifs
done()
})
.start()
}
expect(gifsResponse.gifs.count).to(equal(0))
}
it("should return the thumbnail image") {
expect(gif.thumbnailData).to(beNil())
gifService.retrieveThumbnailImageFor(gif: gif)
.on(next: { gif = $0 } )
.start()
expect(gif.thumbnailData).toEventually(beTruthy(), timeout: 5)
}
}
}
}
| mit | 4897c8125cfdc20ea8a8c48938b24165 | 23.512195 | 121 | 0.535323 | 3.941176 | false | false | false | false |
SmallElephant/FEAlgorithm-Swift | 12-LeetCode/12-LeetCode/MyArray.swift | 1 | 538 | //
// MyArray.swift
// 12-LeetCode
//
// Created by keso on 2017/5/29.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
class MyArray {
func removeDuplicates(_ nums: inout [Int]) -> Int {
if nums.count == 0 {
return 0
}
var index:Int = 1
for i in 1..<nums.count {
if nums[i] != nums[i - 1] {
nums[index] = nums[i]
index += 1
}
}
return index
}
}
| mit | 20c6e0fe429329195b4776646c41cb2e | 17.448276 | 55 | 0.448598 | 3.876812 | false | false | false | false |
ysnrkdm/Graphene | Sources/Graphene/BoardMediator.swift | 1 | 3221 | //
// BoardMediator.swift
// MyFirstSpriteKit
//
// Created by Kodama Yoshinori on 10/17/14.
// Copyright (c) 2014 Yoshinori Kodama. All rights reserved.
//
import Foundation
open class BoardMediator {
fileprivate var board: Board
// MARK: Initialization
public init(board:Board) {
self.board = board
}
open func initializeBoard() {
// FIXME: This assumes 8x8
board.initialize(8, height: 8)
updateGuides(.black)
}
// MARK: Direct access to Board
open func height() -> Int {
return self.board.height()
}
open func width() -> Int {
return self.board.width()
}
open func withinBoard(_ x: Int, y: Int) -> Bool {
return self.board.withinBoard(x, y: y)
}
open func set(_ color: Pieces, x: Int, y: Int) {
self.board.set(color, x: x, y: y)
}
open func get(_ x: Int, y: Int) -> Pieces {
return self.board.get(x, y: y)
}
open func isPieceAt(_ piece: Pieces, x: Int, y: Int) -> Bool {
return self.board.isPieceAt(piece, x: x, y: y)
}
// MARK: Query functions
open func getNumBlack() -> Int {
return self.board.getNumBlack()
}
open func getNumWhite() -> Int {
return self.board.getNumWhite()
}
open func canPut(_ color: Pieces, x: Int, y: Int) -> Bool {
return self.board.canPut(color, x: x, y: y)
}
open func getPuttables(_ color: Pieces) -> [(Int, Int)] {
return self.board.getPuttables(color)
}
open func isAnyPuttable(_ color: Pieces) -> Bool {
return self.board.isAnyPuttable(color)
}
open func isEmpty(_ x: Int, y: Int) -> Bool {
return self.board.isEmpty(x, y: y)
}
open func numPeripherals(_ color: Pieces, x: Int, y: Int) -> Int {
return self.board.numPeripherals(color, x: x, y: y)
}
open func hashValue() -> Int {
return self.board.hashValue()
}
// Only diag or horizontal/vertical lines can change by putting piece at x,y
open func getReversible(_ color: Pieces, x: Int, y: Int) -> [(Int, Int)] {
return self.board.getReversible(color, x: x, y: y)
}
// MARK: Board update functions
open func updateGuides(_ color: Pieces) -> Int {
return self.board.updateGuides(color)
}
// Does set and reverse pieces
// Returns [x,y] of changes (except put piece)
open func put(_ color: Pieces, x: Int, y: Int, guides: Bool = true, returnChanges: Bool = true) -> [(Int, Int)] {
return self.board.put(color, x: x, y: y, guides: guides, returnChanges: returnChanges)
}
// Normalize the board
open func toString() -> String {
return self.board.toString()
}
open func clone() -> BoardMediator {
let b = self.board.clone()
let bm = BoardMediator(board:b)
return bm
}
open func getBoard() -> Board {
return self.board
}
open func nextTurn(_ color: Pieces) -> Pieces {
var s : Pieces = .black
switch color {
case .black:
s = .white
case .white:
s = .black
default:
s = .black
}
return s
}
}
| mit | 0f5c71a3190766ab7cfeaade8db43fe3 | 23.968992 | 117 | 0.570941 | 3.594866 | false | false | false | false |
madeatsampa/MacMagazine-iOS | MacMagazine/PostsDetailViewController.swift | 1 | 7961 | //
// DetailViewController.swift
// MacMagazine
//
// Created by Cassio Rossi on 18/08/17.
// Copyright © 2017 MacMagazine. All rights reserved.
//
import UIKit
class PostsDetailViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
// MARK: - Properties -
@IBOutlet private weak var fullscreenMode: UIBarButtonItem!
@IBOutlet private weak var splitviewMode: UIBarButtonItem!
@IBOutlet private weak var spin: UIActivityIndicatorView!
@IBOutlet private weak var actions: UIBarButtonItem!
var selectedIndex = 0
var links: [PostData] = []
var createWebViewController: ((PostData) -> WebViewController?)?
private(set) lazy var orderedViewControllers: [UIViewController] = {
return links.map { post in
return self.createWebViewController?(post) ?? WebViewController()
}
}()
var showFullscreenModeButton = true
struct PostToShare {
var title: String
var link: URL
var favorite: Bool
}
var shareInfo: PostToShare?
// MARK: - View lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
dataSource = self
delegate = self
var controller = UIViewController()
if !orderedViewControllers.isEmpty {
controller = orderedViewControllers[selectedIndex]
}
setViewControllers([controller], direction: .forward, animated: true, completion: nil)
if Settings().isPad &&
self.splitViewController != nil {
navigationItem.leftBarButtonItem = fullscreenMode
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard !links.isEmpty,
let link = links[selectedIndex].link else {
return
}
updatePostHandoff(title: links[selectedIndex].title, link: link)
updatePostReadStatus(link: link)
guard let title = links[selectedIndex].title,
let url = URL(string: link) else {
return
}
shareInfo = PostToShare(title: title,
link: url,
favorite: links[selectedIndex].favorito)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
userActivity?.invalidate()
}
// MARK: - PageViewController -
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if !completed {
return
}
guard let vc = pageViewController.viewControllers?.first as? WebViewController,
let index = orderedViewControllers.firstIndex(of: vc),
let link = links[index].link
else {
return
}
if Settings().isPad {
NotificationCenter.default.post(name: .updateSelectedPost, object: link)
}
updatePostHandoff(title: links[index].title, link: link)
updatePostReadStatus(link: link)
guard let title = links[index].title,
let url = URL(string: link) else {
return
}
shareInfo = PostToShare(title: title,
link: url,
favorite: links[index].favorito)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.firstIndex(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.firstIndex(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
guard orderedViewControllersCount != nextIndex else {
return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
}
// MARK: - Read status -
extension PostsDetailViewController {
func updatePostReadStatus(link: String) {
CoreDataStack.shared.get(link: link) { (items: [Post]) in
if !items.isEmpty {
items[0].read = true
CoreDataStack.shared.save()
}
}
}
}
// MARK: - Handoff -
extension PostsDetailViewController {
func updatePostHandoff(title: String?, link: String) {
userActivity?.invalidate()
let handoff = NSUserActivity(activityType: "com.brit.macmagazine.details")
handoff.title = title
handoff.webpageURL = URL(string: link)
userActivity = handoff
userActivity?.becomeCurrent()
}
}
// MARK: - Fullscreen Mode -
extension PostsDetailViewController {
@IBAction private func enterFullscreenMode(_ sender: Any?) {
showFullscreenModeButton = false
UIView.animate(withDuration: 0.4,
animations: {
self.splitViewController?.preferredDisplayMode = .primaryHidden
},
completion: { _ in
self.navigationItem.leftBarButtonItem = self.splitviewMode
})
}
func enterFullscreenMode() {
self.enterFullscreenMode(fullscreenMode)
}
@IBAction private func enterSplitViewMode(_ sender: Any?) {
showFullscreenModeButton = true
UIView.animate(withDuration: 0.4,
animations: {
self.splitViewController?.preferredDisplayMode = .allVisible
},
completion: { _ in
self.navigationItem.leftBarButtonItem = self.fullscreenMode
})
}
func enterSplitViewMode() {
self.enterSplitViewMode(splitviewMode)
}
}
// MARK: - SHARE -
extension PostsDetailViewController {
@IBAction private func share(_ sender: Any) {
guard let shareInfo = shareInfo else {
let alertController = UIAlertController(title: "MacMagazine", message: "Não há nada para compartilhar", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default) { _ in
self.dismiss(animated: true)
})
self.present(alertController, animated: true)
return
}
let items: [Any] = [shareInfo.title, shareInfo.link]
let favorito = UIActivityExtensions(title: "Favorito",
image: UIImage(systemName: shareInfo.favorite ? "star.fill" : "star")) { _ in
Favorite().updatePostStatus(using: shareInfo.link.absoluteString) { [weak self] isFavorite in
guard let self = self else {
return
}
self.shareInfo?.favorite = isFavorite
for index in 0..<self.links.count where self.links[index].link == self.shareInfo?.link.absoluteString {
self.links[index].favorito = isFavorite
}
}
}
Share().present(at: actions, using: items, activities: [favorito])
}
func setRightButtomItems(_ buttons: [RightButtons]) {
let rightButtons: [UIBarButtonItem] = buttons.map {
switch $0 {
case .spin: return UIBarButtonItem(customView: spin)
case .actions: return actions
}
}
self.navigationItem.rightBarButtonItems = rightButtons
}
}
| mit | e3e1dbeaafa2f932143c5e790a78867b | 29.490421 | 187 | 0.634959 | 5.027164 | false | false | false | false |
apple/swift-package-manager | Sources/PackagePlugin/PackageModel.swift | 1 | 16774 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
/// Represents a single package in the graph (either the root or a dependency).
public struct Package {
/// Unique identifier for the package.
public let id: ID
public typealias ID = String
/// The name of the package (for display purposes only).
public let displayName: String
/// The absolute path of the package directory in the local file system.
public let directory: Path
/// The origin of the package (root, local, repository, registry, etc).
public let origin: PackageOrigin
/// The tools version specified by the resolved version of the package.
/// Behavior is often gated on the tools version, to make sure older
/// packages continue to work as intended.
public let toolsVersion: ToolsVersion
/// Any dependencies on other packages, in the same order as they are
/// specified in the package manifest.
public let dependencies: [PackageDependency]
/// Any regular products defined in this package (except plugin products),
/// in the same order as they are specified in the package manifest.
public let products: [Product]
/// Any regular targets defined in this package (except plugin targets),
/// in the same order as they are specified in the package manifest.
public let targets: [Target]
}
/// Represents the origin of a package as it appears in the graph.
public enum PackageOrigin {
/// A root package (unversioned).
case root
/// A local package, referenced by path (unversioned).
case local(path: String)
/// A package from a Git repository, with a URL and with a textual
/// description of the resolved version or branch name (for display
/// purposes only), along with the corresponding SCM revision. The
/// revision is the Git commit hash and may be useful for plugins
/// that generates source code that includes version information.
case repository(url: String, displayVersion: String, scmRevision: String)
/// A package from a registry, with an identity and with a textual
/// description of the resolved version or branch name (for display
/// purposes only).
case registry(identity: String, displayVersion: String)
}
/// Represents a version of SwiftPM on whose semantics a package relies.
public struct ToolsVersion {
/// The major version.
public let major: Int
/// The minor version.
public let minor: Int
/// The patch version.
public let patch: Int
}
/// Represents a resolved dependency of a package on another package. This is a
/// separate entity in order to make it easier for future versions of the API to
/// add information about the dependency itself.
public struct PackageDependency {
/// The package to which the dependency was resolved.
public let package: Package
init(package: Package) {
self.package = package
}
}
/// Represents a single product defined in a package.
public protocol Product {
/// Unique identifier for the product.
var id: ID { get }
typealias ID = String
/// The name of the product, as defined in the package manifest. This name
/// is unique among the products of the package in which it is defined.
var name: String { get }
/// The targets that directly comprise the product, in the order in which
/// they are declared in the package manifest. The product will contain the
/// transitive closure of the these targets and their dependencies. Some
/// kinds of products have further restrictions on the set of targets (for
/// example, an executable product must have one and only one target that
/// defines the main entry point for an executable).
var targets: [Target] { get }
}
/// Represents an executable product defined in a package.
public struct ExecutableProduct: Product {
/// Unique identifier for the product.
public let id: ID
/// The name of the product, as defined in the package manifest. This name
/// is unique among the products of the package in which it is defined.
public let name: String
/// The targets that directly comprise the product, in the order in which
/// they are declared in the package manifest. The product will contain the
/// transitive closure of the these targets and their dependencies. For an
/// ExecutableProduct, exactly one of the targets in this list must be an
/// ExecutableTarget.
public let targets: [Target]
/// The target that contains the main entry point of the executable. Every
/// executable product has exactly one main executable target. This target
/// will always be one of the targets in the product's `targets` array.
public let mainTarget: Target
}
/// Represents a library product defined in a package.
public struct LibraryProduct: Product {
/// Unique identifier for the product.
public let id: ID
/// The name of the product, as defined in the package manifest. This name
/// is unique among the products of the package in which it is defined.
public let name: String
/// The targets that directly comprise the product, in the order in which
/// they are declared in the package manifest. The product will contain the
/// transitive closure of the these targets and their dependencies.
public let targets: [Target]
/// Whether the library is static, dynamic, or automatically determined.
public let kind: Kind
/// Represents a kind of library product.
public enum Kind {
/// A static library, whose code is copied into its clients.
case `static`
/// Dynamic library, whose code is referenced by its clients.
case `dynamic`
/// The kind of library produced is unspecified and will be determined
/// by the build system based on how the library is used.
case automatic
}
}
/// Represents a single target defined in a package.
public protocol Target {
/// Unique identifier for the target.
var id: ID { get }
typealias ID = String
/// The name of the target, as defined in the package manifest. This name
/// is unique among the targets of the package in which it is defined.
var name: String { get }
/// The absolute path of the target directory in the local file system.
var directory: Path { get }
/// Any other targets on which this target depends, in the same order as
/// they are specified in the package manifest. Conditional dependencies
/// that do not apply have already been filtered out.
var dependencies: [TargetDependency] { get }
}
/// Represents a dependency of a target on a product or on another target.
public enum TargetDependency {
/// A dependency on a target in the same package.
case target(Target)
/// A dependency on a product in another package.
case product(Product)
}
/// Represents a target consisting of a source code module, containing either
/// Swift or source files in one of the C-based languages.
public protocol SourceModuleTarget: Target {
/// The name of the module produced by the target (derived from the target
/// name, though future SwiftPM versions may allow this to be customized).
var moduleName: String { get }
/// The kind of module, describing whether it contains unit tests, contains
/// the main entry point of an executable, or neither.
var kind: ModuleKind { get }
/// The source files that are associated with this target (any files that
/// have been excluded in the manifest have already been filtered out).
var sourceFiles: FileList { get }
/// Any custom linked libraries required by the module, as specified in the
/// package manifest.
var linkedLibraries: [String] { get }
/// Any custom linked frameworks required by the module, as specified in the
/// package manifest.
var linkedFrameworks: [String] { get }
}
/// Represents the kind of module.
public enum ModuleKind {
/// A module that contains generic code (not a test nor an executable).
case generic
/// A module that contains code for an executable's main module.
case executable
/// A module that contains code for a snippet.
@available(_PackageDescription, introduced: 5.8)
case snippet
/// A module that contains unit tests.
case test
}
/// Represents a target consisting of a source code module compiled using Swift.
public struct SwiftSourceModuleTarget: SourceModuleTarget {
/// Unique identifier for the target.
public let id: ID
/// The name of the target, as defined in the package manifest. This name
/// is unique among the targets of the package in which it is defined.
public let name: String
/// The kind of module, describing whether it contains unit tests, contains
/// the main entry point of an executable, or neither.
public let kind: ModuleKind
/// The absolute path of the target directory in the local file system.
public let directory: Path
/// Any other targets on which this target depends, in the same order as
/// they are specified in the package manifest. Conditional dependencies
/// that do not apply have already been filtered out.
public let dependencies: [TargetDependency]
/// The name of the module produced by the target (derived from the target
/// name, though future SwiftPM versions may allow this to be customized).
public let moduleName: String
/// The source files that are associated with this target (any files that
/// have been excluded in the manifest have already been filtered out).
public let sourceFiles: FileList
/// Any custom compilation conditions specified for the Swift target in the
/// package manifest.
public let compilationConditions: [String]
/// Any custom linked libraries required by the module, as specified in the
/// package manifest.
public let linkedLibraries: [String]
/// Any custom linked frameworks required by the module, as specified in the
/// package manifest.
public let linkedFrameworks: [String]
}
/// Represents a target consisting of a source code module compiled using Clang.
public struct ClangSourceModuleTarget: SourceModuleTarget {
/// Unique identifier for the target.
public let id: ID
/// The name of the target, as defined in the package manifest. This name
/// is unique among the targets of the package in which it is defined.
public let name: String
/// The kind of module, describing whether it contains unit tests, contains
/// the main entry point of an executable, or neither.
public let kind: ModuleKind
/// The absolute path of the target directory in the local file system.
public let directory: Path
/// Any other targets on which this target depends, in the same order as
/// they are specified in the package manifest. Conditional dependencies
/// that do not apply have already been filtered out.
public let dependencies: [TargetDependency]
/// The name of the module produced by the target (derived from the target
/// name, though future SwiftPM versions may allow this to be customized).
public let moduleName: String
/// The source files that are associated with this target (any files that
/// have been excluded in the manifest have already been filtered out).
public let sourceFiles: FileList
/// Any preprocessor definitions specified for the Clang target.
public let preprocessorDefinitions: [String]
/// Any custom header search paths specified for the Clang target.
public let headerSearchPaths: [String]
/// The directory containing public C headers, if applicable. This will
/// only be set for targets that have a directory of a public headers.
public let publicHeadersDirectory: Path?
/// Any custom linked libraries required by the module, as specified in the
/// package manifest.
public let linkedLibraries: [String]
/// Any custom linked frameworks required by the module, as specified in the
/// package manifest.
public let linkedFrameworks: [String]
}
/// Represents a target describing an artifact (e.g. a library or executable)
/// that is distributed as a binary.
public struct BinaryArtifactTarget: Target {
/// Unique identifier for the target.
public let id: ID
/// The name of the target, as defined in the package manifest. This name
/// is unique among the targets of the package in which it is defined.
public let name: String
/// The absolute path of the target directory in the local file system.
public let directory: Path
/// Any other targets on which this target depends, in the same order as
/// they are specified in the package manifest. Conditional dependencies
/// that do not apply have already been filtered out.
public let dependencies: [TargetDependency]
/// The kind of binary artifact.
public let kind: Kind
/// The original source of the binary artifact.
public let origin: Origin
/// The location of the binary artifact in the local file system.
public let artifact: Path
/// Represents a kind of binary artifact.
public enum Kind {
case xcframework
case artifactsArchive
}
// Represents the original location of a binary artifact.
public enum Origin: Equatable {
/// Represents an artifact that was available locally.
case local
/// Represents an artifact that was downloaded from a remote URL.
case remote(url: String)
}
}
/// Represents a target describing a system library that is expected to be
/// present on the host system.
public struct SystemLibraryTarget: Target {
/// Unique identifier for the target.
public let id: ID
/// The name of the target, as defined in the package manifest. This name
/// is unique among the targets of the package in which it is defined.
public var name: String
/// The absolute path of the target directory in the local file system.
public var directory: Path
/// Any other targets on which this target depends, in the same order as
/// they are specified in the package manifest. Conditional dependencies
/// that do not apply have already been filtered out.
public var dependencies: [TargetDependency]
/// The name of the `pkg-config` file, if any, describing the library.
public let pkgConfig: String?
/// Flags from `pkg-config` to pass to Clang (and to SwiftC via `-Xcc`).
public let compilerFlags: [String]
/// Flags from `pkg-config` to pass to the platform linker.
public let linkerFlags: [String]
}
/// Provides information about a list of files. The order is not defined
/// but is guaranteed to be stable. This allows the implementation to be
/// more efficient than a static file list.
public struct FileList {
private var files: [File]
init(_ files: [File]) {
self.files = files
}
}
extension FileList: Sequence {
public struct Iterator: IteratorProtocol {
private var files: ArraySlice<File>
fileprivate init(files: ArraySlice<File>) {
self.files = files
}
mutating public func next() -> File? {
guard let nextInfo = self.files.popFirst() else {
return nil
}
return nextInfo
}
}
public func makeIterator() -> Iterator {
return Iterator(files: ArraySlice(self.files))
}
}
/// Provides information about a single file in a FileList.
public struct File {
/// The path of the file.
public let path: Path
/// File type, as determined by SwiftPM.
public let type: FileType
}
/// Provides information about the type of a file. Any future cases will
/// use availability annotations to make sure existing plugins still work
/// until they increase their required tools version.
public enum FileType {
/// A source file.
case source
/// A header file.
case header
/// A resource file (either processed or copied).
case resource
/// A file not covered by any other rule.
case unknown
}
| apache-2.0 | 856a0b3783aef2b81f0cb1904b3c883f | 36.950226 | 80 | 0.69095 | 4.93934 | false | false | false | false |
iAugux/iBBS-Swift | iBBS/PasscodeLock/Views/PasscodeSignButton.swift | 2 | 2457 | //
// PasscodeSignButton.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
@IBDesignable
public class PasscodeSignButton: UIButton {
@IBInspectable
public var passcodeSign: String = "1"
@IBInspectable
public var borderColor: UIColor = UIColor.whiteColor() {
didSet {
setupView()
}
}
@IBInspectable
public var borderRadius: CGFloat = 30 {
didSet {
setupView()
}
}
@IBInspectable
public var highlightBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
setupView()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupActions()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupActions()
}
public override func intrinsicContentSize() -> CGSize {
return CGSizeMake(60, 60)
}
private var defaultBackgroundColor = UIColor.clearColor()
private func setupView() {
layer.borderWidth = 1
layer.cornerRadius = borderRadius
layer.borderColor = borderColor.CGColor
if let backgroundColor = backgroundColor {
defaultBackgroundColor = backgroundColor
}
}
private func setupActions() {
addTarget(self, action: #selector(PasscodeSignButton.handleTouchDown), forControlEvents: .TouchDown)
addTarget(self, action: #selector(PasscodeSignButton.handleTouchUp), forControlEvents: [.TouchUpInside, .TouchDragOutside, .TouchCancel])
}
func handleTouchDown() {
animateBackgroundColor(highlightBackgroundColor)
}
func handleTouchUp() {
animateBackgroundColor(defaultBackgroundColor)
}
private func animateBackgroundColor(color: UIColor) {
UIView.animateWithDuration(
0.3,
delay: 0.0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0.0,
options: [.AllowUserInteraction, .BeginFromCurrentState],
animations: {
self.backgroundColor = color
},
completion: nil
)
}
}
| mit | 639815975a46a7e3da3ab75f13c71991 | 22.84466 | 145 | 0.576954 | 5.751756 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Components/SendAuxiliaryView/SendAuxiliaryView.swift | 1 | 2636 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxCocoa
import RxSwift
import ToolKit
public final class SendAuxiliaryView: UIView {
// MARK: - Properties
public var presenter: SendAuxiliaryViewPresenter! {
willSet {
disposeBag = DisposeBag()
}
didSet {
maxButtonView.viewModel = presenter.maxButtonViewModel
availableBalanceView.presenter = presenter.availableBalanceContentViewPresenter
networkFeeView.presenter = presenter.networkFeeContentViewPresenter
presenter
.imageContent
.drive(imageView.rx.content)
.disposed(by: disposeBag)
presenter
.state
.map(\.bitpayVisibility)
.drive(imageView.rx.visibility)
.disposed(by: disposeBag)
presenter
.state
.map(\.networkFeeVisibility)
.drive(networkFeeView.rx.visibility)
.disposed(by: disposeBag)
}
}
private let availableBalanceView: ContentLabelView
private let networkFeeView: ContentLabelView
private let imageView: UIImageView
private let maxButtonView: ButtonView
private var disposeBag = DisposeBag()
public init() {
availableBalanceView = ContentLabelView()
networkFeeView = ContentLabelView()
maxButtonView = ButtonView()
imageView = UIImageView()
super.init(frame: UIScreen.main.bounds)
addSubview(availableBalanceView)
addSubview(maxButtonView)
addSubview(networkFeeView)
addSubview(imageView)
availableBalanceView.layoutToSuperview(.centerY)
availableBalanceView.layoutToSuperview(.leading, offset: Spacing.outer)
availableBalanceView.layout(
edge: .trailing,
to: .centerX,
of: self,
relation: .equal
)
networkFeeView.layoutToSuperview(.centerY)
networkFeeView.layoutToSuperview(.trailing, offset: -Spacing.outer)
networkFeeView.layout(
edge: .leading,
to: .centerX,
of: self,
relation: .equal
)
maxButtonView.layoutToSuperview(.centerY)
maxButtonView.layoutToSuperview(.trailing, offset: -Spacing.outer)
maxButtonView.layout(dimension: .height, to: 30)
imageView.layoutToSuperview(.centerY)
imageView.layoutToSuperview(.trailing, offset: -Spacing.outer)
}
required init?(coder: NSCoder) { unimplemented() }
}
| lgpl-3.0 | c014efd6804dd1588a30b41e75e506a4 | 29.639535 | 91 | 0.628083 | 5.355691 | false | false | false | false |
sky15179/swift-learn | data-Base-exercises/data-Base-exercises/LinkList/LRUCache/MemoryCache.swift | 1 | 11429 | //
// MemoryCache.swift
// data-Base-exercises
//
// Created by 王智刚 on 2017/6/13.
// Copyright © 2017年 王智刚. All rights reserved.
//
import Foundation
import QuartzCore
internal class MemoryCacheObject:LRUObj{
var key: String = ""
var cost: Int = 0
var time :TimeInterval = CACurrentMediaTime()
var value:AnyObject
init(key:String,value:AnyObject,cost:Int = 0) {
self.key = key
self.value = value
self.cost = cost
}
}
let prefixName = "com.cahe"
let defaultName = "defaultCahe"
open class MemoryCache {
open var totalCount:Int{
get{
_lock()
let count = _cache.totalCount
_unlock()
return count
}
}
open var totalCost:Int{
get{
_lock()
let cost = _cache.totalCost
_unlock()
return cost
}
}
fileprivate var _countLimit:Int = Int.max
fileprivate var _costLimit:Int = Int.max
fileprivate var _ageLimit:TimeInterval = Double.greatestFiniteMagnitude
open var countLimit:Int{
set{
_lock()
_countLimit = newValue
_unsafeTrim(toCount: newValue)
_unlock()
}
get{
_lock()
let countLimit = _countLimit
_unlock()
return countLimit
}
}
open var costLimit:Int{
set{
_lock()
_costLimit = newValue
_unsafeTrim(toCost: newValue)
_unlock()
}
get{
_lock()
let costLimit = _costLimit
_unlock()
return costLimit
}
}
open var ageLimit:TimeInterval{
set{
_lock()
_ageLimit = newValue
_unsafeTrim(toAge: newValue)
_unlock()
}
get{
_lock()
let ageLimit = _ageLimit
_unlock()
return ageLimit
}
}
fileprivate var _autoRemoveAllobjectWhenMemoryWarning:Bool = true
open var autoRemoveAllobjectWhenMemoryWarning:Bool{
set{
_lock()
_autoRemoveAllobjectWhenMemoryWarning = newValue
_unlock()
}
get{
_lock()
let autoRemoveAllobjectWhenMemoryWarning = _autoRemoveAllobjectWhenMemoryWarning
_unlock()
return autoRemoveAllobjectWhenMemoryWarning
}
}
fileprivate var _autoRemoveAllobjectWhenEnterBackground:Bool = true
open var autoRemoveAllobjectWhenEnterBackground:Bool{
set{
_lock()
_autoRemoveAllobjectWhenEnterBackground = newValue
_unlock()
}
get{
_lock()
let autoRemoveAllobjectWhenEnterBackground = _autoRemoveAllobjectWhenEnterBackground
_unlock()
return autoRemoveAllobjectWhenEnterBackground
}
}
open static let shareInstance = MemoryCache()
fileprivate let _cache:LRU = LRU<MemoryCacheObject>()
fileprivate let _queue:DispatchQueue = DispatchQueue(label: prefixName + String(describing:MemoryCache.self), attributes: DispatchQueue.Attributes.concurrent)
fileprivate var _pthreadLock:pthread_mutex_t = pthread_mutex_t()
public init(){
pthread_mutex_init(&_pthreadLock,nil)
NotificationCenter.default.addObserver(self, selector: #selector(_didReceiveMemoryWarningNotification), name: Notification.Name.UIApplicationDidReceiveMemoryWarning, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(_didEnterBackgroundNotification), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
}
}
public typealias MemoryCacheAsyncCompletion = (_ cache:MemoryCache?,_ key:String?,_ object:AnyObject?)->Void
// MARK: - 缓存的对外暴露方法
public extension MemoryCache{
public func set(object:AnyObject,forKey key:String,cost:Int = 0) {
_lock()
_unsafeSet(object: object, key: key, cost: cost)
_unlock()
}
public func set(obejct:AnyObject,forkey key:String,cost:Int = 0,completion:MemoryCacheAsyncCompletion?) {
_queue.async {
[weak self] in
guard let strongSelf = self else{completion?(nil,key,obejct);return}
strongSelf.set(object: obejct, forKey: key, cost: cost)
completion?(strongSelf,key,obejct)
}
}
public func object(forKey key:String) -> AnyObject? {
var object:AnyObject? = nil
_lock()
let memoryObject: MemoryCacheObject? = _cache.object(forKey: key)
memoryObject?.time = CACurrentMediaTime()
object = memoryObject?.value
_unlock()
return object
}
public func removeObject(forKey key:String) {
_lock()
_ = _cache.removeObject(forKey: key)
_unlock()
}
public func removeAllObjects() {
_lock()
_ = _cache.removeAll()
_unlock()
}
public func object(forKey key:String,completion:MemoryCacheAsyncCompletion?) {
_queue.async {
[weak self] in
guard let strongSelf = self else{completion?(nil,key,nil);return}
let object = strongSelf.object(forKey: key)
completion?(strongSelf,key,object)
}
}
public func removeObject(forKey key:String,completion:MemoryCacheAsyncCompletion?) {
_queue.async {
[weak self] in
guard let strongSelf = self else{completion?(nil,key,nil);return}
strongSelf.removeObject(forKey: key)
completion?(strongSelf,key,nil)
}
}
public func removeAllObjects(_ completion:MemoryCacheAsyncCompletion?) {
_queue.async {
[weak self] in
guard let strongSelf = self else{completion?(nil,nil,nil);return}
strongSelf.removeAllObjects()
completion?(strongSelf,nil,nil)
}
}
public func trim(toCount countLimit:Int) {
_lock()
_unsafeTrim(toCount: countLimit)
_unlock()
}
public func trim(toCost costLimit:Int) {
_lock()
_unsafeTrim(toCost: costLimit)
_unlock()
}
public func trim(toAge ageLimit:TimeInterval) {
_lock()
_unsafeTrim(toAge: ageLimit)
_unlock()
}
func trim(toCount countLimit:Int,completion:MemoryCacheAsyncCompletion?) {
_queue.async {
[weak self] in
guard let strongSelf = self else{completion?(nil,nil,nil);return}
strongSelf.trim(toCount: countLimit)
completion?(strongSelf,nil,nil)
}
}
func trim(toCost costLimit:Int,completion:MemoryCacheAsyncCompletion?) {
_queue.async {
[weak self] in
guard let strongSelf = self else{completion?(nil,nil,nil);return}
strongSelf.trim(toCost: costLimit)
completion?(strongSelf,nil,nil)
}
}
func trim(toAge ageLimit:TimeInterval,completion:MemoryCacheAsyncCompletion?) {
_queue.async {
[weak self] in
guard let strongSelf = self else{completion?(nil,nil,nil);return}
strongSelf.trim(toAge: ageLimit)
completion?(strongSelf,nil,nil)
}
}
public subscript(key:String) -> AnyObject?{
get{
return self.object(forKey:key)
}
set{
if let newValue = newValue{
set(object: newValue, forKey: key)
}else{
removeObject(forKey: key)
}
}
}
}
open class MemoryCacheGenerator: IteratorProtocol {
public typealias Element = (String,AnyObject)
fileprivate var _lruGenerator:LRUGenerator<MemoryCacheObject>
fileprivate var _completion:(()->Void)?
fileprivate init(generate:LRUGenerator<MemoryCacheObject>,cache:MemoryCache,completion:(()->Void)?){
_lruGenerator = generate
_completion = completion
}
open func next() -> (String, AnyObject)? {
if let object = _lruGenerator.next() {
return(object.key,object.value)
}else{
return nil
}
}
deinit {
_completion?()
}
}
// MARK: - 支持序列
extension MemoryCache:Sequence{
public typealias Iterator = MemoryCacheGenerator
public func makeIterator() -> MemoryCacheGenerator {
var generator:MemoryCacheGenerator
_lock()
generator = MemoryCacheGenerator(generate: _cache.makeIterator(), cache: self) {
self._unlock()
}
return generator
}
}
// MARK: - 辅助方法
extension MemoryCache{
/// 删除直到达到数量最大值
///
/// - Parameter countLimit: <#countLimit description#>
func _unsafeTrim(toCount countLimit:Int) {
if _cache.totalCount < countLimit {
return
}
if countLimit == 0 {
removeAllObjects(nil)
}
if let _ = _cache.lastObject() {
while countLimit<_cache.totalCount{
_cache.removeLastObject()
guard let _: MemoryCacheObject = _cache.lastObject() else { break }
}
}
}
func _unsafeTrim(toCost costLimit:Int) {
if _cache.totalCost < costLimit {
return
}
if costLimit == 0 {
removeAllObjects(nil)
}
if let _ = _cache.lastObject() {
while costLimit<_cache.totalCost{
_cache.removeLastObject()
guard let _: MemoryCacheObject = _cache.lastObject() else { break }
}
}
}
func _unsafeTrim(toAge ageLimit:TimeInterval) {
if ageLimit <= 0 {
removeAllObjects(nil)
}
if let last:MemoryCacheObject = _cache.lastObject() {
while (CACurrentMediaTime() - last.time) > ageLimit{
_cache.removeLastObject()
guard let _: MemoryCacheObject = _cache.lastObject() else { break }
}
}
}
@objc fileprivate func _didReceiveMemoryWarningNotification() {
if _autoRemoveAllobjectWhenMemoryWarning {
removeAllObjects(nil)
}
}
@objc fileprivate func _didEnterBackgroundNotification(){
if _autoRemoveAllobjectWhenEnterBackground {
removeAllObjects(nil)
}
}
func _unsafeSet(object:AnyObject,key:String,cost:Int = 0) {
_cache.set(object: MemoryCacheObject(key: key, value: object, cost: cost), forKey: key)
if _cache.totalCost > _costLimit {
_unsafeTrim(toCost: _costLimit)
}
if _cache.totalCount > _countLimit {
_unsafeTrim(toCount: _countLimit)
}
}
func _lock(){
pthread_mutex_lock(&_pthreadLock)
}
func _unlock(){
pthread_mutex_unlock(&_pthreadLock)
}
func _tryLock() {
if pthread_mutex_trylock(&_pthreadLock) == 0 {
}else{
usleep(10 * 1000); //10 ms
}
}
}
| apache-2.0 | b71e4838298b68827abbd18b6c390e35 | 26.302885 | 186 | 0.565064 | 4.722661 | false | false | false | false |
abakhtin/ABProgressButton | ABProgressButton/ABProgressButton.swift | 1 | 18864 | //
// ABProgreeButton.swift
// DreamHome
//
// Created by Alex Bakhtin on 8/5/15.
// Copyright © 2015 bakhtin. All rights reserved.
//
import UIKit
/// ABProgressButton provides functionality for creating custom animation of UIButton during processing some task.
/// Should be created in IB as custom class UIButton to prevent title of the button appearing.
/// Provides mechanism for color inverting on highlitening and using tintColor for textColor(default behavior for system button)
@IBDesignable @objc open class ABProgressButton: UIButton {
@IBInspectable open var animationShift: CGSize = CGSize(width: 0.0, height: 0.0)
/// **UI configuration. IBInspectable.** Allows change corner radius on default button state. Has default value of 5.0
@IBInspectable open var cornerRadius: CGFloat = 5.0
/// **UI configuration. IBInspectable.** Allows change border width on default button state. Has default value of 3.0
@IBInspectable open var borderWidth: CGFloat = 3.0
/// **UI configuration. IBInspectable.** Allows change border color on default button state. Has default value of control tintColor
@IBInspectable open lazy var borderColor: UIColor = {
return self.tintColor
}()
/// **UI configuration. IBInspectable.** Allows change circle radius on processing button state. Has default value of 20.0
@IBInspectable open var circleRadius: CGFloat = 20.0
/// **UI configuration. IBInspectable.** Allows change circle border width on processing button state. Has default value of 3.0
@IBInspectable open var circleBorderWidth: CGFloat = 3.0
/// **UI configuration. IBInspectable.** Allows change circle border color on processing button state. Has default value of control tintColor
@IBInspectable open lazy var circleBorderColor: UIColor = {
return self.tintColor
}()
/// **UI configuration. IBInspectable.** Allows change circle background color on processing button state. Has default value of UIColor.whiteColor()
@IBInspectable open var circleBackgroundColor: UIColor = UIColor.white
/// **UI configuration. IBInspectable.** Allows change circle cut angle on processing button state.
/// Should have value between 0 and 360 degrees. Has default value of 45 degrees
@IBInspectable open var circleCutAngle: CGFloat = 45.0
/// **UI configuration. IBInspectable.**
/// If true, colors of content and background will be inverted on button highlightening. Image should be used as template for correct image color inverting.
/// If false you should use default mechanism for text and images highlitening.
/// Has default value of true
@IBInspectable open var invertColorsOnHighlight: Bool = true
/// **UI configuration. IBInspectable.**
/// If true, tintColor whould be used for text, else value from UIButton.textColorForState() would be used.
/// Has default value of true
@IBInspectable open var useTintColorForText: Bool = true
/** **Buttons states enum**
- .Default: Default state of button with border line.
- .Progressing: State of button without content, button has the form of circle with cut angle with rotation animation.
*/
public enum State {
case `default`, progressing
}
/** **State changing**
Should be used to change state of button from one state to another. All transitions between states would be animated. To update progress indicator use `progress` value
*/
open var progressState: State = .default {
didSet {
if(progressState == .default) { self.updateToDefaultStateAnimated(true)}
if(progressState == .progressing) { self.updateToProgressingState()}
self.updateProgressLayer()
}
}
/** **State changing**
Should be used to change progress indicator. Should have value from 0.0 to 1.0. `progressState` should be .Progressing to allow change progress(except nil value).
*/
open var progress: CGFloat? {
didSet {
if progress != nil {
assert(self.progressState == .progressing, "Progress state should be .Progressing while changing progress value")
}
progress = progress == nil ? nil : min(progress!, CGFloat(1.0))
self.updateProgressLayer()
}
}
// MARK : Initialization
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.privateInit()
self.registerForNotifications()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.privateInit()
self.registerForNotifications()
}
override open func prepareForInterfaceBuilder() {
self.privateInit()
}
deinit {
self.unregisterFromNotifications()
}
fileprivate func privateInit() {
if (self.useTintColorForText) { self.setTitleColor(self.tintColor, for: UIControlState()) }
if (self.invertColorsOnHighlight) { self.setTitleColor(self.shapeBackgroundColor, for: UIControlState.highlighted) }
self.layer.insertSublayer(self.shapeLayer, at: 0)
self.layer.insertSublayer(self.crossLayer, at: 1)
self.layer.insertSublayer(self.progressLayer, at: 2)
self.updateToDefaultStateAnimated(false)
}
override open func layoutSubviews() {
super.layoutSubviews()
self.shapeLayer.frame = self.layer.bounds
self.updateShapeLayer()
self.crossLayer.frame = self.layer.bounds
self.progressLayer.frame = self.layer.bounds
self.bringSubview(toFront: self.imageView!)
}
override open var isHighlighted: Bool {
didSet {
if (self.invertColorsOnHighlight) { self.imageView?.tintColor = isHighlighted ? self.shapeBackgroundColor : self.circleBorderColor }
self.crossLayer.strokeColor = isHighlighted ? self.circleBackgroundColor.cgColor : self.circleBorderColor.cgColor
self.progressLayer.strokeColor = isHighlighted ? self.circleBackgroundColor.cgColor : self.circleBorderColor.cgColor
if (isHighlighted) {
self.shapeLayer.fillColor = (progressState == State.default) ? self.borderColor.cgColor : self.circleBorderColor.cgColor
}
else {
self.shapeLayer.fillColor = (progressState == State.default) ? self.shapeBackgroundColor.cgColor : self.circleBackgroundColor.cgColor
}
}
}
// MARK : Methods used to update states
fileprivate var shapeLayer = CAShapeLayer()
fileprivate lazy var crossLayer: CAShapeLayer = {
let crossLayer = CAShapeLayer()
crossLayer.path = self.crossPath().cgPath
crossLayer.strokeColor = self.circleBorderColor.cgColor
return crossLayer
}()
fileprivate lazy var progressLayer: CAShapeLayer = {
let progressLayer = CAShapeLayer()
progressLayer.strokeColor = self.circleBorderColor.cgColor
progressLayer.fillColor = UIColor.clear.cgColor
return progressLayer
}()
fileprivate lazy var shapeBackgroundColor: UIColor = {
return self.backgroundColor ?? self.circleBackgroundColor
}()
fileprivate func updateToDefaultStateAnimated(_ animated:Bool) {
self.shapeLayer.strokeColor = self.borderColor.cgColor;
self.shapeLayer.fillColor = self.shapeBackgroundColor.cgColor
self.crossLayer.isHidden = true
self.animateDefaultStateAnimated(animated)
}
fileprivate func updateToProgressingState() {
self.titleLabel?.alpha = 0.0
self.shapeLayer.strokeColor = self.circleBorderColor.cgColor
self.shapeLayer.fillColor = self.circleBackgroundColor.cgColor
self.crossLayer.isHidden = false
self.animateProgressingState(self.shapeLayer)
}
fileprivate func updateShapeLayer() {
if self.progressState == .default {
self.shapeLayer.path = self.defaultStatePath().cgPath
}
self.crossLayer.path = self.crossPath().cgPath
}
fileprivate func updateProgressLayer() {
self.progressLayer.isHidden = (self.progressState != .progressing || self.progress == nil)
if (self.progressLayer.isHidden == false) {
let progressCircleRadius = self.circleRadius - self.circleBorderWidth
let progressArcAngle = CGFloat(M_PI) * 2 * self.progress! - CGFloat(M_PI_2)
let circlePath = UIBezierPath()
let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height)
circlePath.addArc(withCenter: center, radius:progressCircleRadius, startAngle:CGFloat(-M_PI_2), endAngle:progressArcAngle, clockwise:true)
circlePath.lineWidth = self.circleBorderWidth
let updateProgressAnimation = CABasicAnimation();
updateProgressAnimation.keyPath = "path"
updateProgressAnimation.fromValue = self.progressLayer.path
updateProgressAnimation.toValue = circlePath.cgPath
updateProgressAnimation.duration = progressUpdateAnimationTime
self.progressLayer.path = circlePath.cgPath
self.progressLayer.add(updateProgressAnimation, forKey: "update progress animation")
}
}
// MARK : Methods used to animate states and transions between them
fileprivate let firstStepAnimationTime = 0.3
fileprivate let secondStepAnimationTime = 0.15
fileprivate let textAppearingAnimationTime = 0.2
fileprivate let progressUpdateAnimationTime = 0.1
fileprivate func animateDefaultStateAnimated(_ animated: Bool) {
if !animated {
self.shapeLayer.path = self.defaultStatePath().cgPath
self.titleLabel?.alpha = 1.0
self.showContentImage()
} else {
self.shapeLayer.removeAnimation(forKey: "rotation animation")
let firstStepAnimation = CABasicAnimation();
firstStepAnimation.keyPath = "path"
firstStepAnimation.fromValue = self.shapeLayer.path
firstStepAnimation.toValue = self.animateToCircleReplacePath().cgPath
firstStepAnimation.duration = secondStepAnimationTime
self.shapeLayer.path = self.animateToCircleFakeRoundPath().cgPath
self.shapeLayer.add(firstStepAnimation, forKey: "first step animation")
let secondStepAnimation = CABasicAnimation();
secondStepAnimation.keyPath = "path"
secondStepAnimation.fromValue = self.shapeLayer.path!
secondStepAnimation.toValue = self.defaultStatePath().cgPath
secondStepAnimation.beginTime = CACurrentMediaTime() + secondStepAnimationTime
secondStepAnimation.duration = firstStepAnimationTime
self.shapeLayer.path = self.defaultStatePath().cgPath
self.shapeLayer.add(secondStepAnimation, forKey: "second step animation")
let delay = secondStepAnimationTime + firstStepAnimationTime
UIView.animate(withDuration: textAppearingAnimationTime, delay: delay, options: UIViewAnimationOptions(),
animations: { () -> Void in
self.titleLabel?.alpha = 1.0
},
completion: { (complete) -> Void in
self.showContentImage()
})
}
}
fileprivate func animateProgressingState(_ layer: CAShapeLayer) {
let firstStepAnimation = CABasicAnimation();
firstStepAnimation.keyPath = "path"
firstStepAnimation.fromValue = layer.path
firstStepAnimation.toValue = self.animateToCircleFakeRoundPath().cgPath
firstStepAnimation.duration = firstStepAnimationTime
layer.path = self.animateToCircleReplacePath().cgPath
layer.add(firstStepAnimation, forKey: "first step animation")
let secondStepAnimation = CABasicAnimation();
secondStepAnimation.keyPath = "path"
secondStepAnimation.fromValue = layer.path
secondStepAnimation.toValue = self.progressingStatePath().cgPath
secondStepAnimation.beginTime = CACurrentMediaTime() + firstStepAnimationTime
secondStepAnimation.duration = secondStepAnimationTime
layer.path = self.progressingStatePath().cgPath
layer.add(secondStepAnimation, forKey: "second step animation")
let animation = CABasicAnimation();
animation.keyPath = "transform.rotation";
animation.fromValue = 0 * M_PI
animation.toValue = 2 * M_PI
animation.repeatCount = Float.infinity
animation.duration = 1.5
animation.beginTime = CACurrentMediaTime() + firstStepAnimationTime + secondStepAnimationTime
layer.add(animation, forKey: "rotation animation")
layer.anchorPoint = CGPoint(x: 0.5 + self.animationShift.width / self.bounds.size.width,
y: 0.5 + self.animationShift.height / self.bounds.size.height)
UIView.animate(withDuration: textAppearingAnimationTime, animations: { () -> Void in
self.titleLabel?.alpha = 0.0
self.hideContentImage()
})
}
// MARK : Pathes creation for different states
fileprivate func defaultStatePath() -> UIBezierPath {
let bordersPath = UIBezierPath(roundedRect:self.bounds, cornerRadius:self.cornerRadius)
bordersPath.lineWidth = self.borderWidth
return bordersPath
}
fileprivate func progressingStatePath() -> UIBezierPath {
let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height)
let circlePath = UIBezierPath()
let startAngle = self.circleCutAngle/180 * CGFloat(M_PI)
let endAngle = 2 * CGFloat(M_PI)
circlePath.addArc(withCenter: center, radius:self.circleRadius, startAngle:startAngle, endAngle:endAngle, clockwise:true)
circlePath.lineWidth = self.circleBorderWidth
return circlePath
}
fileprivate func animateToCircleFakeRoundPath() -> UIBezierPath {
let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height)
let rect = CGRect(x: center.x - self.circleRadius, y: center.y - self.circleRadius, width: self.circleRadius * 2, height: self.circleRadius * 2)
let bordersPath = UIBezierPath(roundedRect: rect, cornerRadius: self.circleRadius)
bordersPath.lineWidth = self.borderWidth
return bordersPath
}
fileprivate func animateToCircleReplacePath() -> UIBezierPath {
let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height)
let circlePath = UIBezierPath()
circlePath.addArc(withCenter: center, radius:self.circleRadius, startAngle:CGFloat(0.0), endAngle:CGFloat(M_PI * 2), clockwise:true)
circlePath.lineWidth = self.circleBorderWidth
return circlePath
}
fileprivate func crossPath() -> UIBezierPath {
let crossPath = UIBezierPath()
let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height)
let point1 = CGPoint(x: center.x - self.circleRadius/2, y: center.y + self.circleRadius / 2)
let point2 = CGPoint(x: center.x + self.circleRadius/2, y: center.y + self.circleRadius / 2)
let point3 = CGPoint(x: center.x + self.circleRadius/2, y: center.y - self.circleRadius / 2)
let point4 = CGPoint(x: center.x - self.circleRadius/2, y: center.y - self.circleRadius / 2)
crossPath.move(to: point1)
crossPath.addLine(to: point3)
crossPath.move(to: point2)
crossPath.addLine(to: point4)
crossPath.lineWidth = self.circleBorderWidth
return crossPath
}
// MARK : processing animation stopping while in background
// Should be done to prevent animation broken on entering foreground
fileprivate func registerForNotifications() {
NotificationCenter.default.addObserver(self, selector:#selector(self.applicationDidEnterBackground(_:)),
name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(self.applicationWillEnterForeground(_:)),
name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
fileprivate func unregisterFromNotifications() {
NotificationCenter.default.removeObserver(self)
}
func applicationDidEnterBackground(_ notification: Notification) {
self.pauseLayer(self.layer)
}
func applicationWillEnterForeground(_ notification: Notification) {
self.resumeLayer(self.layer)
}
fileprivate func pauseLayer(_ layer: CALayer) {
let pausedTime = layer.convertTime(CACurrentMediaTime(), from:nil)
layer.speed = 0.0
layer.timeOffset = pausedTime
}
fileprivate func resumeLayer(_ layer: CALayer) {
let pausedTime = layer.timeOffset
layer.speed = 1.0
layer.timeOffset = 0.0
layer.beginTime = 0.0
let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
layer.beginTime = timeSincePause
}
// MARK : Content images hiding
// The only available way to make images hide is to set the object to nil
// If you now any way else please help me here
fileprivate var imageForNormalState: UIImage?
fileprivate var imageForHighlitedState: UIImage?
fileprivate var imageForDisabledState: UIImage?
fileprivate func hideContentImage() {
self.imageForNormalState = self.image(for: UIControlState())
self.setImage(UIImage(), for: UIControlState())
self.imageForHighlitedState = self.image(for: UIControlState.highlighted)
self.setImage(UIImage(), for: UIControlState.highlighted)
self.imageForDisabledState = self.image(for: UIControlState.disabled)
self.setImage(UIImage(), for: UIControlState.disabled)
}
fileprivate func showContentImage() {
if self.imageForNormalState != nil {
self.setImage(self.imageForNormalState, for: UIControlState());
self.imageForNormalState = nil
}
if self.imageForHighlitedState != nil {
self.setImage(self.imageForHighlitedState, for: UIControlState.highlighted)
self.imageForHighlitedState = nil
}
if self.imageForDisabledState != nil {
self.setImage(self.imageForDisabledState, for: UIControlState.disabled)
self.imageForDisabledState = nil
}
}
}
| mit | 9b0944858a7ada9a174260f1ff16998d | 47.119898 | 171 | 0.684409 | 4.988892 | false | false | false | false |
fruitcoder/ReplaceAnimation | ReplaceAnimation/MountainView.swift | 1 | 3777 | //
// MountainView.swift
// ReplaceAnimation
//
// Created by Alexander Hüllmandel on 07/03/16.
// Copyright © 2016 Alexander Hüllmandel. All rights reserved.
//
import UIKit
class MountainLayer: CALayer {
var peakXToWidthRatio: CGFloat = 0.5 {
// Update your UI when value changes
didSet {
if peakXToWidthRatio <= 1.0 && peakXToWidthRatio >= 0.0 {
self.setNeedsDisplay()
}
}
}
var leftYToHeightRatio: CGFloat = 0.5 {
// Update your UI when value changes
didSet {
if leftYToHeightRatio <= 1.0 && leftYToHeightRatio >= 0.0 {
self.setNeedsDisplay()
}
}
}
var rightYToHeightRatio: CGFloat = 0.5 {
// Update your UI when value changes
didSet {
if rightYToHeightRatio <= 1.0 && rightYToHeightRatio >= 0.0 {
self.setNeedsDisplay()
}
}
}
override func draw(in ctx: CGContext) {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: frame.origin.x, y: frame.origin.y + frame.size.height))
bezierPath.addLine(to: CGPoint(x: frame.origin.x, y: frame.origin.y + leftYToHeightRatio * frame.size.height))
bezierPath.addLine(to: CGPoint(x: frame.origin.x + peakXToWidthRatio * frame.size.width, y: frame.origin.y))
bezierPath.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + rightYToHeightRatio * frame.size.height))
bezierPath.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height))
bezierPath.close()
ctx.setFillColor(UIColor.white.cgColor)
ctx.addPath(bezierPath.cgPath)
ctx.fillPath()
}
}
@IBDesignable
class MountainView: UIView {
@IBInspectable var peakXToWidthRatio: CGFloat = 0.5 {
// Update your UI when value changes
didSet {
if peakXToWidthRatio <= 1.0 && peakXToWidthRatio >= 0.0 {
self.setNeedsDisplay()
}
}
}
@IBInspectable var leftYToHeightRatio: CGFloat = 0.5 {
// Update your UI when value changes
didSet {
if leftYToHeightRatio <= 1.0 && leftYToHeightRatio >= 0.0 {
self.setNeedsDisplay()
}
}
}
@IBInspectable var rightYToHeightRatio: CGFloat = 0.5 {
// Update your UI when value changes
didSet {
if rightYToHeightRatio <= 1.0 && rightYToHeightRatio >= 0.0 {
self.setNeedsDisplay()
}
}
}
override func didMoveToSuperview() {
setNeedsDisplay()
}
override func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height))
bezierPath.addLine(to: CGPoint(x: rect.origin.x,y: rect.origin.y + leftYToHeightRatio * rect.size.height))
bezierPath.addLine(to: CGPoint(x: rect.origin.x + peakXToWidthRatio * rect.size.width, y: rect.origin.y))
bezierPath.addLine(to: CGPoint(x: rect.origin.x + rect.size.width,y: rect.origin.y + rightYToHeightRatio * rect.size.height))
bezierPath.addLine(to: CGPoint(x: rect.origin.x + rect.size.width,y: rect.origin.y + rect.size.height))
bezierPath.close()
tintColor.setFill()
bezierPath.fill()
}
}
| mit | ca6f1106da9d2038c7dcc30ed78c7b24 | 32.105263 | 138 | 0.593005 | 4.040685 | false | false | false | false |
austinzheng/swift | test/Constraints/dictionary_literal.swift | 3 | 5537 | // RUN: %target-typecheck-verify-swift
final class DictStringInt : ExpressibleByDictionaryLiteral {
typealias Key = String
typealias Value = Int
init(dictionaryLiteral elements: (String, Int)...) { }
}
final class MyDictionary<K, V> : ExpressibleByDictionaryLiteral {
typealias Key = K
typealias Value = V
init(dictionaryLiteral elements: (K, V)...) { }
}
func useDictStringInt(_ d: DictStringInt) {}
func useDict<K, V>(_ d: MyDictionary<K,V>) {}
// Concrete dictionary literals.
useDictStringInt(["Hello" : 1])
useDictStringInt(["Hello" : 1, "World" : 2])
useDictStringInt(["Hello" : 1, "World" : 2.5])
// expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
useDictStringInt([4.5 : 2])
// expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary key type 'String'}}
useDictStringInt([nil : 2])
// expected-error@-1 {{'nil' is not compatible with expected dictionary key type 'String'}}
useDictStringInt([7 : 1, "World" : 2])
// expected-error@-1 {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
useDictStringInt(["Hello" : nil])
// expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'Int'}}
typealias FuncBoolToInt = (Bool) -> Int
let dict1: MyDictionary<String, FuncBoolToInt> = ["Hello": nil]
// expected-error@-1 {{'nil' is not compatible with expected dictionary value type '(Bool) -> Int'}}
// Generic dictionary literals.
useDict(["Hello" : 1])
useDict(["Hello" : 1, "World" : 2])
useDict(["Hello" : 1.5, "World" : 2])
useDict([1 : 1.5, 3 : 2.5])
// Fall back to Swift.Dictionary<K, V> if no context is otherwise available.
var a = ["Hello" : 1, "World" : 2]
var a2 : Dictionary<String, Int> = a
var a3 = ["Hello" : 1]
var b = [1 : 2, 1.5 : 2.5]
var b2 : Dictionary<Double, Double> = b
var b3 = [1 : 2.5]
// <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error
// expected-note @+1 {{did you mean to use a dictionary literal instead?}}
var _: MyDictionary<String, (Int) -> Int>? = [ // expected-error {{dictionary of type 'MyDictionary<String, (Int) -> Int>' cannot be initialized with array literal}}
"closure_1" as String, {(Int) -> Int in 0},
"closure_2", {(Int) -> Int in 0}]
var _: MyDictionary<String, Int>? = ["foo", 1] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}}
var _: MyDictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} {{53-54=:}}
var _: MyDictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{cannot convert value of type '[Any]' to specified type 'MyDictionary<String, Int>?'}}
var _: MyDictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
// <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better
var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}}
class A { }
class B : A { }
class C : A { }
func testDefaultExistentials() {
let _ = ["a" : 1, "b" : 2.5, "c" : "hello"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any]}}
let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"]
let _ = ["a" : 1, "b" : nil, "c" : "hello"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any?]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any?]}}
let _: [String : Any?] = ["a" : 1, "b" : nil, "c" : "hello"]
let d2 = [:]
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = d2 // expected-error{{value of type '[AnyHashable : Any]'}}
let _ = ["a": 1,
"b": ["a", 2, 3.14159],
"c": ["a": 2, "b": 3.5]]
// expected-error@-3{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}
let d3 = ["b" : B(), "c" : C()]
let _: Int = d3 // expected-error{{value of type '[String : A]'}}
let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : Any]'}}
let _ = ["a" : "hello", 17 : "string"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : String]'}}
}
// SR-4952, rdar://problem/32330004 - Assertion failure during swift::ASTVisitor<::FailureDiagnosis,...>::visit
func rdar32330004_1() -> [String: Any] {
return ["a""one": 1, "two": 2, "three": 3] // expected-note {{did you mean to use a dictionary literal instead?}}
// expected-error@-1 {{expected ',' separator}}
// expected-error@-2 {{dictionary of type '[String : Any]' cannot be used with array literal}}
}
func rdar32330004_2() -> [String: Any] {
return ["a", 0, "one", 1, "two", 2, "three", 3]
// expected-error@-1 {{dictionary of type '[String : Any]' cannot be used with array literal}}
// expected-note@-2 {{did you mean to use a dictionary literal instead?}} {{14-15=:}} {{24-25=:}} {{34-35=:}} {{46-47=:}}
}
| apache-2.0 | 2f77f97ae61dbdb7d1a35c724d7924ea | 44.760331 | 184 | 0.647643 | 3.460625 | false | false | false | false |
apple/swift | stdlib/public/core/Equatable.swift | 5 | 10793 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Equatable
//===----------------------------------------------------------------------===//
/// A type that can be compared for value equality.
///
/// Types that conform to the `Equatable` protocol can be compared for equality
/// using the equal-to operator (`==`) or inequality using the not-equal-to
/// operator (`!=`). Most basic types in the Swift standard library conform to
/// `Equatable`.
///
/// Some sequence and collection operations can be used more simply when the
/// elements conform to `Equatable`. For example, to check whether an array
/// contains a particular value, you can pass the value itself to the
/// `contains(_:)` method when the array's element conforms to `Equatable`
/// instead of providing a closure that determines equivalence. The following
/// example shows how the `contains(_:)` method can be used with an array of
/// strings.
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
///
/// let nameToCheck = "Kofi"
/// if students.contains(nameToCheck) {
/// print("\(nameToCheck) is signed up!")
/// } else {
/// print("No record of \(nameToCheck).")
/// }
/// // Prints "Kofi is signed up!"
///
/// Conforming to the Equatable Protocol
/// ====================================
///
/// Adding `Equatable` conformance to your custom types means that you can use
/// more convenient APIs when searching for particular instances in a
/// collection. `Equatable` is also the base protocol for the `Hashable` and
/// `Comparable` protocols, which allow more uses of your custom type, such as
/// constructing sets or sorting the elements of a collection.
///
/// You can rely on automatic synthesis of the `Equatable` protocol's
/// requirements for a custom type when you declare `Equatable` conformance in
/// the type's original declaration and your type meets these criteria:
///
/// - For a `struct`, all its stored properties must conform to `Equatable`.
/// - For an `enum`, all its associated values must conform to `Equatable`. (An
/// `enum` without associated values has `Equatable` conformance even
/// without the declaration.)
///
/// To customize your type's `Equatable` conformance, to adopt `Equatable` in a
/// type that doesn't meet the criteria listed above, or to extend an existing
/// type to conform to `Equatable`, implement the equal-to operator (`==`) as
/// a static method of your type. The standard library provides an
/// implementation for the not-equal-to operator (`!=`) for any `Equatable`
/// type, which calls the custom `==` function and negates its result.
///
/// As an example, consider a `StreetAddress` class that holds the parts of a
/// street address: a house or building number, the street name, and an
/// optional unit number. Here's the initial declaration of the
/// `StreetAddress` type:
///
/// class StreetAddress {
/// let number: String
/// let street: String
/// let unit: String?
///
/// init(_ number: String, _ street: String, unit: String? = nil) {
/// self.number = number
/// self.street = street
/// self.unit = unit
/// }
/// }
///
/// Now suppose you have an array of addresses that you need to check for a
/// particular address. To use the `contains(_:)` method without including a
/// closure in each call, extend the `StreetAddress` type to conform to
/// `Equatable`.
///
/// extension StreetAddress: Equatable {
/// static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool {
/// return
/// lhs.number == rhs.number &&
/// lhs.street == rhs.street &&
/// lhs.unit == rhs.unit
/// }
/// }
///
/// The `StreetAddress` type now conforms to `Equatable`. You can use `==` to
/// check for equality between any two instances or call the
/// `Equatable`-constrained `contains(_:)` method.
///
/// let addresses = [StreetAddress("1490", "Grove Street"),
/// StreetAddress("2119", "Maple Avenue"),
/// StreetAddress("1400", "16th Street")]
/// let home = StreetAddress("1400", "16th Street")
///
/// print(addresses[0] == home)
/// // Prints "false"
/// print(addresses.contains(home))
/// // Prints "true"
///
/// Equality implies substitutability---any two instances that compare equally
/// can be used interchangeably in any code that depends on their values. To
/// maintain substitutability, the `==` operator should take into account all
/// visible aspects of an `Equatable` type. Exposing nonvalue aspects of
/// `Equatable` types other than class identity is discouraged, and any that
/// *are* exposed should be explicitly pointed out in documentation.
///
/// Since equality between instances of `Equatable` types is an equivalence
/// relation, any of your custom types that conform to `Equatable` must
/// satisfy three conditions, for any values `a`, `b`, and `c`:
///
/// - `a == a` is always `true` (Reflexivity)
/// - `a == b` implies `b == a` (Symmetry)
/// - `a == b` and `b == c` implies `a == c` (Transitivity)
///
/// Moreover, inequality is the inverse of equality, so any custom
/// implementation of the `!=` operator must guarantee that `a != b` implies
/// `!(a == b)`. The default implementation of the `!=` operator function
/// satisfies this requirement.
///
/// Equality is Separate From Identity
/// ----------------------------------
///
/// The identity of a class instance is not part of an instance's value.
/// Consider a class called `IntegerRef` that wraps an integer value. Here's
/// the definition for `IntegerRef` and the `==` function that makes it
/// conform to `Equatable`:
///
/// class IntegerRef: Equatable {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
///
/// static func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool {
/// return lhs.value == rhs.value
/// }
/// }
///
/// The implementation of the `==` function returns the same value whether its
/// two arguments are the same instance or are two different instances with
/// the same integer stored in their `value` properties. For example:
///
/// let a = IntegerRef(100)
/// let b = IntegerRef(100)
///
/// print(a == a, a == b, separator: ", ")
/// // Prints "true, true"
///
/// Class instance identity, on the other hand, is compared using the
/// triple-equals identical-to operator (`===`). For example:
///
/// let c = a
/// print(c === a, c === b, separator: ", ")
/// // Prints "true, false"
public protocol Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func == (lhs: Self, rhs: Self) -> Bool
}
extension Equatable {
/// Returns a Boolean value indicating whether two values are not equal.
///
/// Inequality is the inverse of equality. For any values `a` and `b`, `a != b`
/// implies that `a == b` is `false`.
///
/// This is the default implementation of the not-equal-to operator (`!=`)
/// for any type that conforms to `Equatable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
// transparent because sometimes types that use this generate compile-time
// warnings, e.g. that an expression always evaluates to true
@_transparent
public static func != (lhs: Self, rhs: Self) -> Bool {
return !(lhs == rhs)
}
}
//===----------------------------------------------------------------------===//
// Reference comparison
//===----------------------------------------------------------------------===//
/// Returns a Boolean value indicating whether two references point to the same
/// object instance.
///
/// This operator tests whether two instances have the same identity, not the
/// same value. For value equality, see the equal-to operator (`==`) and the
/// `Equatable` protocol.
///
/// The following example defines an `IntegerRef` type, an integer type with
/// reference semantics.
///
/// class IntegerRef: Equatable {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
/// }
///
/// func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool {
/// return lhs.value == rhs.value
/// }
///
/// Because `IntegerRef` is a class, its instances can be compared using the
/// identical-to operator (`===`). In addition, because `IntegerRef` conforms
/// to the `Equatable` protocol, instances can also be compared using the
/// equal-to operator (`==`).
///
/// let a = IntegerRef(10)
/// let b = a
/// print(a == b)
/// // Prints "true"
/// print(a === b)
/// // Prints "true"
///
/// The identical-to operator (`===`) returns `false` when comparing two
/// references to different object instances, even if the two instances have
/// the same value.
///
/// let c = IntegerRef(10)
/// print(a == c)
/// // Prints "true"
/// print(a === c)
/// // Prints "false"
///
/// - Parameters:
/// - lhs: A reference to compare.
/// - rhs: Another reference to compare.
@inlinable // trivial-implementation
public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return ObjectIdentifier(l) == ObjectIdentifier(r)
case (nil, nil):
return true
default:
return false
}
}
/// Returns a Boolean value indicating whether two references point to
/// different object instances.
///
/// This operator tests whether two instances have different identities, not
/// different values. For value inequality, see the not-equal-to operator
/// (`!=`) and the `Equatable` protocol.
///
/// - Parameters:
/// - lhs: A reference to compare.
/// - rhs: Another reference to compare.
@inlinable // trivial-implementation
public func !== (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
return !(lhs === rhs)
}
| apache-2.0 | 492db47461cbd8207e99b9f84e803048 | 38.105072 | 81 | 0.603169 | 4.259274 | false | false | false | false |
alltheflow/copypasta | Carthage/Checkouts/VinceRP/vincerp/Common/Util/ReactivePropertyGenerator.swift | 1 | 4163 | //
// Created by Viktor Belenyesi on 25/09/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
public class ReactivePropertyGenerator {
// TODO: unittest -> check for memory leaks
private static var propertyMap = [String: Node]()
private static var observerMap = [String: PropertyObserver]()
init() {}
static func getKey(targetObject: AnyObject, propertyName: String) -> String {
return "\(targetObject.hash)\(propertyName) "
}
static func getEmitter<T>(targetObject: AnyObject, propertyName: String) -> Source<T>? {
let key = getKey(targetObject, propertyName: propertyName)
return propertyMap[key] as! Source<T>?
}
static func synthesizeEmitter<T>(initValue: T) -> Source<T> {
return Source<T>(initValue: initValue)
}
static func synthesizeObserver<T>(targetObject: AnyObject, propertyName: String, initValue: T) -> PropertyObserver {
return PropertyObserver(targetObject: targetObject as! NSObject, propertyName: propertyName) { (currentTargetObject: NSObject, currentPropertyName:String, currentValue:AnyObject) in
if let existingEmitter:Source<T> = getEmitter(currentTargetObject, propertyName: propertyName) {
existingEmitter.update(currentValue as! T)
}
}
}
static func createEmitter<T>(targetObject: AnyObject, propertyName: String, initValue: T) -> Source<T> {
let result = synthesizeEmitter(initValue)
let key = getKey(targetObject, propertyName: propertyName)
propertyMap[key] = result
return result
}
static func createObserver<T>(targetObject: AnyObject, propertyName: String, initValue: T) -> PropertyObserver {
let result = synthesizeObserver(targetObject, propertyName: propertyName, initValue: initValue)
let key = getKey(targetObject, propertyName: propertyName)
observerMap[key] = result
return result
}
public static func source<T>(targetObject: AnyObject, propertyName: String, initValue: T, initializer: ((Source<T>) -> ())? = nil) -> Source<T> {
if let emitter:Source<T> = getEmitter(targetObject, propertyName: propertyName) {
return emitter
}
let emitter = createEmitter(targetObject, propertyName: propertyName, initValue: initValue)
if let i = initializer {
i(emitter)
}
return emitter
}
public static func property<T>(targetObject: AnyObject, propertyName: String, initValue: T, initializer: ((Source<T>) -> ())? = nil) -> Hub<T> {
let result = source(targetObject, propertyName: propertyName, initValue: initValue, initializer: initializer)
createObserver(targetObject, propertyName: propertyName, initValue: initValue)
return result as Hub<T>
}
}
private var propertyObserverContext = 0
class PropertyObserver: NSObject {
let targetObject: NSObject
let propertyName: String
let propertyChangeHandler: (NSObject, String, AnyObject) -> Void
init(targetObject:NSObject, propertyName: String, propertyChangeHandler: (NSObject, String, AnyObject) -> Void) {
self.targetObject = targetObject
self.propertyName = propertyName
self.propertyChangeHandler = propertyChangeHandler
super.init()
self.targetObject.addObserver(self, forKeyPath: propertyName, options: .New, context: &propertyObserverContext)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &propertyObserverContext {
if self.propertyName == keyPath {
if let newValue = change?[NSKeyValueChangeNewKey] {
self.propertyChangeHandler(self.targetObject, self.propertyName, newValue)
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
deinit {
self.targetObject.removeObserver(self, forKeyPath: propertyName, context: &propertyObserverContext)
}
}
| mit | e7ddc13505bbef04f00ff9691b96614e | 41.469388 | 190 | 0.681643 | 4.94887 | false | false | false | false |
aryaxt/TextInputBar | TextInputBar/ViewController.swift | 1 | 3845 | //
// ViewController.swift
// TextInputBar
//
// Created by Aryan Ghassemi on 8/16/15.
// Copyright © 2015 Aryan Ghassemi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, TextInputBarDelegate, UITableViewDataSource {
@IBOutlet private var inputbar: TextInputbar!
@IBOutlet private var tableView: UITableView!
private var messages = [Message]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
populateInitialData()
inputbar.textView.font = UIFont.systemFontOfSize(16)
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .None
tableView.tableFooterView = UIView()
}
// MARK: - Private -
func populateInitialData() {
messages.append(Message(text: "Hey", isMeAuthor: true))
messages.append(Message(text: "What's up?", isMeAuthor: false))
messages.append(Message(text: "I love this component, it saves me a lot of time, and it looks great. I use it in all my apps", isMeAuthor: true))
messages.append(Message(text: "I'm glad you liked it", isMeAuthor: false))
messages.append(Message(text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with", isMeAuthor: true))
messages.append(Message(text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\ne specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", isMeAuthor: false))
}
// MARK: - TextInputToolbarDelegate -
func textInputBar(didSelectSend textInputbar: TextInputbar) {
textInputbar.showProgress(true, animated: true)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) { [weak self] in
self?.tableView.beginUpdates()
let indexPath = NSIndexPath(forRow: self!.messages.count, inSection: 0)
self?.messages.append(Message(text: textInputbar.textView.text, isMeAuthor: true))
self?.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
self?.tableView.endUpdates()
textInputbar.showProgress(false, animated: true)
textInputbar.textView.text = ""
}
}
// MARK: - UITableViewDataSource -
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MessageCell") as! MessageCell
cell.configureWithText(messages[indexPath.row])
return cell
}
}
| mit | 2029a75879b9874f51edb32651afd981 | 50.945946 | 976 | 0.773673 | 4.219539 | false | false | false | false |
powerytg/Accented | Accented/UI/Common/Components/Deck/DeckCacheController.swift | 1 | 8087 | //
// DeckCacheController.swift
// Accented
//
// Created by You, Tiangong on 8/5/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
protocol DeckCacheControllerDelegate : NSObjectProtocol {
// Invoked when the cache has finished initialization (for non-deferred configuration)
func cacheDidFinishInitialization()
// Invoked when the initial selected card has finished initialization (for deferred configuration)
func deferredSelectedCardDidFinishInitialization()
// Invoked when the initial sibling cards hav finished initialization (for deferred configuration)
func deferredSiblingCardsDidFinishInitialization()
// Invoked when a card has been added to cache
func cardDidAddToCache(_ card : CardViewController)
}
class DeckCacheController: NSObject {
// Delegate
weak var delegate : DeckCacheControllerDelegate?
// Reference to the data source
weak var dataSource : DeckViewControllerDataSource?
// Total number of items
private var totalItemCount = 0
// Currently selected card
var selectedCard : CardViewController!
// Left sibling
var leftCard : CardViewController?
// Right sibling
var rightCard : CardViewController?
// Off-screen view controller for heat-up purpose
var offScreenCard : CardViewController?
// Recucled card
var recycledCard : CardViewController?
// All cards, including those on-screen and those already recycled
var cachedCards = [CardViewController]()
// Selected index, initially -1
private var selectedIndex : Int = -1
func initializeCache(_ initialSelectedIndex : Int) {
guard dataSource != nil else { return }
let ds = dataSource!
// Pre-populate the cache with cards
totalItemCount = ds.numberOfCards()
selectedIndex = initialSelectedIndex
// Populate the selected, left, right and off-screen siblings
selectedCard = getCardFromDataSource(initialSelectedIndex)
selectedCard.withinVisibleRange = true
if hasLeftSibling(selectedIndex) {
leftCard = getCardFromDataSource(selectedIndex - 1)
leftCard!.withinVisibleRange = true
}
if hasRightSibling(selectedIndex) {
rightCard = getCardFromDataSource(selectedIndex + 1)
rightCard!.withinVisibleRange = true
}
if hasOffScreenRightSibling(selectedIndex) {
offScreenCard = getCardFromDataSource(selectedIndex + 2)
offScreenCard!.withinVisibleRange = false
}
delegate?.cacheDidFinishInitialization()
}
func initializeSelectedCard(_ initialSelectedIndex : Int) {
guard dataSource != nil else { return }
let ds = dataSource!
totalItemCount = ds.numberOfCards()
selectedIndex = initialSelectedIndex
// Populate the selected card
selectedCard = getCardFromDataSource(initialSelectedIndex)
selectedCard.withinVisibleRange = true
delegate?.deferredSelectedCardDidFinishInitialization()
}
func initializeSelectedCardSiblings() {
if hasLeftSibling(selectedIndex) {
leftCard = getCardFromDataSource(selectedIndex - 1)
leftCard!.withinVisibleRange = true
}
if hasRightSibling(selectedIndex) {
rightCard = getCardFromDataSource(selectedIndex + 1)
rightCard!.withinVisibleRange = true
}
if hasOffScreenRightSibling(selectedIndex) {
offScreenCard = getCardFromDataSource(selectedIndex + 2)
offScreenCard!.withinVisibleRange = false
}
delegate?.deferredSiblingCardsDidFinishInitialization()
}
func hasLeftSibling(_ index : Int) -> Bool {
return (totalItemCount != 0 && index != 0)
}
func hasRightSibling(_ index : Int) -> Bool {
return (totalItemCount != 0 && index != totalItemCount - 1)
}
func hasOffScreenRightSibling(_ index : Int) -> Bool {
return (totalItemCount != 0 && index < totalItemCount - 2)
}
func hasOffScreenLeftSibling(_ index : Int) -> Bool {
return (totalItemCount != 0 && index > 1)
}
func scrollToRight() {
guard dataSource != nil else { return }
guard totalItemCount > 0 else { return }
guard selectedIndex > 0 else { return }
let previousSelectedViewController = selectedCard
let targetSelectedIndex = selectedIndex - 1
// We can recycle the previous off-screen sibling since it'll be two screens away
if offScreenCard != nil {
recycleCard(offScreenCard!)
offScreenCard = nil
}
// Previous left sibling becomes the new selected view controller
if leftCard != nil {
selectedCard = leftCard
selectedCard.withinVisibleRange = true
}
// Previous right card becomes the new right off-screen sibling
offScreenCard = rightCard
offScreenCard?.withinVisibleRange = false
// Previous selected card becomes the right card
rightCard = previousSelectedViewController
rightCard!.withinVisibleRange = true
// Update selected index
selectedIndex = targetSelectedIndex
}
func scrollToLeft() {
guard dataSource != nil else { return }
guard totalItemCount > 0 else { return }
guard selectedIndex < totalItemCount - 1 else { return }
let previousSelectedViewController = selectedCard
let targetSelectedIndex = selectedIndex + 1
// We can recycle the previous left sibling since it'll be two screens away
if leftCard != nil {
recycleCard(leftCard!)
}
// Previous selected vc becomes the new left sibling
if hasLeftSibling(targetSelectedIndex) {
leftCard = previousSelectedViewController
leftCard!.withinVisibleRange = true
} else {
leftCard = nil
}
// Previous right sibling becomes the new selected view controller
if rightCard != nil {
selectedCard = rightCard
selectedCard.withinVisibleRange = true
}
// Previous right off-screen sibling becomes the new right sibling
if hasRightSibling(targetSelectedIndex) {
rightCard = offScreenCard
rightCard?.withinVisibleRange = true
} else {
rightCard = nil
}
// Update selected index
selectedIndex = targetSelectedIndex
}
func populateRightOffScreenSibling() {
// Prepare for off-screen cards
if hasOffScreenRightSibling(selectedIndex) {
offScreenCard = getCardFromDataSource(selectedIndex + 2)
offScreenCard?.withinVisibleRange = false
} else {
offScreenCard = nil
}
}
func populateLeftOffScreenSibling() {
// Prepare for off-screen cards
if hasLeftSibling(selectedIndex) {
leftCard = getCardFromDataSource(selectedIndex - 1)
leftCard?.withinVisibleRange = true
} else {
leftCard = nil
}
}
func getRecycledCardViewController() -> CardViewController? {
if recycledCard != nil {
recycledCard!.withinVisibleRange = true
}
return recycledCard
}
private func getCardFromDataSource(_ index : Int) -> CardViewController {
let card = dataSource!.cardForItemIndex(index)
card.indexInDataSource = index
if !cachedCards.contains(card) {
cachedCards.append(card)
delegate?.cardDidAddToCache(card)
}
return card
}
private func recycleCard(_ card : CardViewController) {
card.prepareForReuse()
recycledCard = card
}
}
| mit | 7d85306da0c70c71c0b5b6a4a2341115 | 31.604839 | 102 | 0.633688 | 5.445118 | false | false | false | false |
nalexn/ViewInspector | Tests/ViewInspectorTests/ViewModifiers/VisualEffectModifiersTests.swift | 1 | 9133 | import XCTest
import SwiftUI
@testable import ViewInspector
// MARK: - ViewGraphicalEffectsTests
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class ViewGraphicalEffectsTests: XCTestCase {
func testBlur() throws {
let sut = EmptyView().blur(radius: 5, opaque: true)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testBlurInspection() throws {
let sut = try EmptyView().blur(radius: 5, opaque: true)
.inspect().emptyView().blur()
XCTAssertEqual(sut.radius, 5)
XCTAssertTrue(sut.isOpaque)
}
func testOpacity() throws {
let sut = EmptyView().opacity(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testOpacityInspection() throws {
let sut = try EmptyView().opacity(5).inspect().emptyView().opacity()
XCTAssertEqual(sut, 5)
}
func testBrightness() throws {
let sut = EmptyView().brightness(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testBrightnessInspection() throws {
let sut = try EmptyView().brightness(5).inspect().emptyView().brightness()
XCTAssertEqual(sut, 5)
}
func testContrast() throws {
let sut = EmptyView().contrast(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testContrastInspection() throws {
let sut = try EmptyView().contrast(5).inspect().emptyView().contrast()
XCTAssertEqual(sut, 5)
}
func testColorInvert() throws {
let sut = EmptyView().colorInvert()
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testColorInvertInspection() throws {
XCTAssertNoThrow(try EmptyView().colorInvert().inspect().emptyView().colorInvert())
XCTAssertThrows(
try EmptyView().padding().inspect().emptyView().colorInvert(),
"EmptyView does not have 'colorInvert' modifier")
}
func testColorMultiply() throws {
let sut = EmptyView().colorMultiply(.red)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testColorMultiplyInspection() throws {
let sut = try EmptyView().colorMultiply(.red).inspect().emptyView().colorMultiply()
XCTAssertEqual(sut, .red)
}
func testSaturation() throws {
let sut = EmptyView().saturation(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testSaturationInspection() throws {
let sut = try EmptyView().saturation(5).inspect().emptyView().saturation()
XCTAssertEqual(sut, 5)
}
func testGrayscale() throws {
let sut = EmptyView().grayscale(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testGrayscaleInspection() throws {
let sut = try EmptyView().grayscale(5).inspect().emptyView().grayscale()
XCTAssertEqual(sut, 5)
}
func testHueRotation() throws {
let sut = EmptyView().hueRotation(.degrees(5))
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testHueRotationInspection() throws {
let angle = Angle(degrees: 5)
let sut = try EmptyView().hueRotation(angle).inspect().emptyView().hueRotation()
XCTAssertEqual(sut, angle)
}
func testLuminanceToAlpha() throws {
let sut = EmptyView().luminanceToAlpha()
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testLuminanceToAlphaInspection() throws {
XCTAssertNoThrow(try EmptyView().luminanceToAlpha().inspect().emptyView().luminanceToAlpha())
XCTAssertThrows(
try EmptyView().padding().inspect().emptyView().luminanceToAlpha(),
"EmptyView does not have 'luminanceToAlpha' modifier")
}
func testShadow() throws {
let sut = EmptyView().shadow(color: .red, radius: 5, x: 5, y: 5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testShadowInspection() throws {
let sut = try EmptyView().shadow(color: .red, radius: 5, x: 6, y: 7)
.inspect().emptyView().shadow()
XCTAssertEqual(sut.color, .red)
XCTAssertEqual(sut.radius, 5)
XCTAssertEqual(sut.offset, CGSize(width: 6, height: 7))
}
func testBorder() throws {
let sut = EmptyView().border(Color.primary, width: 5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testBorderInspection() throws {
let gradient = LinearGradient(gradient: Gradient(colors: [.red]),
startPoint: .bottom, endPoint: .top)
let sut1 = try EmptyView().border(gradient, width: 7)
.inspect().emptyView().border(LinearGradient.self)
XCTAssertEqual(sut1.shapeStyle, gradient)
XCTAssertEqual(sut1.width, 7)
let borderSimulator = Rectangle()
.strokeBorder(Color.red, lineWidth: 3, antialiased: true)
let sut2 = try EmptyView().overlay(borderSimulator).inspect()
let border = try sut2.border(Color.self)
XCTAssertEqual(border.width, 3)
XCTAssertNoThrow(try sut2.overlay().shape())
let sut3 = EmptyView().padding()
XCTAssertThrows(try sut3.inspect().border(LinearGradient.self),
"EmptyView does not have 'border' modifier")
}
func testBlendMode() throws {
let sut = EmptyView().blendMode(.darken)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testBlendModeInspection() throws {
let sut = try EmptyView().blendMode(.darken).inspect().emptyView().blendMode()
XCTAssertEqual(sut, .darken)
}
func testCompositingGroup() throws {
let sut = EmptyView().compositingGroup()
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testDrawingGroup() throws {
let sut = Rectangle().drawingGroup()
XCTAssertNoThrow(try sut.inspect().shape())
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension LinearGradient: BinaryEquatable { }
// MARK: - ViewMaskingTests
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class ViewMaskingTests: XCTestCase {
func testClipped() throws {
let sut = EmptyView().clipped(antialiased: false)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testClippedInspection() throws {
let sut = try EmptyView().clipped(antialiased: false).inspect().emptyView()
XCTAssertNoThrow(try sut.clipShape(Rectangle.self))
let isAntialiased = try sut.clipStyle().isAntialiased
XCTAssertFalse(isAntialiased)
}
func testClipShape() throws {
let sut = EmptyView().clipShape(Capsule(), style: FillStyle())
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testClipShapeInspection() throws {
let style = FillStyle()
let sut = try EmptyView().clipShape(Capsule(), style: style).inspect().emptyView()
XCTAssertNoThrow(try sut.clipShape(Capsule.self))
let sutStyle = try sut.clipStyle()
XCTAssertEqual(sutStyle, style)
}
func testCornerRadius() throws {
let sut = EmptyView().cornerRadius(5, antialiased: false)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testCornerRadiusInspection() throws {
let sut = try EmptyView().cornerRadius(5, antialiased: false)
.inspect().emptyView().cornerRadius()
XCTAssertEqual(sut, 5)
}
func testMask() throws {
let sut = EmptyView().mask(Text(""))
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testMaskInspection() throws {
let string = "abc"
let sut = try EmptyView().mask(Text(string))
.inspect().emptyView().mask().text().string()
XCTAssertEqual(sut, string)
}
func testMaskSearch() throws {
let view = EmptyView().mask(Text("test"))
XCTAssertNoThrow(try view.inspect().find(text: "test"))
}
}
// MARK: - ViewHidingTests
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class ViewHidingTests: XCTestCase {
func testHidden() throws {
let sut = EmptyView().hidden()
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testHiddenInspection() throws {
let sut1 = try EmptyView().hidden().inspect().emptyView()
XCTAssertTrue(sut1.isHidden())
let sut2 = try EmptyView().padding().inspect().emptyView()
XCTAssertFalse(sut2.isHidden())
}
func testDisabled() throws {
let sut = EmptyView().disabled(true)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testDisabledInspection() throws {
let sut1 = EmptyView().disabled(true)
let sut2 = EmptyView().disabled(false)
let sut3 = EmptyView().padding()
XCTAssertTrue(try sut1.inspect().emptyView().isDisabled())
XCTAssertFalse(try sut2.inspect().emptyView().isDisabled())
XCTAssertFalse(try sut3.inspect().emptyView().isDisabled())
}
}
| mit | 02a213be45df21051e0b21e6f805929d | 33.078358 | 101 | 0.624658 | 4.690806 | false | true | false | false |
taniele/quake-parser | QuakeLogParser.swift | 1 | 5366 | import Foundation
enum Action: String {
case Kill = "Kill", InitGame = "InitGame", ShutdownGame = "ShutdownGame"
}
class Game {
var id: String = ""
var totalKills: Int = 0
var players: [String] = [String]()
var kills: [String:Int] = [String:Int]()
func addPlayer(player: String) {
if self.players.contains(player) == false {
self.players.append(player)
}
if self.kills.keys.contains(player) == false {
self.kills[player] = 0
}
}
func advanceKill(player: String, by: Int) {
self.addPlayer(player: player)
if let currentKills = self.kills[player] {
self.kills[player] = currentKills + by
} else {
self.kills[player] = by
}
}
func toDictionary() -> [String:Any] {
let mirror = Mirror(reflecting: self)
var out = [String:Any]();
for (_, attr) in mirror.children.enumerated() {
if let label = attr.label {
out[label] = attr.value
}
}
return out
}
}
class QuakeLogParser {
var games = [[String:Any]]();
let parseKillRegex = "Kill:\\s+\\d+\\s+\\d+\\s+\\d+:\\s+([\\d\\w<>]+)\\s+killed\\s+([\\d\\w<>]+)\\s+by\\s+(MOD_\\w+)"
func requestLog(url: String, onSuccess:@escaping (Data) -> Void, onFailure:@escaping (String) -> Void) {
let requestURL:URL = URL(string: url)!
let request:NSMutableURLRequest = NSMutableURLRequest(url: requestURL)
let session:URLSession = URLSession.shared
let task = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if error != nil {
if let message = error?.localizedDescription {
print (message)
onFailure(message)
return
}
onFailure("Unknown error")
}
switch statusCode {
case 200:
guard data != nil else {
onFailure("No data received")
return
}
onSuccess(data!)
break
default:
onFailure("Cannot get data. HTTP status: \(statusCode)")
break
}
}
task.resume()
}
func parseLog(entries:[String]) {
var i = 1
var game = Game()
for entry in entries {
if let action = parseAction(entry: entry) {
switch action {
case Action.Kill:
game = parseKill(entry: entry, game: game)
break
case Action.InitGame:
// Assuming InitGame events will always precede a ShutdownGame
game = Game()
game.id = "game_\(i)"
break
case Action.ShutdownGame:
games.append(game.toDictionary())
i += 1
break
}
}
}
}
func parseAction(entry: String) -> Action? {
let action = regexMatches(pattern: "^\\s*\\d+:\\d+\\s+(Kill|InitGame|ShutdownGame)", inString: entry).first
guard action != nil else {
return nil
}
return Action(rawValue: action!)
}
func regexMatches(pattern: String, inString: String) -> [String] {
var out = [String]();
do {
let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
let matches = regex.matches(in: inString, options: [], range: NSRange(location: 0, length: inString.utf8.count))
for match in matches {
for i in 1..<match.numberOfRanges {
let range = match.rangeAt(i)
let stringRange = inString.index(inString.startIndex, offsetBy: range.location) ..< inString.index(inString.startIndex, offsetBy: range.location + range.length)
out.append(inString.substring(with: stringRange))
}
}
return out
} catch {
return out
}
}
func parseKill(entry: String, game: Game) -> Game {
let matches: [String] = regexMatches(pattern: self.parseKillRegex, inString: entry)
guard matches.count == 3 else {
return game;
}
game.totalKills += 1
game.addPlayer(player: matches[1])
if matches[0] == "<world>" {
game.advanceKill(player: matches[1], by: -1)
} else {
game.advanceKill(player: matches[0], by: 1)
}
return game
}
func killsByReason(entries: [String]) -> [String:Int] {
var out = [String:Int]()
for entry in entries {
let matches = regexMatches(pattern: self.parseKillRegex, inString: entry)
guard matches.count == 3 else {
continue
}
if out.keys.contains(matches[2]) == false {
out[matches[2]] = 0
}
let currentKills = out[matches[2]];
out[matches[2]] = currentKills! + 1;
}
return out
}
} | mit | 6d54c7723e7083094587194f6077c3c4 | 28.651934 | 180 | 0.507827 | 4.578498 | false | false | false | false |
SomeSimpleSolutions/MemorizeItForever | MemorizeItForever/MemorizeItForever/ViewControllers/Phrase/PhraseHistoryViewController.swift | 1 | 3009 | //
// PhraseHistoryViewController.swift
// MemorizeItForever
//
// Created by Hadi Zamani on 12/7/16.
// Copyright © 2016 SomeSimpleSolutions. All rights reserved.
//
import UIKit
import MemorizeItForeverCore
final class PhraseHistoryViewController: UIViewController, UIPopoverPresentationControllerDelegate {
// MARK: Variables
var wordModel: WordModel?
// MARK: Field Injection
var wordService: WordServiceProtocol!
var dataSource: PhraseTableDataSourceProtocol!
// MARK: Override Methods
override func viewDidLoad() {
super.viewDidLoad()
initialize()
let closeTitle = NSLocalizedString("Close", comment: "Close")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: closeTitle, style: .plain, target: self, action: #selector(PhraseHistoryViewController.closeBarButtonTapHandler))
self.navigationItem.leftBarButtonItem?.tintColor = ColorPicker.backgroundView
self.view.backgroundColor = ColorPicker.backgroundView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
// MARK: Internal Methods
@objc func closeBarButtonTapHandler() {
self.dismiss(animated: true, completion: nil)
}
// MARK: Private Methods
private func initialize(){
self.title = NSLocalizedString("Phrase Failure History", comment: "Phrase Failure History")
tableView.dataSource = dataSource
tableView.delegate = dataSource
tableView.registerClass(Value1UITableViewCell.self, forCellReuseIdentifierEnum: .phraseHistoryTableCellIdentifier)
automaticallyAdjustsScrollViewInsets = false
}
private func setModel(wordHistoryModelList: [WordHistoryModel]){
dataSource.setModels(wordHistoryModelList)
}
private func fetchData(){
guard let wordModel = wordModel else {
return // TODO Notify Error
}
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: {
let list = self.wordService.fetchWordHistoryByWord(wordModel: wordModel)
if list.count > 0{
self.setModel(wordHistoryModelList: list)
}
else{
var wordHistoryModel = WordHistoryModel()
wordHistoryModel.word = wordModel
self.setModel(wordHistoryModelList: [wordHistoryModel])
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
}
// MARK: Controls and Actions
@IBOutlet weak var tableView: UITableView!
}
| mit | 81d9c000bf9f79450db47923b5730d62 | 31.695652 | 184 | 0.662566 | 5.740458 | false | false | false | false |
Legoless/iOS-Course | 2015-1/Lesson5_6/Converter/Converter/ViewController.swift | 2 | 1828 | //
// ViewController.swift
// Converter
//
// Created by Dal Rupnik on 21/10/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let usdRate = 1.14
let jpyRate = 136.12
var currentCurrency = Currency(type: "USD", rate: 1.14)
var converter = Converter.instance
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var usdButton: UIButton!
@IBOutlet weak var jpyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//usdButton.selected = true
}
@IBAction func usdButtonTap(sender: UIButton) {
currentCurrency = Currency(type: "USD", rate: usdRate)
usdButton.selected = true
jpyButton.selected = false
}
@IBAction func jpyButtonTap(sender: UIButton) {
currentCurrency = Currency(type: "JPY", rate: jpyRate)
usdButton.selected = false
jpyButton.selected = true
}
@IBAction func convertButtonTap(sender: UIButton) {
//NSException(name: "Test", reason: "I want to crash", userInfo: nil).raise()
currentCurrency = Currency()
if currentCurrency == Currency() {
print ("Currencies are equal")
return
}
if let value = Double(textField.text!) {
let (converted, _) = value.convert(Currency(), to: currentCurrency)
resultLabel.text = "In \(currentCurrency.type): \(converted)"
resultLabel.textColor = UIColor.blackColor()
}
else {
resultLabel.text = "Error: Enter valid value!"
resultLabel.textColor = UIColor.redColor()
}
}
}
| mit | 5334279336d318a858211f8fe3070da8 | 25.867647 | 85 | 0.59168 | 4.696658 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Source/SwiftEntryKit.swift | 2 | 7435 | //
// SwiftEntryKit.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 4/29/18.
//
import UIKit
/**
A stateless, threadsafe (unless described otherwise) entry point that contains the display and the dismissal logic of entries.
*/
public final class SwiftEntryKit {
/** Describes the a single or multiple entries for possible dismissal states */
public enum EntryDismissalDescriptor {
/** Describes specific entry / entries with name */
case specific(entryName: String)
/** Describes a group of entries with lower or equal display priority */
case prioritizedLowerOrEqualTo(priority: EKAttributes.Precedence.Priority)
/** Describes all the entries that are currently in the queue and pending presentation */
case enqueued
/** Describes all the entries */
case all
/** Describes the currently displayed entry */
case displayed
}
/** The window to rollback to after dismissal */
public enum RollbackWindow {
/** The main window */
case main
/** A given custom window */
case custom(window: UIWindow)
}
/** Completion handler for the dismissal method */
public typealias DismissCompletionHandler = () -> Void
/** Cannot be instantiated, customized, inherited. */
private init() {}
/**
Returns true if **any** entry is currently displayed.
- Not thread safe - should be called from the main queue only in order to receive a reliable result.
- Convenience computed variable. Using it is the same as invoking **isCurrentlyDisplaying() -> Bool** (witohut the name of the entry).
*/
public class var isCurrentlyDisplaying: Bool {
return isCurrentlyDisplaying()
}
/**
Returns true if an entry with a given name is currently displayed.
- Not thread safe - should be called from the main queue only in order to receive a reliable result.
- If invoked with *name* = *nil* or without the parameter value, it will return *true* if **any** entry is currently displayed.
- Returns a *false* value for currently enqueued entries.
- parameter name: The name of the entry. Its default value is *nil*.
*/
public class func isCurrentlyDisplaying(entryNamed name: String? = nil) -> Bool {
return EKWindowProvider.shared.isCurrentlyDisplaying(entryNamed: name)
}
/**
Returns true if **any** entry is currently enqueued and waiting to be displayed.
- Not thread safe - should be called from the main queue only in order to receive a reliable result.
- Convenience computed variable. Using it is the same as invoking **~queueContains() -> Bool** (witohut the name of the entry)
*/
public class var isQueueEmpty: Bool {
return !queueContains()
}
/**
Returns true if an entry with a given name is currently enqueued and waiting to be displayed.
- Not thread safe - should be called from the main queue only in order to receive a reliable result.
- If invoked with *name* = *nil* or without the parameter value, it will return *true* if **any** entry is currently displayed, meaning, the queue is not currently empty.
- parameter name: The name of the entry. Its default value is *nil*.
*/
public class func queueContains(entryNamed name: String? = nil) -> Bool {
return EKWindowProvider.shared.queueContains(entryNamed: name)
}
/**
Displays a given entry view using an attributes struct.
- A thread-safe method - Can be invokes from any thread
- A class method - Should be called on the class
- parameter view: Custom view that is to be displayed
- parameter attributes: Display properties
- parameter presentInsideKeyWindow: Indicates whether the entry window should become the key window.
- parameter rollbackWindow: After the entry has been dismissed, SwiftEntryKit rolls back to the given window. By default it is *.main* which is the app main window
*/
public class func display(entry view: UIView, using attributes: EKAttributes, presentInsideKeyWindow: Bool = false, rollbackWindow: RollbackWindow = .main) {
DispatchQueue.main.async {
EKWindowProvider.shared.display(view: view, using: attributes, presentInsideKeyWindow: presentInsideKeyWindow, rollbackWindow: rollbackWindow)
}
}
/**
Displays a given entry view controller using an attributes struct.
- A thread-safe method - Can be invokes from any thread
- A class method - Should be called on the class
- parameter view: Custom view that is to be displayed
- parameter attributes: Display properties
- parameter presentInsideKeyWindow: Indicates whether the entry window should become the key window.
- parameter rollbackWindow: After the entry has been dismissed, SwiftEntryKit rolls back to the given window. By default it is *.main* - which is the app main window
*/
public class func display(entry viewController: UIViewController, using attributes: EKAttributes, presentInsideKeyWindow: Bool = false, rollbackWindow: RollbackWindow = .main) {
DispatchQueue.main.async {
EKWindowProvider.shared.display(viewController: viewController, using: attributes, presentInsideKeyWindow: presentInsideKeyWindow, rollbackWindow: rollbackWindow)
}
}
/**
ALPHA FEATURE: Transform the previous entry to the current one using the previous attributes struct.
- A thread-safe method - Can be invoked from any thread.
- A class method - Should be called on the class.
- This feature hasn't been fully tested. Use with caution.
- parameter view: Custom view that is to be displayed instead of the currently displayed entry
*/
public class func transform(to view: UIView) {
DispatchQueue.main.async {
EKWindowProvider.shared.transform(to: view)
}
}
/**
Dismisses the currently presented entry and removes the presented window instance after the exit animation is concluded.
- A thread-safe method - Can be invoked from any thread.
- A class method - Should be called on the class.
- parameter descriptor: A descriptor for the entries that are to be dismissed. The default value is *.displayed*.
- parameter completion: A completion handler that is to be called right after the entry is dismissed (After the animation is concluded).
*/
public class func dismiss(_ descriptor: EntryDismissalDescriptor = .displayed, with completion: DismissCompletionHandler? = nil) {
DispatchQueue.main.async {
EKWindowProvider.shared.dismiss(descriptor, with: completion)
}
}
/**
Layout the view hierarchy that is rooted in the window.
- In case you use complex animations, you can call it to refresh the AutoLayout mechanism on the entire view hierarchy.
- A thread-safe method - Can be invoked from any thread.
- A class method - Should be called on the class.
*/
public class func layoutIfNeeded() {
if Thread.isMainThread {
EKWindowProvider.shared.layoutIfNeeded()
} else {
DispatchQueue.main.async {
EKWindowProvider.shared.layoutIfNeeded()
}
}
}
}
| apache-2.0 | 424c1ffbf26320378a1a1fa640f207dd | 45.46875 | 181 | 0.684331 | 4.989933 | false | false | false | false |
qx/PageMenu | Demos/Demo 5/PageMenuDemoSegmentedControl/PageMenuDemoSegmentedControl/TestTableViewController.swift | 1 | 2900 | //
// TestTableViewController.swift
// NFTopMenuController
//
// Created by Niklas Fahl on 12/17/14.
// Copyright (c) 2014 Niklas Fahl. All rights reserved.
//
import UIKit
class TestTableViewController: UITableViewController {
var parentNavigationController : UINavigationController?
var namesArray : [String] = ["David Fletcher", "Charles Gray", "Timothy Jones", "Marie Turner", "Kim White"]
var photoNameArray : [String] = ["man8.jpg", "man2.jpg", "man3.jpg", "woman4.jpg", "woman1.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "FriendTableViewCell", bundle: nil), forCellReuseIdentifier: "FriendTableViewCell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print("\(self.title) page: viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
self.tableView.showsVerticalScrollIndicator = false
super.viewDidAppear(animated)
self.tableView.showsVerticalScrollIndicator = true
print("favorites page: viewDidAppear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return namesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : FriendTableViewCell = tableView.dequeueReusableCellWithIdentifier("FriendTableViewCell") as! FriendTableViewCell
// Configure the cell...
cell.nameLabel.text = namesArray[indexPath.row]
cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row])
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 94.0
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var newVC : UIViewController = UIViewController()
newVC.view.backgroundColor = UIColor.purpleColor()
newVC.title = "Favorites"
parentNavigationController!.pushViewController(newVC, animated: true)
}
} | bsd-3-clause | 74a325ea9b6dd59163d62ef148ba024d | 33.951807 | 133 | 0.686207 | 5.350554 | false | false | false | false |
syd24/DouYuZB | DouYu/DouYu/classes/main/view/PageTitleView.swift | 1 | 5556 | //
// PageTitleView.swift
// DouYu
//
// Created by Kobe24 on 16/10/23.
// Copyright © 2016年 ADMIN. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate:class {
func pageTitleView(titleView: PageTitleView , selectedIndex : Int);
}
private let KNormalColor: (CGFloat , CGFloat ,CGFloat) = (85,85,85);
private let KSelectColor: (CGFloat , CGFloat ,CGFloat) = (255,128,0);
private let KScrollViewLineH : CGFloat = 2;
class PageTitleView: UIView {
weak var delegate: PageTitleViewDelegate?
fileprivate var currentIndex: Int = 0;
fileprivate var titles : [String];
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
fileprivate lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false;
scrollView.bounces = false;
scrollView.scrollsToTop = false;
return scrollView;
}()
fileprivate lazy var scrollViewLine: UIView = {
let scrollViewLine = UIView()
scrollViewLine.backgroundColor = UIColor.orange;
return scrollViewLine;
}()
init(frame: CGRect , titles: [String]) {
self.titles = titles;
super.init(frame: frame);
//
setUpUI();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView{
fileprivate func setUpUI() {
addSubview(scrollView);
scrollView.frame = bounds;
//
setupTitlesLabel();
//
setupScrollViewLine();
}
fileprivate func setupTitlesLabel(){
let labelY : CGFloat = 0;
let labelW = frame.width/4;
let labelH = frame.height - KScrollViewLineH;
for (index, title) in titles.enumerated() {
let label = UILabel()
label.text = title;
label.tag = index;
label.font = UIFont.systemFont(ofSize: 16);
label.textAlignment = .center
let labelX : CGFloat = labelW * CGFloat(index);
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH);
label.textColor = UIColor.init(r: KNormalColor.0, g: KNormalColor.1, b: KNormalColor.2);
scrollView.addSubview(label);
titleLabels.append(label);
//为label 添加手势
label.isUserInteractionEnabled = true;
let tapGes = UITapGestureRecognizer(target: self, action: #selector(labelClick));
label.addGestureRecognizer(tapGes);
}
}
fileprivate func setupScrollViewLine(){
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray;
let bottomLineH: CGFloat = 0.5;
bottomLine.frame = CGRect(x: 0, y: frame.height - bottomLineH, width: KScreenH, height: bottomLineH);
scrollView.addSubview(bottomLine);
guard let firstLabel = titleLabels.first else {
return;
}
firstLabel.textColor = UIColor.init(r: KSelectColor.0, g: KSelectColor.1, b: KSelectColor.2);
scrollViewLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - KScrollViewLineH, width: firstLabel.frame.width, height: KScrollViewLineH);
scrollView.addSubview(scrollViewLine);
}
}
extension PageTitleView{
@objc fileprivate func labelClick(tapGes: UITapGestureRecognizer){
guard let currentLabel = tapGes.view as? UILabel else {return;}
//
if currentLabel.tag == currentIndex { return;}
let oldLabel = titleLabels[currentIndex];
currentLabel.textColor = UIColor.init(r: KSelectColor.0, g: KSelectColor.1, b: KSelectColor.2);
oldLabel.textColor = UIColor.init(r: KNormalColor.0, g: KNormalColor.1, b: KNormalColor.2);
currentIndex = currentLabel.tag;
let scrollViewLineX = CGFloat(currentIndex) * oldLabel.frame.width;
UIView.animate(withDuration: 0.15) {
self.scrollViewLine.frame.origin.x = scrollViewLineX;
}
delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex);
}
}
extension PageTitleView{
func pagetitleViewWith(progress: CGFloat , sourceIndex: Int ,targetIndex: Int ) {
//
let sourceLabel = titleLabels[sourceIndex];
let targetLabel = titleLabels[targetIndex];
let moveTotal = targetLabel.frame.origin.x - sourceLabel.frame.origin.x;
let moveX = moveTotal * progress;
scrollViewLine.frame.origin.x = sourceLabel.frame.origin.x + moveX;
//
let colorDelta = (KSelectColor.0 - KNormalColor.0,KSelectColor.1 - KNormalColor.1, KSelectColor.2 - KNormalColor.2);
sourceLabel.textColor = UIColor(r: KSelectColor.0 - colorDelta.0 * progress, g: KSelectColor.1 - colorDelta.1 * progress, b: KSelectColor.2 - colorDelta.2 * progress);
targetLabel.textColor = UIColor(r: KNormalColor.0 + colorDelta.0 * progress, g: KNormalColor.1 + colorDelta.1 * progress, b: KNormalColor.2 + colorDelta.2 * progress);
//
currentIndex = targetIndex;
}
}
| mit | 5e9ce17d125e27af0cf79b6b25713d93 | 27.869792 | 175 | 0.598773 | 4.824195 | false | false | false | false |
luismatute/On-The-Map | On The Map/WhereAreYouVC.swift | 1 | 4668 | //
// WhereAreYouVC.swift
// On The Map
//
// Created by Luis Matute on 6/1/15.
// Copyright (c) 2015 Luis Matute. All rights reserved.
//
import Foundation
import UIKit
import MapKit
class WhereAreYouVC: UIViewController {
// MARK: - Outlets
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
// MARK: - Properties
var region = MKCoordinateRegion()
var dropPin = MKPointAnnotation()
var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var tapRecognizer: UITapGestureRecognizer? = nil
// MARK: - View's Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.loadingView.alpha = 0.0
self.tapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
self.tapRecognizer?.numberOfTapsRequired = 1
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "postSegue" {
if var postVC = segue.destinationViewController as? PostVC {
postVC.region = self.region
postVC.dropPin = self.dropPin
postVC.locationString = locationTextField.text
}
}
}
// MARK: - Actions
@IBAction func cancelAction(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func findOnMap(sender: AnyObject) {
if locationTextField.text == "" {
self.showError(title: "Error", msg: "Please make sure to fill in all fields.")
return
}
let geoCoder = CLGeocoder()
self.showLoading(true)
geoCoder.geocodeAddressString(locationTextField.text){ info, error in
if let e = error {
self.showError(title: "", msg: error.localizedDescription)
} else {
if let places = info as? [CLPlacemark]{
let coordinate = places[0].location.coordinate
let span = MKCoordinateSpan(latitudeDelta: 3, longitudeDelta: 3)
self.region = MKCoordinateRegion(center: coordinate, span: span)
self.dropPin.coordinate = coordinate
self.performSegueWithIdentifier("postSegue", sender: nil)
}
}
self.showLoading(false)
}
}
// MARK: - Methods
func showError(title: String = "", msg: String = "") {
var alert = UIAlertView()
alert.title = (title == "") ? "Bad Location" : title
alert.message = (msg == "") ? "Could not find location specified." : msg
alert.addButtonWithTitle("OK")
alert.show()
}
func showLoading(show: Bool) {
if show {
UIView.animateWithDuration(0.4, animations: {
self.loadingView.alpha = 1.0
self.spinner.startAnimating()
})
} else {
UIView.animateWithDuration(0.4, animations: {
self.loadingView.alpha = 0.0
self.spinner.stopAnimating()
})
}
}
func keyboardWillShow(notification:NSNotification){
self.view.frame.origin = CGPointMake(0.0, -getKeyboardHeight(notification))
}
func keyboardWillHide(notification:NSNotification){
self.view.frame.origin = CGPointMake(0.0, 0.0)
}
func getKeyboardHeight(notification:NSNotification)->CGFloat{
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
func subscribeToKeyboardNotifications(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications(){
NSNotificationCenter.defaultCenter().removeObserver(self, name:UIKeyboardWillShowNotification, object:nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name:UIKeyboardWillHideNotification, object:nil)
}
} | mit | c27a73e8472473a55704783c778b6a51 | 36.95935 | 144 | 0.637532 | 5.274576 | false | false | false | false |
kstaring/swift | test/SILGen/super_init_refcounting.swift | 1 | 3634 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
class Foo {
init() {}
init(_ x: Foo) {}
init(_ x: Int) {}
}
class Bar: Foo {
// CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Barc
// CHECK: [[SELF_VAR:%.*]] = alloc_box $@box Bar
// CHECK: [[PB:%.*]] = project_box [[SELF_VAR]]
// CHECK: [[SELF_MUI:%.*]] = mark_uninitialized [derivedself] [[PB]]
// CHECK: [[ORIG_SELF:%.*]] = load_borrow [[SELF_MUI]]
// CHECK-NOT: copy_value [[ORIG_SELF]]
// CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]]
// CHECK-NOT: copy_value [[ORIG_SELF_UP]]
// CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo
// CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]])
// CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK: store [[NEW_SELF_DOWN]] to [init] [[SELF_MUI]]
override init() {
super.init()
}
}
extension Foo {
// CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Fooc
// CHECK: [[SELF_VAR:%.*]] = alloc_box $@box Foo
// CHECK: [[PB:%.*]] = project_box [[SELF_VAR]]
// CHECK: [[SELF_MUI:%.*]] = mark_uninitialized [delegatingself] [[PB]]
// CHECK: [[ORIG_SELF:%.*]] = load_borrow [[SELF_MUI]]
// CHECK-NOT: copy_value [[ORIG_SELF]]
// CHECK: [[SUPER_INIT:%.*]] = class_method
// CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]])
// CHECK: store [[NEW_SELF]] to [init] [[SELF_MUI]]
convenience init(x: Int) {
self.init()
}
}
class Zim: Foo {
var foo = Foo()
// CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Zimc
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo
}
class Zang: Foo {
var foo: Foo
override init() {
foo = Foo()
super.init()
}
// CHECK-LABEL: sil hidden @_TFC22super_init_refcounting4Zangc
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo
}
class Bad: Foo {
// Invalid code, but it's not diagnosed till DI. We at least shouldn't
// crash on it.
override init() {
super.init(self)
}
}
class Good: Foo {
let x: Int
// CHECK-LABEL: sil hidden @_TFC22super_init_refcounting4Goodc
// CHECK: [[SELF_BOX:%.*]] = alloc_box $@box Good
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELF:%.*]] = mark_uninitialized [derivedself] [[PB]]
// CHECK: store %0 to [init] [[SELF]]
// CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]]
// CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x
// CHECK: assign {{.*}} to [[X_ADDR]] : $*Int
// CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]] : $*Good
// CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo
// CHECK: [[SUPER_INIT:%.*]] = function_ref @_TFC22super_init_refcounting3FoocfSiS0_ : $@convention(method) (Int, @owned Foo) -> @owned Foo
// CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]]
// CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] : $*Int
// CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]])
override init() {
x = 10
super.init(x)
}
}
| apache-2.0 | 33973f9f680e0b0c32317201d54e11b2 | 38.075269 | 149 | 0.538525 | 3.267986 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WKRKit/WKRKitTests/WKRKitPageFetcherTests.swift | 2 | 6703 | //
// WKRKitPageFetcherTests.swift
// WKRKitTests
//
// Created by Andrew Finke on 9/3/17.
// Copyright © 2017 Andrew Finke. All rights reserved.
//
import XCTest
@testable import WKRKit
class WKRKitPageFetcherTests: WKRKitTestCase {
func testConnectionTester() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testConnectionTester")
WKRConnectionTester.start { connected in
XCTAssert(connected)
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testError() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testError")
WKRPageFetcher.fetch(path: "", useCache: false) { page, _ in
XCTAssertNil(page)
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testRandom() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testRandom")
WKRPageFetcher.fetchRandom { page in
XCTAssertNotNil(page)
guard let unwrappedPage = page else {
XCTFail("Page nil")
return
}
XCTAssertNotNil(unwrappedPage.title)
guard let title = unwrappedPage.title else {
XCTFail("Title nil")
return
}
XCTAssert(!title.isEmpty)
XCTAssert(unwrappedPage.url.absoluteString.contains("https://en.m.wikipedia.org/wiki/"))
XCTAssertFalse(unwrappedPage.url.absoluteString.contains("Special:Random"))
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testPage() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testPage")
WKRPageFetcher.fetch(path: "/Apple_Inc.", useCache: false) { page, _ in
XCTAssertNotNil(page)
guard let unwrappedPage = page else {
XCTFail("Page nil")
return
}
XCTAssertNotNil(unwrappedPage.title)
guard let title = unwrappedPage.title else {
XCTFail("Title nil")
return
}
XCTAssertEqual(title, "Apple Inc.")
XCTAssertEqual(unwrappedPage.url.absoluteString, "https://en.m.wikipedia.org/wiki/Apple_Inc.")
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testURL() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testURL")
WKRPageFetcher.fetch(url: URL(string: "https://en.m.wikipedia.org/wiki/Apple_Inc.")!, useCache: false) { page, _ in
XCTAssertNotNil(page)
guard let unwrappedPage = page else {
XCTFail("Page nil")
return
}
XCTAssertNotNil(unwrappedPage.title)
guard let title = unwrappedPage.title else {
XCTFail("Title nil")
return
}
XCTAssertEqual(title, "Apple Inc.")
XCTAssertEqual(unwrappedPage.url.absoluteString, "https://en.m.wikipedia.org/wiki/Apple_Inc.")
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testSource() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testSource")
WKRPageFetcher.fetchSource(url: URL(string: "https://en.m.wikipedia.org/wiki/Apple_Inc.")!, useCache: false, progressHandler: { _ in }) { source, _ in
XCTAssertNotNil(source)
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testLinkedPageFetcher() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let fetcher = WKRLinkedPagesFetcher()
let url = URL(string: "https://en.m.wikipedia.org/wiki/Positive_feedback")!
fetcher.start(for: WKRPage(title: nil, url: url))
let testExpectation = expectation(description: "testLinkedPageFetcher")
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
XCTAssertGreaterThan(fetcher.foundURLs.count, 400)
XCTAssertLessThan(fetcher.foundURLs.count, 800)
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testRedirect() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testRedirect")
WKRPageFetcher.fetch(path: "/USA", useCache: false) { page, isRedirect in
XCTAssertNotNil(page)
XCTAssertTrue(isRedirect)
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
func testNotRedirect() {
self.measureMetrics([.wallClockTime], automaticallyStartMeasuring: true) {
let testExpectation = expectation(description: "testRedirect")
WKRPageFetcher.fetch(path: "/United_States", useCache: false) { page, isRedirect in
XCTAssertNotNil(page)
XCTAssertFalse(isRedirect)
testExpectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: { _ in
self.stopMeasuring()
})
}
}
}
| mit | 28387ca8c9a8a11861dace8739948ea8 | 37.728324 | 163 | 0.557164 | 5.385852 | false | true | false | false |
uber/RIBs | ios/tutorials/tutorial4-completed/TicTacToe/Root/RootInteractor.swift | 1 | 2847 | //
// Copyright (c) 2017. Uber Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import RIBs
import RxSwift
protocol RootRouting: ViewableRouting {
func routeToLoggedIn(withPlayer1Name player1Name: String, player2Name: String) -> LoggedInActionableItem
}
protocol RootPresentable: Presentable {
var listener: RootPresentableListener? { get set }
// TODO: Declare methods the interactor can invoke the presenter to present data.
}
protocol RootListener: AnyObject {
// TODO: Declare methods the interactor can invoke to communicate with other RIBs.
}
final class RootInteractor: PresentableInteractor<RootPresentable>, RootInteractable, RootPresentableListener, RootActionableItem, UrlHandler {
weak var router: RootRouting?
weak var listener: RootListener?
// TODO: Add additional dependencies to constructor. Do not perform any logic
// in constructor.
override init(presenter: RootPresentable) {
super.init(presenter: presenter)
presenter.listener = self
}
override func didBecomeActive() {
super.didBecomeActive()
// TODO: Implement business logic here.
}
override func willResignActive() {
super.willResignActive()
// TODO: Pause any business logic.
}
// MARK: - LoggedOutListener
func didLogin(withPlayer1Name player1Name: String, player2Name: String) {
let loggedInActionableItem = router?.routeToLoggedIn(withPlayer1Name: player1Name, player2Name: player2Name)
if let loggedInActionableItem = loggedInActionableItem {
loggedInActionableItemSubject.onNext(loggedInActionableItem)
}
}
// MARK: - UrlHandler
func handle(_ url: URL) {
let launchGameWorkflow = LaunchGameWorkflow(url: url)
launchGameWorkflow
.subscribe(self)
.disposeOnDeactivate(interactor: self)
}
// MARK: - RootActionableItem
func waitForLogin() -> Observable<(LoggedInActionableItem, ())> {
return loggedInActionableItemSubject
.map { (loggedInItem: LoggedInActionableItem) -> (LoggedInActionableItem, ()) in
(loggedInItem, ())
}
}
// MARK: - Private
private let loggedInActionableItemSubject = ReplaySubject<LoggedInActionableItem>.create(bufferSize: 1)
}
| apache-2.0 | 30664dcaebd40d1feee1385d0c535520 | 32.104651 | 143 | 0.708114 | 4.621753 | false | false | false | false |
irace/Objchecklist | Objchecklist/MasterViewController.swift | 1 | 2780 | import UIKit
class MasterViewController: UITableViewController {
var issues: [Issue] = []
// MARK: - UIViewController
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "objc.io"
issues = DataService.latestIssues()
tableView.registerClass(IssueCell.self, forCellReuseIdentifier: IssueCell.reuseIdentifier)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Would be cool to drive this off of bindings instead
updateVisibleCellReadStates()
}
// MARK: - Private
func updateVisibleCellReadStates() {
if let visibleIndexPaths = tableView.indexPathsForVisibleRows() as [NSIndexPath]? {
for indexPath in visibleIndexPaths {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as IssueCell? {
updateCellForReadState(cell, indexPath: indexPath)
}
}
}
}
func updateCellForReadState(cell: IssueCell, indexPath: NSIndexPath) {
let issue = issues[indexPath.row]
cell.read = issue.read
cell.detailTextLabel?.text = "\(issue.readCount)/\(issue.articles.count)"
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return issues.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let issue = issues[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(IssueCell.reuseIdentifier, forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "\(issue.number): \(issue.title)"
cell.accessoryType = .DisclosureIndicator
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
updateCellForReadState(cell as IssueCell, indexPath: indexPath)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.showDetailViewController(IssueViewController(issue: issues[indexPath.row]), sender: nil)
}
}
| mit | d7c096fb74d96ba63f18b16a7cf7738d | 32.902439 | 134 | 0.653597 | 5.708419 | false | false | false | false |
matsprea/omim | iphone/Maps/UI/Search/Filters/FilterCheckCell.swift | 1 | 1394 | @objc(MWMFilterCheckCellDelegate)
protocol FilterCheckCellDelegate {
func checkCellButtonTap(_ button: UIButton)
}
@objc(MWMFilterCheckCell)
final class FilterCheckCell: MWMTableViewCell {
@IBOutlet private var checkButtons: [UIButton]!
@IBOutlet private var checkLabels: [UILabel]!
@IBOutlet weak var checkInLabel: UILabel! {
didSet {
checkInLabel.text = L("booking_filters_check_in").uppercased()
}
}
@IBOutlet weak var checkOutLabel: UILabel! {
didSet {
checkOutLabel.text = L("booking_filters_check_out").uppercased()
}
}
@IBOutlet weak var checkIn: UIButton!
@IBOutlet weak var checkOut: UIButton!
@IBOutlet private weak var offlineLabel: UILabel! {
didSet {
offlineLabel.text = L("booking_filters_offline")
}
}
@IBOutlet private weak var offlineLabelBottomOffset: NSLayoutConstraint!
@objc var isOffline = false {
didSet {
offlineLabel.isHidden = !isOffline
offlineLabelBottomOffset.priority = isOffline ? .defaultHigh : .defaultLow
checkLabels.forEach { $0.isEnabled = !isOffline }
checkButtons.forEach { $0.isEnabled = !isOffline }
}
}
@objc weak var delegate: FilterCheckCellDelegate?
@IBAction private func tap(sender: UIButton!) {
delegate?.checkCellButtonTap(sender)
}
override func awakeFromNib() {
super.awakeFromNib()
isSeparatorHidden = true
}
}
| apache-2.0 | b63fd34a9242b9e86d7764cf1fed60e0 | 26.333333 | 80 | 0.708752 | 4.397476 | false | false | false | false |
dtrauger/Charts | Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift | 1 | 2148 | //
// ChartDataEntryBase.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
open class ChartDataEntryBase: NSObject
{
/// the y value
@objc open var y = Double(0.0)
/// optional spot for additional data this Entry represents
@objc open var data: AnyObject?
public override required init()
{
super.init()
}
/// An Entry represents one single entry in the chart.
/// - parameter y: the y value (the actual value of the entry)
public init(y: Double)
{
super.init()
self.y = y
}
/// - parameter y: the y value (the actual value of the entry)
/// - parameter data: Space for additional data this Entry represents.
public init(y: Double, data: AnyObject?)
{
super.init()
self.y = y
self.data = data
}
// MARK: NSObject
open override func isEqual(_ object: Any?) -> Bool
{
if object == nil
{
return false
}
if !(object! as AnyObject).isKind(of: type(of: self))
{
return false
}
if (object! as AnyObject).data !== data && !((object! as AnyObject).data??.isEqual(self.data))!
{
return false
}
if fabs((object! as AnyObject).y - y) > Double.ulpOfOne
{
return false
}
return true
}
// MARK: NSObject
open override var description: String
{
return "ChartDataEntryBase, y \(y)"
}
}
public func ==(lhs: ChartDataEntryBase, rhs: ChartDataEntryBase) -> Bool
{
if lhs === rhs
{
return true
}
if !lhs.isKind(of: type(of: rhs))
{
return false
}
if lhs.data !== rhs.data && !lhs.data!.isEqual(rhs.data)
{
return false
}
if fabs(lhs.y - rhs.y) > Double.ulpOfOne
{
return false
}
return true
}
| apache-2.0 | f36b85c5a7cebe3a0a58c597b996e92e | 19.457143 | 103 | 0.530726 | 4.313253 | false | false | false | false |
firebase/quickstart-ios | database/DatabaseExampleSwiftUI/DatabaseExample/Shared/Models/Post.swift | 1 | 2724 | //
// Copyright (c) 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import FirebaseDatabase
struct Post: Identifiable {
var id: String
var uid: String
var author: String
var title: String
var body: String
var starCount: Int
var starDictionary: [String: Bool]
init(id: String, uid: String, author: String, title: String, body: String) {
self.id = id
self.uid = uid
self.author = author
self.title = title
self.body = body
starCount = 0
starDictionary = [:]
}
init?(id: String, dict: [String: Any]) {
guard let uid = dict["uid"] as? String else { return nil }
guard let author = dict["author"] as? String else { return nil }
guard let title = dict["title"] as? String else { return nil }
guard let body = dict["body"] as? String else { return nil }
let starCount = dict["starCount"] as? Int ?? 0
self.id = id
self.uid = uid
self.author = author
self.title = title
self.body = body
self.starCount = starCount
starDictionary = [:]
}
init() {
self.init(id: "", uid: "", author: "", title: "", body: "")
}
mutating func didTapStarButton(isStarred: Bool) {
let ref: DatabaseReference = {
Database.database().reference()
}()
if isStarred {
// add current user to the post.starDictionary
starDictionary[uid] = true
ref.child("/posts/\(id)/starDictionary").setValue(starDictionary)
ref.child("/user-posts/\(uid)/\(id)/starDictionary").setValue(starDictionary)
// increment starCount on current post
ref.child("/posts/\(id)/starCount").setValue(starCount + 1)
ref.child("/user-posts/\(uid)/\(id)/starCount").setValue(starCount + 1)
} else {
// remove current user from the post.starDictionary
starDictionary.removeValue(forKey: uid)
ref.child("/posts/\(id)/starDictionary").setValue(starDictionary)
ref.child("/user-posts/\(uid)/\(id)/starDictionary").setValue(starDictionary)
// decrement starCount on current post
ref.child("/posts/\(id)/starCount").setValue(starCount - 1)
ref.child("/user-posts/\(uid)/\(id)/starCount").setValue(starCount - 1)
}
}
}
| apache-2.0 | 1202b0ad473776ab3a25c28c2637cfa8 | 32.62963 | 83 | 0.659325 | 3.880342 | false | false | false | false |
arsonik/AKTrakt | Source/shared/Requests/People.swift | 1 | 3979 | //
// People.swift
// Pods
//
// Created by Florian Morello on 26/05/16.
//
//
import Foundation
import Alamofire
/// Get all people related an object
public class TraktRequestMediaPeople<T: TraktObject where T: protocol<Credits>>: TraktRequest {
public init(type: T.Type, id: AnyObject, extended: TraktRequestExtendedOptions? = nil) {
super.init(path: "/\(type.listName)/\(id)/people", params: extended?.value())
}
public func request(trakt: Trakt, completion: ([TraktCharacter]?, [TraktCrewPosition: [TraktCrew]]?, NSError?) -> Void) -> Request? {
return trakt.request(self) { response in
guard let result = response.result.value as? JSONHash else {
return completion(nil, nil, response.result.error)
}
let casting = (result["cast"] as? [JSONHash])?.flatMap {
TraktCharacter(data: $0)
}
var crew: [TraktCrewPosition: [TraktCrew]]? = nil
if let crewData = (result["crew"] as? [String: [JSONHash]]) {
crew = [:]
crewData.forEach {
guard let position = TraktCrewPosition(rawValue: $0) else {
return
}
crew![position] = $1.flatMap {
TraktCrew(data: $0)
}
}
}
completion(casting, crew, response.result.error)
}
}
}
/// Get a single person
public class TraktRequestPeople: TraktRequest {
public init(id: AnyObject, extended: TraktRequestExtendedOptions = .Min) {
super.init(path: "/people/\(id)", params: extended.value())
}
public func request(trakt: Trakt, completion: (TraktPerson?, NSError?) -> Void) -> Request? {
return trakt.request(self) { response in
completion(TraktPerson(data: response.result.value as? JSONHash), response.result.error)
}
}
}
/// Get a person credits in a media type
public class TraktRequestPeopleCredits<T: TraktObject where T: protocol<Credits>>: TraktRequest {
let type: T.Type
public init(type: T.Type, id: AnyObject, extended: TraktRequestExtendedOptions = .Min) {
self.type = type
super.init(path: "/people/\(id)/\(type.listName)", params: extended.value())
}
public typealias CreditsCompletionObject = (cast: [(character: String, media: T)]?, crew: [TraktCrewPosition: [(job: String, media: T)]]?)
public func request(trakt: Trakt, completion: (CreditsCompletionObject?, NSError?) -> Void) -> Request? {
return trakt.request(self) { response in
guard let result = response.result.value as? JSONHash else {
return completion(nil, response.result.error)
}
var tuple: CreditsCompletionObject = (cast: [], crew: [:])
// Crew
(result["crew"] as? [String: [JSONHash]])?.forEach { key, values in
guard let position = TraktCrewPosition(rawValue: key) else {
return
}
tuple.crew![position] = values.flatMap {
let media: T? = self.type.init(data: $0[self.type.objectName] as? JSONHash)
guard let job = $0["job"] as? String where media != nil else {
print("cannot find job or media")
return nil
}
return (job: job, media: media!)
}
}
// Cast
tuple.cast = (result["cast"] as? [JSONHash])?.flatMap {
let media: T? = self.type.init(data: $0[self.type.objectName] as? JSONHash)
guard let character = $0["character"] as? String where media != nil else {
return nil
}
return (character: character, media: media!)
}
completion(tuple, response.result.error)
}
}
}
| mit | 07580643f712d75087afbc2adf352f86 | 37.631068 | 142 | 0.55617 | 4.382159 | false | false | false | false |
t-ae/ImageTrimmer | ImageTrimmer/Components/ScalableImageView.swift | 1 | 1000 |
import Foundation
import Cocoa
class ScalableImageView: NSImageView {
override func awakeFromNib() {
super.awakeFromNib()
wantsLayer = true
let zoomRecog = NSMagnificationGestureRecognizer(target: self, action: #selector(onZoom))
addGestureRecognizer(zoomRecog)
}
@objc func onZoom(_ recognizer: NSMagnificationGestureRecognizer) {
let magnification = recognizer.magnification
let scaleFactor = (magnification >= 0.0) ? (1.0 + magnification) : 1.0 / (1.0 - magnification)
let location = CGPoint(x: self.bounds.width/2 ,y: self.bounds.height/2)
let move = CGPoint(x: location.x * (scaleFactor-1), y: location.y * (scaleFactor-1))
self.layer!.sublayerTransform *= CATransform3DMakeScale(scaleFactor, scaleFactor, 1)
self.layer!.sublayerTransform *= CATransform3DMakeTranslation(-move.x, -move.y, 0)
recognizer.magnification = 0
}
}
| mit | 7ae74640d4c73895f5f151ddd059f161 | 33.482759 | 102 | 0.645 | 4.444444 | false | false | false | false |
yosan/SwifTumblr | Pod/Classes/PostLink.swift | 1 | 2117 | //
// PostLink.swift
// Pods
//
// Created by Takahashi Yosuke on 2015/10/19.
//
//
import Foundation
import AEXML
public struct PostLink: PostProtocol {
public let id: String?
public let url: URL?
public let urlWithSlug: URL?
public let type: String?
public let date: Date?
public let format: String?
public let reblogKey: String?
public let slug: String?
public let linkText: String?
public let linkURL: URL?
public let linkDescription: String?
public let tags: [String]?
public init?(postXml: AEXMLElement?) {
guard let postXml = postXml else { return nil }
id = postXml.attributes["id"]
url = postXml.attributes["url"].flatMap { URL(string: $0) }
urlWithSlug = postXml.attributes["url-with-slug"].flatMap { URL(string: $0) }
type = postXml.attributes["type"]
date = postXml.attributes["date-gmt"].flatMap { Date.parse($0) }
format = postXml.attributes["format"]
reblogKey = postXml.attributes["reblog-key"]
slug = postXml.attributes["slug"]
linkText = postXml["link-text"].string
linkURL = URL(string: postXml["link-url"].string)
linkDescription = postXml["link-description"].string
tags = postXml.sameElementStrings("tag")
}
}
extension PostLink: CustomDebugStringConvertible {
public var debugDescription: String {
var properties = ["id:\(String(describing: id))", "url:\(String(describing: url))", "urlWithSlug:\(String(describing: urlWithSlug))", "type:\(String(describing: type))", "date:\(String(describing: date))", "format:\(String(describing: format))", "reblogKey:\(String(describing: reblogKey))", "slug:\(String(describing: slug))", "link-text:\(String(describing: linkText))", "link-url:\(String(describing: linkURL))", "link-description:\(String(describing: linkDescription))"]
if let tags = tags {
properties = tags.reduce([String](), { (pros, tag) -> [String] in pros + ["tag:\(tag)"] })
}
return properties.joined(separator: "\n")
}
}
| mit | c649c8a53e918f1776ba4f2b840bf84f | 36.140351 | 482 | 0.634388 | 4.047801 | false | false | false | false |
apple/swift-system | Sources/System/SystemString.swift | 1 | 9237 | /*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// A platform-native character representation, currently used for file paths
internal struct SystemChar: RawRepresentable, Comparable, Hashable, Codable {
internal typealias RawValue = CInterop.PlatformChar
internal var rawValue: RawValue
internal init(rawValue: RawValue) { self.rawValue = rawValue }
internal init(_ rawValue: RawValue) { self.init(rawValue: rawValue) }
static func < (lhs: SystemChar, rhs: SystemChar) -> Bool {
lhs.rawValue < rhs.rawValue
}
}
extension SystemChar {
internal init(ascii: Unicode.Scalar) {
self.init(rawValue: numericCast(UInt8(ascii: ascii)))
}
internal init(codeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit) {
self.init(rawValue: codeUnit._platformChar)
}
internal static var null: SystemChar { SystemChar(0x0) }
internal static var slash: SystemChar { SystemChar(ascii: "/") }
internal static var backslash: SystemChar { SystemChar(ascii: #"\"#) }
internal static var dot: SystemChar { SystemChar(ascii: ".") }
internal static var colon: SystemChar { SystemChar(ascii: ":") }
internal static var question: SystemChar { SystemChar(ascii: "?") }
internal var codeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit {
rawValue._platformCodeUnit
}
internal var asciiScalar: Unicode.Scalar? {
guard isASCII else { return nil }
return Unicode.Scalar(UInt8(truncatingIfNeeded: rawValue))
}
internal var isASCII: Bool {
(0...0x7F).contains(rawValue)
}
internal var isLetter: Bool {
guard isASCII else { return false }
let asciiRaw: UInt8 = numericCast(rawValue)
return (UInt8(ascii: "a") ... UInt8(ascii: "z")).contains(asciiRaw) ||
(UInt8(ascii: "A") ... UInt8(ascii: "Z")).contains(asciiRaw)
}
}
// A platform-native string representation, currently for file paths
//
// Always null-terminated.
internal struct SystemString {
internal typealias Storage = [SystemChar]
internal var nullTerminatedStorage: Storage
}
extension SystemString {
internal init() {
self.nullTerminatedStorage = [.null]
_invariantCheck()
}
internal var length: Int {
let len = nullTerminatedStorage.count - 1
assert(len == self.count)
return len
}
// Common funnel point. Ensure all non-empty inits go here.
internal init(nullTerminated storage: Storage) {
self.nullTerminatedStorage = storage
_invariantCheck()
}
// Ensures that result is null-terminated
internal init<C: Collection>(_ chars: C) where C.Element == SystemChar {
var rawChars = Storage(chars)
if rawChars.last != .null {
rawChars.append(.null)
}
self.init(nullTerminated: rawChars)
}
}
extension SystemString {
fileprivate func _invariantCheck() {
#if DEBUG
precondition(nullTerminatedStorage.last! == .null)
precondition(nullTerminatedStorage.firstIndex(of: .null) == length)
#endif // DEBUG
}
}
extension SystemString: RandomAccessCollection, MutableCollection {
internal typealias Element = SystemChar
internal typealias Index = Storage.Index
internal typealias Indices = Range<Index>
internal var startIndex: Index {
nullTerminatedStorage.startIndex
}
internal var endIndex: Index {
nullTerminatedStorage.index(before: nullTerminatedStorage.endIndex)
}
internal subscript(position: Index) -> SystemChar {
_read {
precondition(position >= startIndex && position <= endIndex)
yield nullTerminatedStorage[position]
}
set(newValue) {
precondition(position >= startIndex && position <= endIndex)
nullTerminatedStorage[position] = newValue
_invariantCheck()
}
}
}
extension SystemString: RangeReplaceableCollection {
internal mutating func replaceSubrange<C: Collection>(
_ subrange: Range<Index>, with newElements: C
) where C.Element == SystemChar {
defer { _invariantCheck() }
nullTerminatedStorage.replaceSubrange(subrange, with: newElements)
}
internal mutating func reserveCapacity(_ n: Int) {
defer { _invariantCheck() }
nullTerminatedStorage.reserveCapacity(1 + n)
}
// TODO: Below include null terminator, is this desired?
internal func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<SystemChar>) throws -> R
) rethrows -> R? {
try nullTerminatedStorage.withContiguousStorageIfAvailable(body)
}
internal mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<SystemChar>) throws -> R
) rethrows -> R? {
defer { _invariantCheck() }
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body)
}
}
extension SystemString: Hashable, Codable {}
extension SystemString {
// TODO: Below include null terminator, is this desired?
internal func withSystemChars<T>(
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
) rethrows -> T {
try withContiguousStorageIfAvailable(f)!
}
internal func withCodeUnits<T>(
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
) rethrows -> T {
try withSystemChars { chars in
let length = chars.count * MemoryLayout<SystemChar>.stride
let count = length / MemoryLayout<CInterop.PlatformUnicodeEncoding.CodeUnit>.stride
return try chars.baseAddress!.withMemoryRebound(
to: CInterop.PlatformUnicodeEncoding.CodeUnit.self,
capacity: count
) { pointer in
try f(UnsafeBufferPointer(start: pointer, count: count))
}
}
}
}
extension Slice where Base == SystemString {
internal func withCodeUnits<T>(
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
) rethrows -> T {
try base.withCodeUnits {
try f(UnsafeBufferPointer(rebasing: $0[indices]))
}
}
internal var string: String {
withCodeUnits { String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) }
}
internal func withPlatformString<T>(
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
) rethrows -> T {
// FIXME: avoid allocation if we're at the end
return try SystemString(self).withPlatformString(f)
}
}
extension String {
internal init(decoding str: SystemString) {
// TODO: Can avoid extra strlen
self = str.withPlatformString {
String(platformString: $0)
}
}
internal init?(validating str: SystemString) {
// TODO: Can avoid extra strlen
guard let str = str.withPlatformString(String.init(validatingPlatformString:))
else { return nil }
self = str
}
}
extension SystemString: ExpressibleByStringLiteral {
internal init(stringLiteral: String) {
self.init(stringLiteral)
}
internal init(_ string: String) {
// TODO: can avoid extra strlen
self = string.withPlatformString {
SystemString(platformString: $0)
}
}
}
extension SystemString: CustomStringConvertible, CustomDebugStringConvertible {
internal var string: String { String(decoding: self) }
internal var description: String { string }
internal var debugDescription: String { description.debugDescription }
}
extension SystemString {
/// Creates a system string by copying bytes from a null-terminated platform string.
///
/// - Parameter platformString: A pointer to a null-terminated platform string.
internal init(platformString: UnsafePointer<CInterop.PlatformChar>) {
let count = 1 + system_platform_strlen(platformString)
// TODO: Is this the right way?
let chars: Array<SystemChar> = platformString.withMemoryRebound(
to: SystemChar.self, capacity: count
) {
let bufPtr = UnsafeBufferPointer(start: $0, count: count)
return Array(bufPtr)
}
self.init(nullTerminated: chars)
}
/// Calls the given closure with a pointer to the contents of the sytem string,
/// represented as a null-terminated platform string.
///
/// - Parameter body: A closure with a pointer parameter
/// that points to a null-terminated platform string.
/// If `body` has a return value,
/// that value is also used as the return value for this method.
/// - Returns: The return value, if any, of the `body` closure parameter.
///
/// The pointer passed as an argument to `body` is valid
/// only during the execution of this method.
/// Don't try to store the pointer for later use.
internal func withPlatformString<T>(
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
) rethrows -> T {
try withSystemChars { chars in
let length = chars.count * MemoryLayout<SystemChar>.stride
return try chars.baseAddress!.withMemoryRebound(
to: CInterop.PlatformChar.self,
capacity: length / MemoryLayout<CInterop.PlatformChar>.stride
) { pointer in
assert(pointer[self.count] == 0)
return try f(pointer)
}
}
}
}
// TODO: SystemString should use a COW-interchangable storage form rather
// than array, so you could "borrow" the storage from a non-bridged String
// or Data or whatever
| apache-2.0 | b1fbf864ad909cc11bdb8f0afa29be2b | 30.525597 | 89 | 0.708996 | 4.383958 | false | false | false | false |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModel/Private/Services/Events/ConcreteEventsService.swift | 1 | 9968 | import EventBus
import Foundation
class ConcreteEventsService: ClockDelegate, EventsService {
// MARK: Nested Types
struct ChangedEvent {}
struct EventUnfavouritedEvent {
var identifier: EventIdentifier
}
private class FavouriteEventHandler: EventConsumer {
private let service: ConcreteEventsService
init(service: ConcreteEventsService) {
self.service = service
}
func consume(event: DomainEvent.FavouriteEvent) {
let identifier = event.identifier
service.persistFavouritedEvent(identifier: identifier)
service.favouriteEventIdentifiers.append(identifier)
}
}
private class UnfavouriteEventHandler: EventConsumer {
private let service: ConcreteEventsService
init(service: ConcreteEventsService) {
self.service = service
}
func consume(event: DomainEvent.UnfavouriteEvent) {
let identifier = event.identifier
service.dataStore.performTransaction { (transaction) in
transaction.deleteFavouriteEventIdentifier(identifier)
}
service.favouriteEventIdentifiers.firstIndex(of: identifier).let({ service.favouriteEventIdentifiers.remove(at: $0) })
let event = EventUnfavouritedEvent(identifier: identifier)
service.eventBus.post(event)
}
}
// MARK: Properties
private var observers = [EventsServiceObserver]()
private let dataStore: DataStore
private let imageCache: ImagesCache
private let clock: Clock
private let timeIntervalForUpcomingEventsSinceNow: TimeInterval
private let eventBus: EventBus
private let shareableURLFactory: ShareableURLFactory
private(set) var events = [EventCharacteristics]()
private(set) var rooms = [RoomCharacteristics]()
private(set) var tracks = [TrackCharacteristics]()
private(set) var days = [ConferenceDayCharacteristics]()
private var runningEvents: [EventImpl] = []
private var upcomingEvents: [EventImpl] = []
private(set) var eventModels = [EventImpl]() {
didSet {
refreshEventProperties()
}
}
private(set) var dayModels = [Day]()
private(set) var favouriteEventIdentifiers = [EventIdentifier]() {
didSet {
favouriteEventIdentifiers.sort { (first, second) -> Bool in
guard let firstEvent = eventModels.first(where: { $0.identifier == first }) else { return false }
guard let secondEvent = eventModels.first(where: { $0.identifier == second }) else { return false }
return firstEvent.startDate < secondEvent.startDate
}
provideFavouritesInformationToObservers()
}
}
// MARK: Initialization
init(eventBus: EventBus,
dataStore: DataStore,
imageCache: ImagesCache,
clock: Clock,
timeIntervalForUpcomingEventsSinceNow: TimeInterval,
shareableURLFactory: ShareableURLFactory) {
self.dataStore = dataStore
self.imageCache = imageCache
self.clock = clock
self.timeIntervalForUpcomingEventsSinceNow = timeIntervalForUpcomingEventsSinceNow
self.eventBus = eventBus
self.shareableURLFactory = shareableURLFactory
eventBus.subscribe(consumer: DataStoreChangedConsumer(handler: reconstituteEventsFromDataStore))
eventBus.subscribe(consumer: FavouriteEventHandler(service: self))
eventBus.subscribe(consumer: UnfavouriteEventHandler(service: self))
reconstituteEventsFromDataStore()
reconstituteFavouritesFromDataStore()
clock.setDelegate(self)
}
func clockDidTick(to time: Date) {
refreshUpcomingEvents()
updateObserversWithLatestScheduleInformation()
}
func eventsSatisfying(predicate: (Event) -> Bool) -> [Event] {
return eventModels.filter(predicate)
}
// MARK: Functions
func fetchEvent(identifier: EventIdentifier) -> Event? {
return eventModels.first(where: { $0.identifier == identifier })
}
func makeEventsSchedule() -> EventsSchedule {
return EventsScheduleAdapter(schedule: self, clock: clock, eventBus: eventBus)
}
func makeEventsSearchController() -> EventsSearchController {
return InMemoryEventsSearchController(schedule: self, eventBus: eventBus)
}
func add(_ observer: EventsServiceObserver) {
observers.append(observer)
provideScheduleInformation(to: observer)
}
// MARK: Private
private func refreshEventProperties() {
refreshRunningEvents()
refreshUpcomingEvents()
updateObserversWithLatestScheduleInformation()
}
private func refreshRunningEvents() {
let now = clock.currentDate
runningEvents = eventModels.filter { (event) -> Bool in
return DateInterval(start: event.startDate, end: event.endDate).contains(now)
}
}
private func refreshUpcomingEvents() {
let now = clock.currentDate
let range = DateInterval(start: now, end: now.addingTimeInterval(timeIntervalForUpcomingEventsSinceNow))
upcomingEvents = eventModels.filter { (event) -> Bool in
return event.startDate > now && range.contains(event.startDate)
}
}
private func updateObserversWithLatestScheduleInformation() {
observers.forEach(provideScheduleInformation)
}
private func provideScheduleInformation(to observer: EventsServiceObserver) {
observer.runningEventsDidChange(to: runningEvents)
observer.upcomingEventsDidChange(to: upcomingEvents)
observer.eventsDidChange(to: eventModels)
observer.favouriteEventsDidChange(favouriteEventIdentifiers)
}
private func provideFavouritesInformationToObservers() {
observers.forEach { (observer) in
observer.favouriteEventsDidChange(favouriteEventIdentifiers)
}
}
private func reconstituteEventsFromDataStore() {
let events = dataStore.fetchEvents()
let rooms = dataStore.fetchRooms()
let tracks = dataStore.fetchTracks()
let conferenceDays = dataStore.fetchConferenceDays()
if let events = events, let rooms = rooms, let tracks = tracks, let conferenceDays = conferenceDays {
self.days = conferenceDays.reduce(.empty, { (result, next) in
if result.contains(where: { $0.identifier == next.identifier }) { return result }
return result + [next]
})
self.events = events
self.rooms = rooms
self.tracks = tracks
eventModels = events.sorted(by: { $0.startDateTime < $1.startDateTime }).compactMap(makeEventModel)
dayModels = makeDays(from: days)
eventBus.post(ConcreteEventsService.ChangedEvent())
}
}
func makeEventModel(from event: EventCharacteristics) -> EventImpl? {
guard let room = rooms.first(where: { $0.identifier == event.roomIdentifier }) else { return nil }
guard let track = tracks.first(where: { $0.identifier == event.trackIdentifier }) else { return nil }
guard let day = days.first(where: { $0.identifier == event.dayIdentifier }) else { return nil }
let tags = event.tags
let containsTag: (String) -> Bool = { tags?.contains($0) ?? false }
let title: String = {
if containsTag("essential_subtitle") {
return event.title.appending(" - ").appending(event.subtitle)
} else {
return event.title
}
}()
let eventIdentifier = EventIdentifier(event.identifier)
let favouriteEventIdentifiers = dataStore.fetchFavouriteEventIdentifiers().defaultingTo([])
return EventImpl(eventBus: eventBus,
imageCache: imageCache,
shareableURLFactory: shareableURLFactory,
isFavourite: favouriteEventIdentifiers.contains(eventIdentifier),
identifier: eventIdentifier,
title: title,
subtitle: event.subtitle,
abstract: event.abstract,
room: Room(name: room.name),
track: Track(name: track.name),
hosts: event.panelHosts,
startDate: event.startDateTime,
endDate: event.endDateTime,
eventDescription: event.eventDescription,
posterImageId: event.posterImageId,
bannerImageId: event.bannerImageId,
isSponsorOnly: containsTag("sponsors_only"),
isSuperSponsorOnly: containsTag("supersponsors_only"),
isArtShow: containsTag("art_show"),
isKageEvent: containsTag("kage"),
isDealersDen: containsTag("dealers_den"),
isMainStage: containsTag("main_stage"),
isPhotoshoot: containsTag("photoshoot"),
isAcceptingFeedback: event.isAcceptingFeedback,
day: day)
}
private func reconstituteFavouritesFromDataStore() {
favouriteEventIdentifiers = dataStore.fetchFavouriteEventIdentifiers().defaultingTo(.empty)
}
private func makeDays(from models: [ConferenceDayCharacteristics]) -> [Day] {
return models.map(makeDay).sorted()
}
private func makeDay(from model: ConferenceDayCharacteristics) -> Day {
return Day(date: model.date)
}
private func persistFavouritedEvent(identifier: EventIdentifier) {
dataStore.performTransaction { (transaction) in
transaction.saveFavouriteEventIdentifier(identifier)
}
}
}
| mit | 006d0938a848fa34079bfa7914166fbf | 35.647059 | 130 | 0.640851 | 5.336188 | false | false | false | false |
yuewko/themis | vendor/github.com/apache/thrift/lib/swift/Sources/TStruct.swift | 7 | 3608 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/// Protocol for Generated Structs to conform to
/// Dictionary maps field names to internal IDs and uses Reflection
/// to iterate through all fields.
/// `writeFieldValue(_:name:type:id:)` calls `TSerializable.write(to:)` internally
/// giving a nice recursive behavior for nested TStructs, TLists, TMaps, and TSets
public protocol TStruct : TSerializable {
static var fieldIds: [String: Int32] { get }
static var structName: String { get }
}
public extension TStruct {
public static var fieldIds: [String: (id: Int32, type: TType)] { return [:] }
public static var thriftType: TType { return .struct }
public func write(to proto: TProtocol) throws {
// Write struct name first
try proto.writeStructBegin(name: Self.structName)
try self.forEach { name, value, id in
// Write to protocol
try proto.writeFieldValue(value, name: name,
type: value.thriftType, id: id)
}
try proto.writeFieldStop()
try proto.writeStructEnd()
}
public var hashValue: Int {
let prime = 31
var result = 1
self.forEach { _, value, _ in
result = prime &* result &+ (value.hashValue)
}
return result
}
/// Provides a block for handling each (available) thrift property using reflection
/// Caveat: Skips over optional values
/// Provides a block for handling each (available) thrift property using reflection
///
/// - parameter block: block for handling property
///
/// - throws: rethrows any Error thrown in block
private func forEach(_ block: (_ name: String, _ value: TSerializable, _ id: Int32) throws -> Void) rethrows {
// Mirror the object, getting (name: String?, value: Any) for every property
let mirror = Mirror(reflecting: self)
// Iterate through all children, ignore empty property names
for (propName, propValue) in mirror.children {
guard let propName = propName else { continue }
if let tval = unwrap(any: propValue) as? TSerializable, let id = Self.fieldIds[propName] {
try block(propName, tval, id)
}
}
}
/// Any can mysteriously be an Optional<Any> at the same time,
/// this checks and always returns Optional<Any> without double wrapping
/// we then try to bind value as TSerializable to ignore any extension properties
/// and the like and verify the property exists and grab the Thrift
/// property ID at the same time
///
/// - parameter any: Any instance to attempt to unwrap
///
/// - returns: Unwrapped Any as Optional<Any>
private func unwrap(any: Any) -> Any? {
let mi = Mirror(reflecting: any)
if mi.displayStyle != .optional { return any }
if mi.children.count == 0 { return nil }
let (_, some) = mi.children.first!
return some
}
}
| apache-2.0 | 24c2b0ebc5e11253d95108080860a552 | 35.08 | 112 | 0.683758 | 4.341757 | false | false | false | false |
andreacremaschi/CopyPaper | CopyPaperExampleTests/CopyPaperExampleTests.swift | 1 | 1357 | import XCTest
@testable import CopyPaperExample
class CopyPaperExampleTests: XCTestCase {
func testCopyPaper() {
// Create a viewcontroller
let vc1 = UIViewController()
let hitView1 = vc1.view.hitTest(CGPoint.zero, withEvent: UIEvent())
XCTAssert(vc1.view === hitView1)
// Overlay a viewcontroller on top of the first one
let vc2 = UIViewController()
vc1.overlayViewController(vc2)
XCTAssert(vc2.view.superview === vc1.view)
XCTAssert(vc2.view.backgroundColor == UIColor.clearColor())
// Check that the gestures received from the top vc are passed underneath
let hitView2 = vc2.view.hitTest(CGPoint.zero, withEvent: UIEvent())
XCTAssert(hitView2 === vc1.view)
// Insert a non-passthrough view below the view2 and check that it receives gestures
let view3 = UIView(frame: vc2.view.frame)
vc1.view.insertSubview(view3, belowSubview: vc2.view)
let hitView3 = vc2.view.hitTest(CGPoint.zero, withEvent: UIEvent())
XCTAssert(hitView3 === view3)
// Make it passthrough and check if the vc1.view receives the gestures
view3.passThrough = true
let hitView4 = vc2.view.hitTest(CGPoint.zero, withEvent: UIEvent())
XCTAssert(hitView4 === vc1.view)
}
}
| mit | 6533bf9c40d72f84e73dfe48049fa381 | 36.694444 | 92 | 0.653648 | 4.321656 | false | true | false | false |
iosdevzone/SwiftStandardLibraryPlaygrounds | Zip2.playground/section-1.swift | 1 | 428 |
// String example
var vs = [ "hablo", "hablas", "habla", "hablamos", "habláis", "hablan" ]
let ps = [ "yo", "tú", "él/ella", "nosotros", "vosotros", "ellos/ellas"]
let pv = map(Zip2(ps, vs)) { "\($0) \($1)" }
pv
// Numerical example
var v1 = [ 1.0, 2.0, 3.0 ]
var v2 = [ 3.0, 2.0, 1.0 ]
func dot(v1 : [Double], v2: [Double]) -> Double {
return map(Zip2(v1,v2), *).reduce(0.0, +)
}
dot(v1, v2)
| mit | fecec8312fe389f18c53181504538187 | 9.625 | 72 | 0.505882 | 2.190722 | false | false | false | false |
nodes-vapor/sugar | Sources/Sugar/Helpers/String.swift | 1 | 1479 | import Crypto
import COperatingSystem
public extension String {
static func randomAlphaNumericString(_ length: Int = 64) -> String {
func makeRandom(min: Int, max: Int) -> Int {
let top = max - min + 1
#if os(Linux)
// will always be initialized
guard randomInitialized else { fatalError() }
return Int(COperatingSystem.random() % top) + min
#else
return Int(arc4random_uniform(UInt32(top))) + min
#endif
}
let letters: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = letters.count
var randomString = ""
for _ in 0 ..< length {
let rand = makeRandom(min: 0, max: Int(len - 1))
let char = letters[letters.index(letters.startIndex, offsetBy: rand)]
randomString += String(char)
}
return randomString
}
}
#if os(Linux)
/// Generates a random number between (and inclusive of)
/// the given minimum and maximum.
private let randomInitialized: Bool = {
/// This stylized initializer is used to work around dispatch_once
/// not existing and still guarantee thread safety
let current = Date().timeIntervalSinceReferenceDate
let salt = current.truncatingRemainder(dividingBy: 1) * 100000000
COperatingSystem.srand(UInt32(current + salt))
return true
}()
#endif
| mit | d692362d65d7b11b0f5932ef6ce638db | 34.214286 | 94 | 0.608519 | 4.84918 | false | false | false | false |
TwoRingSoft/shared-utils | Examples/Pippin/Pods/PinpointKit/PinpointKit/PinpointKit/Sources/Core/PinpointKit.swift | 1 | 6958 | //
// PinpointKit.swift
// PinpointKit
//
// Created by Paul Rehkugler on 1/22/16.
// Copyright © 2016 Lickability. All rights reserved.
//
import Foundation
/// `PinpointKit` is an object that can be used to collect feedback from application users.
open class PinpointKit {
/// The configuration struct that specifies how PinpointKit should be configured.
fileprivate let configuration: Configuration
/// A delegate that is notified of significant events.
fileprivate weak var delegate: PinpointKitDelegate?
fileprivate weak var displayingViewController: UIViewController?
/**
Initializes a `PinpointKit` object with a configuration and an optional delegate.
- parameter configuration: The configuration struct that specifies how PinpointKit should be configured.
- parameter delegate: A delegate that is notified of significant events.
*/
public init(configuration: Configuration, delegate: PinpointKitDelegate? = nil) {
self.configuration = configuration
self.delegate = delegate
self.configuration.feedbackCollector.feedbackDelegate = self
self.configuration.sender.delegate = self
}
/**
Initializes a `PinpointKit` with a default configuration supplied with feedback recipients and an optional delegate.
- parameter feedbackRecipients: The recipients of the feedback submission. Suitable for email recipients in the "To:" field.
- parameter title: The default title of the feedback.
- parameter body: The default body text of the feedback.
- parameter delegate: A delegate that is notified of significant events.
*/
public convenience init(feedbackRecipients: [String], title: String? = FeedbackConfiguration.DefaultTitle, body: FeedbackConfiguration.Body? = nil, delegate: PinpointKitDelegate? = nil) {
let feedbackConfiguration = FeedbackConfiguration(recipients: feedbackRecipients, title: title, body: body)
let configuration = Configuration(feedbackConfiguration: feedbackConfiguration)
self.init(configuration: configuration, delegate: delegate)
}
/**
Shows PinpointKit’s feedback collection UI from a given view controller.
- parameter viewController: The view controller from which to present.
- parameter screenshot: The screenshot to be annotated. The default value is a screenshot taken at the time this method is called. This image is intended to match the device’s screen size in points.
*/
open func show(from viewController: UIViewController, screenshot: UIImage? = Screenshotter.takeScreenshot()) {
displayingViewController = viewController
configuration.editor.clearAllAnnotations()
configuration.feedbackCollector.collectFeedback(with: screenshot, from: viewController)
}
/// Presents an alert signifying the inability to compose a Mail message.
open func presentFailureToComposeMailAlert() {
let alertTitle = NSLocalizedString("Can’t Send Email", comment: "Title for an alert shown when attempting to send mail without a mail account setup.")
let alertMessage = NSLocalizedString("Make sure that you have at least one email account set up.", comment: "Message for an alert shown when attempting to send mail without a mail account setup.")
let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: "OK button on mail send failure alert."), style: .default, handler: nil)
alertController.addAction(okAction)
configuration.feedbackCollector.viewController.present(alertController, animated: true, completion: nil)
}
}
// MARK: - FeedbackCollectorDelegate
extension PinpointKit: FeedbackCollectorDelegate {
public func feedbackCollector(_ feedbackCollector: FeedbackCollector, didCollect feedback: Feedback) {
delegate?.pinpointKit(self, willSend: feedback)
configuration.sender.send(feedback, from: feedbackCollector.viewController)
}
}
// MARK: - SenderDelegate
extension PinpointKit: SenderDelegate {
public func sender(_ sender: Sender, didSend feedback: Feedback?, success: SuccessType?) {
guard let feedback = feedback else { return }
delegate?.pinpointKit(self, didSend: feedback)
displayingViewController?.dismiss(animated: true, completion: nil)
}
public func sender(_ sender: Sender, didFailToSend feedback: Feedback?, error: Error) {
if case MailSender.Error.mailCanceled = error { return }
guard let feedback = feedback else { return }
if let delegate = delegate {
delegate.pinpointKit(self, didFailToSend: feedback, error: error)
} else if case MailSender.Error.mailCannotSend = error {
presentFailureToComposeMailAlert()
}
}
}
/// A protocol describing an object that can be notified of events from PinpointKit.
public protocol PinpointKitDelegate: class {
/**
Notifies the delegate that PinpointKit is about to send user feedback.
- parameter pinpointKit: The `PinpointKit` instance responsible for the feedback.
- parameter feedback: The feedback that’s about to be sent.
*/
func pinpointKit(_ pinpointKit: PinpointKit, willSend feedback: Feedback)
/**
Notifies the delegate that PinpointKit has just sent user feedback.
- parameter pinpointKit: The `PinpointKit` instance responsible for the feedback.
- parameter feedback: The feedback that’s just been sent.
*/
func pinpointKit(_ pinpointKit: PinpointKit, didSend feedback: Feedback)
/**
Notifies the delegate that PinpointKit has failed to send user feedback.
- parameter pinpointKit: The `PinpointKit` instance responsible for the feedback.
- parameter feedback: The feedback that failed to send.
- parameter error: The error that occurred.
*/
func pinpointKit(_ pinpointKit: PinpointKit, didFailToSend feedback: Feedback, error: Error)
}
/// An extension on `PinpointKitDelegate` that makes all delegate methods optional to implement. The `pinpointKit(_:didFailToSend:error)` implementation presents a default alert for the `MailSender.Error.mailCannotSend` error.
public extension PinpointKitDelegate {
func pinpointKit(_ pinpointKit: PinpointKit, willSend feedback: Feedback) {}
func pinpointKit(_ pinpointKit: PinpointKit, didSend feedback: Feedback) {}
func pinpointKit(_ pinpointKit: PinpointKit, didFailToSend feedback: Feedback, error: Error) {
guard case MailSender.Error.mailCannotSend = error else { return }
pinpointKit.presentFailureToComposeMailAlert()
}
}
| mit | 4c367dce0cec6cb2a71204a3c8549f98 | 45.939189 | 226 | 0.714985 | 4.969242 | false | true | false | false |
emilstahl/swift | validation-test/compiler_crashers_fixed/0183-swift-inflightdiagnostic-fixitreplacechars.swift | 13 | 1720 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
class m<j>: NSObject {
var h: j
g -> k = l $n
}
b f: _ = j() {
}
}
func k<g {
enum k {
func l
var _ = l
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> ) -> d)
import Foundation
class k<f>: NSObject {
d e: f
g(e: f) {
j h.g()
}
}
d
protocol i : d { func d
i
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
}
class i {
func d((h: (Any, AnyObject)) {
d(h)
}
}
d
h)
func d<i>() -> (i, i -> i) -> i {
i j i.f = {
}
protocol d {
class func f()
}
class i: d{ class func f {}
func f() {
({})
}
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
class c {
func b((Any, c))( typealias g = a<d<i>i) {
}
let d = a
d()
a=d g a=d
protocol a : a {
}
class a {
typealias b = b
| apache-2.0 | 4c8ca4e1eb2aef266d36d7574119b93d | 13.098361 | 87 | 0.437791 | 2.464183 | false | false | false | false |
vivekjkumar/VoiceButton-Swift | VoiceConverter/VoiceButton/VoiceButtonView.swift | 1 | 5412 | //
// VoiceButtonView.swift
// VoiceConverter
//
// Created by Vivek Jayakumar on 1/6/17.
import UIKit
/// Voice Button Delegate Protocol
protocol VoiceButtonDelegate {
func updateSpeechText(_ text: String)
func startedRecording()
func stoppedRecording()
func notifyError(_ error: String)
}
@IBDesignable
class VoiceButtonView: UIView {
// MARK:- Public Properties
/// Button Background Color
public var buttonBGColor: UIColor? {
willSet(newColor) {
if let image = voiceButton.backgroundImage(for: .normal), let color = newColor {
let newImage = image.maskWithColor(color: color)
voiceButton.setBackgroundImage(newImage, for: .normal)
}
}
}
/// Button Image Color
public var buttonImageColor: UIColor? {
willSet(newColor) {
if let image = voiceButton.image(for: .normal), let color = newColor {
let newImage = image.maskWithColor(color: color)
voiceButton.setImage(newImage, for: .normal)
}
}
}
/// Button foreground Image
public var buttonImage: UIImage {
set {
voiceButton.setImage(newValue, for: .normal)
}
get {
return self.buttonImage
}
}
// MARK:- Private Properties
@IBOutlet fileprivate weak var buttonContainer: UIView!
@IBOutlet fileprivate weak var voiceButton: UIButton!
@IBOutlet fileprivate weak var voiceRangeView: UIView!
@IBOutlet fileprivate weak var spinnerView: SpinnerView!
private var isRecording: Bool = false
private var speechRecorder: SpeechRecorder?
var voiceButtonDelegate: VoiceButtonDelegate?
// MARK:- Initialise View
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clear
buttonContainer = loadViewFromNib()
buttonContainer.frame = bounds
// Default Values
self.buttonBGColor = UIColor(red:0.15, green:0.45, blue:0.66, alpha:1.0) // #2574A9
self.buttonImageColor = .white
addSubview(buttonContainer)
spinnerView.isHidden = true
speechRecorder = SpeechRecorder()
speechRecorder?.delegate = self
speechRecorder?.setupSpeechRecorder(completion: { [weak self] (returnValue) -> Void in
if returnValue.0 == false {
print(returnValue.1)
self?.voiceButtonDelegate?.notifyError(returnValue.1)
}
})
}
private func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {
return view
} else {
return UIView()
}
}
// func scaleView() {
// UIView.animate(withDuration: 0.6, animations: { [weak self] in
// self?.voiceRangeView.transform = CGAffineTransform.identity.scaledBy(x: 0.6, y: 0.6)
// }, completion: { [weak self] (finish) in
// UIView.animate(withDuration: 0.6, animations: {
// self?.voiceRangeView.transform = CGAffineTransform.identity
// })
// })
// }
//
// MARK:- Voice Button Actions
@IBAction func buttonPressed() {
if self.isRecording == false {
if let image = self.voiceButton.backgroundImage(for: .normal) {
let newImage = image.maskWithColor(color: UIColor(red:0.95, green:0.15, blue:0.07, alpha:1.0)) //F22613
self.voiceButton.setBackgroundImage(newImage, for: .normal)
}
self.voiceButton.setImage(#imageLiteral(resourceName: "stop_icon"), for: .normal)
speechRecorder?.startRecording(completion: { [weak self] (returnValue) -> Void in
if returnValue.0 == false {
print(returnValue.1)
self?.voiceButtonDelegate?.notifyError(returnValue.1)
} else {
self?.voiceButtonDelegate?.startedRecording()
}
})
} else {
if let image = self.voiceButton.backgroundImage(for: .normal), let color = self.buttonBGColor {
let newImage = image.maskWithColor(color: color)
self.voiceButton.setBackgroundImage(newImage, for: .normal)
}
self.voiceButton.setImage(#imageLiteral(resourceName: "microphone_icon"), for: .normal)
if let image = self.voiceButton.image(for: .normal), let color = self.buttonImageColor {
let newImage = image.maskWithColor(color: color)
self.voiceButton.setImage(newImage, for: .normal)
}
speechRecorder?.stopRecording()
voiceButtonDelegate?.stoppedRecording()
}
self.isRecording = !self.isRecording
}
//MARK: Spinner
func showLoader() {
voiceButton.alpha = 0.5
spinnerView.isHidden = false
}
func hideLoader() {
voiceButton.alpha = 1
spinnerView.isHidden = true
}
}
extension VoiceButtonView : SpeechRecorderDelegate {
func updateSpeechText(_ text: String) {
voiceButtonDelegate?.updateSpeechText(text)
}
}
| mit | c7a2576e644df4c88567263f83fa6c7d | 30.649123 | 115 | 0.616408 | 4.517529 | false | false | false | false |
huangxiangdan/XLPagerTabStrip | Example/Example/ChildControllers/TableChildExampleViewController.swift | 2 | 3358 | // TableChildExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2016 Xmartlabs ( 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 XLPagerTabStrip
class TableChildExampleViewController: UITableViewController, IndicatorInfoProvider {
let cellIdentifier = "postCell"
var blackTheme = false
var itemInfo = IndicatorInfo(title: "View")
init(style: UITableViewStyle, itemInfo: IndicatorInfo) {
self.itemInfo = itemInfo
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "PostCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: cellIdentifier)
tableView.estimatedRowHeight = 60.0;
tableView.rowHeight = UITableViewAutomaticDimension
tableView.allowsSelection = false
if blackTheme {
tableView.backgroundColor = UIColor(red: 15/255.0, green: 16/255.0, blue: 16/255.0, alpha: 1.0)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataProvider.sharedInstance.postsData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PostCell
let data = DataProvider.sharedInstance.postsData.objectAtIndex(indexPath.row) as!
NSDictionary
cell.configureWithData(data)
if blackTheme {
cell.changeStylToBlack()
}
return cell
}
// MARK: - IndicatorInfoProvider
func indicatorInfoForPagerTabStrip(pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return itemInfo
}
}
| mit | 0ffde43ca81c50dd74854fab4ef4bf69 | 38.505882 | 128 | 0.715009 | 5.111111 | false | false | false | false |
iOS-mamu/SS | P/Pods/PSOperations/PSOperations/LocationOperation.swift | 1 | 2714 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Shows how to retrieve the user's location with an operation.
*/
#if !os(OSX)
import Foundation
import CoreLocation
/**
`LocationOperation` is an `Operation` subclass to do a "one-shot" request to
get the user's current location, with a desired accuracy. This operation will
prompt for `WhenInUse` location authorization, if the app does not already
have it.
*/
open class LocationOperation: Operation, CLLocationManagerDelegate {
// MARK: Properties
fileprivate let accuracy: CLLocationAccuracy
fileprivate var manager: CLLocationManager?
fileprivate let handler: (CLLocation) -> Void
// MARK: Initialization
public init(accuracy: CLLocationAccuracy, locationHandler: @escaping (CLLocation) -> Void) {
self.accuracy = accuracy
self.handler = locationHandler
super.init()
#if !os(tvOS)
addCondition(Capability(Location.whenInUse))
#else
addCondition(Capability(Location()))
#endif
addCondition(MutuallyExclusive<CLLocationManager>())
addObserver(BlockObserver(cancelHandler: { [weak self] _ in
DispatchQueue.main.async {
self?.stopLocationUpdates()
}
}))
}
override open func execute() {
DispatchQueue.main.async {
/*
`CLLocationManager` needs to be created on a thread with an active
run loop, so for simplicity we do this on the main queue.
*/
let manager = CLLocationManager()
manager.desiredAccuracy = self.accuracy
manager.delegate = self
if #available(iOS 9.0, *) {
manager.requestLocation()
} else {
#if !os(tvOS) && !os(watchOS)
manager.startUpdatingLocation()
#endif
}
self.manager = manager
}
}
fileprivate func stopLocationUpdates() {
manager?.stopUpdatingLocation()
manager = nil
}
// MARK: CLLocationManagerDelegate
open func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last, location.horizontalAccuracy <= accuracy {
stopLocationUpdates()
handler(location)
finish()
}
}
open func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
stopLocationUpdates()
finishWithError(error as NSError?)
}
}
#endif
| mit | 6b24f0c99fd97b655564c041d5988adc | 29.47191 | 105 | 0.616888 | 5.40239 | false | false | false | false |
dshahidehpour/IGListKit | Examples/Examples-iOS/IGListKitExamples/Models/User.swift | 4 | 1292 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
final class User: IGListDiffable {
let pk: Int
let name: String
let handle: String
init(pk: Int, name: String, handle: String) {
self.pk = pk
self.name = name
self.handle = handle
}
//MARK: IGListDiffable
func diffIdentifier() -> NSObjectProtocol {
return pk as NSObjectProtocol
}
func isEqual(toDiffableObject object: IGListDiffable?) -> Bool {
guard self !== object else { return true }
guard let object = object as? User else { return false }
return name == object.name && handle == object.handle
}
}
| bsd-3-clause | 615eb77ae9538169d9d5f133db2ef85f | 30.512195 | 80 | 0.702786 | 4.681159 | false | false | false | false |
KrishMunot/swift | test/SILGen/objc_enum.swift | 6 | 2123 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen > %t.out
// RUN: FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize %s < %t.out
// RUN: FileCheck -check-prefix=NEGATIVE %s < %t.out
// REQUIRES: objc_interop
import gizmo
// CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsC
// CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsg8rawValueSi
// CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsg9hashValueSi
// Non-payload enum ctors don't need to be instantiated at all.
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions5MinceFMS_S_
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions12QuinceSlicedFMS_S_
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions15QuinceJuliennedFMS_S_
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions11QuinceDicedFMS_S_
var runcing: NSRuncingOptions = .mince
var raw = runcing.rawValue
var eq = runcing == .quinceSliced
var hash = runcing.hashValue
func testEm<E: Equatable>(_ x: E, _ y: E) {}
func hashEm<H: Hashable>(_ x: H) {}
func rawEm<R: RawRepresentable>(_ x: R) {}
testEm(NSRuncingOptions.mince, .quinceSliced)
hashEm(NSRuncingOptions.mince)
rawEm(NSRuncingOptions.mince)
rawEm(NSFungingMask.asset)
protocol Bub {}
extension NSRuncingOptions: Bub {}
// CHECK-32-DAG: integer_literal $Builtin.Int2048, -2147483648
// CHECK-64-DAG: integer_literal $Builtin.Int2048, 2147483648
_ = NSFungingMask.toTheMax
// CHECK-DAG: sil_witness_table shared [fragile] NSRuncingOptions: RawRepresentable module gizmo
// CHECK-DAG: sil_witness_table shared [fragile] NSRuncingOptions: Equatable module gizmo
// CHECK-DAG: sil_witness_table shared [fragile] NSRuncingOptions: Hashable module gizmo
// CHECK-DAG: sil_witness_table shared [fragile] NSFungingMask: RawRepresentable module gizmo
// CHECK-DAG: sil shared [transparent] [thunk] @_TTWOSC16NSRuncingOptionss16RawRepresentable5gizmoFS0_C
// Extension conformances get linkage according to the protocol's accessibility, as normal.
// CHECK-DAG: sil_witness_table hidden NSRuncingOptions: Bub module objc_enum
| apache-2.0 | bcbace6d2fd8b9dee7f8d841338564f5 | 39.826923 | 105 | 0.772963 | 3.375199 | false | false | false | false |
KrishMunot/swift | test/decl/subscript/subscripting.swift | 3 | 7365 | // RUN: %target-parse-verify-swift
struct X { }
// Simple examples
struct X1 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored
}
mutating
set {
stored = newValue
}
}
}
struct X2 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored + i
}
set(v) {
stored = v - i
}
}
}
struct X3 {
var stored : Int
subscript (_ : Int) -> Int {
get {
return stored
}
set(v) {
stored = v
}
}
}
struct X4 {
var stored : Int
subscript (i : Int, j : Int) -> Int {
get {
return stored + i + j
}
set(v) {
stored = v + i - j
}
}
}
// Semantic errors
struct Y1 {
var x : X
subscript(i: Int) -> Int {
get {
return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}}
}
set {
x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}}
}
}
}
struct Y2 {
subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
class Y3 {
subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
protocol ProtocolGetSet0 {
subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet1 {
subscript(i: Int) -> Int { get }
}
protocol ProtocolGetSet2 {
subscript(i: Int) -> Int { set } // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet3 {
subscript(i: Int) -> Int { get set }
}
protocol ProtocolGetSet4 {
subscript(i: Int) -> Int { set get }
}
protocol ProtocolWillSetDidSet1 {
subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet2 {
subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet3 {
subscript(i: Int) -> Int { willSet didSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet4 {
subscript(i: Int) -> Int { didSet willSet } // expected-error {{expected get or set in a protocol property}}
}
class DidSetInSubscript {
subscript(_: Int) -> Int {
didSet { // expected-error {{didSet is not allowed in subscripts}}
print("eek")
}
get {}
}
}
class WillSetInSubscript {
subscript(_: Int) -> Int {
willSet { // expected-error {{willSet is not allowed in subscripts}}
print("eek")
}
get {}
}
}
subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
func f() {
subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
}
struct NoSubscript { }
struct OverloadedSubscript {
subscript(i: Int) -> Int {
get {
return i
}
set {}
}
subscript(i: Int, j: Int) -> Int {
get { return i }
set {}
}
}
struct RetOverloadedSubscript {
subscript(i: Int) -> Int { // expected-note {{found this candidate}}
get { return i }
set {}
}
subscript(i: Int) -> Float { // expected-note {{found this candidate}}
get { return Float(i) }
set {}
}
}
struct MissingGetterSubscript1 {
subscript (i : Int) -> Int {
} // expected-error {{computed property must have accessors specified}}
}
struct MissingGetterSubscript2 {
subscript (i : Int, j : Int) -> Int { // expected-error{{subscript declarations must have a getter}}
set {}
}
}
func test_subscript(_ x2: inout X2, i: Int, j: Int, value: inout Int, no: NoSubscript,
ovl: inout OverloadedSubscript, ret: inout RetOverloadedSubscript) {
no[i] = value // expected-error{{type 'NoSubscript' has no subscript members}}
value = x2[i]
x2[i] = value
value = ovl[i]
ovl[i] = value
value = ovl[(i, j)]
ovl[(i, j)] = value
value = ovl[(i, j, i)] // expected-error{{cannot convert value of type '(Int, Int, Int)' to expected argument type 'Int'}}
ret[i] // expected-error{{ambiguous use of 'subscript'}}
value = ret[i]
ret[i] = value
}
func subscript_rvalue_materialize(_ i: inout Int) {
i = X1(stored: 0)[i]
}
func subscript_coerce(_ fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {}
func test_subscript_coerce() {
subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] })
}
struct no_index {
subscript () -> Int { return 42 }
func test() -> Int {
return self[]
}
}
struct tuple_index {
subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) }
func test() -> (Int, Int) {
return self[123, 456]
}
}
struct SubscriptTest1 {
subscript(keyword:String) -> Bool { return true } // expected-note 2 {{found this candidate}}
subscript(keyword:String) -> String? {return nil } // expected-note 2 {{found this candidate}}
}
func testSubscript1(_ s1 : SubscriptTest1) {
let _ : Int = s1["hello"] // expected-error {{ambiguous subscript with base type 'SubscriptTest1' and index type 'String'}}
if s1["hello"] {}
let _ = s1["hello"] // expected-error {{ambiguous use of 'subscript'}}
}
struct SubscriptTest2 {
subscript(a : String, b : Int) -> Int { return 0 }
subscript(a : String, b : String) -> Int { return 0 }
}
func testSubscript1(_ s2 : SubscriptTest2) {
_ = s2["foo"] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type 'String'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
let a = s2["foo", 1.0] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type '(String, Double)'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
let b = s2[1, "foo"] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
// sr-114 & rdar://22007370
class Foo {
subscript(key: String) -> String { // expected-note {{'subscript' previously declared here}}
get { a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript'}}
get { a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
}
// <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please
protocol r23952125 {
associatedtype ItemType
var count: Int { get }
subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get set \}}}
var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
// <rdar://problem/16812341> QoI: Poor error message when providing a default value for a subscript parameter
struct S4 {
subscript(subs: Int = 0) -> Int { // expected-error {{default arguments are not allowed in subscripts}}
get {
return 1
}
}
}
| apache-2.0 | 991de43df8a3fb93fe7565d12341bf14 | 24.484429 | 156 | 0.623218 | 3.585686 | false | false | false | false |
divljiboy/IOSChatApp | Quick-Chat/Pods/Swinject/Sources/InstanceWrapper.swift | 1 | 2735 | //
// Lazy.swift
// Swinject
//
// Created by Jakub Vaňo on 07/03/2018.
// Copyright © 2018 Swinject Contributors. All rights reserved.
//
protocol InstanceWrapper {
static var wrappedType: Any.Type { get }
init?(inContainer container: Container, withInstanceFactory factory: (() -> Any?)?)
}
/// Wrapper to enable delayed dependency instantiation.
/// `Lazy<Type>` does not need to be explicitly registered into the `Container` - resolution will work
/// as long as there is a registration for the `Type`.
public final class Lazy<Service>: InstanceWrapper {
static var wrappedType: Any.Type { return Service.self }
private let factory: () -> Any?
private let graphIdentifier: GraphIdentifier?
private weak var container: Container?
init?(inContainer container: Container, withInstanceFactory factory: (() -> Any?)?) {
guard let factory = factory else { return nil }
self.factory = factory
self.graphIdentifier = container.currentObjectGraph
self.container = container
}
private var _instance: Service?
/// Getter for the wrapped object.
/// It will be resolved from the `Container` when first accessed, all other calls will return the same instance.
public var instance: Service {
if let instance = _instance {
return instance
} else {
_instance = makeInstance()
return _instance!
}
}
private func makeInstance() -> Service? {
guard let container = container else {
return nil
}
if let graphIdentifier = graphIdentifier {
container.restoreObjectGraph(graphIdentifier)
}
return factory() as? Service
}
}
/// Wrapper to enable delayed dependency instantiation.
/// `Provider<Type>` does not need to be explicitly registered into the `Container` - resolution will work
/// as long as there is a registration for the `Type`.
public final class Provider<Service>: InstanceWrapper {
static var wrappedType: Any.Type { return Service.self }
private let factory: () -> Any?
init?(inContainer container: Container, withInstanceFactory factory: (() -> Any?)?) {
guard let factory = factory else { return nil }
self.factory = factory
}
/// Getter for the wrapped object.
/// New instance will be resolved from the `Container` every time it is accessed.
public var instance: Service {
return factory() as! Service
}
}
extension Optional: InstanceWrapper {
static var wrappedType: Any.Type { return Wrapped.self }
init?(inContainer container: Container, withInstanceFactory factory: (() -> Any?)?) {
self = factory?() as? Wrapped
}
}
| mit | 4bb2f35af0fb275d618eb562405a9d8d | 32.740741 | 116 | 0.663374 | 4.655877 | false | false | false | false |
gchance22/HarrierQueue | HarrierQueue/HarrierTask.swift | 1 | 4454 | //
// HarrierTask.swift
// HarrierQueue
//
// Created by Graham Chance on 8/29/15.
//
//
import Foundation
/// No retry constant.
public let kNoRetryLimit = -1
/**
Task status.
- Waiting: Queued, but not running.
- Running: Currently running.
- Done: Done running.
*/
public enum HarrierTaskStatus: String {
case Waiting
case Running
case Done
}
/**
Completion status of a task.
- Success: Completed entirely with no issues.
- Failed: Failed to complete.
- Abandon: Task has been abandoned, i.e. not completed, but will not be attempted again.
*/
public enum HarrierTaskCompletionStatus: String {
case Success
case Failed
case Abandon
}
/**
* The delegate for HarrierTasks.
*/
internal protocol HarrierTaskDelegate {
func taskDidCompleteWithStatus(task: HarrierTask, status: HarrierTaskCompletionStatus)
}
/// A Task to be queued in a HarrierQueue.
public class HarrierTask: Equatable {
private var status: HarrierTaskStatus?
private var delegate: HarrierTaskDelegate?
/// The number of times the task has failed.
internal var failCount: Int64
/// The name of the task. Not required. Note it is used in the uniqueIdentifier.
public let name: String?
/// The priority measurement that ranks above all others. 0 (low priority) - infinity (high priority)
public let priorityLevel: Int64
/// The date the task was first initialized.
public let dateCreated: NSDate
/// The number of times the task can be retried before it is abandoned.
public let retryLimit: Int64
/// Any data or information that the task holds.
public let data: NSDictionary
/// The soonest the task can be executed.
public var availabilityDate: NSDate
/// A combination of task name and data, creating a unique ID.
public var uniqueIdentifier: String {
var identifier = ""
if let taskName = name { identifier += taskName }
for (key, value) in data {
identifier += "-\(key):\(value)"
}
return identifier
}
/**
HarrierTask Initializer.
- parameter name: Task name.
- parameter priority: Priority of task relative to others (0 is lowest priority).
- parameter taskAttributes: A dictionary of any data the task contains.
- parameter retryLimit: How many times the task should be reattempted if it fails.
- parameter availabilityDate: Date the task can be first attempted.
- parameter dateCreated: Current date by default. Don't change unless you have a good reason.
- returns: Returns a new HarrierTask with the given properties.
*/
public init(name: String?, priority: Int64, taskAttributes: [String: String], retryLimit: Int64, availabilityDate: NSDate, dateCreated: NSDate = NSDate()) {
self.name = name
self.priorityLevel = priority
self.data = taskAttributes
self.retryLimit = retryLimit
self.availabilityDate = availabilityDate
self.dateCreated = dateCreated
self.failCount = 0
}
/**
Compares the task to another, based on priority in the queue.
- parameter other: The task to compare to.
- returns: Returns whether this task is higher priority to the given task.
*/
public func isHigherPriority(thanTask other: HarrierTask) -> Bool {
if self.availabilityDate.timeIntervalSinceNow > 0 {
return self.availabilityDate.timeIntervalSinceNow < other.availabilityDate.timeIntervalSinceNow
} else if other.availabilityDate.timeIntervalSinceNow > 0 {
return true
} else {
return priorityLevel > other.priorityLevel || (priorityLevel == other.priorityLevel && failCount < other.failCount && dateCreated.timeIntervalSince1970 < other.dateCreated.timeIntervalSince1970)
}
}
/**
Completes the task.
- parameter completionStatus: The status of completion, i.e. success, failed, or abandoned.
*/
internal func completeWithStatus(completionStatus: HarrierTaskCompletionStatus) {
self.status = .Done
delegate?.taskDidCompleteWithStatus(self, status: completionStatus)
}
}
public func ==(lhs: HarrierTask, rhs: HarrierTask) -> Bool {
return lhs.uniqueIdentifier == rhs.uniqueIdentifier
}
| mit | 8dae8247d710a1596a3adc2cb613af2e | 30.588652 | 206 | 0.666592 | 4.582305 | false | false | false | false |
NghiaTranUIT/WatchKit-Apps | 2- DataSharing/DataSharing/ItemsViewController.swift | 7 | 1594 | //
// ItemsViewController.swift
// DataSharing
//
// Created by Konstantin Koval on 15/12/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
import UIKit
class ItemsViewController: UITableViewController {
var viewModel = ItemsViewModel()
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
@IBAction func createItem(sender: UITextField) {
viewModel.append(sender.text)
sender.text = nil
tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.items.count
}
// MARK: TableView
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = viewModel.items[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
viewModel.removeItemAt(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
break
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
}
| mit | decdbc50ccd0b50bc6023618d075b1d0 | 27.464286 | 155 | 0.731493 | 5.158576 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.