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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
milseman/swift
|
test/Parse/foreach.swift
|
8
|
1443
|
// RUN: %target-typecheck-verify-swift
struct IntRange<Int> : Sequence, IteratorProtocol {
typealias Element = (Int, Int)
func next() -> (Int, Int)? {}
typealias Iterator = IntRange<Int>
func makeIterator() -> IntRange<Int> { return self }
}
func for_each(r: Range<Int>, iir: IntRange<Int>) { // expected-note {{did you mean 'r'?}}
var sum = 0
// Simple foreach loop, using the variable in the body
for i in CountableRange(r) {
sum = sum + i
}
// Check scoping of variable introduced with foreach loop
i = 0 // expected-error{{use of unresolved identifier 'i'}}
// For-each loops with two variables and varying degrees of typedness
for (i, j) in iir {
sum = sum + i + j
}
for (i, j) in iir {
sum = sum + i + j
}
for (i, j) : (Int, Int) in iir {
sum = sum + i + j
}
// Parse errors
// FIXME: Bad diagnostics; should be just 'expected 'in' after for-each patter'.
for i r { // expected-error {{found an unexpected second identifier in constant declaration}}
} // expected-note @-1 {{join the identifiers together}}
// expected-note @-2 {{join the identifiers together with camel-case}}
// expected-error @-3 {{expected 'in' after for-each pattern}}
// expected-error @-4 {{expected Sequence expression for for-each loop}}
for i in CountableRange(r) sum = sum + i; // expected-error{{expected '{' to start the body of for-each loop}}
}
|
apache-2.0
|
5933a16555fb326782a614d6510e45b3
| 35.075 | 112 | 0.634096 | 3.719072 | false | false | false | false |
armcknight/TrigKit
|
TrigKit/Definitions.swift
|
1
|
2599
|
//
// Definitions.swift
// TrigKit
//
// Created by Andrew McKnight on 8/7/16.
// Copyright © 2016 Two Ring Software. All rights reserved.
//
import Foundation
public enum Quadrant {
case first
case second
case third
case fourth
public init(angle: Angle) {
let cc = angle.counterclockwise.radians
if cc <= .pi / 2 {
self = .first
} else if cc <= .pi {
self = .second
} else if cc <= 3 * .pi / 2 {
self = .third
} else {
self = .fourth
}
}
public func isPositiveX() -> Bool {
return self == .first || self == .fourth
}
public func isPositiveY() -> Bool {
return self == .first || self == .second
}
}
public enum Measure: Int {
case arc
case hypotenuse
case chord
case sine
case cosine
case tangent
case sineOpposite
case cosineOpposite
case secant
case cosecant
case cotangent
case versine
case coversine
case exsecant
case excosecant
public func shortName() -> String {
switch self {
case .arc: return "arc"
case .hypotenuse: return "hyp"
case .chord: return "crd"
case .sine, .sineOpposite: return "sin"
case .cosine, .cosineOpposite: return "cos"
case .tangent: return "tan"
case .secant: return "sec"
case .cosecant: return "csc"
case .cotangent: return "cot"
case .versine: return "siv"
case .coversine: return "cvs"
case .exsecant: return "exsec"
case .excosecant: return "excsc"
}
}
public func longName() -> String {
switch self {
case .arc: return "Arc"
case .hypotenuse: return "Hypotenuse"
case .chord: return "Chord"
case .sine: return "Sine"
case .cosine: return "Cosine"
case .sineOpposite: return "Opposite Sine"
case .cosineOpposite: return "Opposite Cosine"
case .tangent: return "Tangent"
case .secant: return "Secant"
case .cosecant: return "Cosecant"
case .cotangent: return "Cotangent"
case .versine: return "Versine"
case .coversine: return "Coversine"
case .exsecant: return "Exsecant"
case .excosecant: return "Excosecant"
}
}
public static func allMeasures() -> [Measure] {
return [
arc, hypotenuse, chord, sine, sineOpposite, cosineOpposite, cosine, tangent, secant, cosecant, cotangent, versine, coversine, exsecant, excosecant
]
}
}
|
mit
|
2282f66126d75d0acfa0d21dac788fe7
| 23.980769 | 154 | 0.575443 | 3.942337 | false | false | false | false |
pinterest/plank
|
Sources/Core/ObjectiveCDictionaryExtension.swift
|
1
|
12817
|
//
// ObjectiveCDictionaryExtension.swift
// plank
//
// Created by Martin Matejovic on 18/05/2017.
//
//
import Foundation
extension ObjCModelRenderer {
func renderGenerateDictionary() -> ObjCIR.Method {
let dictionary = "dict"
let props = properties.filter { (_, schema) -> Bool in
!schema.schema.isBoolean()
}.map { (param, schemaObj) -> String in
ObjCIR.ifStmt("_" + "\(self.dirtyPropertiesIVarName).\(dirtyPropertyOption(propertyName: param, className: self.className))") { [
schemaObj.schema.isPrimitiveType ?
self.renderAddToDictionaryStatement(.ivar(param), schemaObj.schema, dictionary) :
ObjCIR.ifElseStmt("_\(Languages.objectiveC.snakeCaseToPropertyName(param)) != nil") { [
self.renderAddToDictionaryStatement(.ivar(param), schemaObj.schema, dictionary),
] } { [
"[\(dictionary) setObject:[NSNull null] forKey:@\"\(param)\"];",
] },
] }
}.joined(separator: "\n")
let boolProps = properties.filter { (_, schema) -> Bool in
schema.schema.isBoolean()
}.map { (param, _) -> String in
let ivarName = "_\(booleanPropertiesIVarName).\(booleanPropertyOption(propertyName: param, className: self.className))"
return ObjCIR.ifStmt("_" + "\(self.dirtyPropertiesIVarName).\(dirtyPropertyOption(propertyName: param, className: self.className))") { [
"[\(dictionary) setObject:@(\(ivarName)) forKey: @\"\(param)\"];",
] }
}
return ObjCIR.method("- (NSDictionary *)dictionaryObjectRepresentation") { [
"NSMutableDictionary *\(dictionary) = " +
(self.isBaseClass ? "[[NSMutableDictionary alloc] initWithCapacity:\(self.properties.count)];" :
"[[super dictionaryObjectRepresentation] mutableCopy];"),
props,
] + boolProps + ["return \(dictionary);"] }
}
}
private enum CollectionClass {
case array
case set
func name() -> String {
switch self {
case .array:
return "NSArray"
case .set:
return "NSSet"
}
}
func mutableName() -> String {
switch self {
case .array:
return "NSMutableArray"
case .set:
return "NSMutableSet"
}
}
func initializer() -> String {
switch self {
case .array:
return "arrayWithCapacity:"
case .set:
return "setWithCapacity:"
}
}
}
enum ParamType {
case ivar(String)
case localVariable(String)
func paramVariable() -> String {
switch self {
case let .ivar(paramName):
return "_\(Languages.objectiveC.snakeCaseToPropertyName(paramName))"
case let .localVariable(paramName)
:
return Languages.objectiveC.snakeCaseToPropertyName(paramName)
}
}
func paramName() -> String {
switch self {
case let .ivar(paramName):
return paramName
case let .localVariable(paramName)
:
return paramName
}
}
}
extension ObjCFileRenderer {
func renderAddToDictionaryStatement(_ paramWrapped: ParamType, _ schema: Schema, _ dictionary: String, counter: Int = 0) -> String {
let param = paramWrapped.paramName()
let propIVarName = paramWrapped.paramVariable()
switch schema {
// TODO: After nullability PR landed we should revisit this and don't check for nil if
// the ivar is nonnull in all of this cases
case .boolean, .float, .integer:
return "[\(dictionary) setObject:@(\(propIVarName)) forKey: @\"\(param)\"];"
case .object:
return "[\(dictionary) setObject:[\(propIVarName) dictionaryObjectRepresentation] forKey:@\"\(param)\"];"
case .string(format: .none),
.string(format: .some(.email)),
.string(format: .some(.hostname)),
.string(format: .some(.ipv4)),
.string(format: .some(.ipv6)):
return "[\(dictionary) setObject:\(propIVarName) forKey:@\"\(param)\"];"
case .string(format: .some(.uri)):
return "[\(dictionary) setObject:[\(propIVarName) absoluteString] forKey:@\"\(param)\"];"
case .string(format: .some(.dateTime)):
return [
"NSValueTransformer *valueTransformer = [NSValueTransformer valueTransformerForName:\(dateValueTransformerKey)];",
ObjCIR.ifElseStmt("[[valueTransformer class] allowsReverseTransformation]") { [
"[\(dictionary) setObject:[valueTransformer reverseTransformedValue:\(propIVarName)] forKey:@\"\(param)\"];",
] } { [
"[\(dictionary) setObject:[NSNull null] forKey:@\"\(param)\"];",
] },
].joined(separator: "\n")
case .enumT(.integer):
return "[\(dictionary) setObject:@(\(propIVarName)) forKey:@\"\(param)\"];"
case .enumT(.string):
return "[\(dictionary) setObject:" + enumToStringMethodName(propertyName: param, className: className) + "(\(propIVarName))" + " forKey:@\"\(param)\"];"
case let .array(itemType: itemType?), let .set(itemType: itemType?):
func collectionClass(schema: Schema) -> CollectionClass {
if case .array = schema {
return .array
} else {
return .set
}
}
func createCollection(destCollection: String, processObject: String, collectionSchema: Schema, collectionCounter: Int = 0) -> String {
switch collectionSchema {
case .reference, .object, .oneOf(types: _):
return "[\(destCollection) addObject:[\(processObject) dictionaryObjectRepresentation]];"
case let .array(itemType: type), let .set(itemType: type):
let currentResult = "result\(collectionCounter)"
let parentResult = "result\(collectionCounter - 1)"
let currentObj = "obj\(collectionCounter)"
let collectionItemClass = type.map { typeFromSchema("", $0.nonnullProperty()) } ?? "id"
return [
"\(collectionClass(schema: collectionSchema).name()) *items\(collectionCounter) = \(processObject);",
"\(CollectionClass.array.mutableName()) *\(currentResult) = [\(CollectionClass.array.mutableName()) \(CollectionClass.array.initializer())items\(collectionCounter).count];",
ObjCIR.forStmt("\(collectionItemClass) \(currentObj) in items\(collectionCounter)") { [
createCollection(destCollection: currentResult, processObject: currentObj, collectionSchema: type!, collectionCounter: collectionCounter + 1),
] },
"[\(parentResult) addObject:\(currentResult)];",
].joined(separator: "\n")
case .map(valueType: .none):
return "[\(destCollection) addObject:\(processObject)];"
case let .map(valueType: .some(type)):
let currentResult = "result\(collectionCounter)"
let parentResult = "result\(collectionCounter - 1)"
let key = "key\(collectionCounter)"
return [
"\(typeFromSchema("", collectionSchema.nonnullProperty())) items\(collectionCounter) = \(processObject);",
"__auto_type \(currentResult) = [NSMutableDictionary new];",
ObjCIR.forStmt("NSString *\(key) in items\(collectionCounter)") { [
"\(typeFromSchema("", type.nonnullProperty())) tmp\(collectionCounter) = [items\(collectionCounter) objectForKey:\(key)];",
"NSMutableDictionary *tmpDict\(collectionCounter) = [NSMutableDictionary new];",
self.renderAddToDictionaryStatement(.localVariable("tmp\(collectionCounter)"), type, "tmpDict\(collectionCounter)", counter: collectionCounter + 1),
"\(currentResult)[\(key)] = tmpDict\(collectionCounter)[@\"tmp\(collectionCounter)\"];",
] },
"[\(parentResult) addObject:\(currentResult)];",
].joined(separator: "\n")
case .integer, .float, .boolean:
return "[\(destCollection) addObject:\(processObject)];"
case .string(format: .none),
.string(format: .some(.email)),
.string(format: .some(.hostname)),
.string(format: .some(.ipv4)),
.string(format: .some(.ipv6)):
return "[\(destCollection) addObject:\(processObject)];"
case .string(format: .some(.uri)):
return "[\(destCollection) addObject:[\(processObject) absoluteString]];"
case .string(format: .some(.dateTime)):
return [
"NSValueTransformer *valueTransformer = [NSValueTransformer valueTransformerForName:\(dateValueTransformerKey)];",
ObjCIR.ifElseStmt("[[valueTransformer class] allowsReverseTransformation]") { [
"[\(destCollection) addObject:[valueTransformer reverseTransformedValue:\(propIVarName)]];",
] } { [
"[\(destCollection) addObject:[NSNull null]];",
] },
].joined(separator: "\n")
case .enumT(.integer):
return "[\(destCollection) addObject:@(\(processObject))];"
case .enumT(.string):
return "[\(destCollection) addObject:" + enumToStringMethodName(propertyName: param, className: className) + "(\(propIVarName))];"
}
}
let currentResult = "result\(counter)"
let currentObj = "obj\(counter)"
let itemClass = itemType.isPrimitiveType ? "id" : typeFromSchema(param, itemType.nonnullProperty())
return [
"__auto_type items\(counter) = \(propIVarName);",
"\(CollectionClass.array.mutableName()) *\(currentResult) = [\(CollectionClass.array.mutableName()) \(CollectionClass.array.initializer())items\(counter).count];",
ObjCIR.forStmt("\(itemClass) \(currentObj) in items\(counter)") { [
createCollection(destCollection: currentResult, processObject: currentObj, collectionSchema: itemType, collectionCounter: counter + 1),
] },
"[\(dictionary) setObject:\(currentResult) forKey:@\"\(param)\"];",
].joined(separator: "\n")
case let .map(valueType: .some(valueType)):
switch valueType {
case .map, .array, .reference(with: _), .oneOf(types: _), .object:
return [
"NSMutableDictionary *items\(counter) = [NSMutableDictionary new];",
ObjCIR.forStmt("NSString *key\(counter) in \(propIVarName)") { [
"__auto_type dictValue\(counter) = \(propIVarName)[key\(counter)];",
"NSMutableDictionary *tmp\(counter) = [NSMutableDictionary new];",
self.renderAddToDictionaryStatement(.localVariable("dictValue\(counter)"), valueType, "tmp\(counter)", counter: counter + 1),
"[items\(counter) setObject:tmp\(counter)[@\"dictValue\(counter)\"] forKey:key\(counter)];",
] },
"[\(dictionary) setObject:items\(counter) forKey:@\"\(param)\"];",
].joined(separator: "\n")
default:
return "[\(dictionary) setObject:\(propIVarName) forKey:@\"\(param)\"];"
}
case .oneOf(types: _):
// oneOf (ADT) types have a dictionaryObjectRepresentation method we will use here
return "[\(dictionary) setObject:[\(propIVarName) dictionaryObjectRepresentation] forKey:@\"\(param)\"];"
case let .reference(with: ref):
return ref.force().map {
renderAddToDictionaryStatement(paramWrapped, $0, dictionary)
} ?? {
assert(false, "TODO: Forward optional across methods")
return ""
}()
case .map(valueType: .none), .array(.none), .set(.none):
return "[\(dictionary) setObject:\(propIVarName) forKey:@\"\(param)\"];"
}
}
}
|
apache-2.0
|
ddcb2b4759896d7acf0d9279c74a62d2
| 51.314286 | 197 | 0.552079 | 5.062006 | false | false | false | false |
lozisung/SwipeToFlipButton
|
SwipeToFlipButton/SwipeToFlipButton/SwipeToFlipButton.swift
|
1
|
4913
|
//
// SwipeToFlipButton.swift
// Flex test
//
// Created by Jason Lo on 11/02/2016.
// Copyright © 2016 Losoftware. All rights reserved.
//
import UIKit
protocol SwipeToFlipProtocol {
func swipeButtonTapped()
}
public class SwipeToFlipButton: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var seqArray: NSArray //array of strings or values for display on label
var currentItem: Int
var backShowing = false
var backView: UILabel
var frontView: UILabel
var delegate: AnyObject!
var alignment: NSTextAlignment = NSTextAlignment.Center
var animateDuration: Double = 0.375
var buttonFont: UIFont = UIFont(name: "Helvetica", size: 14)!
var backgroundColour: UIColor = UIColor.whiteColor()
var fontColour: UIColor = UIColor.blackColor()
var cornerRadius: CGFloat = 0
var borderColour: UIColor = UIColor.blackColor()
var borderWidth: CGFloat = 0
public init(frame: CGRect, sequenceArray: NSArray, defaultArrayItem: Int, tapDelegate: AnyObject!) {
seqArray = sequenceArray
currentItem = defaultArrayItem
backView = UILabel(frame: CGRect(origin: CGPoint(x: 0,y: 0), size: frame.size))
frontView = UILabel(frame: CGRect(origin: CGPoint(x: 0,y: 0), size: frame.size))
frontView.text = "\(seqArray[currentItem])"
super.init(frame: frame)
let rightSwipeGesture: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swiped:")
rightSwipeGesture.direction = UISwipeGestureRecognizerDirection.Right
let leftSwipeGesture: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swiped:")
leftSwipeGesture.direction = UISwipeGestureRecognizerDirection.Left
if tapDelegate != nil {
delegate = tapDelegate
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: delegate, action: "swipeButtonTapped")
self.addGestureRecognizer(tapGesture)
}
self.addGestureRecognizer(rightSwipeGesture)
self.addGestureRecognizer(leftSwipeGesture)
self.userInteractionEnabled = true
self.initButton()
self.addSubview(frontView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func swiped(sender: AnyObject) {
if sender.isKindOfClass(UISwipeGestureRecognizer) {
let swipeGesture: UISwipeGestureRecognizer = sender as! UISwipeGestureRecognizer
var showString: String = "\(seqArray[currentItem])"
print(currentItem)
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Left:
print("Swipe left")
if currentItem > 0 {
showString = "\(seqArray[--currentItem])"
self.flipView(UIViewAnimationOptions.TransitionFlipFromRight, textString: showString)
}
break
case UISwipeGestureRecognizerDirection.Right:
print("Swipe right")
if currentItem + 1 < seqArray.count {
showString = "\(seqArray[++currentItem])"
self.flipView(UIViewAnimationOptions.TransitionFlipFromLeft, textString: showString)
}
break
default:
break
}
}
}
public func initButton () {
self.backView = self.setupButtonView(self.backView)
self.frontView = self.setupButtonView(self.frontView)
}
func setupButtonView(theView: UILabel) -> UILabel {
theView.clipsToBounds = true
theView.textAlignment = alignment
theView.font = buttonFont
theView.textColor = fontColour
theView.backgroundColor = backgroundColour
theView.layer.cornerRadius = cornerRadius
theView.layer.borderColor = borderColour.CGColor
theView.layer.borderWidth = borderWidth
return theView
}
func flipView(direction: UIViewAnimationOptions, textString: String) {
let fromView : UILabel = backShowing ? backView : frontView
let toView : UILabel = backShowing ? frontView : backView
toView.text = textString
UIView.transitionFromView(fromView, toView: toView, duration: animateDuration, options: direction, completion: nil)
backShowing = !backShowing
}
}
|
gpl-3.0
|
d37c98131bf9e9acdff611af098b656d
| 32.421769 | 123 | 0.623779 | 5.658986 | false | false | false | false |
Stitch7/mclient
|
mclient/PrivateMessages/_MessageKit/Views/MessageLabel.swift
|
1
|
16377
|
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
open class MessageLabel: UILabel {
// MARK: - Private Properties
private lazy var layoutManager: NSLayoutManager = {
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(self.textContainer)
return layoutManager
}()
private lazy var textContainer: NSTextContainer = {
let textContainer = NSTextContainer()
textContainer.lineFragmentPadding = 0
textContainer.maximumNumberOfLines = self.numberOfLines
textContainer.lineBreakMode = self.lineBreakMode
textContainer.size = self.bounds.size
return textContainer
}()
private lazy var textStorage: NSTextStorage = {
let textStorage = NSTextStorage()
textStorage.addLayoutManager(self.layoutManager)
return textStorage
}()
private lazy var rangesForDetectors: [DetectorType: [(NSRange, MessageTextCheckingType)]] = [:]
private var isConfiguring: Bool = false
// MARK: - Public Properties
open weak var delegate: MessageLabelDelegate?
open var enabledDetectors: [DetectorType] = [] {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var attributedText: NSAttributedString? {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var text: String? {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var font: UIFont! {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open override var textColor: UIColor! {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open override var lineBreakMode: NSLineBreakMode {
didSet {
textContainer.lineBreakMode = lineBreakMode
if !isConfiguring { setNeedsDisplay() }
}
}
open override var numberOfLines: Int {
didSet {
textContainer.maximumNumberOfLines = numberOfLines
if !isConfiguring { setNeedsDisplay() }
}
}
open override var textAlignment: NSTextAlignment {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open var textInsets: UIEdgeInsets = .zero {
didSet {
if !isConfiguring { setNeedsDisplay() }
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += textInsets.horizontal
size.height += textInsets.vertical
return size
}
internal var messageLabelFont: UIFont?
private var attributesNeedUpdate = false
public static var defaultAttributes: [NSAttributedString.Key: Any] = {
return [
NSAttributedString.Key.foregroundColor: UIColor.darkText,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.underlineColor: UIColor.darkText
]
}()
open internal(set) var addressAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var dateAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var phoneNumberAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var urlAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var transitInformationAttributes: [NSAttributedString.Key: Any] = defaultAttributes
public func setAttributes(_ attributes: [NSAttributedString.Key: Any], detector: DetectorType) {
switch detector {
case .phoneNumber:
phoneNumberAttributes = attributes
case .address:
addressAttributes = attributes
case .date:
dateAttributes = attributes
case .url:
urlAttributes = attributes
case .transitInformation:
transitInformationAttributes = attributes
}
if isConfiguring {
attributesNeedUpdate = true
} else {
updateAttributes(for: [detector])
}
}
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
// MARK: - Open Methods
open override func drawText(in rect: CGRect) {
let insetRect = rect.inset(by: textInsets)
textContainer.size = CGSize(width: insetRect.width, height: rect.height)
let origin = insetRect.origin
let range = layoutManager.glyphRange(for: textContainer)
layoutManager.drawBackground(forGlyphRange: range, at: origin)
layoutManager.drawGlyphs(forGlyphRange: range, at: origin)
}
// MARK: - Public Methods
public func configure(block: () -> Void) {
isConfiguring = true
block()
if attributesNeedUpdate {
updateAttributes(for: enabledDetectors)
}
attributesNeedUpdate = false
isConfiguring = false
setNeedsDisplay()
}
// MARK: - Private Methods
private func setTextStorage(_ newText: NSAttributedString?, shouldParse: Bool) {
guard let newText = newText, newText.length > 0 else {
textStorage.setAttributedString(NSAttributedString())
setNeedsDisplay()
return
}
let style = paragraphStyle(for: newText)
let range = NSRange(location: 0, length: newText.length)
let mutableText = NSMutableAttributedString(attributedString: newText)
mutableText.addAttribute(.paragraphStyle, value: style, range: range)
if shouldParse {
rangesForDetectors.removeAll()
let results = parse(text: mutableText)
setRangesForDetectors(in: results)
}
for (detector, rangeTuples) in rangesForDetectors {
if enabledDetectors.contains(detector) {
let attributes = detectorAttributes(for: detector)
rangeTuples.forEach { (range, _) in
mutableText.addAttributes(attributes, range: range)
}
}
}
let modifiedText = NSAttributedString(attributedString: mutableText)
textStorage.setAttributedString(modifiedText)
if !isConfiguring { setNeedsDisplay() }
}
private func paragraphStyle(for text: NSAttributedString) -> NSParagraphStyle {
guard text.length > 0 else { return NSParagraphStyle() }
var range = NSRange(location: 0, length: text.length)
let existingStyle = text.attribute(.paragraphStyle, at: 0, effectiveRange: &range) as? NSMutableParagraphStyle
let style = existingStyle ?? NSMutableParagraphStyle()
style.lineBreakMode = lineBreakMode
style.alignment = textAlignment
return style
}
private func updateAttributes(for detectors: [DetectorType]) {
guard let attributedText = attributedText, attributedText.length > 0 else { return }
let mutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
for detector in detectors {
guard let rangeTuples = rangesForDetectors[detector] else { continue }
for (range, _) in rangeTuples {
let attributes = detectorAttributes(for: detector)
mutableAttributedString.addAttributes(attributes, range: range)
}
let updatedString = NSAttributedString(attributedString: mutableAttributedString)
textStorage.setAttributedString(updatedString)
}
}
private func detectorAttributes(for detectorType: DetectorType) -> [NSAttributedString.Key: Any] {
switch detectorType {
case .address:
return addressAttributes
case .date:
return dateAttributes
case .phoneNumber:
return phoneNumberAttributes
case .url:
return urlAttributes
case .transitInformation:
return transitInformationAttributes
}
}
private func detectorAttributes(for checkingResultType: NSTextCheckingResult.CheckingType) -> [NSAttributedString.Key: Any] {
switch checkingResultType {
case .address:
return addressAttributes
case .date:
return dateAttributes
case .phoneNumber:
return phoneNumberAttributes
case .link:
return urlAttributes
case .transitInformation:
return transitInformationAttributes
default:
fatalError(MessageKitError.unrecognizedCheckingResult)
}
}
private func setupView() {
numberOfLines = 0
lineBreakMode = .byWordWrapping
}
// MARK: - Parsing Text
private func parse(text: NSAttributedString) -> [NSTextCheckingResult] {
guard enabledDetectors.isEmpty == false else { return [] }
let checkingTypes = enabledDetectors.reduce(0) { $0 | $1.textCheckingType.rawValue }
let detector = try? NSDataDetector(types: checkingTypes)
let range = NSRange(location: 0, length: text.length)
let matches = detector?.matches(in: text.string, options: [], range: range) ?? []
guard enabledDetectors.contains(.url) else {
return matches
}
// Enumerate NSAttributedString NSLinks and append ranges
var results: [NSTextCheckingResult] = matches
text.enumerateAttribute(NSAttributedString.Key.link, in: range, options: []) { value, range, _ in
guard let url = value as? URL else { return }
let result = NSTextCheckingResult.linkCheckingResult(range: range, url: url)
results.append(result)
}
return results
}
private func setRangesForDetectors(in checkingResults: [NSTextCheckingResult]) {
guard checkingResults.isEmpty == false else { return }
for result in checkingResults {
switch result.resultType {
case .address:
var ranges = rangesForDetectors[.address] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .addressComponents(result.addressComponents))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .address)
case .date:
var ranges = rangesForDetectors[.date] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .date(result.date))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .date)
case .phoneNumber:
var ranges = rangesForDetectors[.phoneNumber] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .phoneNumber(result.phoneNumber))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .phoneNumber)
case .link:
var ranges = rangesForDetectors[.url] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .link(result.url))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .url)
case .transitInformation:
var ranges = rangesForDetectors[.transitInformation] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .transitInfoComponents(result.components))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .transitInformation)
default:
fatalError("Received an unrecognized NSTextCheckingResult.CheckingType")
}
}
}
// MARK: - Gesture Handling
private func stringIndex(at location: CGPoint) -> Int? {
guard textStorage.length > 0 else { return nil }
var location = location
location.x -= textInsets.left
location.y -= textInsets.top
let index = layoutManager.glyphIndex(for: location, in: textContainer)
let lineRect = layoutManager.lineFragmentUsedRect(forGlyphAt: index, effectiveRange: nil)
var characterIndex: Int?
if lineRect.contains(location) {
characterIndex = layoutManager.characterIndexForGlyph(at: index)
}
return characterIndex
}
open func handleGesture(_ touchLocation: CGPoint) -> Bool {
guard let index = stringIndex(at: touchLocation) else { return false }
for (detectorType, ranges) in rangesForDetectors {
for (range, value) in ranges {
if range.contains(index) {
handleGesture(for: detectorType, value: value)
return true
}
}
}
return false
}
private func handleGesture(for detectorType: DetectorType, value: MessageTextCheckingType) {
switch value {
case let .addressComponents(addressComponents):
var transformedAddressComponents = [String: String]()
guard let addressComponents = addressComponents else { return }
addressComponents.forEach { (key, value) in
transformedAddressComponents[key.rawValue] = value
}
handleAddress(transformedAddressComponents)
case let .phoneNumber(phoneNumber):
guard let phoneNumber = phoneNumber else { return }
handlePhoneNumber(phoneNumber)
case let .date(date):
guard let date = date else { return }
handleDate(date)
case let .link(url):
guard let url = url else { return }
handleURL(url)
case let .transitInfoComponents(transitInformation):
var transformedTransitInformation = [String: String]()
guard let transitInformation = transitInformation else { return }
transitInformation.forEach { (key, value) in
transformedTransitInformation[key.rawValue] = value
}
handleTransitInformation(transformedTransitInformation)
}
}
private func handleAddress(_ addressComponents: [String: String]) {
delegate?.didSelectAddress(addressComponents)
}
private func handleDate(_ date: Date) {
delegate?.didSelectDate(date)
}
private func handleURL(_ url: URL) {
delegate?.didSelectURL(url)
}
private func handlePhoneNumber(_ phoneNumber: String) {
delegate?.didSelectPhoneNumber(phoneNumber)
}
private func handleTransitInformation(_ components: [String: String]) {
delegate?.didSelectTransitInformation(components)
}
}
private enum MessageTextCheckingType {
case addressComponents([NSTextCheckingKey: String]?)
case date(Date?)
case phoneNumber(String?)
case link(URL?)
case transitInfoComponents([NSTextCheckingKey: String]?)
}
|
mit
|
a354b0e30bef19c3ddb9e507fb1dcfed
| 33.550633 | 129 | 0.640777 | 5.437251 | false | false | false | false |
tutsplus/iOS-AVFoundation-FinishedProject
|
MP3Player/ViewController.swift
|
1
|
2250
|
//
// ViewController.swift
// MP3Player
//
// Created by James Tyner on 7/5/15.
// Copyright (c) 2015 James Tyner. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var mp3Player:MP3Player?
var timer:NSTimer?
@IBOutlet weak var trackName: UILabel!
@IBOutlet weak var trackTime: UILabel!
@IBOutlet weak var progressBar: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
mp3Player = MP3Player()
setupNotificationCenter()
updateViews()
setTrackName()
}
@IBAction func playSong(sender: AnyObject) {
mp3Player?.play()
startTimer()
}
@IBAction func stopSong(sender: AnyObject) {
mp3Player?.stop()
updateViews()
timer?.invalidate()
}
@IBAction func pauseSong(sender: AnyObject) {
mp3Player?.pause()
timer?.invalidate()
}
@IBAction func playNextSong(sender: AnyObject) {
mp3Player?.nextSong(false)
startTimer()
}
@IBAction func setVolume(sender: UISlider) {
mp3Player?.setVolume(sender.value)
}
@IBAction func playPreviousSong(sender: AnyObject) {
mp3Player?.previousSong()
startTimer()
}
func setTrackName(){
trackName.text = mp3Player?.getCurrentTrackName()
}
func setupNotificationCenter(){
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"setTrackName",
name:"SetTrackNameText",
object:nil)
}
func startTimer(){
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateViewsWithTimer:"), userInfo: nil, repeats: true)
}
func updateViewsWithTimer(theTimer: NSTimer){
updateViews()
}
func updateViews(){
trackTime.text = mp3Player?.getCurrentTimeAsString()
if let progress = mp3Player?.getProgress() {
progressBar.progress = progress
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
bsd-2-clause
|
a515e15d70f5efe9ae315c6c443dcc1b
| 22.684211 | 152 | 0.614667 | 4.746835 | false | false | false | false |
imindeu/iMindLib.swift
|
Tests/iMindLibTests/UIImageView+ExtensionsTests.swift
|
1
|
1109
|
//
// UIImageView+ExtensionsTests.swift
// iMindLib
//
// Created by David Frenkel on 28/02/2017.
// Copyright © 2017 iMind. All rights reserved.
//
#if !os(macOS) && !os(Linux) && !os(watchOS)
import XCTest
@testable import iMindLib
class UIImageViewExtensionsTests: XCTestCase {
func testFlash() {
let testImage = UIImage(named: "testImage.jpg", in: Bundle(for: type(of: self)), compatibleWith: nil)
let imageView = UIImageView(image: testImage)
imageView.flashView()
XCTAssertTrue(imageView.alpha <= 1 || imageView.alpha >= 0)
}
func testCircleShape() {
let defaultView = UIImageView()
let customView = UIImageView()
defaultView.circleShape()
customView.circleShape(bordered: false, borderColor: UIColor.red)
XCTAssertEqual(defaultView.layer.borderWidth, 2.5)
XCTAssertEqual(defaultView.layer.borderColor, UIColor.white.cgColor)
XCTAssertEqual(customView.layer.borderWidth, 0.0)
XCTAssertEqual(customView.layer.borderColor, UIColor.red.cgColor)
}
}
#endif
|
mit
|
b0329993b4bb04a8beecf7db6632aad0
| 28.157895 | 109 | 0.669675 | 4.19697 | false | true | false | false |
mattrajca/swift-corelibs-foundation
|
Foundation/URLSession/Message.swift
|
4
|
4201
|
// Foundation/URLSession/Message.swift - Message parsing for native protocols
//
// 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
extension _NativeProtocol {
/// A native protocol like FTP or HTTP header being parsed.
///
/// It can either be complete (i.e. the final CR LF CR LF has been
/// received), or partial.
internal enum _ParsedResponseHeader {
case partial(_ResponseHeaderLines)
case complete(_ResponseHeaderLines)
init() {
self = .partial(_ResponseHeaderLines())
}
}
/// A type safe wrapper around multiple lines of headers.
///
/// This can be converted into an `HTTPURLResponse`.
internal struct _ResponseHeaderLines {
let lines: [String]
init() {
self.lines = []
}
init(headerLines: [String]) {
self.lines = headerLines
}
}
}
extension _NativeProtocol._ParsedResponseHeader {
/// Parse a header line passed by libcurl.
///
/// These contain the <CRLF> ending and the final line contains nothing but
/// that ending.
/// - Returns: Returning nil indicates failure. Otherwise returns a new
/// `ParsedResponseHeader` with the given line added.
func byAppending(headerLine data: Data) -> _NativeProtocol._ParsedResponseHeader? {
// The buffer must end in CRLF
guard 2 <= data.count &&
data[data.endIndex - 2] == _Delimiters.CR &&
data[data.endIndex - 1] == _Delimiters.LF
else { return nil }
let lineBuffer = data.subdata(in: Range(data.startIndex..<data.endIndex-2))
guard let line = String(data: lineBuffer, encoding: String.Encoding.utf8) else { return nil}
return byAppending(headerLine: line)
}
/// Append a status line.
///
/// If the line is empty, it marks the end of the header, and the result
/// is a complete header. Otherwise it's a partial header.
/// - Note: Appending a line to a complete header results in a partial
/// header with just that line.
private func byAppending(headerLine line: String) -> _NativeProtocol._ParsedResponseHeader {
if line.isEmpty {
switch self {
case .partial(let header): return .complete(header)
case .complete: return .partial(_NativeProtocol._ResponseHeaderLines())
}
} else {
let header = partialResponseHeader
return .partial(header.byAppending(headerLine: line))
}
}
private var partialResponseHeader: _NativeProtocol._ResponseHeaderLines {
switch self {
case .partial(let header): return header
case .complete: return _NativeProtocol._ResponseHeaderLines()
}
}
}
private extension _NativeProtocol._ResponseHeaderLines {
/// Returns a copy of the lines with the new line appended to it.
func byAppending(headerLine line: String) -> _NativeProtocol._ResponseHeaderLines {
var l = self.lines
l.append(line)
return _NativeProtocol._ResponseHeaderLines(headerLines: l)
}
}
// Characters that we need for Header parsing:
struct _Delimiters {
/// *Carriage Return* symbol
static let CR: UInt8 = 0x0d
/// *Line Feed* symbol
static let LF: UInt8 = 0x0a
/// *Space* symbol
static let Space = UnicodeScalar(0x20)
static let HorizontalTab = UnicodeScalar(0x09)
static let Colon = UnicodeScalar(0x3a)
/// *Separators* according to RFC 2616
static let Separators = NSCharacterSet(charactersIn: "()<>@,;:\\\"/[]?={} \t")
}
|
apache-2.0
|
5d37c6fa3f131498749fde3e94f0ae15
| 37.190909 | 100 | 0.621281 | 4.678174 | false | false | false | false |
rjalkuino/youtubeApiSample
|
YTSample/YoutubeTableViewCell.swift
|
1
|
1022
|
//
// YoutubeTableViewCell.swift
// YTSample
//
// Created by robert john alkuino on 1/6/17.
// Copyright © 2017 thousandminds. All rights reserved.
//
import UIKit
import SDWebImage
class YoutubeTableViewCell: UITableViewCell {
let thumbnail = UIImageView()
let title = UILabel()
required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
thumbnail.frame = CGRect(x:10,y:10,width:100,height:80)
addSubview(thumbnail)
title.font = UIFont.boldSystemFont(ofSize: 20.0)
title.frame = CGRect(x:110,y:20,width:self.frame.width - 110,height:30)
addSubview(title)
}
func bind(cellInfo:YoutubeApiMapper) {
title.text = cellInfo.title
thumbnail.sd_setImage(with: NSURL(string: cellInfo.thumbnailUrl!) as URL!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
30ea18f0c306624a2539dadb91186da8
| 27.361111 | 83 | 0.666014 | 4.019685 | false | false | false | false |
skyfe79/TIL
|
about.iOS/about.AVFoundation/02_CustomVideoProcessing/CustomVideoProcessing/ViewController.swift
|
1
|
8162
|
//
// ViewController.swift
// CustomVideoProcessing
//
// Created by burt on 2016. 3. 27..
// Copyright © 2016년 BurtK. All rights reserved.
//
// @see https://www.invasivecode.com/weblog/a-quasi-real-time-video-processing-on-ios-in/
/**
To appreciate what we are going to do, we need to build a custom camera preview.
If we want to process a video buffer and show the result in real-time, we cannot use the
AVCaptureVideoPreviewLayer as shown in this post,
because that camera preview renders the signal directly and does not offer any way to process it, before the rendering.
To make this possible, you need to take the video buffer, process it and then render it on a custom CALayer.
Let’s see how to do that.
*/
import UIKit
import AVFoundation
import Accelerate
class ViewController: UIViewController {
lazy var cameraSession : AVCaptureSession = {
let s = AVCaptureSession()
if s.canSetSessionPreset(AVCaptureSessionPreset1280x720) {
s.sessionPreset = AVCaptureSessionPreset1280x720
} else if s.canSetSessionPreset(AVCaptureSessionPreset640x480) {
s.sessionPreset = AVCaptureSessionPreset640x480
} else {
s.sessionPreset = AVCaptureSessionPresetLow
}
return s
}()
lazy var previewLayer : AVCaptureVideoPreviewLayer = {
let preview = AVCaptureVideoPreviewLayer(session: self.cameraSession)
preview.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
// position을 설정해 주는 것. 중요하다. 아랫줄을 주석처리하고 실행해 보라.
preview.position = CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds))
preview.videoGravity = AVLayerVideoGravityResize
return preview
}()
lazy var customPreviewLayer: CALayer = {
let preview = CALayer()
// 중요! portrait 설정을 하는 방법을 보라
preview.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.height, height: self.view.bounds.width)
// position을 설정해 주는 것. 중요하다. 아랫줄을 주석처리하고 실행해 보라.
preview.position = CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds))
preview.setAffineTransform(CGAffineTransformMakeRotation(CGFloat(M_PI_2)))
return preview
}()
override func viewDidLoad() {
super.viewDidLoad()
setupCameraSession()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//view.layer.addSublayer(self.previewLayer)
view.layer.addSublayer(self.customPreviewLayer)
cameraSession.startRunning()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension ViewController {
func setupCameraSession() {
// 비디오를 캡쳐하는 기본 장치를 얻는다.
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) as AVCaptureDevice
do {
// 위에서 얻은 장치를 input 으로 만든다. 즉, 비디오 스트림을 방출하도록 만든다.
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
// 세션 설정 시작
cameraSession.beginConfiguration()
if cameraSession.canAddInput(deviceInput) {
cameraSession.addInput(deviceInput)
}
// 비디오 데이터의 출력 부분을 만든다.
// 출력이므로 픽셀포멧에 관한 설정이 필요하다
// 여기서는 YCbCr을 사용한다.
// @see https://en.wikipedia.org/wiki/YCbCr
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [ kCVPixelBufferPixelFormatTypeKey : UInt(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) ]
// 아주 중요한 설정이다.
// 간혹 비디오 프레임이 아주 느리게 나올 때가 있는데 그 때는 해당 프레임을 그냥 버리도록한다.
// 왜냐하면 그 프레임을 기다리면서 UI를 멈춰야 하기 때문이다.
dataOutput.alwaysDiscardsLateVideoFrames = true
if cameraSession.canAddOutput(dataOutput) == true {
cameraSession.addOutput(dataOutput)
}
// 세션 설정 종료
cameraSession.commitConfiguration()
// 카메라 프레임을 처리할 큐 설정
let queue = dispatch_queue_create("kr.pe.burt.videoQueue", DISPATCH_QUEUE_SERIAL)
dataOutput.setSampleBufferDelegate(self, queue: queue)
}
catch let error as NSError {
print("\(error), \(error.localizedDescription)")
}
}
}
extension ViewController : AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(captureOutput: AVCaptureOutput!, didDropSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
// discard되어 드롭된 프레임이 발생할 경우 호출된다.
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
// 비디오 영상의 각 프레임을 여기서 처리할 수 있다.
// 효과나 얼굴추출 그런 것들
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
// 이미지 버퍼 수정을 위해 Lock한다.
CVPixelBufferLockBaseAddress(imageBuffer, 0)
let width = CVPixelBufferGetWidthOfPlane(imageBuffer, 0)
let height = CVPixelBufferGetHeightOfPlane(imageBuffer, 0)
let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0)
// Remember the video buffer is in YUV format, so I extract the luma component from the buffer in this way:
let lumaBuffer = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)
let (processedBuffer, toReleaseData) = imageProcessing(lumaBuffer, width: width, height: height, bytesPerRow: bytesPerRow)
/**
Now, let’s render this buffer on the layer.
To do so, we need to use Core Graphics:
create a color space,
create a graphic context and render the buffer onto the graphic context using the created color space:
*/
let grayColorSpace = CGColorSpaceCreateDeviceGray()
let context = CGBitmapContextCreate(processedBuffer, width, height, 8, bytesPerRow, grayColorSpace, CGImageAlphaInfo.None.rawValue)
let dstImage = CGBitmapContextCreateImage(context)
/**
So, the dstImage is a Core Graphics image (CGImage), created from the captured buffer.
Finally, we render this image on the layer, changing its contents. We do that on the main queue:
*/
dispatch_sync(dispatch_get_main_queue()) { [weak self] in
self?.customPreviewLayer.contents = dstImage
}
free(toReleaseData)
}
}
extension ViewController {
func imageProcessing(lumaBuffer : UnsafeMutablePointer<Void>, width : Int, height : Int, bytesPerRow: Int) -> (UnsafeMutablePointer<Void>, UnsafeMutablePointer<Void>) {
var inImage = vImage_Buffer(data: lumaBuffer, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: bytesPerRow)
let outBuffer : UnsafeMutablePointer<Void> = calloc(width * height, sizeof(Pixel_8))
var outImage = vImage_Buffer(data: outBuffer, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: bytesPerRow)
let kernelSize = 7
vImageMin_Planar8(&inImage, &outImage, nil, 0, 0, vImagePixelCount(kernelSize), vImagePixelCount(kernelSize), vImage_Flags(kvImageDoNotTile))
return (outImage.data, outBuffer)
}
}
|
mit
|
2842e9a2e66388565b219bf1e413116b
| 40.872222 | 172 | 0.660475 | 4.123085 | false | false | false | false |
chenchangqing/travelMapMvvm
|
travelMapMvvm/travelMapMvvm/Views/Map/DistanceAnnotation.swift
|
1
|
1059
|
//
// DistanceAnnotation.swift
// travelMap
//
// Created by green on 15/7/23.
// Copyright (c) 2015年 com.city8. All rights reserved.
//
import UIKit
import MapKit
class DistanceAnnotation: MKPointAnnotation {
var distance: String!
init(latitude:CLLocationDegrees, longitude: CLLocationDegrees, distance: String) {
super.init()
super.coordinate = CLLocationCoordinate2DMake(latitude, longitude)
self.distance = distance
}
// MARK: - 重写比较方法
override func isEqual(object: AnyObject?) -> Bool {
if let object=object as? DistanceAnnotation {
if object.coordinate.latitude == self.coordinate.latitude && object.coordinate.longitude == self.coordinate.longitude {
return true
}
}
return false
}
override var hash: Int {
get {
return "\(self.coordinate.latitude)\(self.coordinate.longitude)".hash
}
}
}
|
apache-2.0
|
ec3c81f7d9be86641fb3920279baaf41
| 22.75 | 131 | 0.580861 | 4.906103 | false | false | false | false |
at-internet/atinternet-ios-swift-sdk
|
Tracker/Tracker/MediaPlayer.swift
|
1
|
4986
|
/*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// Player.swift
// Tracker
//
import UIKit
public class MediaPlayer {
/// Tracker instance
var tracker: Tracker
/// Player ID
public var playerId: Int = 1
/// List of videos attached to this player
public lazy var videos: Videos = Videos(player: self)
/// List of audios attached to this player
public lazy var audios: Audios = Audios(player: self)
/// List of live videos attached to this player
public lazy var liveVideos: LiveVideos = LiveVideos(player: self)
/// List of live audios attached to this player
public lazy var liveAudios: LiveAudios = LiveAudios(player: self)
/**
Players initializer
- parameter tracker: the tracker instance
- returns: Players instance
*/
init(tracker: Tracker) {
self.tracker = tracker
}
}
public class MediaPlayers {
/// Tracker instance
var tracker: Tracker
/// Player ids
lazy var playerIds: [Int: MediaPlayer] = [Int: MediaPlayer]()
/**
Players initializer
- parameter tracker: the tracker instance
- returns: Players instance
*/
init(tracker: Tracker) {
self.tracker = tracker
}
/**
Add a new ATMediaPlayer
- returns: ATMediaPlayer instance
*/
public func add() -> MediaPlayer {
let player = MediaPlayer(tracker: tracker)
if playerIds.count > 0 {
player.playerId = playerIds.keys.max()! + 1
} else {
player.playerId = 1
}
playerIds[player.playerId] = player
return player
}
/**
Add a new ATMediaPlayer
- parameter playerId: the player identifier
- returns: ATMediaPlayer instance
*/
public func add(_ playerId: Int) -> MediaPlayer {
if (playerIds.index(forKey: playerId) != nil) {
self.tracker.delegate?.warningDidOccur("A player with the same id already exists.")
return playerIds[playerId]!
} else {
let player = MediaPlayer(tracker: tracker)
player.playerId = playerId
playerIds[player.playerId] = player
return player
}
}
/**
Remove an ATMediaPlayer
- parameter playerId: the player identifier
*/
public func remove(_ playerId: Int) {
let player = playerIds[playerId]
if let player = player {
self.sendStops(player)
}
playerIds.removeValue(forKey: playerId)
}
/**
Remove all ATMediaPlayer
*/
public func removeAll() {
for (player) in self.playerIds.values {
self.sendStops(player)
}
playerIds.removeAll(keepingCapacity: false)
}
func sendStops(_ player: MediaPlayer) {
for (video) in (player.videos.list.values) {
if let timer = video.timer {
if (timer.isValid) {
video.sendStop()
}
}
}
for (audio) in (player.audios.list.values) {
if let timer = audio.timer {
if (timer.isValid) {
audio.sendStop()
}
}
}
for (liveVideo) in (player.liveVideos.list.values) {
if let timer = liveVideo.timer {
if (timer.isValid) {
liveVideo.sendStop()
}
}
}
for (liveAudio) in (player.liveAudios.list.values) {
if let timer = liveAudio.timer {
if (timer.isValid) {
liveAudio.sendStop()
}
}
}
}
}
|
mit
|
3cf13cff56a333b726045dc3e0f24990
| 27.318182 | 141 | 0.598716 | 4.783109 | false | false | false | false |
roecrew/AudioKit
|
AudioKit/Common/Playgrounds/Effects.playground/Pages/Ring Modulator.xcplaygroundpage/Contents.swift
|
2
|
2034
|
//: ## Ring Modulator
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var ringModulator = AKRingModulator(player)
ringModulator.frequency1 = 440 // Hz
ringModulator.frequency2 = 660 // Hz
ringModulator.balance = 0.5
ringModulator.mix = 0.5
AudioKit.output = ringModulator
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Ring Modulator")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: processingPlaygroundFiles))
addSubview(AKBypassButton(node: ringModulator))
addSubview(AKPropertySlider(
property: "Frequency 1",
format: "%0.2f Hz",
value: ringModulator.frequency1, minimum: 0.5, maximum: 8000,
color: AKColor.greenColor()
) { sliderValue in
ringModulator.frequency1 = sliderValue
})
addSubview(AKPropertySlider(
property: "Frequency 2",
format: "%0.2f Hz",
value: ringModulator.frequency2, minimum: 0.5, maximum: 8000,
color: AKColor.greenColor()
) { sliderValue in
ringModulator.frequency2 = sliderValue
})
addSubview(AKPropertySlider(
property: "Balance",
value: ringModulator.balance,
color: AKColor.redColor()
) { sliderValue in
ringModulator.balance = sliderValue
})
addSubview(AKPropertySlider(
property: "Mix",
value: ringModulator.mix,
color: AKColor.cyanColor()
) { sliderValue in
ringModulator.mix = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
|
mit
|
0ae3921f0a0a3e3166e3db12d0a0c79e
| 27.25 | 73 | 0.623402 | 5.034653 | false | false | false | false |
zapdroid/RXWeather
|
Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift
|
1
|
28351
|
//
// PrimitiveSequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Observable sequences containing 0 or 1 element.
public struct PrimitiveSequence<Trait, Element> {
fileprivate let source: Observable<Element>
init(raw: Observable<Element>) {
source = raw
}
}
/// Sequence containing exactly 1 element
public enum SingleTrait {}
/// Represents a push style sequence containing 1 element.
public typealias Single<Element> = PrimitiveSequence<SingleTrait, Element>
/// Sequence containing 0 or 1 elements
public enum MaybeTrait {}
/// Represents a push style sequence containing 0 or 1 element.
public typealias Maybe<Element> = PrimitiveSequence<MaybeTrait, Element>
/// Sequence containing 0 elements
public enum CompletableTrait {}
/// Represents a push style sequence containing 0 elements.
public typealias Completable = PrimitiveSequence<CompletableTrait, Swift.Never>
/// Observable sequences containing 0 or 1 element
public protocol PrimitiveSequenceType {
/// Additional constraints
associatedtype TraitType
/// Sequence element type
associatedtype ElementType
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
var primitiveSequence: PrimitiveSequence<TraitType, ElementType> { get }
}
extension PrimitiveSequence: PrimitiveSequenceType {
/// Additional constraints
public typealias TraitType = Trait
/// Sequence element type
public typealias ElementType = Element
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
public var primitiveSequence: PrimitiveSequence<TraitType, ElementType> {
return self
}
}
extension PrimitiveSequence: ObservableConvertibleType {
/// Type of elements in sequence.
public typealias E = Element
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
public func asObservable() -> Observable<E> {
return source
}
}
// <Single>
public enum SingleEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
}
extension PrimitiveSequenceType where TraitType == SingleTrait {
public typealias SingleObserver = (SingleEvent<ElementType>) -> Void
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping SingleObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case let .success(element):
observer.on(.next(element))
observer.on(.completed)
case let .error(error):
observer.on(.error(error))
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (SingleEvent<ElementType>) -> Void) -> Disposable {
var stopped = false
return primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case let .next(element):
observer(.success(element))
case let .error(error):
observer(.error(error))
case .completed:
rxFatalError("Singles can't emit a completion event")
}
}
}
/**
Subscribes a success handler, and an error handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
return primitiveSequence.subscribe { event in
switch event {
case let .success(element):
onSuccess?(element)
case let .error(error):
onError?(error)
}
}
}
}
// </Single>
// <Maybe>
public enum MaybeEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
public extension PrimitiveSequenceType where TraitType == MaybeTrait {
public typealias MaybeObserver = (MaybeEvent<ElementType>) -> Void
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping MaybeObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case let .success(element):
observer.on(.next(element))
observer.on(.completed)
case let .error(error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (MaybeEvent<ElementType>) -> Void) -> Disposable {
var stopped = false
return primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case let .next(element):
observer(.success(element))
case let .error(error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a success handler, an error handler, and a completion handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Disposable {
return primitiveSequence.subscribe { event in
switch event {
case let .success(element):
onSuccess?(element)
case let .error(error):
onError?(error)
case .completed:
onCompleted?()
}
}
}
}
// </Maybe>
// <Completable>
public enum CompletableEvent {
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
public extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Swift.Never {
public typealias CompletableObserver = (CompletableEvent) -> Void
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping CompletableObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case let .error(error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (CompletableEvent) -> Void) -> Disposable {
var stopped = false
return primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next:
rxFatalError("Completables can't emit values")
case let .error(error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a completion handler and an error handler for this sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onCompleted: (() -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
return primitiveSequence.subscribe { event in
switch event {
case let .error(error):
onError?(error)
case .completed:
onCompleted?()
}
}
}
}
// </Completable>
extension PrimitiveSequence {
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.deferred {
try observableFactory().asObservable()
})
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: Element) -> PrimitiveSequence<Trait, ElementType> {
return PrimitiveSequence(raw: Observable.just(element))
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> PrimitiveSequence<Trait, ElementType> {
return PrimitiveSequence(raw: Observable.just(element, scheduler: scheduler))
}
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.never())
}
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delaySubscription(dueTime, scheduler: scheduler))
}
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delay(dueTime, scheduler: scheduler))
}
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.do(
onNext: onNext,
onError: onError,
onCompleted: onCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (E) throws -> Bool)
-> Maybe<Element> {
return Maybe(raw: source.filter(predicate))
}
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<R>(_ transform: @escaping (E) throws -> R)
-> PrimitiveSequence<Trait, R> {
return PrimitiveSequence<Trait, R>(raw: source.map(transform))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<R>(_ selector: @escaping (ElementType) throws -> PrimitiveSequence<Trait, R>)
-> PrimitiveSequence<Trait, R> {
return PrimitiveSequence<Trait, R>(raw: source.flatMap(selector))
}
/**
Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription
actions have side-effects that require to be run on a scheduler, use `subscribeOn`.
- seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html)
- parameter scheduler: Scheduler to notify observers on.
- returns: The source sequence whose observations happen on the specified scheduler.
*/
public func observeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.observeOn(scheduler))
}
/**
Wraps the source sequence in order to run its subscription and unsubscription logic on the specified
scheduler.
This operation is not commonly used.
This only performs the side-effects of subscription and unsubscription on the specified scheduler.
In order to invoke observer callbacks on a `scheduler`, use `observeOn`.
- seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html)
- parameter scheduler: Scheduler to perform subscription and unsubscription actions on.
- returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.subscribeOn(scheduler))
}
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
public func catchError(_ handler: @escaping (Swift.Error) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.catchError { try handler($0).asObservable() })
}
/**
Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates.
If you encounter an error and want it to retry once, then you must use `retry(2)`
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to repeat the sequence.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
public func retry(_ maxAttemptCount: Int)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retry(maxAttemptCount))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Prints received events for all observers on standard output.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter identifier: Identifier that is printed together with event description to standard output.
- parameter trimOutput: Should output be trimmed to max 40 characters.
- returns: An observable sequence whose events are printed to standard output.
*/
public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function))
}
}
extension PrimitiveSequenceType where ElementType: SignedInteger {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
public static func timer(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable<ElementType>.timer(dueTime, scheduler: scheduler))
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> PrimitiveSequence<MaybeTrait, ElementType> {
return PrimitiveSequence(raw: Observable.empty())
}
}
extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never {
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> PrimitiveSequence<CompletableTrait, Never> {
return PrimitiveSequence(raw: Observable.empty())
}
}
extension ObservableType {
/**
The `asSingle` operator throws a `RxError.noElements` or `RxError.moreThanOneElement`
if the source Observable does not emit exactly one element before successfully completing.
- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)
- returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted.
*/
public func asSingle() -> Single<E> {
return PrimitiveSequence(raw: AsSingle(source: asObservable()))
}
/**
The `asMaybe` operator throws a ``RxError.moreThanOneElement`
if the source Observable does not emit at most one element before successfully completing.
- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)
- returns: An observable sequence that emits a single element, completes or throws an exception if more of them are emitted.
*/
public func asMaybe() -> Maybe<E> {
return PrimitiveSequence(raw: AsMaybe(source: asObservable()))
}
}
extension ObservableType where E == Never {
/**
- returns: An observable sequence that completes.
*/
public func asCompletable()
-> Completable {
return PrimitiveSequence(raw: asObservable())
}
}
|
mit
|
cc52ea5c50c0180362a3b8d956c6e336
| 42.085106 | 254 | 0.693086 | 5.199927 | false | false | false | false |
georgievtodor/ios
|
TV Show Calendar/TV Show Calendar/ViewControllers/FollowingTableViewController.swift
|
1
|
2104
|
import UIKit
class FollowingTableViewController: UITableViewController {
let reuseIdentifier = "Following Cell"
var data: LocalData?
var tvShows = [TvShowModelDelegate]() {
didSet {
tableView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
tvShows = [TvShowModelDelegate]()
data = LocalData()
tableView.dataSource = self
let followingTvShows = data?.getAll()
followingTvShows?.forEach {
tvShow in
let curr = TvShowModel(id: tvShow.id!, imagePath: tvShow.imagePath, backDropPath: tvShow.backDropPath, name: tvShow.name!, description: tvShow.tvDescription, rating: tvShow.rating)
tvShows.append(curr)
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nextVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TvShowVC") as! TvShowViewController
nextVC.tvShow = self.tvShows[indexPath.row]
self.show(nextVC, sender: self)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tvShows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = tableView.backgroundColor
let tvShow = tvShows[indexPath.row]
cell.imageView?.setImageFromUrl(imageUrl: URL(string: tvShow.imagePath!)!)
cell.textLabel?.text = tvShow.name
return cell
}
}
|
mit
|
c9f783cf70f62aa9d88662614ff1ba8a
| 32.935484 | 192 | 0.657795 | 5.082126 | false | false | false | false |
cikelengfeng/HTTPIDL
|
HTTPIDLDemo/HTTPIDLDemoTests/HTTPIDLDemoTests.swift
|
1
|
28518
|
//
// HTTPIDLDemoTests.swift
// HTTPIDLDemoTests
//
// Created by 徐 东 on 2017/1/11// Copyright © 2017年 dx lab. All rights reserved//
import XCTest
import HTTPIDL
struct TestRequest: Request {
public static var defaultMethod: String = "GET"
var method: String = TestRequest.defaultMethod
var _config: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _config else {
return BaseRequestConfiguration.create(from: BaseRequestManagerConfiguration.shared, request: self)
}
return config
}
set {
_config = newValue
}
}
var uri: String = "/my/test"
var content: RequestContent?
init(content: RequestContent?) {
self.content = content
}
}
struct TestHTTPRequest: HTTPRequest {
var chunkedTransfer: Bool?
static let stub = TestHTTPRequest(method: "GET", url: URL(fileURLWithPath: "xxxx"), headers: [:], bodyStream: nil)
var method: String
var headers: [String: String]
var url: URL
var bodyStream: InputStream?
var cachePolicy: URLRequest.CachePolicy?
var networkServiceType: URLRequest.NetworkServiceType?
var timeoutInterval: TimeInterval?
var shouldUsePipelining: Bool?
var shouldHandleCookies: Bool?
var allowsCellularAccess: Bool?
init(method: String, url: URL, headers: [String: String], bodyStream: InputStream?) {
self.method = method
self.url = url
self.headers = headers
self.bodyStream = bodyStream
}
}
struct TestResponse: HTTPResponse {
var bodyStream: OutputStream?
static let empty = TestResponse(statusCode: 200, headers: [:], bodyStream: nil, request: TestHTTPRequest.stub)
var statusCode: Int
var headers: [String: String]
var request: HTTPRequest
init(statusCode: Int, headers: [String: String], bodyStream: OutputStream?, request: HTTPRequest) {
self.statusCode = statusCode
self.headers = headers
self.bodyStream = bodyStream
self.request = request
}
}
class HTTPIDLDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
BaseRequestManagerConfiguration.shared.baseURLString = "http://api.everphoto.cn"
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testURLEncodedQueryRequest() {
let encoder = URLEncodedQueryEncoder.shared
var testRequest = TestRequest(content: RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64)))
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持int64型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 12312313)
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持int32型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: false)
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持bool型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 0.22)
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持double型的根参数")
} catch _ {
}
testRequest.content = RequestContent.string(value: "yyyy")
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持string型的根参数")
} catch _ {
}
testRequest.content = RequestContent.file(value: URL(fileURLWithPath: "xxx"), fileName: nil, mimeType: "image/*")
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持file型的根参数")
} catch _ {
}
testRequest.content = RequestContent.data(value: Data(), fileName: "xxx", mimeType: "image/jpeg")
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持data型的根参数")
} catch _ {
}
testRequest.content = RequestContent.array(value: [RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64))])
do {
let _ = try encoder.encode(testRequest)
XCTFail("url encode 不支持array型的根参数")
} catch _ {
}
let fileURL = URL(fileURLWithPath: "xxx")
let dataString = "xxxxx"
let data = dataString.data(using: String.Encoding.utf8)!
testRequest.content = RequestContent.dictionary(value: [
"int32": RequestContent.number(value: 123123),
"int64": RequestContent.number(value: NSNumber(value: 12312312312312 as Int64)),
"bool": RequestContent.number(value: true),
"double": RequestContent.number(value: 0.023131),
"string": RequestContent.string(value: "hey"),
"file": RequestContent.file(value: fileURL, fileName: nil, mimeType: "image/*"),
"data": RequestContent.data(value: data, fileName: "xxx", mimeType: "image/jpeg"),
"array": RequestContent.array(value: [
RequestContent.number(value: 123123),
RequestContent.number(value: NSNumber(value: 12312312312312 as Int64)),
RequestContent.number(value: true),
RequestContent.number(value: 0.023131),
RequestContent.string(value: "hey"),
RequestContent.file(value: fileURL, fileName: nil, mimeType: "image/*"),
RequestContent.data(value: data, fileName: "xxx", mimeType: "image/jpeg")
])
])
do {
let encoded = try encoder.encode(testRequest)
guard let int32 = encoded.url.obtainFirstQuery(for: "int32") else {
XCTFail()
return
}
XCTAssert(int32 == "123123")
guard let int64 = encoded.url.obtainFirstQuery(for: "int64") else {
XCTFail()
return
}
XCTAssert(int64 == "12312312312312")
guard let bool = encoded.url.obtainFirstQuery(for: "bool") else {
XCTFail()
return
}
XCTAssert(bool == "1")
guard let double = encoded.url.obtainFirstQuery(for: "double") else {
XCTFail()
return
}
XCTAssert(double == "0.023131")
guard let string = encoded.url.obtainFirstQuery(for: "string") else {
XCTFail()
return
}
XCTAssert(string == "hey")
guard let file = encoded.url.obtainFirstQuery(for: "file") else {
XCTFail()
return
}
XCTAssert(file == fileURL.absoluteString)
guard let data = encoded.url.obtainFirstQuery(for: "data") else {
XCTFail()
return
}
XCTAssert(data == dataString)
let array = encoded.url.obtainQuery(for: "array")
XCTAssert(array[0] == "123123")
XCTAssert(array[1] == "12312312312312")
XCTAssert(array[2] == "1")
XCTAssert(array[3] == "0.023131")
XCTAssert(array[4] == "hey")
XCTAssert(array[5] == fileURL.absoluteString)
XCTAssert(array[6] == dataString)
} catch _ {
XCTFail()
}
}
func testJSONEncoder() {
let encoder = JSONEncoder.shared
var testRequest = TestRequest(content: RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64)))
do {
let _ = try encoder.encode(testRequest)
XCTFail("json encode 不支持int64型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 12312313)
do {
let _ = try encoder.encode(testRequest)
XCTFail("json encode 不支持int32型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: false)
do {
let _ = try encoder.encode(testRequest)
XCTFail("json encode 不支持bool型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 0.22)
do {
let _ = try encoder.encode(testRequest)
XCTFail("json encode 不支持double型的根参数")
} catch _ {
}
testRequest.content = RequestContent.string(value: "yyyy")
do {
let _ = try encoder.encode(testRequest)
XCTFail("json encode 不支持string型的根参数")
} catch _ {
}
testRequest.content = RequestContent.file(value: URL(fileURLWithPath: "xxx"), fileName: nil, mimeType: "image/*")
do {
let _ = try encoder.encode(testRequest)
XCTFail("json encode 不支持file型的根参数")
} catch _ {
}
testRequest.content = RequestContent.data(value: Data(), fileName: "xxx", mimeType: "image/jpeg")
do {
let _ = try encoder.encode(testRequest)
XCTFail("json encode 不支持data型的根参数")
} catch _ {
}
testRequest.content = RequestContent.array(value: [
RequestContent.number(value: 123123),
RequestContent.number(value: NSNumber(value: 12312312312312 as Int64)),
RequestContent.number(value: true),
RequestContent.number(value: 0.023131),
RequestContent.string(value: "hey")
])
do {
let encoded = try encoder.encode(testRequest)
let jsonObject = try JSONSerialization.jsonObject(with: encoded.bodyStream!.data(), options: .allowFragments)
guard let array = jsonObject as? [Any] else {
XCTFail()
return
}
guard let int32 = array[0] as? Int32, int32 == 123123 else {
XCTFail()
return
}
guard let int64 = array[1] as? Int64, int64 == 12312312312312 else {
XCTFail()
return
}
guard let bool = array[2] as? Bool, bool else {
XCTFail()
return
}
guard let double = array[3] as? Double, double == 0.023131 else {
XCTFail()
return
}
guard let string = array[4] as? String, string == "hey" else {
XCTFail()
return
}
}catch _ {
XCTFail()
}
}
func testURLEncodedFormEncoder() {
let encoder = URLEncodedFormEncoder.shared
var testRequest = TestRequest(content: RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64)))
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持int64型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 12312313)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持int32型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: false)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持bool型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 0.22)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持double型的根参数")
} catch _ {
}
testRequest.content = RequestContent.string(value: "yyyy")
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持string型的根参数")
} catch _ {
}
testRequest.content = RequestContent.file(value: URL(fileURLWithPath: "xxx"), fileName: nil, mimeType: "image/*")
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持file型的根参数")
} catch _ {
}
testRequest.content = RequestContent.data(value: Data(), fileName: "xxx", mimeType: "image/jpeg")
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持data型的根参数")
} catch _ {
}
testRequest.content = RequestContent.array(value: [RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64))])
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("url encode 不支持array型的根参数")
} catch _ {
}
let fileURL = URL(fileURLWithPath: "xxx")
let dataString = "xxxxx"
let data = dataString.data(using: String.Encoding.utf8)!
testRequest.content = RequestContent.dictionary(value: [
"int32": RequestContent.number(value: 123123),
"int64": RequestContent.number(value: NSNumber(value: 12312312312312 as Int64)),
"bool": RequestContent.number(value: true),
"double": RequestContent.number(value: 0.023131),
"string": RequestContent.string(value: "hey"),
"string1": RequestContent.string(value: "hey+jude"),
"stri+ng2": RequestContent.string(value: "hey+jude"),
"stri+ng3": RequestContent.string(value: "hey jude"),
"stri ng4": RequestContent.string(value: "hey jude"),
"file": RequestContent.file(value: fileURL, fileName: nil, mimeType: "image/*"),
"data": RequestContent.data(value: data, fileName: "xxx", mimeType: "image/jpeg"),
"array": RequestContent.array(value: [
RequestContent.number(value: 123123),
RequestContent.number(value: NSNumber(value: 12312312312312 as Int64)),
RequestContent.number(value: true),
RequestContent.number(value: 0.023131),
RequestContent.string(value: "hey"),
RequestContent.file(value: fileURL, fileName: nil, mimeType: "image/*"),
RequestContent.data(value: data, fileName: "xxx", mimeType: "image/jpeg")
])
])
do {
let encoded = try encoder.encode(testRequest)
let formData = encoded.bodyStream!.data()
let formString = String(data: formData, encoding: String.Encoding.utf8)!
let formPairs = formString.components(separatedBy: "&").map({ (kvString) -> (String, String) in
let components = kvString.components(separatedBy: "=")
return (components[0], components[1])
})
let formDict = formPairs.reduce([String: Any](), { (soFar, soGood) in
var ret = soFar
if let exists = ret[soGood.0] {
var arr = [soGood.1]
if let exists = exists as? [String] {
ret[soGood.0] = exists + arr
} else if let exists = exists as? String {
arr.insert(exists, at: 0)
ret[soGood.0] = arr
}
} else {
ret[soGood.0] = soGood.1
}
return ret
})
guard let int32 = formDict["int32"] as? String else {
XCTFail()
return
}
XCTAssert(int32 == "123123")
guard let int64 = formDict["int64"] as? String else {
XCTFail()
return
}
XCTAssert(int64 == "12312312312312")
guard let double = formDict["double"] as? String else {
XCTFail()
return
}
XCTAssert(double == "0.023131")
guard let string = formDict["string"] as? String else {
XCTFail()
return
}
XCTAssert(string == "hey")
guard let string1 = formDict["string1"] as? String else {
XCTFail()
return
}
XCTAssert(string1 == "hey%2Bjude")
guard let string2 = formDict["stri%2Bng2"] as? String else {
XCTFail()
return
}
XCTAssert(string2 == "hey%2Bjude")
guard let string3 = formDict["stri%2Bng3"] as? String else {
XCTFail()
return
}
XCTAssert(string3 == "hey+jude")
guard let string4 = formDict["stri+ng4"] as? String else {
XCTFail()
return
}
XCTAssert(string4 == "hey+jude")
guard let file = formDict["file"] as? String else {
XCTFail()
return
}
XCTAssert(file == fileURL.absoluteString)
guard let data = formDict["data"] as? String else {
XCTFail()
return
}
XCTAssert(data == dataString)
guard let array = formDict["array"] as? [String] else {
XCTFail()
return
}
XCTAssert(array[0] == "123123")
XCTAssert(array[1] == "12312312312312")
XCTAssert(array[2] == "1")
XCTAssert(array[3] == "0.023131")
XCTAssert(array[4] == "hey")
XCTAssert(array[5] == fileURL.absoluteString)
XCTAssert(array[6] == dataString)
} catch _ {
XCTFail()
}
}
func testJSONDecoder() {
let decoder = HTTPIDL.JSONDecoder()
let jsonDict: [String : Any] = ["number": 123, "bool": true, "string": "hey jude", "array": [1, 2], "dict": ["foo": "bar"]]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])
let outputStream = decoder.outputStream!
outputStream.open()
try! jsonData.writeTo(stream: outputStream)
outputStream.close()
let testResponse = TestResponse(statusCode: 200, headers: [:], bodyStream: outputStream, request: TestHTTPRequest.stub)
do {
guard let responseContent = try decoder.decode(testResponse) else {
XCTFail()
return
}
guard case .dictionary(let dict) = responseContent else {
XCTFail()
return
}
guard let number = dict["number"], case .number(let intValue) = number, intValue == 123 else {
XCTFail()
return
}
guard let bool = dict["bool"], case .number(let boolValue) = bool, boolValue.boolValue else {
XCTFail()
return
}
guard let string = dict["string"], case .string(let stringValue) = string, stringValue == "hey jude" else {
XCTFail()
return
}
guard let array = dict["array"], case .array(let arrayValue) = array else {
XCTFail()
return
}
guard case .number(let intInArr0) = arrayValue[0], intInArr0 == 1 else {
XCTFail()
return
}
guard case .number(let intInArr1) = arrayValue[1], intInArr1 == 2 else {
XCTFail()
return
}
guard let innerDict = dict["dict"], case .dictionary(let dictValue) = innerDict else {
XCTFail()
return
}
guard let foo = dictValue["foo"] else {
XCTFail()
return
}
guard case .string(let bar) = foo, bar == "bar" else {
XCTFail()
return
}
} catch _ {
XCTFail()
}
}
func testMultipartFormEncoder() {
let encoder = MultipartEncoder.shared
var testRequest = TestRequest(content: RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64)))
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持int64型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 12312313)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持int32型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: false)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持bool型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 0.22)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持double型的根参数")
} catch _ {
}
testRequest.content = RequestContent.string(value: "yyyy")
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持string型的根参数")
} catch _ {
}
testRequest.content = RequestContent.file(value: URL(fileURLWithPath: "xxx"), fileName: nil, mimeType: "image/*")
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持file型的根参数")
} catch _ {
}
testRequest.content = RequestContent.data(value: Data(), fileName: "xxx", mimeType: "image/jpeg")
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持data型的根参数")
} catch _ {
}
testRequest.content = RequestContent.array(value: [RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64))])
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持array型的根参数")
} catch _ {
}
let dataString = "xxxxx"
let data = dataString.data(using: String.Encoding.utf8)!
testRequest.content = RequestContent.dictionary(value: [
"number": RequestContent.number(value: NSNumber(value: 123123123123 as Int64)),
"bool": RequestContent.number(value: false),
"string": RequestContent.string(value: "yellow submarine"),
"file": RequestContent.file(value: Bundle.main.url(forResource: "China", withExtension: "png")!, fileName: "test_file", mimeType: "image/png"),
"data": RequestContent.data(value: data, fileName: "test_data", mimeType: "text/plain")
])
do {
let encoded = try encoder.encode(testRequest)
let body = encoded.bodyStream!.data()
XCTAssert(body.count == 46929)
} catch _ {
XCTFail()
}
}
func testBinaryEncoder() {
let encoder = BinaryEncoder.shared
var testRequest = TestRequest(content: RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64)))
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("binary encode 不支持int64型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 12312313)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("binary encode 不支持int32型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: false)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("binary encode 不支持bool型的根参数")
} catch _ {
}
testRequest.content = RequestContent.number(value: 0.22)
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("binary encode 不支持double型的根参数")
} catch _ {
}
testRequest.content = RequestContent.string(value: "yyyy")
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("binary encode 不支持string型的根参数")
} catch _ {
}
testRequest.content = RequestContent.array(value: [RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64))])
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持array型的根参数")
} catch _ {
}
testRequest.content = RequestContent.dictionary(value: ["xxx": RequestContent.number(value: NSNumber(value: 12312312312321313 as Int64))])
do {
let _ = try encoder.encode(testRequest).bodyStream!.data()
XCTFail("multipart encode 不支持dictionary型的根参数")
} catch _ {
}
let url = Bundle.main.url(forResource: "China", withExtension: "png")!
testRequest.content = RequestContent.file(value: url, fileName: "test_file", mimeType: "image/png")
do {
let encoded = try encoder.encode(testRequest)
let body = encoded.bodyStream!.data()
let data = try! Data(contentsOf: url)
XCTAssert(body.count == data.count)
} catch _ {
XCTFail()
}
let dataString = "xxxxx"
let data = dataString.data(using: String.Encoding.utf8)!
testRequest.content = RequestContent.data(value: data, fileName: "test_data", mimeType: "text/plain")
do {
let encoded = try encoder.encode(testRequest)
let body = encoded.bodyStream!.data()
XCTAssert(body.count == 5)
} catch _ {
XCTFail()
}
}
}
|
mit
|
829f47c2fd1f916dfb9941864fe24666
| 37.97067 | 173 | 0.516396 | 4.957889 | false | true | false | false |
fitpay/fitpay-ios-sdk
|
FitpaySDK/PaymentDevice/EventListeners/FitpayEventBinding.swift
|
1
|
923
|
import Foundation
open class FitpayEventBinding: NSObject {
open var eventId: FitpayEventTypeProtocol
open var listener: FitpayEventListener
private static var bindingIdCounter = 0
private let bindingId: Int
public init(eventId: FitpayEventTypeProtocol, listener: FitpayEventListener) {
self.eventId = eventId
self.listener = listener
bindingId = FitpayEventBinding.bindingIdCounter
FitpayEventBinding.bindingIdCounter += 1
super.init()
}
override open func isEqual(_ object: Any?) -> Bool {
return bindingId == (object as? FitpayEventBinding)?.bindingId
}
}
extension FitpayEventBinding: FitpayEventListener {
public func dispatchEvent(_ event: FitpayEvent) {
listener.dispatchEvent(event)
}
public func invalidate() {
listener.invalidate()
}
}
|
mit
|
a5742e54890ba99d02afd62ec39fe983
| 23.289474 | 82 | 0.654388 | 5.156425 | false | false | false | false |
AlesTsurko/AudioKit
|
Tests/Tests/AKVariableFrequencyResponseBandPassFilter.swift
|
2
|
2118
|
//
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/22/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: Float = 10.0
class Instrument : AKInstrument {
var auxilliaryOutput = AKAudio()
override init() {
super.init()
let oscillator = AKFMOscillator()
auxilliaryOutput = AKAudio.globalParameter()
assignOutput(auxilliaryOutput, to:oscillator)
}
}
class Processor : AKInstrument {
init(audioSource: AKAudio) {
super.init()
let cutoffFrequency = AKLine(firstPoint: 220.ak, secondPoint: 3000.ak, durationBetweenPoints: testDuration.ak)
let bandwidth = AKLine(firstPoint: 10.ak, secondPoint: 100.ak, durationBetweenPoints: testDuration.ak)
let variableFrequencyResponseBandPassFilter = AKVariableFrequencyResponseBandPassFilter(audioSource: audioSource)
variableFrequencyResponseBandPassFilter.cutoffFrequency = cutoffFrequency
variableFrequencyResponseBandPassFilter.bandwidth = bandwidth
variableFrequencyResponseBandPassFilter.scalingFactor = AKVariableFrequencyResponseBandPassFilter.scalingFactorPeak()
let balance = AKBalance(input: variableFrequencyResponseBandPassFilter, comparatorAudioSource: audioSource)
setAudioOutput(balance)
enableParameterLog(
"Cutoff Frequency = ",
parameter: variableFrequencyResponseBandPassFilter.cutoffFrequency,
timeInterval:0.1
)
enableParameterLog(
"Bandwidth = ",
parameter: variableFrequencyResponseBandPassFilter.bandwidth,
timeInterval:0.1
)
resetParameter(audioSource)
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
let processor = Processor(audioSource: instrument.auxilliaryOutput)
AKOrchestra.addInstrument(instrument)
AKOrchestra.addInstrument(processor)
processor.play()
instrument.play()
let manager = AKManager.sharedManager()
while(manager.isRunning) {} //do nothing
println("Test complete!")
|
lgpl-3.0
|
18ab807719a766c065a099bb63ce079a
| 29.257143 | 125 | 0.72899 | 5.295 | false | true | false | false |
ObjectAlchemist/OOUIKit
|
Sources/View/Basic/ViewImageButton.swift
|
1
|
1761
|
//
// ViewImageButton.swift
// OOSwift
//
// Created by Karsten Litsche on 01.09.17.
//
//
import UIKit
import OOBase
import OOFoundation
/**
A view displaying an image button with an action.
When trigger the button interaction after deallocating this object it will crash (objc compatibility issue)!
Hint: Use edgeInsets e.g. UIEdgeInsets(10, 10, 10. 10) to shorten image draw area. This results in a larger tap area.
*/
public final class ViewImageButton: OOView {
// MARK: init
public init(image: OOImage, action: OOExecutable, tintColor: OOColor, edgeInsets: UIEdgeInsets = UIEdgeInsets.zero) {
self.image = image
self.action = DoObjC(action) // encapsulate it so we can use it as selector
self.tintColor = tintColor
self.edgeInsets = edgeInsets
}
// MARK: protocol OOView
private var _ui: UIButton?
public var ui: UIView {
if _ui == nil { _ui = createView() }
return _ui!
}
public func setNeedsRefresh() {
if _ui != nil { update(button: _ui!) }
_ui?.setNeedsLayout()
}
// MARK: private
private let image: OOImage
private let action: DoObjC
private let tintColor: OOColor
private let edgeInsets: UIEdgeInsets
private func createView() -> UIButton {
let button = UIButton(type: .custom)
button.addTarget(action, action: #selector(DoObjC.execute), for: .touchUpInside)
button.imageEdgeInsets = edgeInsets
update(button: button)
return button
}
private func update(button: UIButton) {
button.setImage(image.ui, for: .normal)
button.tintColor = tintColor.value // if not set, self defined image will be blue
}
}
|
mit
|
8aec7789262e509233bc0aef6439f64c
| 26.952381 | 121 | 0.645088 | 4.358911 | false | false | false | false |
YifengBai/YuDou
|
YuDou/YuDou/Classes/Home/ViewModel/AmuseViewModel.swift
|
1
|
1036
|
//
// AmuseViewModel.swift
// YuDou
//
// Created by Bemagine on 2017/1/22.
// Copyright © 2017年 bemagine. All rights reserved.
//
import UIKit
class AmuseViewModel : BaseViewModel {
var identification: String?
}
extension AmuseViewModel {
func loadAmuseData(finishedCallback: @escaping () -> ()) {
let urlString = "api/homeCate/getHotRoom"
let params = ["identification" : identification ?? "", "client_sys" : "ios"]
NetWorkTools.loadData(URLString: urlString, params: params) { (reponse) in
guard let resultDict = reponse as? [String : Any] else { return }
guard let dataArray = resultDict["data"] as? [[String : Any]] else { return }
for dict in dataArray {
let groupModel = BaseGroupRoomModel(dict: dict)
self.groupData.append(groupModel)
}
finishedCallback()
}
}
}
|
mit
|
7957ed6f0d9633bd67b1c63a91a9c35c
| 24.195122 | 89 | 0.54211 | 4.782407 | false | false | false | false |
mattiasjahnke/arduino-projects
|
matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/OrderedCallbacker.swift
|
1
|
3169
|
//
// OrderedCallbacker.swift
// Flow
//
// Created by Måns Bernhardt on 2017-01-19.
// Copyright © 2017 iZettle. All rights reserved.
//
import Foundation
/// OrderedCallbacker holds a list of callbacks that can be call backed ordered by a provided `OrderedValue` value
/// A callback won't be called until the previous callback's returned future has completed
/// Use `addCallback` to register a new callback and orderedValue, and dispose the returned `Disposable` to unregister.
/// - Note: Is thread safe.
public final class OrderedCallbacker<OrderedValue, CallbackValue> {
private var callbacks: [Key : (OrderedValue, (CallbackValue) -> Future<()>)] = [:]
private var _mutex = pthread_mutex_t()
private var mutex: PThreadMutex { return PThreadMutex(&_mutex) }
public init() {
mutex.initialize()
}
deinit {
mutex.deinitialize()
}
/// - Returns: True if no callbacks has been registered.
public var isEmpty: Bool {
return mutex.protect { callbacks.isEmpty }
}
/// Register a callback and orderedValue to be called when `callAll` is executed.
/// - Parameter callback: The next callback won't be called until `callback` return `Future` completes
/// - Parameter orderedValue: The value used to order this callback
/// - Returns: A `Disposable` to be disposed to unregister the callback.
public func addCallback(_ callback: @escaping (CallbackValue) -> Future<()>, orderedBy orderedValue: OrderedValue) -> Disposable {
return mutex.protect {
let key = generateKey()
callbacks[key] = (orderedValue, callback)
return Disposer {
self.mutex.protect { self.callbacks[key] = nil }
}
}
}
/// Will call all registered callbacks with `value` in the order set by `isOrderedBefore`
/// - Returns: A `Future` that will complete when all callbacks has been called.
@discardableResult
public func callAll(with value: CallbackValue, isOrderedBefore: (OrderedValue, OrderedValue) -> Bool) -> Future<()> {
return mutex.protect {
callbacks.values.sorted { isOrderedBefore($0.0, $1.0) }.map { $1 }
}.mapToFuture { $0(value) }.toVoid()
}
}
public extension OrderedCallbacker {
/// Register a callback and orderedValue to be called when `callAll` is executed.
/// - Parameter orderedValue: The value used to order this callback
/// - Returns: A `Disposable` to be disposed to unregister the callback.
func addCallback(_ callback: @escaping (CallbackValue) -> Void, orderedBy orderedValue: OrderedValue) -> Disposable {
return addCallback({ v -> Future<()> in callback(v); return Future() }, orderedBy: orderedValue)
}
}
public extension OrderedCallbacker where OrderedValue: Comparable {
/// Will call all registered callbacks with `value` in the order set by `Comparable`
/// - Returns: A `Future` that will complete when all callbacks has been called.
@discardableResult
public func callAll(with value: CallbackValue) -> Future<()> {
return callAll(with: value, isOrderedBefore: <)
}
}
|
mit
|
81b9287e17f173c615a8fd3ecdb319c0
| 41.226667 | 134 | 0.674455 | 4.466855 | false | false | false | false |
vanyaland/Tagger
|
Tagger/Sources/Common/Helpers/WebService/Flickr/API/FlickrApiClient+Constants.swift
|
1
|
6869
|
/**
* Copyright (c) 2016 Ivan Magda
*
* 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
// MARK: FlickrApiClient (Constants)
extension FlickrApiClient {
typealias SearchCoordinateRange = (start: Double, end: Double)
// MARK: - Constants
struct Constants {
struct Flickr {
static let baseURL = "https://api.flickr.com/services/rest"
static let searchBBoxHalfWidth = 1.0
static let searchBBoxHalfHeight = 1.0
static let searchLatRange = SearchCoordinateRange(start: -90.0, end: 90.0)
static let searchLonRange = SearchCoordinateRange(start: -180.0, end: 180.0)
}
// MARK: - Params -
struct Params {
struct Keys {
static let method = "method"
static let apiKey = "api_key"
static let galleryId = "gallery_id"
static let extras = "extras"
static let format = "format"
static let noJSONCallback = "nojsoncallback"
static let safeSearch = "safe_search"
static let text = "text"
static let page = "page"
static let perPage = "per_page"
static let period = "period"
static let count = "count"
static let contentType = "content_type"
static let tag = "tag"
static let tags = "tags"
static let userId = "user_id"
}
struct Values {
static let apiKey = Tagger.Constants.Flickr.applicationKey
static let responseFormat = "json"
static let disableJSONCallback = "1"
static let searchMethod = "flickr.photos.search"
static let tagsHotList = "flickr.tags.getHotList"
static let tagsGetRelated = "flickr.tags.getRelated"
static let galleryPhotosMethod = "flickr.galleries.getPhotos"
static let testLogin = "flickr.test.login"
static let peopleGetInfo = "flickr.people.getInfo"
static let thumbnailURL = "url_t"
static let smallURL = "url_s"
static let mediumURL = "url_m"
static let useSafeSearch = "1"
static let dayPeriod = "day"
static let weekPeriod = "week"
static let perPageDefault = 100
static let perPageMax = 500
enum ContentType: Int {
case photos = 1
case screenshots
case other
}
}
}
struct Response {
struct Keys {
static let status = "stat"
static let photos = "photos"
static let photo = "photo"
static let id = "id"
static let NSID = "nsid"
static let title = "title"
static let thumbnailURL = "url_t"
static let smallURL = "url_s"
static let mediumURL = "url_m"
static let page = "page"
static let pages = "pages"
static let perPage = "perpage"
static let total = "total"
static let hotTags = "hottags"
static let tag = "tag"
static let tags = "tags"
static let owner = "owner"
static let secret = "secret"
static let server = "server"
static let farm = "farm"
static let score = "score"
static let content = "_content"
static let userID = "user_id"
static let iconServer = "iconserver"
static let iconFarm = "iconfarm"
static let username = "username"
static let realName = "realname"
static let person = "person"
}
struct Values {
static let okStatus = "ok"
}
}
// MARK: - Errors -
struct Error {
// MARK: Domains & Code
static let ErrorDomain = "\(Tagger.Constants.Error.baseDomain).FlickrApiClient"
static let ErrorCode = 300
static let NumberOfPagesForPhotoSearchErrorDomain = "\(ErrorDomain).number-of-pages"
static let NumberOfPagesForPhotoSearchErrorCode = 301
static let FetchPhotosErrorDomain = "\(ErrorDomain).fetch-photos"
static let FetchPhotosErrorCode = 302
static let GetTagsHotListErrorDomain = "\(ErrorDomain).tags-getHotList"
static let GetTagsHotListErrorCode = 303
static let LoadImageErrorDomain = "\(ErrorDomain).load-image"
static let LoadImageErrorCode = 304
static let EmptyResultErrorDomain = "\(ErrorDomain).empty-result"
static let EmptyResultErrorCode = 305
static let DefaultErrorCode = 307
static let DefaultError = NSError(
domain: FlickrApiClient.Constants.Error.ErrorDomain,
code: FlickrApiClient.Constants.Error.DefaultErrorCode,
userInfo: [NSLocalizedDescriptionKey : "An error occured. Try again later."]
)
static let EmptyResponseError = NSError(
domain: FlickrApiClient.Constants.Error.EmptyResultErrorDomain,
code: FlickrApiClient.Constants.Error.EmptyResultErrorCode,
userInfo: [NSLocalizedDescriptionKey : "No data was returned."]
)
}
}
}
|
mit
|
f9d8f9fb1d8fb7092d99bb9cf2ac56b8
| 38.251429 | 96 | 0.559325 | 5.287914 | false | false | false | false |
GianniCarlo/Audiobook-Player
|
BookPlayer/Views/BPMarqueeLabel.swift
|
1
|
480
|
//
// BPMarqueeLabel.swift
// BookPlayer
//
// Created by Florian Pichler on 10.05.18.
// Copyright © 2018 Tortuga Power. All rights reserved.
//
import MarqueeLabel
import UIKit
class BPMarqueeLabel: MarqueeLabel {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.animationDelay = 2.0
self.speed = .rate(7.5)
self.fadeLength = 10.0
self.leadingBuffer = 10.0
self.trailingBuffer = 10.0
}
}
|
gpl-3.0
|
121742d49b66f98f7731cbf07a9de395
| 20.772727 | 56 | 0.645094 | 3.548148 | false | false | false | false |
jtbandes/swift
|
test/decl/var/lazy_properties.swift
|
2
|
4553
|
// RUN: %target-typecheck-verify-swift -parse-as-library -swift-version 3
// RUN: %target-typecheck-verify-swift -parse-as-library -swift-version 4
lazy func lazy_func() {} // expected-error {{'lazy' may only be used on 'var' declarations}} {{1-6=}}
lazy var b = 42 // expected-error {{'lazy' may not be used on an already-lazy global}} {{1-6=}}
struct S {
lazy static var lazy_global = 42 // expected-error {{'lazy' may not be used on an already-lazy global}} {{3-8=}}
}
protocol SomeProtocol {
lazy var x : Int // expected-error {{'lazy' isn't allowed on a protocol requirement}} {{3-8=}}
// expected-error@-1 {{property in protocol must have explicit { get } or { get set } specifier}}
lazy var y : Int { get } // expected-error {{'lazy' isn't allowed on a protocol requirement}} {{3-8=}}
}
class TestClass {
lazy var a = 42
lazy var a1 : Int = 42
lazy let b = 42 // expected-error {{'lazy' cannot be used on a let}} {{3-8=}}
lazy var c : Int { return 42 } // expected-error {{'lazy' may not be used on a computed property}} {{3-8=}}
lazy var d : Int // expected-error {{lazy properties must have an initializer}} {{3-8=}}
lazy var (e, f) = (1,2) // expected-error {{'lazy' cannot destructure an initializer}} {{3-8=}}
lazy var g = { 0 }() // single-expr closure
lazy var h : Int = { 0 }() // single-expr closure
lazy var i = { () -> Int in return 0 }()+1 // multi-stmt closure
lazy var j : Int = { return 0 }()+1 // multi-stmt closure
lazy var k : Int = { () -> Int in return 0 }()+1 // multi-stmt closure
lazy var l : Int = 42 { // expected-error {{lazy properties may not have observers}} {{3-8=}}
didSet {
}
}
init() {
lazy var localvar = 42 // expected-error {{lazy is only valid for members of a struct or class}} {{5-10=}}
localvar += 1
_ = localvar
}
}
struct StructTest {
lazy var p1 : Int = 42
mutating func f1() -> Int {
return p1
}
// expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
func f2() -> Int {
return p1 // expected-error {{cannot use mutating getter on immutable value: 'self' is immutable}}
}
static func testStructInits() {
let a = StructTest() // default init
let b = StructTest(p1: 42) // Override the lazily init'd value.
_ = a; _ = b
}
}
// <rdar://problem/16889110> capture lists in lazy member properties cannot use self
class CaptureListInLazyProperty {
lazy var closure1 = { [weak self] in return self!.i }
lazy var closure2: () -> Int = { [weak self] in return self!.i }
var i = 42
}
// Crash when initializer expression is type-checked both to infer the
// property type and also as part of the getter
class WeShouldNotReTypeCheckStatements {
lazy var firstCase = {
_ = nil // expected-error {{'nil' requires a contextual type}}
_ = ()
}
lazy var secondCase = {
_ = ()
_ = ()
}
}
protocol MyProtocol {
func f() -> Int
}
struct MyStruct : MyProtocol {
func f() -> Int { return 0 }
}
struct Outer {
static let p: MyProtocol = MyStruct()
struct Inner {
lazy var x = p.f()
lazy var y = {_ = 3}()
// expected-warning@-1 {{variable 'y' inferred to have type '()', which may be unexpected}}
// expected-note@-2 {{add an explicit type annotation to silence this warning}}
}
}
// https://bugs.swift.org/browse/SR-2616
struct Construction {
init(x: Int, y: Int? = 42) { }
}
class Constructor {
lazy var myQ = Construction(x: 3)
}
// Problems with self references
class BaseClass {
var baseInstanceProp = 42
static var baseStaticProp = 42
}
class ReferenceSelfInLazyProperty : BaseClass {
lazy var refs = (i, f())
lazy var trefs: (Int, Int) = (i, f())
lazy var qrefs = (self.i, self.f())
lazy var qtrefs: (Int, Int) = (self.i, self.f())
lazy var crefs = { (i, f()) }()
lazy var ctrefs: (Int, Int) = { (i, f()) }()
lazy var cqrefs = { (self.i, self.f()) }()
lazy var cqtrefs: (Int, Int) = { (self.i, self.f()) }()
lazy var mrefs = { () -> (Int, Int) in return (i, f()) }()
// expected-error@-1 {{call to method 'f' in closure requires explicit 'self.' to make capture semantics explicit}}
// expected-error@-2 {{reference to property 'i' in closure requires explicit 'self.' to make capture semantics explicit}}
lazy var mtrefs: (Int, Int) = { return (i, f()) }()
lazy var mqrefs = { () -> (Int, Int) in (self.i, self.f()) }()
lazy var mqtrefs: (Int, Int) = { return (self.i, self.f()) }()
var i = 42
func f() -> Int { return 0 }
}
|
apache-2.0
|
e1be687af55c7d35fca0871b78fb0666
| 28.374194 | 124 | 0.614759 | 3.395227 | false | false | false | false |
fgengine/quickly
|
Quickly/Xml/QXmlReader.swift
|
1
|
3165
|
//
// Quickly
//
public final class QXmlReader {
public var document: QXmlDocument
public init(data: Data) throws {
let delegate = Delegate()
let parser = XMLParser(data: data)
parser.delegate = delegate
if parser.parse() == true {
self.document = delegate.document
} else {
if let error = parser.parserError {
throw error
}
throw QXmlError.notXml
}
}
public convenience init(string: String, encoding: String.Encoding = String.Encoding.utf8) throws {
guard let data = string.data(using: encoding) else {
throw QXmlError.notXml
}
try self.init(data: data)
}
}
private extension QXmlReader {
class Delegate : NSObject, XMLParserDelegate {
public var document: QXmlDocument
private var rootNodes: [QXmlNode]
private var recurseNodes: [QXmlNode]
private var trimmingCharacterSet: CharacterSet
public override init() {
self.document = QXmlDocument()
self.rootNodes = []
self.recurseNodes = []
self.trimmingCharacterSet = CharacterSet.whitespacesAndNewlines
super.init()
}
public func parserDidEndDocument(_ parser: XMLParser) {
self.document.nodes = self.rootNodes
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
let attributes = attributeDict.compactMap({ (key, value) -> QXmlAttribute in
return QXmlAttribute(name: key, value: QXmlValue(text: value))
})
let node = QXmlNode(name: elementName, attributes: attributes)
if let parentNode = self.recurseNodes.last {
parentNode.nodes.append(node)
} else {
self.rootNodes.append(node)
}
self.recurseNodes.append(node)
}
public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
guard let node = self.recurseNodes.last else {
parser.abortParsing()
return
}
if node.name != elementName {
parser.abortParsing()
}
self.recurseNodes.removeLast()
}
public func parser(_ parser: XMLParser, foundCharacters string: String) {
let trimString = string.trimmingCharacters(in: self.trimmingCharacterSet)
if trimString.count > 0 {
if let node = self.recurseNodes.last {
if let value = node.value {
value.text.append(trimString)
} else {
node.value = QXmlValue(text: trimString)
}
} else {
parser.abortParsing()
}
}
}
}
}
|
mit
|
e5dd45690a375c002a49ac562add04f1
| 32.670213 | 190 | 0.546603 | 5.137987 | false | false | false | false |
SwiftKit/Reactant
|
Source/Core/Styling/Extensions/UIColor+Init.swift
|
2
|
2346
|
//
// UIColor+Init.swift
// Reactant
//
// Created by Filip Dolnik on 16.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import UIKit
extension UIColor {
/**
* Parses passed hex string and returns corresponding UIColor.
* - parameter hex: string consisting of hex color, including hash symbol - accepted formats: "#RRGGBB" and "#RRGGBBAA"
* - WARNING: This is not a failable **init** (i.e. it doesn't return nil if it fails to parse the passed string, instead it crashes the app) and therefore is NOT recommended for parsing colors received from back-end.
*/
public convenience init(hex: String) {
let hexNumber = String(hex.dropFirst())
let length = hexNumber.count
guard length == 6 || length == 8 else {
preconditionFailure("Hex string \(hex) has to be in format #RRGGBB or #RRGGBBAA !")
}
if let hexValue = UInt(hexNumber, radix: 16) {
if length == 6 {
self.init(rgb: hexValue)
} else {
self.init(rgba: hexValue)
}
} else {
preconditionFailure("Hex string \(hex) could not be parsed!")
}
}
/**
* Parses passed (Red, Green, Blue) UInt and returns corresponding UIColor, alpha is 1.
* - parameter rgba: UInt of a color - (e.g. 0x33F100)
* - WARNING: Passing in negative number or number higher than 0xFFFFFF is undefined behavior.
*/
public convenience init(rgb: UInt) {
if rgb > 0xFFFFFF {
print("WARNING: RGB color is greater than the value of white (0xFFFFFF) which is probably developer error.")
}
self.init(rgba: (rgb << 8) + 0xFF)
}
/**
* Parses passed (Red, Green, Blue, Alpha) UInt and returns corresponding UIColor.
* - parameter rgba: UInt of a color - (e.g. 0x33F100EE)
* - WARNING: Passing in negative number or number higher than 0xFFFFFFFF is undefined behavior.
*/
public convenience init(rgba: UInt) {
let red = CGFloat((rgba & 0xFF000000) >> 24) / 255.0
let green = CGFloat((rgba & 0xFF0000) >> 16) / 255.0
let blue = CGFloat((rgba & 0xFF00) >> 8) / 255.0
let alpha = CGFloat(rgba & 0xFF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
|
mit
|
47611036c742e873acea4228ba12f2d8
| 37.442623 | 221 | 0.604691 | 4.10683 | false | false | false | false |
bengottlieb/HelpKit
|
HelpKit/Framework Code/TooltipView.Appearance.swift
|
1
|
3222
|
//
// Appearance.swift
// HelpKit
//
// Created by Ben Gottlieb on 2/6/17.
// Copyright © 2017 Stand Alone, Inc. All rights reserved.
//
import UIKit
extension TooltipView {
public struct Appearance {
public static var standard = Appearance()
public static var maxTooltipWidth: CGFloat = 200
public var tipBackgroundColor = UIColor.white /// what color is the 'bubble' of the tooltip?
public static var backgroundColor = UIColor.clear /// what color (if any) is the 'blocking' view behind the tip?
public var tipCornerRadius: CGFloat = 5 /// how round are the tip's bubble's corners?
public var titleColor = UIColor.black
public var titleFont = UIFont.systemFont(ofSize: 14)
public var titleAlignment: NSTextAlignment = .center
public var bodyColor = UIColor.black
public var bodyFont = UIFont.systemFont(ofSize: 13)
public var bodyAlignment: NSTextAlignment = .center
public var borderWidth: CGFloat = 0.5
public var borderColor = UIColor.gray
public var backgroundInset = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
public var arrowDistance: CGFloat = 5 /// how far is the arrow from its target view?
public var arrowSpread: CGFloat = 8 /// how wide is the base of the arrow?
public var arrowPoint: CGFloat = 1 /// how wide is the tip of the arrow?
public var arrowLength: CGFloat = 8 /// how 'long' is the arrow?
public var layerClass = TooltipView.BackgroundLayer.self
}
}
extension TooltipView.Appearance {
var titleAttributes: [NSAttributedStringKey: Any] {
let paraStyle = NSMutableParagraphStyle(); paraStyle.alignment = self.titleAlignment
return [ NSAttributedStringKey.font: self.titleFont, NSAttributedStringKey.foregroundColor: self.titleColor, NSAttributedStringKey.paragraphStyle: paraStyle ]
}
var bodyAttributes: [NSAttributedStringKey: Any] {
let paraStyle = NSMutableParagraphStyle(); paraStyle.alignment = self.bodyAlignment
return [ NSAttributedStringKey.font: self.bodyFont, NSAttributedStringKey.foregroundColor: self.bodyColor, NSAttributedStringKey.paragraphStyle: paraStyle ]
}
func minimumHeight(forTitle title: String?, and body: String?) -> CGFloat {
var height: CGFloat = 0
if title != nil { height += self.titleFont.lineHeight }
if body != nil { height += self.titleFont.lineHeight }
return height
}
func contentInset(for direction: TooltipView.TipPosition) -> UIEdgeInsets {
var insets = self.backgroundInset
let diag = sqrt(pow(self.arrowDistance, 2) / 2)
switch direction {
case .belowRight: insets.top += diag + self.arrowLength; //insets.rightSide += diag
case .belowLeft: insets.top += diag + self.arrowLength; //insets.leftSide += diag
case .below: insets.top += self.arrowDistance + self.arrowLength
case .rightSide: insets.left += self.arrowDistance + self.arrowLength
case .leftSide: insets.right += self.arrowDistance + self.arrowLength
case .above: insets.bottom += self.arrowDistance + self.arrowLength
case .aboveRight: insets.bottom += diag + self.arrowLength; //insets.rightSide += diag
case .aboveLeft: insets.bottom += diag + self.arrowLength; //insets.leftSide += diag
case .best: break
}
return insets
}
}
|
mit
|
354fc3082a3aed89eb0d0c72e1aa8fb6
| 36.894118 | 160 | 0.733002 | 4.001242 | false | false | false | false |
codestergit/swift
|
test/Sanitizers/Inputs/tsan-uninstrumented.swift
|
3
|
1300
|
// This is uninstrumented code used for testing calls into uninstrumented
// modules.
public struct UninstrumentedStruct {
public init() { }
public func read() -> Int {
return 0
}
public mutating func mutate() { }
public var storedProperty1: Int = 7
public var storedProperty2: Int = 22
public subscript(index: Int) -> Int {
get { return 0 }
set(newValue) { }
}
public var storedClass: UninstrumentedClass? = nil
}
public class UninstrumentedClass {
public init() { }
public func read() -> Int {
return 0
}
public func mutate() { }
public var storedProperty1: Int = 7
public var storedProperty2: Int = 22
public subscript(index: Int) -> Int {
get { return 0 }
set(newValue) { }
}
public var storedStructProperty: UninstrumentedStruct = UninstrumentedStruct()
public var computedStructProperty: UninstrumentedStruct {
get { return UninstrumentedStruct() }
set { }
}
}
public func uninstrumentedTakesInout(_ i: inout Int) { }
public var storedGlobalInUninstrumentedModule1: Int = 7
public var storedGlobalInUninstrumentedModule2: Int = 88
public var computedGlobalInUninstrumentedModule1: Int {
get { return 0 }
set { }
}
public var computedGlobalInUninstrumentedModule2: Int {
get { return 0 }
set { }
}
|
apache-2.0
|
bd03adc4c8c5c0754372565766faf14b
| 19.967742 | 80 | 0.695385 | 3.892216 | false | false | false | false |
nlampi/SwiftGridView
|
Examples/Universal/SwiftGridExample/Cells/BasicTextCell.swift
|
1
|
2716
|
// BasicTextCell.swift
// Copyright (c) 2016 Nathan Lampi (http://nathanlampi.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
import SwiftGridView
open class BasicTextCell : SwiftGridCell {
open var textLabel : UILabel!
open var padding : CGFloat!
override init(frame: CGRect) {
super.init(frame: frame)
self.initCell()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initCell()
}
fileprivate func initCell() {
self.backgroundView = UIView()
self.selectedBackgroundView = UIView()
self.selectedBackgroundView?.backgroundColor = UIColor.orange
self.padding = 8.0
self.textLabel = UILabel.init(frame: self.frame)
self.textLabel.textColor = UIColor.black
self.textLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(self.textLabel)
let views : [String : Any] = ["tL": self.textLabel!]
let metrics : [String : Any] = ["p": self.padding!]
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-p-[tL]-p-|",
options: NSLayoutConstraint.FormatOptions.directionLeftToRight, metrics: metrics, views: views))
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[tL]|",
options: NSLayoutConstraint.FormatOptions.directionLeftToRight, metrics: metrics, views: views))
}
open override class func reuseIdentifier() -> String {
return "BasicCellReuseId"
}
}
|
mit
|
1e9af10e59e235c53851db1a8b132ec1
| 39.537313 | 108 | 0.699558 | 4.867384 | false | false | false | false |
rob-nash/Zip
|
Zip/QuickZip.swift
|
1
|
3563
|
//
// QuickZip.swift
// Zip
//
// Created by Roy Marmelstein on 16/01/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import Foundation
extension Zip {
//MARK: Quick Unzip
/**
Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name.
- parameter path: Path of zipped file. NSURL.
- throws: Error if unzipping fails or if file is not found. Can be printed with a description variable.
- returns: NSURL of the destination folder.
*/
public class func quickUnzipFile(_ path: URL) throws -> URL {
return try quickUnzipFile(path, progress: nil)
}
/**
Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name.
- parameter path: Path of zipped file. NSURL.
- parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1.
- throws: Error if unzipping fails or if file is not found. Can be printed with a description variable.
- notes: Supports implicit progress composition
- returns: NSURL of the destination folder.
*/
public class func quickUnzipFile(_ path: URL, progress: ((_ progress: Double) -> ())?) throws -> URL {
let fileManager = FileManager.default
let fileExtension = path.pathExtension
let fileName = path.lastPathComponent
let directoryName = fileName.replacingOccurrences(of: ".\(fileExtension)", with: "")
let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
do {
let destinationUrl = documentsUrl.appendingPathComponent(directoryName, isDirectory: true)
try self.unzipFile(path, destination: destinationUrl, overwrite: true, password: nil, progress: progress)
return destinationUrl
}catch{
throw(ZipError.unzipFail)
}
}
//MARK: Quick Zip
/**
Quick zip files.
- parameter paths: Array of NSURL filepaths.
- parameter fileName: File name for the resulting zip file.
- throws: Error if zipping fails.
- notes: Supports implicit progress composition
- returns: NSURL of the destination folder.
*/
public class func quickZipFiles(_ paths: [URL], fileName: String, destinationURL: URL) throws -> URL {
return try quickZipFiles(paths, fileName: fileName, destinationURL: destinationURL, progress: nil)
}
/**
Quick zip files.
- parameter paths: Array of NSURL filepaths.
- parameter fileName: File name for the resulting zip file.
- parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1.
- throws: Error if zipping fails.
- notes: Supports implicit progress composition
- returns: NSURL of the destination folder.
*/
public class func quickZipFiles(_ paths: [URL], fileName: String, destinationURL: URL, progress: ((_ progress: Double) -> ())?) throws -> URL {
// let fileManager = FileManager.default
// let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
// let destinationUrl = documentsUrl.appendingPathComponent("\(fileName).zip")
try self.zipFiles(paths: paths, zipFilePath: destinationURL, password: nil, progress: progress)
return destinationURL
}
}
|
mit
|
88ac6b53bf06dc63bc3e28868a44a424
| 35.721649 | 147 | 0.656654 | 4.886145 | false | false | false | false |
viWiD/Evergreen
|
Sources/Evergreen/Handler.swift
|
3
|
3413
|
//
// Handler.swift
// Evergreen
//
// Created by Nils Fischer on 12.10.14.
// Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved.
//
import Foundation
// MARK: - Record
public struct Record: CustomStringConvertible {
public let date: Date
public let logLevel: LogLevel?
public let description: String
}
// MARK: - Handler
open class Handler {
open var logLevel: LogLevel?
open var formatter: Formatter
public init(formatter: Formatter) {
self.formatter = formatter
}
/// Called by a logger to handle an event. The event's log level is checked against the handler's and the given formatter is used to obtain a record from the event. Subsequently, `emit` is called to produce the output.
public final func emit<M>(_ event: Event<M>) {
if let handlerLogLevel = self.logLevel,
let eventLogLevel = event.logLevel,
eventLogLevel < handlerLogLevel {
return
}
self.emit(self.formatter.record(from: event))
}
/// Called to actually produce some output from a record. Override this method to send the record to an output stream of your choice. The default implementation simply prints the record to the console.
open func emit(_ record: Record) {
print(record)
}
}
// MARK: - Console Handler Class
/// A handler that writes log records to the console.
public class ConsoleHandler: Handler {
public convenience init() {
self.init(formatter: Formatter(style: .default))
}
override public func emit(_ record: Record) {
// TODO: use debugPrint?
print(record)
}
}
// MARK: - File Handler Class
/// A handler that writes log records to a file.
public class FileHandler: Handler, CustomStringConvertible {
private var file: FileHandle!
private let fileURL: URL
public convenience init?(fileURL: URL) {
self.init(fileURL: fileURL, formatter: Formatter(style: .full))
}
public init?(fileURL: URL, formatter: Formatter) {
self.fileURL = fileURL
super.init(formatter: formatter)
let fileManager = FileManager.default
guard fileURL.isFileURL else {
return nil
}
let path = fileURL.path
guard fileManager.createFile(atPath: path, contents: nil, attributes: nil) else {
return nil
}
guard let file = FileHandle(forWritingAtPath: path) else {
return nil
}
file.seekToEndOfFile()
self.file = file
}
override public func emit(_ record: Record) {
if let recordData = (record.description + "\n").data(using: String.Encoding.utf8, allowLossyConversion: true) {
self.file.write(recordData)
} else {
// TODO
}
}
public var description: String {
return "FileHandler(\(fileURL))"
}
}
// MARK: Stenography Handler
/// A handler that appends log records to an array.
public class StenographyHandler: Handler {
// TODO: make sure there is no memory problem when this array becomes too large
/// All records logged to this handler
public private(set) var records: [Record] = []
public convenience init() {
self.init(formatter: Formatter(style: .default))
}
override public func emit(_ record: Record) {
self.records.append(record)
}
}
|
mit
|
c05961ffa2a0683fb431dc7a3ee59680
| 25.053435 | 222 | 0.645473 | 4.455614 | false | false | false | false |
danielsaidi/KeyboardKit
|
Sources/KeyboardKit/Extensions/UITextDocumentProxy+Content.swift
|
1
|
3193
|
//
// UITextDocumentProxy+Content.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2020-12-28.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UITextDocumentProxy {
/**
Whether or not the text document proxy cursor is at the
beginning of a new sentence.
*/
var isCursorAtNewSentence: Bool {
guard let pre = trimmedDocumentContextBeforeInput else { return true }
let lastCharacter = String(pre.suffix(1))
return pre.isEmpty || lastCharacter.isSentenceDelimiter
}
/**
Whether or not the text document proxy cursor is at the
beginning of a new word.
*/
var isCursorAtNewWord: Bool {
guard let pre = documentContextBeforeInput else { return true }
let lastCharacter = String(pre.suffix(1))
return pre.isEmpty || lastCharacter.isWordDelimiter
}
/**
The last ended sentence right before the cursor, if any.
*/
var sentenceBeforeInput: String? {
guard isCursorAtNewSentence else { return nil }
guard let context = documentContextBeforeInput else { return nil }
let components = context.split(by: sentenceDelimiters).filter { !$0.isEmpty }
let ignoreLast = components.last?.trimmed().count == 0
return ignoreLast ? nil : components.last
}
/**
The last ended word right before the cursor, if any.
*/
var wordBeforeInput: String? {
if isCursorAtNewSentence { return nil }
guard isCursorAtNewWord else { return nil }
guard let context = documentContextBeforeInput else { return nil }
guard let result = context.split(by: wordDelimiters).dropLast().last?.trimmed() else { return nil }
return result.isEmpty ? nil : result
}
/**
A list of western sentence delimiters.
*/
var sentenceDelimiters: [String] { String.sentenceDelimiters }
/**
Trimmed textual content after the text cursor.
*/
var trimmedDocumentContextAfterInput: String? {
documentContextAfterInput?.trimmed()
}
/**
Trimmed textual content before the text cursor.
*/
var trimmedDocumentContextBeforeInput: String? {
documentContextBeforeInput?.trimmed()
}
/**
A list of western word delimiters.
*/
var wordDelimiters: [String] { String.wordDelimiters }
/**
End the current sentence by removing all trailing space
characters, then injecting a dot and a space.
*/
func endSentence() {
guard isCursorAtTheEndOfTheCurrentWord else { return }
while (documentContextBeforeInput ?? "").hasSuffix(" ") {
deleteBackward(times: 1)
}
insertText(". ")
}
}
// MARK: - Private Functions
private extension String {
var hasTrimmedContent: Bool {
!trimmed().isEmpty
}
func split(by separators: [String]) -> [String] {
let separators = CharacterSet(charactersIn: separators.joined())
return components(separatedBy: separators)
}
func trimmed() -> String {
trimmingCharacters(in: .whitespaces)
}
}
|
mit
|
e4c28297cf8e12b806dd1931b91763e0
| 28.284404 | 107 | 0.639098 | 4.764179 | false | false | false | false |
sammyd/VT_InAppPurchase
|
projects/03_Receipts/003_DemoStarter/GreenGrocer/ShoppingListTableViewController.swift
|
6
|
3474
|
/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class ShoppingListTableViewController: UITableViewController, DataStoreOwner, IAPContainer {
var dataStore : DataStore?
var iapHelper : IAPHelper?
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 70
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataStore?.shoppingLists.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ShoppingListCell", forIndexPath: indexPath)
if let cell = cell as? ShoppingListTableViewCell {
cell.shoppingList = dataStore?.shoppingLists[indexPath.row]
}
return cell
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
if let shoppingList = dataStore?.shoppingLists[indexPath.row] {
dataStore?.removeShoppingList(shoppingList)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destVC = segue.destinationViewController as? ShoppingListViewController {
let selectedRowIndex = tableView.indexPathForSelectedRow
destVC.shoppingList = dataStore?.shoppingLists[selectedRowIndex?.row ?? 0]
destVC.dataStore = dataStore
} else if let destVC = segue.destinationViewController as? CreateShoppingListViewController {
destVC.dataStore = dataStore
}
}
}
extension ShoppingListTableViewController {
@IBAction func unwindToShoppingListTableVC(unwindSegue: UIStoryboardSegue) {
tableView.reloadData()
}
}
|
mit
|
7504c5c0e1836c7b2bb0ac85c779fe95
| 36.354839 | 155 | 0.750432 | 5.303817 | false | false | false | false |
treejames/firefox-ios
|
FxAClient/Frontend/SignIn/FxAContentViewController.swift
|
3
|
6246
|
/* 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 Shared
import SnapKit
import UIKit
import WebKit
protocol FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void
func contentViewControllerDidCancel(viewController: FxAContentViewController)
}
/**
* A controller that manages a single web view connected to the Firefox
* Accounts (Desktop) Sync postMessage interface.
*
* The postMessage interface is not really documented, but it is simple
* enough. I reverse engineered it from the Desktop Firefox code and the
* fxa-content-server git repository.
*/
class FxAContentViewController: SettingsContentViewController, WKScriptMessageHandler {
private enum RemoteCommand: String {
case CanLinkAccount = "can_link_account"
case Loaded = "loaded"
case Login = "login"
case SessionStatus = "session_status"
case SignOut = "sign_out"
}
var delegate: FxAContentViewControllerDelegate?
init() {
super.init(backgroundColor: UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0), title: NSAttributedString(string: "Firefox Accounts"))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func makeWebView() -> WKWebView {
// Inject our setup code after the page loads.
let source = getJS()
let userScript = WKUserScript(
source: source,
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true
)
// Handle messages from the content server (via our user script).
let contentController = WKUserContentController()
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(
self,
name: "accountsCommandHandler"
)
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(
frame: CGRect(x: 0, y: 0, width: 1, height: 1),
configuration: config
)
webView.navigationDelegate = self
// Don't allow overscrolling.
webView.scrollView.bounces = false
return webView
}
// Send a message to the content server.
func injectData(type: String, content: [String: AnyObject]) {
NSLog("injectData: " + type)
let data = [
"type": type,
"content": content,
]
let json = JSON(data).toString(pretty: false)
let script = "window.postMessage(\(json), '\(self.url)');"
webView.evaluateJavaScript(script, completionHandler: nil)
}
private func onCanLinkAccount(data: JSON) {
// // We need to confirm a relink - see shouldAllowRelink for more
// let ok = shouldAllowRelink(accountData.email);
let ok = true
injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]]);
}
// We're not signed in to a Firefox Account at this time, which we signal by returning an error.
private func onSessionStatus(data: JSON) {
injectData("message", content: ["status": "error"])
}
// We're not signed in to a Firefox Account at this time. We should never get a sign out message!
private func onSignOut(data: JSON) {
injectData("message", content: ["status": "error"])
}
// The user has signed in to a Firefox Account. We're done!
private func onLogin(data: JSON) {
NSLog("onLogin: " + data.toString())
injectData("message", content: ["status": "login"])
self.delegate?.contentViewControllerDidSignIn(self, data: data)
}
// The content server page is ready to be shown.
private func onLoaded() {
NSLog("Handling loaded remote command.");
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
// Handle a message coming from the content server.
func handleRemoteCommand(rawValue: String, data: JSON) {
if let command = RemoteCommand(rawValue: rawValue) {
NSLog("Handling remote command '\(rawValue)' .");
if !isLoaded && command != .Loaded {
// Work around https://github.com/mozilla/fxa-content-server/issues/2137
NSLog("Synthesizing loaded remote command.")
onLoaded()
}
switch (command) {
case .Loaded:
onLoaded()
case .Login:
onLogin(data)
case .CanLinkAccount:
onCanLinkAccount(data)
case .SessionStatus:
onSessionStatus(data)
case .SignOut:
onSignOut(data)
}
} else {
NSLog("Unknown remote command '\(rawValue)'; ignoring.");
}
}
// Dispatch webkit messages originating from our child webview.
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if (message.name == "accountsCommandHandler") {
let body = JSON(message.body)
let detail = body["detail"]
handleRemoteCommand(detail["command"].asString!, data: detail["data"])
} else {
NSLog("Got unrecognized message \(message)")
}
}
private func getJS() -> String {
let fileRoot = NSBundle.mainBundle().pathForResource("FxASignIn", ofType: "js")
return NSString(contentsOfFile: fileRoot!, encoding: NSUTF8StringEncoding, error: nil)! as String
}
override func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
// Ignore for now.
}
override func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
// Ignore for now.
}
}
|
mpl-2.0
|
1ef053d1d60c8f7174c95836bad9c914
| 35.104046 | 168 | 0.633365 | 4.894984 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/Model/Option/ReformaCrossing/Abstract/MOptionReformaCrossingSounds.swift
|
1
|
918
|
import SpriteKit
class MOptionReformaCrossingSounds
{
let soundCoin:SKAction
let soundFail:SKAction
let soundHonk:SKAction
let soundVictory:SKAction
let sound1up:SKAction
private let kSoundCoin:String = "soundCoin.caf"
private let kSoundFail:String = "soundFail.caf"
private let kSoundHonk:String = "soundCarHorn.caf"
private let kSoundVictory:String = "soundVictory.caf"
private let kSound1up:String = "sound1up.caf"
init()
{
soundCoin = SKAction.playSoundFileNamed(kSoundCoin, waitForCompletion:false)
soundFail = SKAction.playSoundFileNamed(kSoundFail, waitForCompletion:false)
soundHonk = SKAction.playSoundFileNamed(kSoundHonk, waitForCompletion:false)
soundVictory = SKAction.playSoundFileNamed(kSoundVictory, waitForCompletion:false)
sound1up = SKAction.playSoundFileNamed(kSound1up, waitForCompletion:false)
}
}
|
mit
|
eb04e4a8949bdb300dfdb7411cf60b89
| 37.25 | 90 | 0.751634 | 4.25 | false | false | false | false |
bvic23/VinceRP
|
VinceRPTests/Common/Threading/DynamicVariableSpec.swift
|
1
|
2503
|
//
// Created by Viktor Belenyesi on 18/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
@testable import VinceRP
import Quick
import Nimble
class DynamicVariableSpec: QuickSpec {
override func spec() {
describe("dynamic variable") {
var dyn: DynamicVariable<Int>!
var doSomething: (() -> String)!
var r1: String!
var r2: String!
beforeEach {
dyn = DynamicVariable(0)
doSomething = {
guard let v = dyn.value else {
return ""
}
return "\(NSThread.currentThread().name!): \(v)"
}
r1 = nil
r2 = nil
}
it("ensures the different context for different threads") {
// when
Runnable("thread-1") {
r1 = dyn.withValue(10, doSomething)
}.start()
Runnable("thread-2") {
r2 = dyn.withValue(20, doSomething)
}.start()
// then
expect(r1) =~ "thread-1: 10"
expect(r2) =~ "thread-2: 20"
}
it("shares the same variable in same thread") {
// when
Runnable("thread-1") {
r1 = dyn.withValue(10, doSomething)
r2 = dyn.withValue(20, doSomething)
}.start()
// then
expect(r1) =~ "thread-1: 10"
expect(r2) =~ "thread-1: 20"
}
// This test does not pass since there is no hiearchy between NSThreads
// So you cannot inherit the parent thread's dynvalue :-(
// That is the difference between ThreadLocal and InheritedThreadLocal
/*
it("passes the value to the embedded thread") {
// when
dyn.withValue(10) { () -> String in
Runnable("thread-1") {
r1 = doSomething()
}.start()
Runnable("thread-2") {
r2 = doSomething()
}.start()
return ""
}
// then
expect(r1) =~ "thread-1: 10"
expect(r2) =~ "thread-2: 10"
}
*/
}
}
}
|
mit
|
d50d24690461c49d361cd1379d0f833c
| 27.443182 | 83 | 0.412705 | 5.087398 | false | false | false | false |
wireapp/wire-ios-sync-engine
|
Source/UserSession/Search/AddressBookSearch.swift
|
1
|
1811
|
//
// Wire
// Copyright (C) 2016 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/.
//
import Foundation
import Contacts
/// Search for contacts in the address book
class AddressBookSearch {
/// Maximum number of contacts to consider when matching/searching,
/// for performance reasons
fileprivate let maximumSearchRange: UInt = 3000
/// Address book
fileprivate let addressBook: AddressBookAccessor?
init(addressBook: AddressBookAccessor? = nil) {
self.addressBook = addressBook ?? AddressBook.factory()
}
}
// MARK: - Search contacts
extension AddressBookSearch {
/// Returns address book contacts matching the query, excluding the one with the given identifier
func contactsMatchingQuery(_ query: String, identifiersToExclude: [String]) -> [ZMAddressBookContact] {
let excluded = Set(identifiersToExclude)
let addressBookMatches = self.addressBook?.contacts(matchingQuery: query.lowercased()) ?? []
return addressBookMatches.filter { contact in
guard let identifier = contact.localIdentifier else {
return true
}
return !excluded.contains(identifier)
}
}
}
|
gpl-3.0
|
e53fe91f7e7f046ba146e120ab4ffa2c
| 33.826923 | 107 | 0.711761 | 4.778364 | false | false | false | false |
nasser0099/Express
|
Express/Action.swift
|
1
|
8592
|
//===--- Action.swift -----------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express 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 Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
import BrightFutures
public protocol AbstractActionType {
}
public protocol ActionType : AbstractActionType {
typealias Content
}
public protocol FlushableAction : AbstractActionType, FlushableType {
}
public protocol IntermediateActionType : AbstractActionType {
func nextAction<RequestContent : ConstructableContentType>(request:Request<RequestContent>) -> Future<(AbstractActionType, Request<RequestContent>?), AnyError>
}
public protocol SelfSufficientActionType : AbstractActionType {
func handle<RequestContent : ConstructableContentType>(app:Express, routeId:String, request:Request<RequestContent>, out:DataConsumerType) -> Future<Void, AnyError>
}
public class Action<C : FlushableContentType> : ActionType, AbstractActionType {
public typealias Content = C
}
class ResponseAction<C : FlushableContentType> : Action<C>, FlushableAction {
let response:Response<C>
init(response:Response<C>) {
self.response = response
}
func flushTo(out: DataConsumerType) -> Future<Void, AnyError> {
return response.flushTo(out)
}
}
extension ResponseAction where C : FlushableContent {
convenience init(response:ResponseType) {
let content = response.content.map { content in
C(content: content)
}
let mappedResponse = Response<C>(status: response.status, content: content, headers: response.headers)
self.init(response: mappedResponse)
}
}
class RenderAction<C : FlushableContentType, Context> : Action<C>, IntermediateActionType {
let view:String
let context:Context?
let status:StatusCode
let headers:Dictionary<String, String>
init(view:String, context:Context?, status:StatusCode = .Ok, headers:Dictionary<String, String> = Dictionary()) {
self.view = view
self.context = context
self.status = status
self.headers = headers
}
private func response<RC:FlushableContentType>(status:StatusCode, content:RC?, headers:Dictionary<String, String>) -> Response<RC> {
return Response(status: status, content: content, headers: headers)
}
func nextAction<RequestContent : ConstructableContentType>(request:Request<RequestContent>) -> Future<(AbstractActionType, Request<RequestContent>?), AnyError> {
return request.app.views.render(view, context: context).map { content in
let response = Response(status: self.status, content: content, headers: self.headers)
return (ResponseAction(response: response), nil)
}
}
}
class ChainAction<C : FlushableContentType, ReqC: ConstructableContentType> : Action<C>, SelfSufficientActionType {
let request:Request<ReqC>?
init(request:Request<ReqC>? = nil) {
self.request = request
}
func handle<RequestContent : ConstructableContentType>(app:Express, routeId:String, request:Request<RequestContent>, out:DataConsumerType) -> Future<Void, AnyError> {
let req = self.request.map {$0 as RequestHeadType} .getOrElse(request)
let body = self.request.map {$0.body.map {$0 as ContentType}} .getOrElse(request.body)
let route = app.nextRoute(routeId, request: request)
return route.map { (r:(RouteType, [String: String]))->Future<Void, AnyError> in
let req = req.withParams(r.1)
let transaction = r.0.factory(req, out)
for b in body {
if !transaction.tryConsume(b) {
if let flushableBody = b as? FlushableContentType {
flushableBody.flushTo(transaction)
} else {
print("Can not chain this action")
}
}
}
transaction.selfProcess()
return Future()
}.getOrElse {
future(ImmediateExecutionContext) { ()->Void in
throw ExpressError.PageNotFound(path: request.path)
}
}
}
}
public extension Action {
public class func ok(content:Content? = nil, headers:Dictionary<String, String> = Dictionary()) -> Action<C> {
let response = Response<Content>(status: 200, content: content, headers: headers)
return ResponseAction(response: response)
}
internal class func notFound(filename:String) -> Action<AnyContent> {
let response = Response<AnyContent>(status: 404, content: AnyContent(str: "404 File Not Found\n\n" + filename), headers: Dictionary())
return ResponseAction(response: response)
}
internal class func routeNotFound(path:String) -> Action<AnyContent> {
let response = Response<AnyContent>(status: 404, content: AnyContent(str: "404 Route Not Found\n\n\tpath: " + path), headers: Dictionary())
return ResponseAction(response: response)
}
internal class func internalServerError(description:String) -> Action<AnyContent> {
let response = Response<AnyContent>(status: 500, content: AnyContent(str: "500 Internal Server Error\n\n" + description), headers: Dictionary())
return ResponseAction(response: response)
}
internal class func nilRequest() -> Request<AnyContent>? {
return nil
}
public class func chain<ReqC : ConstructableContentType>(request:Request<ReqC>? = nil) -> Action<C> {
return ChainAction(request: request)
}
public class func chain() -> Action<C> {
return chain(nilRequest())
}
public class func render<Context>(view:String, context:Context? = nil, status:StatusCode = .Ok, headers:Dictionary<String, String> = Dictionary()) -> Action<C> {
return RenderAction(view: view, context: context, status: status, headers: headers)
}
public class func response(response:Response<C>) -> Action<C> {
return ResponseAction(response: response)
}
public class func response(status:UInt16, content:C? = nil, headers:Dictionary<String, String> = Dictionary()) -> Action<C> {
return response(Response(status: status, content: content, headers: headers))
}
public class func response(status:StatusCode, content:C? = nil, headers:Dictionary<String, String> = Dictionary()) -> Action<C> {
return response(status.rawValue, content: content, headers: headers)
}
public class func status(status:UInt16) -> Action<C> {
return response(status)
}
public class func status(status:StatusCode) -> Action<C> {
return self.status(status.rawValue)
}
public class func redirect(url:String, status:RedirectStatusCode) -> Action<C> {
let headers = ["Location": url]
return response(status.rawValue, headers: headers)
}
public class func redirect(url:String, permanent:Bool = false) -> Action<C> {
let code:RedirectStatusCode = permanent ? .MovedPermanently : .TemporaryRedirect
return redirect(url, status: code)
}
public class func found(url:String) -> Action<C> {
return redirect(url, status: .Found)
}
public class func movedPermanently(url:String) -> Action<C> {
return redirect(url, status: .MovedPermanently)
}
public class func seeOther(url:String) -> Action<C> {
return redirect(url, status: .SeeOther)
}
public class func temporaryRedirect(url:String) -> Action<C> {
return redirect(url, status: .TemporaryRedirect)
}
}
public extension Action where C : AnyContent {
public class func ok(str:String?) -> Action<AnyContent> {
return Action<AnyContent>.ok(AnyContent(str: str))
}
}
|
gpl-3.0
|
508882f573f0095ec7a9e23e022709b6
| 38.782407 | 170 | 0.660498 | 4.458744 | false | false | false | false |
HarrisLee/Utils
|
MySampleCode-master/AutolayoutScrollViewInCode/AutolayoutScrollViewInCode/ViewController.swift
|
1
|
8118
|
//
// ViewController.swift
// AutolayoutScrollViewInCode
//
// Created by 张星宇 on 15/12/21.
// Copyright © 2015年 张星宇. All rights reserved.
//
import UIKit
import SnapKit
let ScreenWidth = UIScreen.mainScreen().bounds.width
let ScreenHeight = UIScreen.mainScreen().bounds.height
let topScrollHeight: CGFloat = UIScreen.mainScreen().bounds.height / 3
let boxWidth: CGFloat = ScreenWidth * 2 / 3
let boxGap: CGFloat = 20
class ViewController: UIViewController {
let scrollView = UIScrollView()
let containerView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
/**
使用Container进行布局
Use container in scrollview to layout subviews
*/
/**
使用外部视图进行布局
Use views outside to locate subviews in scrollview
*/
layoutWithContainer()
// layoutWithAbsoluteView()
// layoutWithCustomePageSize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
// scrollView.contentSize = CGSizeMake(1000, topScrollHeight)
// scrollView.contentSize.width = 1000
print(scrollView.contentSize.width)
}
}
// MARK: - 用Container实现自动布局
extension ViewController {
func layoutWithContainer() {
scrollView.bounces = false
view.addSubview(scrollView)
scrollView.backgroundColor = UIColor.yellowColor()
scrollView.addSubview(containerView)
containerView.backgroundColor = scrollView.backgroundColor
/**
* 对scrollView添加约束
* Add constraints to scrollView
*/
scrollView.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(view.snp_centerY)
make.left.right.equalTo(view)
make.height.equalTo(topScrollHeight)
}
/**
* 对containerView添加约束,接下来只要确定containerView的宽度即可
* Add constraints to containerView, the only thing we will do
* is to define the width of containerView
*/
containerView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(scrollView)
make.height.equalTo(topScrollHeight)
}
for i in 0...5 {
let box = UIView()
box.backgroundColor = UIColor.redColor()
containerView.addSubview(box)
box.snp_makeConstraints(closure: { (make) -> Void in
make.top.height.equalTo(containerView) // 确定top和height之后,box在竖直方向上完全确定
make.width.equalTo(boxWidth)
if i == 0 {
make.left.equalTo(containerView).offset(boxGap / 2)
}
else if let previousBox = containerView.subviews[i - 1] as? UIView{
make.left.equalTo(previousBox.snp_right).offset(boxGap)
}
if i == 5 {
containerView.snp_makeConstraints(closure: { (make) -> Void in
// 这一步是关键,它确定了container的宽度,也就确定了contentSize
// This step is very important, it set the width of container, so the
// contentSize is available now
make.right.equalTo(box)
})
}
})
}
}
}
extension ViewController {
func layoutWithAbsoluteView() {
scrollView.bounces = false
view.addSubview(scrollView)
scrollView.backgroundColor = UIColor.yellowColor()
scrollView.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(view.snp_centerY)
make.left.right.equalTo(view)
make.height.equalTo(topScrollHeight)
}
for i in 0...5 {
let box = UIView()
box.backgroundColor = UIColor.redColor()
scrollView.addSubview(box)
// box依赖于外部视图布局,不能依赖scrollView
// The position of box rely on self.view instead of scrollView
box.snp_makeConstraints(closure: { (make) -> Void in
make.top.equalTo(0)
// This bottom can be incorret when device is rotated
make.bottom.equalTo(view).offset(-(ScreenHeight - topScrollHeight) / 2)
make.height.equalTo(topScrollHeight)
make.width.equalTo(boxWidth)
if i == 0 {
make.left.equalTo(boxGap / 2)
}
else if let previousBox = scrollView.subviews[i - 1] as? UIView{
make.left.equalTo(previousBox.snp_right).offset(boxGap)
}
if i == 5 {
// 这里设定最右侧的box,距离contentSize的右边界距离
// The the distance from the box on the right side
// to the right side of contentSize
make.right.equalTo(scrollView)
}
})
}
}
}
// MARK: - 用Container实现自动布局
extension ViewController {
/**
The key is to set clipsToBounds to false and make the width of frame of scrollview less than the width of screen.
Usually the width now is padding + subviewWidth
关键在于clipsToBounds设置为no,scrollview自身的width小于屏幕宽度,一般设置为padding + 子视图width
*/
func layoutWithCustomePageSize() {
scrollView.bounces = false
view.addSubview(scrollView)
scrollView.pagingEnabled = true
scrollView.clipsToBounds = false // *important!* //
scrollView.backgroundColor = UIColor.yellowColor()
scrollView.addSubview(containerView)
containerView.backgroundColor = scrollView.backgroundColor
/**
* 对scrollView添加约束
* Add constraints to scrollView
*/
scrollView.snp_makeConstraints { (make) -> Void in
make.center.equalTo(view.snp_center)
make.width.equalTo(boxWidth + boxGap) // *important!* //
make.height.equalTo(topScrollHeight)
}
/**
* 对containerView添加约束,接下来只要确定containerView的宽度即可
* Add constraints to containerView, the only thing we will do
* is to define the width of containerView
*/
containerView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(scrollView)
make.height.equalTo(topScrollHeight)
}
for i in 0...40 {
let box = UIView()
box.backgroundColor = UIColor.redColor()
containerView.addSubview(box)
box.snp_makeConstraints(closure: { (make) -> Void in
make.top.height.equalTo(containerView) // 确定top和height之后,box在竖直方向上完全确定
make.width.equalTo(boxWidth)
if i == 0 {
make.left.equalTo(containerView).offset(boxGap / 2)
}
else if let previousBox = containerView.subviews[i - 1] as? UIView{
make.left.equalTo(previousBox.snp_right).offset(boxGap)
}
if i == 40 {
containerView.snp_makeConstraints(closure: { (make) -> Void in
// 这一步是关键,它确定了container的宽度,也就确定了contentSize
// This step is very important, it set the width of container, so the
// contentSize is available now
make.right.equalTo(box).offset(boxGap / 2)
})
}
})
}
}
}
|
mit
|
485eca6a776283aa543ad095ff7879ee
| 34.127854 | 118 | 0.564019 | 4.90625 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
WordPress/Classes/ViewRelated/Reader/ReaderTagStreamHeader.swift
|
2
|
1786
|
import Foundation
import WordPressShared
@objc open class ReaderTagStreamHeader: UIView, ReaderStreamHeader {
@IBOutlet fileprivate weak var borderedView: UIView!
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var followButton: PostMetaButton!
open var delegate: ReaderStreamHeaderDelegate?
// MARK: - Lifecycle Methods
open override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
adjustInsetsForTextDirection()
}
func applyStyles() {
backgroundColor = WPStyleGuide.greyLighten30()
borderedView.layer.borderColor = WPStyleGuide.readerCardCellBorderColor().cgColor
borderedView.layer.borderWidth = 1.0
WPStyleGuide.applyReaderStreamHeaderTitleStyle(titleLabel)
}
// MARK: - Configuration
open func configureHeader(_ topic: ReaderAbstractTopic) {
titleLabel.text = topic.title
WPStyleGuide.applyReaderFollowButtonStyle(followButton)
followButton.isSelected = topic.following
}
open func enableLoggedInFeatures(_ enable: Bool) {
followButton.isHidden = !enable
}
fileprivate func adjustInsetsForTextDirection() {
guard userInterfaceLayoutDirection() == .rightToLeft else {
return
}
followButton.contentEdgeInsets = followButton.contentEdgeInsets.flippedForRightToLeftLayoutDirection()
followButton.imageEdgeInsets = followButton.imageEdgeInsets.flippedForRightToLeftLayoutDirection()
followButton.titleEdgeInsets = followButton.titleEdgeInsets.flippedForRightToLeftLayoutDirection()
}
// MARK: - Actions
@IBAction func didTapFollowButton(_ sender: UIButton) {
delegate?.handleFollowActionForHeader(self)
}
}
|
gpl-2.0
|
ddb80ea6e75aca1453f421edabc79073
| 30.892857 | 110 | 0.726764 | 5.81759 | false | false | false | false |
evgenyneu/moa
|
Moa/Utils/MoaString.swift
|
1
|
523
|
import Foundation
//
// Helpers for working with strings
//
struct MoaString {
static func contains(_ text: String, substring: String,
ignoreCase: Bool = false,
ignoreDiacritic: Bool = false) -> Bool {
var options = NSString.CompareOptions()
if ignoreCase { _ = options.insert(NSString.CompareOptions.caseInsensitive) }
if ignoreDiacritic { _ = options.insert(NSString.CompareOptions.diacriticInsensitive) }
return text.range(of: substring, options: options) != nil
}
}
|
mit
|
7e4e216d58c9ac7131fc5b5c559dabcf
| 26.526316 | 91 | 0.684512 | 4.470085 | false | false | false | false |
jamy0801/LGWeChatKit
|
LGWeChatKit/LGChatKit/conversion/imagePick/LGAssetToolView.swift
|
1
|
4077
|
//
// LGAssetToolView.swift
// LGChatViewController
//
// Created by jamy on 10/23/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
private let buttonWidth = 20
private let durationTime = 0.3
class LGAssetToolView: UIView {
var preViewButton: UIButton!
var totalButton: UIButton!
var sendButton: UIButton!
weak var parent: UIViewController!
var selectCount = Int() {
willSet {
if newValue > 0 {
totalButton.addAnimation(durationTime)
totalButton.hidden = false
totalButton.setTitle("\(newValue)", forState: .Normal)
} else {
totalButton.hidden = true
}
}
}
var addSelectCount: Int? {
willSet {
selectCount += newValue!
}
}
convenience init(leftTitle:String, leftSelector: Selector, rightSelector: Selector, parent: UIViewController) {
self.init()
self.parent = parent
preViewButton = UIButton(type: .Custom)
preViewButton.titleLabel?.font = UIFont.systemFontOfSize(14.0)
preViewButton.setTitle(leftTitle, forState: .Normal)
preViewButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
preViewButton.addTarget(parent, action: leftSelector, forControlEvents: .TouchUpInside)
totalButton = UIButton(type: .Custom)
totalButton.titleLabel?.font = UIFont.systemFontOfSize(14.0)
totalButton.setBackgroundImage(UIImage.imageWithColor(UIColor.greenColor()), forState: .Normal)
totalButton.layer.cornerRadius = CGFloat(buttonWidth / 2)
totalButton.layer.masksToBounds = true
totalButton.hidden = true
sendButton = UIButton(type: .Custom)
sendButton.titleLabel?.font = UIFont.systemFontOfSize(14.0)
sendButton.setTitle("发送", forState: .Normal)
sendButton.setTitleColor(UIColor.grayColor(), forState: .Normal)
sendButton.addTarget(parent, action: rightSelector, forControlEvents: .TouchUpInside)
backgroundColor = UIColor.groupTableViewBackgroundColor()
addSubview(preViewButton)
addSubview(totalButton)
addSubview(sendButton)
preViewButton.translatesAutoresizingMaskIntoConstraints = false
totalButton.translatesAutoresizingMaskIntoConstraints = false
sendButton.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: preViewButton, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 5))
addConstraint(NSLayoutConstraint(item: preViewButton, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: sendButton, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: -5))
addConstraint(NSLayoutConstraint(item: sendButton, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: totalButton, attribute: .Right, relatedBy: .Equal, toItem: sendButton, attribute: .Left, multiplier: 1, constant: -5))
addConstraint(NSLayoutConstraint(item: totalButton, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
totalButton.addConstraint(NSLayoutConstraint(item: totalButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: CGFloat(buttonWidth)))
totalButton.addConstraint(NSLayoutConstraint(item: totalButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: CGFloat(buttonWidth)))
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
c3d8f09dc5fe2fceb936fd58c0950cf2
| 44.244444 | 191 | 0.680501 | 4.882494 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/Base/View/OMSTableView.swift
|
1
|
1521
|
//
// OMSTableView.swift
// OMS-WH
//
// Created by xuech on 2017/9/7.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class OMSTableView: UITableView,UITableViewDelegate,UITableViewDataSource{
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: private method
func setupUI() {
self.delegate = self
self.dataSource = self
// self.isScrollEnabled = true
// self.register(UINib(nibName: "CommonOrderInfoCell", bundle: nil), forCellReuseIdentifier: CommonOrderCellReuseIdentifier)
self.separatorStyle = UITableViewCellSeparatorStyle.none
delaysContentTouches = false
canCancelContentTouches = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 5
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
}
|
mit
|
65d796b76b2521695370fe6302b220ec
| 28.192308 | 139 | 0.655468 | 5.02649 | false | false | false | false |
didinozka/Projekt_Bakalarka
|
bp_v1/Beacon.swift
|
1
|
1285
|
//
// Beacon.swift
// bp_v1
//
// Created by Dusan Drabik on 15/03/16.
// Copyright © 2016 Dusan Drabik. All rights reserved.
//
import CoreLocation
import Foundation
class Beacon: NSObject{
// for now, concreteUUID is objectID from DB
private var _identifierUUID: String!
private var _proximityUUID: String!
private var _major: Int?
private var _minor: Int?
override var hash: Int {
let a = 31 &* _major!.hashValue
let b = _minor!.hashValue
return a &+ b
}
private var _beacon: CLBeacon!
init(beacon: CLBeacon){
_beacon = beacon
_major = beacon.major.integerValue
_minor = beacon.minor.integerValue
}
init(identifier: String, UUID: String, major: Int, minor: Int){
_identifierUUID = identifier
_proximityUUID = UUID
_major = major
_minor = minor
}
override init() {}
var Beacon: CLBeacon {
return _beacon
}
var ProximityUUID: String {
return _proximityUUID
}
var ConcreteUUID: String {
return _identifierUUID
}
var MajorValue: Int {
return _major!
}
var MinorValue: Int {
return _minor!
}
}
|
apache-2.0
|
6b0c9c57e1b86fdb40b39b164ee57e13
| 18.469697 | 67 | 0.563863 | 4.337838 | false | false | false | false |
Mosquito1123/WTPhotoBrowser
|
PhotoBrowser/WTPhotoBrowser.swift
|
1
|
15077
|
//
// PhotoBrowser.swift
// PhotoBrowser-swift
//
// Created by zhangwentong on 2017/5/30.
// Copyright © 2017年 YiXue. All rights reserved.
//
import UIKit
public enum WTPhotoBrowserIndicatorStyle {
case label
case pageControl
}
public enum WTPhotoBrowserIndicatorPosition {
case top
case bottom
}
public protocol WTPhotoBrowserDelegate {
func photoViewHasBeenLongPressed(_ longPress:UILongPressGestureRecognizer,_ cell:WTPhotoCell,_ image:UIImage,_ photoBrowser:WTPhotoBrowser)
}
public class WTPhotoBrowser: UIViewController {
public var photoBrowserDelegate:WTPhotoBrowserDelegate?
//提示 label
public var hud = UILabel()
fileprivate var originWindowLevel:UIWindowLevel!
public var photos: [WTPhoto]?
public var currentIndex: Int! {
didSet{
pageLabel.text = "\(currentIndex + 1) / \(photos?.count ?? 0)"
pageControl.currentPage = currentIndex
}
}
public var indicatorStyle = WTPhotoBrowserIndicatorStyle.label
public var indicatorPosition = WTPhotoBrowserIndicatorPosition.bottom
public var defaultPlaceholderImage: UIImage? {
didSet{
guard let defaultPlaceholderImage = defaultPlaceholderImage else {
return
}
photos?.forEach { (p) in
p.placeholderImage = defaultPlaceholderImage
}
}
}
public init(photos: [WTPhoto], currentIndex: Int, sourceImageViewClosure: ((Int)->(UIImageView))? = nil) {
super.init(nibName: nil, bundle: nil)
self.photos = photos
self.sourceImageViewClosure = sourceImageViewClosure
self.currentIndex = currentIndex
modalPresentationStyle = .custom
transitioningDelegate = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
sourceImageViewClosure = nil
}
var sourceImageView: UIImageView? {
return sourceImageViewClosure?(currentIndex)
}
var displayImageView: UIImageView? {
let cell = collectionView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? WTPhotoCell
return cell?.imageView
}
fileprivate var sourceImageViewClosure: ((Int)->(UIImageView))?
fileprivate let presentPhotoTransition = WTPhotoTransition(style: .present)
fileprivate let dismissPhotoTransition = WTPhotoTransition(style: .dismiss)
fileprivate var isOriginalStatusBarHidden = true
/*
lazy var actionBtn: UIButton = {
let actionBtn = UIButton()
actionBtn.setImage(UIImage(named: "icon_action"), for: .normal)
actionBtn.addTarget(self, action: #selector(WTPhotoBrowser.actionBtnClick), for: .touchUpInside)
return actionBtn
}()
*/
lazy var pageLabel: UILabel = {
let pageLabel = UILabel()
pageLabel.textColor = UIColor.white
pageLabel.font = UIFont.boldSystemFont(ofSize: 16)
pageLabel.textAlignment = .center
pageLabel.text = "\(self.currentIndex + 1) / \(self.photos?.count ?? 0)"
return pageLabel
}()
lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.pageIndicatorTintColor = UIColor.lightGray
pageControl.currentPageIndicatorTintColor = UIColor.white
pageControl.hidesForSinglePage = true
pageControl.isEnabled = false
return pageControl
}()
lazy var layout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = self.view.bounds.size
layout.sectionInset.right = layout.minimumLineSpacing
return layout
}()
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.layout.itemSize.width + self.layout.minimumLineSpacing, height: self.layout.itemSize.height), collectionViewLayout: self.layout)
collectionView.register(WTPhotoCell.self, forCellWithReuseIdentifier: String(describing: WTPhotoCell.self))
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isPagingEnabled = true
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.clear
return collectionView
}()
lazy var backgroundView: UIView = {
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.black
return backgroundView
}()
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
setupLayout()
setupGesture()
}
/// 遮盖状态栏。以改变windowLevel的方式遮盖
fileprivate func coverStatusBar(_ cover: Bool) {
let win = view.window ?? UIApplication.shared.keyWindow
guard let window = win else {
return
}
if originWindowLevel == nil {
originWindowLevel = window.windowLevel
}
if cover {
if window.windowLevel == UIWindowLevelStatusBar + 1 {
return
}
window.windowLevel = UIWindowLevelStatusBar + 1
}
else {
if window.windowLevel == originWindowLevel {
return
}
window.windowLevel = originWindowLevel
}
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.isHidden = sourceImageView != nil
isOriginalStatusBarHidden = UIApplication.shared.isStatusBarHidden
self.coverStatusBar(true)
// UIApplication.shared.setStatusBarHidden(true, with: .fade)
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.coverStatusBar(false)
// UIApplication.shared.setStatusBarHidden(isOriginalStatusBarHidden, with: .fade)
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
sourceImageView?.isHidden = false
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collectionView.isHidden = false
sourceImageView?.isHidden = true
}
// override public var prefersStatusBarHidden: Bool {
// return true
// }
}
extension WTPhotoBrowser: UIViewControllerTransitioningDelegate {
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return dismissPhotoTransition
}
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentPhotoTransition
}
}
extension WTPhotoBrowser: UICollectionViewDelegate, UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos?.count ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: WTPhotoCell.self), for: indexPath) as? WTPhotoCell else{
return WTPhotoCell()
}
cell.photo = photos?[indexPath.item]
return cell
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
sourceImageView?.isHidden = false
currentIndex = indexPath.item
sourceImageView?.isHidden = true
}
}
extension WTPhotoBrowser {
func setupUI() {
view.backgroundColor = UIColor.clear
view.addSubview(backgroundView)
view.addSubview(collectionView)
view.addSubview(pageLabel)
view.addSubview(pageControl)
// view.addSubview(actionBtn)
pageControl.numberOfPages = photos?.count ?? 0
switch indicatorStyle {
case .label:
pageControl.isHidden = true
pageLabel.isHidden = false
case .pageControl:
pageControl.isHidden = false
pageLabel.isHidden = true
}
collectionView.scrollToItem(at: IndexPath(item: self.currentIndex, section: 0), at: .left, animated: false)
}
func setupGesture() {
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(WTPhotoBrowser.doubleTap))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
let singleTap = UITapGestureRecognizer(target: self, action: #selector(WTPhotoBrowser.singleTap))
view.addGestureRecognizer(singleTap)
singleTap.require(toFail: doubleTap)
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(WTPhotoBrowser.longPress(_:)))
view.addGestureRecognizer(longPress)
let pan = UIPanGestureRecognizer(target: self, action: #selector(WTPhotoBrowser.pan(_:)))
view.addGestureRecognizer(pan)
}
func setupLayout() {
backgroundView.frame = view.bounds
// actionBtn.frame.size = CGSize(width: 44, height: 44)
// actionBtn.frame.origin.x = view.bounds.width - actionBtn.frame.width
// actionBtn.frame.origin.y = view.bounds.height - actionBtn.frame.height
switch indicatorPosition {
case .bottom:
pageLabel.frame.size.height = 44
pageLabel.frame.size.width = view.bounds.width
pageLabel.frame.origin.y = view.bounds.height - pageLabel.frame.height
default:
pageLabel.frame.size.height = 44
pageLabel.frame.size.width = view.bounds.width
// pageLabel.frame.origin.y = view.bounds.height - pageLabel.frame.height
}
pageControl.frame = pageLabel.frame
}
}
extension WTPhotoBrowser {
func pan(_ pan: UIPanGestureRecognizer) {
let transition = pan.translation(in: view)
let cell = collectionView.visibleCells.last
switch pan.state {
case .began:
break
case .ended, .cancelled, .failed, .possible:
if transition.y > 30 {
dismiss(animated: true, completion: nil)
}else {
UIView.animate(withDuration: 0.25, animations: {
self.backgroundView.alpha = 1
cell?.transform = CGAffineTransform.identity
})
}
case .changed:
let scale = 1 - transition.y / UIScreen.main.bounds.height
var transform = CGAffineTransform(translationX: transition.x, y: transition.y)
if transition.y > 0 {
transform = transform.concatenating(CGAffineTransform(scaleX: scale, y: scale))
}
backgroundView.alpha = scale
cell?.transform = transform
}
}
func doubleTap() {
let cell = collectionView.visibleCells.last as? WTPhotoCell
cell?.didZoom()
}
func singleTap() {
dismiss(animated: true, completion: nil)
}
func longPress(_ longPress: UILongPressGestureRecognizer) {
if let cell = self.collectionView.visibleCells.last as? WTPhotoCell, let image = cell.imageView.image {
photoBrowserDelegate?.photoViewHasBeenLongPressed(longPress, cell, image, self)
}
}
/*
func actionBtnClick() {
let alertC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
alertC.addAction(UIAlertAction(title: "保存图片", style: .default, handler: { (_) in
if let cell = self.collectionView.visibleCells.last as? WTPhotoCell, let image = cell.imageView.image {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(WTPhotoBrowser.image(image:didFinishSavingWithError:contextInfo:)), nil)
}
}))
present(alertC, animated: true, completion: nil)
}
func image(image: UIImage, didFinishSavingWithError: Error?, contextInfo: Any?) {
hud.layer.cornerRadius = 5
hud.textAlignment = .center
hud.textColor = UIColor.white
hud.font = UIFont.systemFont(ofSize: 14)
hud.backgroundColor = UIColor.black.withAlphaComponent(0.75)
hud.clipsToBounds = true
if didFinishSavingWithError == nil {
hud.text = "保存成功"
}else {
hud.text = "保存失败"
}
hud.sizeToFit()
hud.frame.size.width += 30
hud.frame.size.height += 20
hud.center = view.center
hud.alpha = 0
if hud.isDescendant(of: view){
}else{
view.addSubview(hud)
}
UIView.animate(withDuration: 0.25, animations: {
self.hud.alpha = 1
}) { (_) in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
UIView.animate(withDuration: 0.25, animations: {
self.hud.alpha = 0
}, completion: { (_) in
if self.hud.isDescendant(of: self.view){
self.hud.removeFromSuperview()
}else{
}
})
})
}
}
*/
}
|
mit
|
bedc8941797e1235c853e2a636a859c0
| 29.148594 | 212 | 0.592314 | 5.732722 | false | false | false | false |
SlayterDev/FermChamber
|
FermentationTracker/DatePickerTextField.swift
|
1
|
2729
|
//
// DatePickerTextField.swift
// FementationTracker
//
// Created by Bradley Slayter on 2/4/16.
//
import UIKit
/* --- ABOUT THIS SHARED CLASS
Creates an extension of `RoundedBorderTextField` which sets a date picker as the input interface, rather than a default alphanumeric keyboard.
Uses the `DoneAccessoryView` to close the date picker.
Initialization:
- Must pass in a frame and the parent view controller.
- The parent view controller will be "self" in the class which creates an instance of this class
- Uses the parentVC to determine the width of the accessory view
*/
protocol DatePickerProtocol {
func didPickDate()
}
class DatePickerTextField: SharedTextField {
let datePicker = UIDatePicker()
var date: NSDate?
var pickerDelegate: DatePickerProtocol?
init(frame: CGRect, parentVC: UIViewController) {
super.init(frame: frame)
self.placeholder = "MM/dd/yyyy"
// Create datePicker
datePicker.setDate(NSDate(), animated: false)
datePicker.datePickerMode = .Date;
datePicker.addTarget(self, action: #selector(didChooseDate), forControlEvents: .ValueChanged)
self.inputView = datePicker
// Create "Done" button to close date picker
let accessoryView = DoneAccessoryView(frame: CGRect(x: 0.0, y: 0.0, width: parentVC.view.frame.size.width, height: 40.0))
accessoryView.doneButton!.addTarget(self, action: #selector(closeDatePicker), forControlEvents: .TouchUpInside)
self.inputAccessoryView = accessoryView
}
// Close the date picker
func closeDatePicker() {
if self.text == "" {
didChooseDate()
}
self.resignFirstResponder()
}
// Get the selected date and populate the text field with it
func didChooseDate() {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let selectedDate = datePicker.date
self.date = selectedDate
let dateString = String(dateFormatter.stringFromDate(selectedDate))
self.text = dateString
}
override func resignFirstResponder() -> Bool {
pickerDelegate?.didPickDate()
return super.resignFirstResponder()
}
override func becomeFirstResponder() -> Bool {
if self.text != "" {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
datePicker.date = dateFormatter.dateFromString(self.text!)!
}
return super.becomeFirstResponder()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
mit
|
188c14cefa32be4eeba6c122915687a5
| 29.322222 | 142 | 0.654086 | 4.847247 | false | false | false | false |
wess/overlook
|
Sources/env/env.swift
|
1
|
1649
|
//
// env.swift
// overlook
//
// Created by Wesley Cope on 9/30/16.
//
//
import Foundation
import PathKit
public struct Env {
public let path:Path
public init() {
self.init(Path.current)
}
public init(_ path:String) {
self.init(Path(path))
}
public init(_ path:Path) {
self.path = path
setup()
}
private func setup() {
var path = ProcessInfo.processInfo.environment["PATH"] ?? ""
path += ":\(Path.current.absolute())"
set("PATH", value: path)
}
@discardableResult
private func exec(_ arguments:[String]) -> String? {
let pipe = Pipe()
let process = Process()
process.launchPath = "/usr/bin/env"
process.arguments = arguments
process.standardOutput = pipe
process.launch()
let handle = pipe.fileHandleForReading
let data = handle.readDataToEndOfFile()
return String(data: data, encoding: .utf8)
}
}
extension Env /* Get/Set */ {
public func get(_ key:String) -> String? {
return ProcessInfo.processInfo.environment[key]
}
public func set(_ key:String, value:String) {
set(key, value:value, override:true)
}
public func set(_ key:String, value:String, override:Bool = true) {
setenv(key, value, override ? 1 : 0)
}
public func delete(_ key:String) {
unsetenv(key)
}
}
extension Env /* subscript */ {
public subscript(key:String) -> String? {
get {
return self.get(key)
}
set {
guard let newValue = newValue else {
self.delete(key)
return
}
self.set(key, value: newValue)
}
}
}
|
mit
|
04e0f816b69daa5d9a097330dfa16fa1
| 17.322222 | 69 | 0.588235 | 3.747727 | false | false | false | false |
jalehman/rottentomatoes
|
RottenTomatoes/Movie.swift
|
1
|
1078
|
//
// Movie.swift
// RottenTomatoes
//
// Created by Josh Lehman on 2/5/15.
// Copyright (c) 2015 Josh Lehman. All rights reserved.
//
import Foundation
class Movie: NSObject {
// MARK: Properties
let id: String
let title: String
let year: Int
let mpaaRating: String
let criticScore: Int
let audienceScore: Int
let synopsis: String
let lowResImageURL: NSURL
let imageURL: NSURL
// MARK: API
init(id: String, title: String, year: Int, mpaaRating: String, criticScore: Int, audienceScore: Int, synopsis: String, imageURL: String) {
self.id = id
self.title = title
self.year = year
self.mpaaRating = mpaaRating
self.criticScore = criticScore
self.audienceScore = audienceScore
self.synopsis = synopsis
// TODO: Use a Swift setter?
self.lowResImageURL = NSURL(string: imageURL)!
self.imageURL = NSURL(string: imageURL.stringByReplacingOccurrencesOfString("_tmb.", withString: "_ori.", options: nil, range: nil))!
}
}
|
gpl-2.0
|
3603f4b6d35fd5c09fe8063d747cd9d5
| 25.975 | 142 | 0.635436 | 3.963235 | false | false | false | false |
cseduardorangel/Cantina
|
Cantina/Class/ViewController/ProductsViewController.swift
|
1
|
4112
|
//
// ProductsViewController.swift
// Cantina
//
// Created by Eduardo Rangel on 8/26/15.
// Copyright © 2015 Concrete Solutions. All rights reserved.
//
import UIKit
class ProductsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ProductCellDelegate {
//////////////////////////////////////////////////////////////////////
// MARK: IBOutlets
@IBOutlet weak var tableView: UITableView!
//////////////////////////////////////////////////////////////////////
// MARK: - Variables
var sales: NSMutableArray! = NSMutableArray()
var products: [Product] = []
var credential: Credentials?
//////////////////////////////////////////////////////////////////////
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
CredentialsService.getUser(CredentialStore().get(), completion : { (success, object) -> Void in
self.credential = object
})
ProductService.getAllProducts({ (objects, error) -> Void in
self.products = objects as! [Product]
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//////////////////////////////////////////////////////////////////////
// MARK: - IBActions
@IBAction func buyProducts(sender: AnyObject) {
let totalPrice = self.sales.reduce(0) {
$0 + CGFloat(($1 as! Sale).product.price)
}
let alertController = UIAlertController(title: "Confirma", message: "Compra no valor de R$" + String(format: "%.2f", totalPrice) + "?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Não", style: .Cancel) { (action) in
}
let OKAction = UIAlertAction(title: "Sim", style: .Default) { (action) in
SaleService.saveAll(self.sales, completion: { (success, error) -> Void in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
print("Comprando #\(self.sales)!", terminator: "")
})
})
}
alertController.addAction(OKAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true) {
}
}
@IBAction func close(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
//////////////////////////////////////////////////////////////////////
// MARK: - ProductCellDelegate
func addProductToBuy(product: Product) {
let sale = Sale()
sale.product = product
sale.buyer = credential!
self.sales.addObject(sale)
}
func removeProductToBuy(product: Product) {
let sale = Sale()
sale.product = product
sale.buyer = credential!
self.sales.removeObject(sale)
}
//////////////////////////////////////////////////////////////////////
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.products.count
}
//////////////////////////////////////////////////////////////////////
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: ProductCell = tableView.dequeueReusableCellWithIdentifier("ProductCell", forIndexPath: indexPath) as! ProductCell
cell.configureCell(self.products[indexPath.row], delegate: self)
return cell
}
//////////////////////////////////////////////////////////////////////
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
|
mit
|
55a12bf5ababf5263efe4c331c2bb5e8
| 27.950704 | 168 | 0.49927 | 5.982533 | false | false | false | false |
Senspark/ee-x
|
src/ios/ee/facebook_ads/FacebookInterstitialAd.swift
|
1
|
5280
|
//
// FacebookInterstitialAd.swift
// Pods
//
// Created by eps on 6/24/20.
//
import FBAudienceNetwork
import Foundation
private let kTag = "\(FacebookInterstitialAd.self)"
internal class FacebookInterstitialAd:
NSObject, IFullScreenAd, FBInterstitialAdDelegate {
private let _bridge: IMessageBridge
private let _logger: ILogger
private let _adId: String
private let _messageHelper: MessageHelper
private var _helper: FullScreenAdHelper?
private var _isLoaded = false
private var _displaying = false
private var _ad: FBInterstitialAd?
init(_ bridge: IMessageBridge,
_ logger: ILogger,
_ adId: String) {
_bridge = bridge
_logger = logger
_adId = adId
_messageHelper = MessageHelper("FacebookInterstitialAd", _adId)
super.init()
_helper = FullScreenAdHelper(_bridge, self, _messageHelper)
registerHandlers()
}
func destroy() {
deregisterHandlers()
destroyInternalAd()
}
func registerHandlers() {
_helper?.registerHandlers()
}
func deregisterHandlers() {
_helper?.deregisterHandlers()
}
func createInternalAd() -> FBInterstitialAd {
if let currentAd = _ad {
return currentAd
}
let ad = FBInterstitialAd(placementID: _adId)
ad.delegate = self
_ad = ad
return ad
}
func destroyInternalAd() {
Thread.runOnMainThread {
guard let ad = self._ad else {
return
}
ad.delegate = nil
self._ad = nil
}
}
var isLoaded: Bool {
return _isLoaded
}
func load() {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
let ad = self.createInternalAd()
ad.load()
}
}
func show() {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
guard let rootView = Utils.getCurrentRootViewController() else {
assert(false, "Current rootView is null")
self._bridge.callCpp(self._messageHelper.onFailedToShow, EEJsonUtils.convertDictionary(toString: [
"code": -1,
"message": "Null root view"
]))
return
}
self._displaying = true
let ad = self.createInternalAd()
let result = ad.show(fromRootViewController: rootView)
if result {
// OK.
} else {
self._isLoaded = false
self.destroyInternalAd()
self._bridge.callCpp(self._messageHelper.onFailedToShow, EEJsonUtils.convertDictionary(toString: [
"code": -1,
"message": "Failed to show ad"
]))
}
}
}
func interstitialAdDidLoad(_ interstitialAd: FBInterstitialAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
self._isLoaded = true
self._bridge.callCpp(self._messageHelper.onLoaded)
}
}
func interstitialAd(_ interstitialAd: FBInterstitialAd, didFailWithError error: Error) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId) message = \(error.localizedDescription)")
self.destroyInternalAd()
if self._displaying {
self._displaying = false
self._isLoaded = false
self._bridge.callCpp(self._messageHelper.onFailedToShow, EEJsonUtils.convertDictionary(toString: [
"code": (error as NSError).code,
"message": error.localizedDescription
]))
} else {
self._bridge.callCpp(self._messageHelper.onFailedToLoad, EEJsonUtils.convertDictionary(toString: [
"code": (error as NSError).code,
"message": error.localizedDescription
]))
}
}
}
func interstitialAdWillLogImpression(_ interstitialAd: FBInterstitialAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
}
}
func interstitialAdDidClick(_ interstitialAd: FBInterstitialAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
self._bridge.callCpp(self._messageHelper.onClicked)
}
}
func interstitialAdWillClose(_ interstitialAd: FBInterstitialAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
}
}
func interstitialAdDidClose(_ interstitialAd: FBInterstitialAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
self._displaying = false
self._isLoaded = false
self.destroyInternalAd()
self._bridge.callCpp(self._messageHelper.onClosed)
}
}
}
|
mit
|
a80b9eba2ff548a2ac562c4669e42803
| 31.195122 | 115 | 0.55322 | 4.976437 | false | false | false | false |
joemcbride/outlander-osx
|
src/Outlander/PresetCommandHandler.swift
|
1
|
1886
|
//
// PresetCommandHandler.swift
// Outlander
//
// Created by Joseph McBride on 1/24/17.
// Copyright © 2017 Joe McBride. All rights reserved.
//
import Foundation
@objc
class PresetCommandHandler : NSObject, CommandHandler {
class func newInstance() -> PresetCommandHandler {
return PresetCommandHandler()
}
func canHandle(command: String) -> Bool {
return command.lowercaseString.hasPrefix("#preset")
}
func handle(command: String, withContext: GameContext) {
let text = command
.substringFromIndex(command.startIndex.advancedBy(7))
.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let options = text.componentsSeparatedByString(" ")
if options.count > 0 && options[0].lowercaseString == "reload" {
let loader = PresetLoader.newInstance(withContext, fileSystem: LocalFileSystem())
loader.load()
withContext.events.echoText("Preset colors reloaded", mono: true, preset: "")
return
}
handleAddUpdate(options, context: withContext)
}
func handleAddUpdate(options: [String], context: GameContext) {
guard options.count > 2 else {
context.events.echoText("You must provide a preset name and value", mono: true, preset: "scripterror")
return
}
let name = options[0]
let foreColor = options[1]
let backgroundColor = options.count > 2 ? options[2] : ""
let presetColor = ColorPreset(name, foreColor, backgroundColor, "")
if let found = context.presets[name] {
found.color = foreColor
if backgroundColor.characters.count > 0 {
found.backgroundColor = backgroundColor
}
} else {
context.presets[name] = presetColor
}
}
}
|
mit
|
2d456add42c327aec4f5a7662e362b5c
| 30.416667 | 114 | 0.63183 | 4.772152 | false | false | false | false |
thompsonate/Shifty
|
Shifty/AppDelegate.swift
|
1
|
11363
|
//
// AppDelegate.swift
// Shifty
//
// Created by Nate Thompson on 5/3/17.
//
//
import Cocoa
import ServiceManagement
import AppCenter
import AppCenterAnalytics
import AppCenterCrashes
import LetsMove
import MASPreferences_Shifty
import AXSwift
import SwiftLog
import Sparkle
import Intents
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let prefs = UserDefaults.standard
@IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
var statusItemClicked: (() -> Void)?
lazy var preferenceWindowController: PrefWindowController = {
return PrefWindowController(
viewControllers: [
PrefGeneralViewController(),
PrefShortcutsViewController(),
PrefAboutViewController()],
title: NSLocalizedString("prefs.title", comment: "Preferences"))
}()
var setupWindow: NSWindow!
var setupWindowController: NSWindowController!
func applicationDidFinishLaunching(_ aNotification: Notification) {
#if !DEBUG
PFMoveToApplicationsFolderIfNecessary()
#endif
UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true])
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: Keys.analyticsPermission) {
#if !DEBUG
AppCenter.start(withAppSecret: "a0d14d8b-fd4d-4512-8901-d5cfe5249548", services:[Analytics.self, Crashes.self])
#endif
} else if userDefaults.bool(forKey: Keys.hasSetupWindowShown)
&& userDefaults.value(forKey: Keys.lastInstalledShiftyVersion) == nil {
// If updated from beta version
userDefaults.set(true, forKey: Keys.analyticsPermission)
}
// Initialize Sparkle
SUUpdater.shared()
let versionObject = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
userDefaults.set(versionObject as? String ?? "", forKey: Keys.lastInstalledShiftyVersion)
Event.appLaunched(preferredLocalization: Bundle.main.preferredLocalizations.first ?? "").record()
logw("")
logw("App launched")
logw("macOS \(ProcessInfo().operatingSystemVersionString)")
logw("Shifty Version \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")")
verifyOperatingSystemVersion()
verifySupportsNightShift()
let launcherAppIdentifier = "io.natethompson.ShiftyHelper"
let startedAtLogin = NSWorkspace.shared.runningApplications.contains {
$0.bundleIdentifier == launcherAppIdentifier
}
if startedAtLogin {
DistributedNotificationCenter.default().post(name: .terminateApp, object: Bundle.main.bundleIdentifier!)
}
//Show alert if accessibility permissions have been revoked while app is not running
if UserDefaults.standard.bool(forKey: Keys.isWebsiteControlEnabled) && !UIElement.isProcessTrusted() {
Event.accessibilityRevokedAlertShown.record()
logw("Accessibility permissions revoked while app was not running")
showAccessibilityDeniedAlert()
UserDefaults.standard.set(false, forKey: Keys.isWebsiteControlEnabled)
}
observeAccessibilityApiNotifications()
logw("Night Shift state: \(NightShiftManager.shared.isNightShiftEnabled)")
logw("Schedule: \(NightShiftManager.shared.schedule)")
logw("")
updateMenuBarIcon()
setStatusToggle()
NightShiftManager.shared.onNightShiftChange {
self.updateMenuBarIcon()
}
statusItem.behavior = .terminationOnRemoval
statusItem.isVisible = true
let hasSetupWindowShown = userDefaults.bool(forKey: Keys.hasSetupWindowShown)
if (!hasSetupWindowShown && !UIElement.isProcessTrusted()) || ProcessInfo.processInfo.environment["show_setup"] == "true" {
showSetupWindow()
}
}
//MARK: Called after application launch
func verifyOperatingSystemVersion() {
if !ProcessInfo().isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 10, minorVersion: 12, patchVersion: 4)) {
Event.oldMacOSVersion(version: ProcessInfo().operatingSystemVersionString).record()
logw("Operating system version not supported")
NSApplication.shared.activate(ignoringOtherApps: true)
let alert: NSAlert = NSAlert()
alert.messageText = NSLocalizedString("alert.version_message", comment: "This version of macOS does not support Night Shift")
alert.informativeText = NSLocalizedString("alert.version_informative", comment: "Update your Mac to version 10.12.4 or higher to use Shifty.")
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: NSLocalizedString("general.ok", comment: "OK"))
alert.runModal()
NSApplication.shared.terminate(self)
}
}
func verifySupportsNightShift() {
if !NightShiftManager.supportsNightShift {
Event.unsupportedHardware.record()
logw("System does not support Night Shift")
NSApplication.shared.activate(ignoringOtherApps: true)
let alert: NSAlert = NSAlert()
alert.messageText = NSLocalizedString("alert.hardware_message", comment: "Your Mac does not support Night Shift")
alert.informativeText = NSLocalizedString("alert.hardware_informative", comment: "A newer Mac is required to use Shifty.")
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: NSLocalizedString("general.ok", comment: "OK"))
alert.runModal()
NSApplication.shared.terminate(self)
}
}
func showAccessibilityDeniedAlert() {
NSApplication.shared.activate(ignoringOtherApps: true)
let alert: NSAlert = NSAlert()
alert.messageText = NSLocalizedString("alert.accessibility_disabled_message", comment: "Accessibility permissions for Shifty have been disabled")
alert.informativeText = NSLocalizedString("alert.accessibility_disabled_informative", comment: "Accessibility must be allowed to enable website shifting. Grant access to Shifty in Security & Privacy preferences, located in System Preferences.")
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: NSLocalizedString("alert.open_preferences", comment: "Open System Preferences"))
alert.addButton(withTitle: NSLocalizedString("alert.not_now", comment: "Not now"))
if alert.runModal() == .alertFirstButtonReturn {
NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")!)
logw("Open System Preferences button clicked")
} else {
logw("Not now button clicked")
}
}
func showSetupWindow() {
let storyboard = NSStoryboard(name: "Setup", bundle: nil)
setupWindowController = storyboard.instantiateInitialController() as? NSWindowController
setupWindow = setupWindowController.window
NSApplication.shared.activate(ignoringOtherApps: true)
setupWindowController.showWindow(self)
setupWindow.makeMain()
UserDefaults.standard.set(true, forKey: Keys.hasSetupWindowShown)
}
func observeAccessibilityApiNotifications() {
DistributedNotificationCenter.default().addObserver(forName: NSNotification.Name("com.apple.accessibility.api"), object: nil, queue: nil) { _ in
logw("Accessibility permissions changed: \(UIElement.isProcessTrusted(withPrompt: false))")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
if UIElement.isProcessTrusted(withPrompt: false) {
UserDefaults.standard.set(true, forKey: Keys.isWebsiteControlEnabled)
} else {
UserDefaults.standard.set(false, forKey: Keys.isWebsiteControlEnabled)
}
})
}
}
//MARK: Status menu item
func updateMenuBarIcon() {
var icon: NSImage
if UserDefaults.standard.bool(forKey: Keys.isIconSwitchingEnabled),
NightShiftManager.shared.isNightShiftEnabled == false
{
icon = #imageLiteral(resourceName: "sunOpenIcon")
} else {
icon = #imageLiteral(resourceName: "shiftyMenuIcon")
}
icon.isTemplate = true
DispatchQueue.main.async {
self.statusItem.button?.image = icon
}
}
func setStatusToggle() {
statusItem.menu = nil
if let button = statusItem.button {
button.action = #selector(statusBarButtonClicked)
button.sendAction(on: [.leftMouseUp, .leftMouseDown, .rightMouseUp, .rightMouseDown])
}
}
@objc func statusBarButtonClicked(sender: NSStatusBarButton) {
guard let event = NSApp.currentEvent else { return }
if UserDefaults.standard.bool(forKey: Keys.isStatusToggleEnabled) {
if event.type == .rightMouseDown
|| event.type == .rightMouseUp
|| event.modifierFlags.contains(.control)
{
statusItem.menu = statusMenu
statusItem.button?.performClick(sender)
statusItem.menu = nil
} else if event.type == .leftMouseUp {
statusItemClicked?()
}
} else {
if event.type == .rightMouseUp
|| (event.type == .leftMouseUp
&& event.modifierFlags.contains(.control))
{
statusItemClicked?()
} else if event.type == .leftMouseDown
&& !event.modifierFlags.contains(.control)
{
statusItem.menu = statusMenu
statusItem.button?.performClick(sender)
statusItem.menu = nil
}
}
}
func applicationWillTerminate(_ aNotification: Notification) {
logw("App terminated")
}
@available(macOS 12.0, *)
func application(_ application: NSApplication, handlerFor intent: INIntent) -> Any? {
if intent is GetNightShiftStateIntent {
return GetNightShiftStateIntentHandler()
}
if intent is SetNightShiftStateIntent {
return SetNightShiftStateIntentHandler()
}
if intent is GetColorTemperatureIntent {
return GetColorTemperatureIntentHandler()
}
if intent is SetColorTemperatureIntent {
return SetColorTemperatureIntentHandler()
}
if intent is SetDisableTimerIntent {
return SetDisableTimerIntentHandler()
}
if intent is GetTrueToneStateIntent {
return GetTrueToneStateIntentHandler()
}
if intent is SetTrueToneStateIntent {
return SetTrueToneStateIntentHandler()
}
return nil
}
}
|
gpl-3.0
|
5c2a5cadacb362acc16a16cb4911b65b
| 38.730769 | 252 | 0.644284 | 5.304855 | false | false | false | false |
jlmatus/ClientSuccessAPI
|
ClientSuccessSwift/ClientSuccess.swift
|
1
|
1982
|
//
// ClientSuccess.swift
// ClientSuccess
//
// Created by Jose on 10/28/15.
// Copyright © 2015 Rain Agency. All rights reserved.
//
import Foundation
public class ClientSuccess {
public static let sharedController = ClientSuccess()
private let clientSucessURL = "https://usage.clientsuccess.com/collector/1.0.0/projects/"
private let eventString = "/events/"
public var apiKey: String?
public var projectId: String?
public func addEvent(eventId: String, organizationId: String, organizationName: String, userId: String, userName: String, userEmail: String, eventValue: String, completionHandler handler: (() -> ())? = nil, errorHandler: ((errorMessage: String) -> ())? = nil) {
if let apiKey = apiKey, projectId = projectId, urlString = (clientSucessURL.stringByAppendingString(projectId).stringByAppendingString(eventString).stringByAppendingString(eventId + "?api_key=").stringByAppendingString(apiKey)).stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()), url = NSURL(string: urlString) {
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = "{\n \"identity\": {\n \"organization\": {\n \"id\": \(organizationId),\n \"name\": \"\(organizationName)\"\n },\n \"user\": {\n \"id\": \(userId),\n \"name\": \"\(userName)\",\n \"email\": \"\(userEmail)\"\n }\n },\n \"value\": \(eventValue)\n}".dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { _, _, error in
if let errorMessage = error?.description {
errorHandler?(errorMessage: errorMessage)
} else {
handler?()
}
}
task.resume()
}
}
}
|
mit
|
74d9043094c2bbe8e2cf28eb66cecd36
| 49.794872 | 352 | 0.636042 | 4.773494 | false | false | false | false |
eytanbiala/On-The-Map
|
On The Map/User.swift
|
1
|
925
|
//
// User.swift
// On The Map
//
// Created by Eytan Biala on 6/13/16.
// Copyright © 2016 Udacity. All rights reserved.
//
import Foundation
import MapKit
struct User {
let first: String
let last: String
let url: String
let location: String
let coordinate: CLLocationCoordinate2D
init(dictionary: Dictionary<String, AnyObject>) {
first = dictionary["firstName"] as! String
last = dictionary["lastName"] as! String
url = dictionary["mediaURL"] as! String
location = dictionary["mapString"] as! String
if let latitude = dictionary["latitude"] as? Double, longitude = dictionary["longitude"] as? Double {
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
} else {
coordinate = kCLLocationCoordinate2DInvalid
}
}
func full() -> String {
return "\(first) \(last)"
}
}
|
mit
|
ead0329005c7889310d31ff8a011570d
| 26.205882 | 109 | 0.636364 | 4.379147 | false | false | false | false |
digipost/ios
|
Digipost/UIToolbar+Actions.swift
|
1
|
7768
|
//
// Copyright (C) Posten Norge AS
//
// 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 UIKit
extension UIToolbar {
func invoiceButtonInLetterController(_ letterViewController: POSLetterViewController) -> UIBarButtonItem {
let invoiceButton = UIButton(frame: CGRect(x: 0, y: 0, width: 170, height: 44))
invoiceButton.addTarget(letterViewController, action: #selector(letterViewController.didTapInvoice), for: UIControlEvents.touchUpInside)
invoiceButton.setTitle(letterViewController.attachment.invoice.titleForInvoiceButtonLabel(letterViewController.isSendingInvoice), for: UIControlState())
invoiceButton.setTitleColor(UIColor.digipostSpaceGrey(), for: UIControlState())
invoiceButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
invoiceButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 3, right: 15)
invoiceButton.accessibilityLabel = NSLocalizedString("actions toolbar invoice accessibility label", comment: "read when user taps invoice button on voice over")
let invoiceBarButtonItem = UIBarButtonItem(customView: invoiceButton)
return invoiceBarButtonItem
}
func infoBarButtonItemInLetterViewController(_ letterViewController: POSLetterViewController) -> UIBarButtonItem {
let infoBarButtonItem = UIBarButtonItem(image: UIImage(named: "Info"), style: UIBarButtonItemStyle.done, target: letterViewController, action: #selector(POSLetterViewController.didTapInformationBarButtonItem))
infoBarButtonItem.accessibilityLabel = NSLocalizedString("actions toolbar info accessibility label", comment: "read when user taps the info button on voice over")
return infoBarButtonItem
}
func moveDocumentBarButtonItemInLetterViewController(_ letterViewController: POSLetterViewController) -> UIBarButtonItem {
let moveDocumentBarButtonItem = UIBarButtonItem(image: UIImage(named: "Move"), style: UIBarButtonItemStyle.done, target: letterViewController, action: #selector(POSLetterViewController.didTapMoveDocumentBarButtonItem))
moveDocumentBarButtonItem.accessibilityLabel = NSLocalizedString("actions toolbar move accessibility label", comment: "read when user taps move button on voice over")
return moveDocumentBarButtonItem
}
func deleteDocumentBarButtonItemInLetterViewController(_ letterViewController: POSLetterViewController) -> UIBarButtonItem {
let deleteDocumentBarButtonItem = UIBarButtonItem(image: UIImage(named: "Delete"), style: UIBarButtonItemStyle.done, target: letterViewController, action: #selector(POSLetterViewController.didTapDeleteDocumentBarButtonItem))
deleteDocumentBarButtonItem.accessibilityLabel = NSLocalizedString("actions toolbar delete accessibility label", comment: "read when user taps delete button on voice over")
return deleteDocumentBarButtonItem
}
func renameDocumentBarButtonItemInLetterViewController(_ letterViewController: POSLetterViewController) -> UIBarButtonItem {
let renameDocumentBarButtonItem = UIBarButtonItem(image: UIImage(named: "New name"), style: UIBarButtonItemStyle.done, target: letterViewController, action: #selector(POSLetterViewController.didTapRenameDocumentBarButtonItem))
renameDocumentBarButtonItem.accessibilityLabel = NSLocalizedString("actions toolbar rename accessibility label", comment: "read when user taps rename button on voice over")
return renameDocumentBarButtonItem
}
func openDocumentBarButtonItemInLetterViewController(_ letterViewController: POSLetterViewController) -> UIBarButtonItem {
let openDocumentBarButtonItem = UIBarButtonItem(image: UIImage(named: "Open_in"), style: UIBarButtonItemStyle.done, target: letterViewController, action: #selector(POSLetterViewController.didTapOpenDocumentInExternalAppBarButtonItem))
openDocumentBarButtonItem.accessibilityLabel = NSLocalizedString("actions toolbar openIn accessibility label", comment: "read when user taps openIn button on voice over")
return openDocumentBarButtonItem
}
@objc func setupIconsForLetterViewController(_ letterViewController: POSLetterViewController) -> NSArray{
barTintColor = UIColor.white
let flexibleSpaceBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let items = NSMutableArray()
items.add(infoBarButtonItemInLetterViewController(letterViewController))
items.add(flexibleSpaceBarButtonItem)
if let attachment = letterViewController.attachment as POSAttachment? {
if attachment.hasValidToPayInvoice() {
if (attachment.mainDocument.boolValue){
items.addObjects(from: itemsForValidInvoice(letterViewController) as [AnyObject])
}else {
items.addObjects(from: itemsForAttachmentThatIsInvoice(letterViewController) as [AnyObject])
}
} else {
items.addObjects(from: itemsForStandardLetter(letterViewController) as [AnyObject])
}
}
self.tintColor = UIColor.digipostSpaceGrey()
return items
}
fileprivate func itemsForValidInvoice (_ letterViewController: POSLetterViewController) -> NSArray {
let items = NSMutableArray()
let flexibleSpaceBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let moreOptionsBarButtonItem = UIBarButtonItem(image: UIImage(named: "More"), style: UIBarButtonItemStyle.done, target: letterViewController, action: #selector(letterViewController.didTapMoreOptionsBarButtonItem))
items.add(invoiceButtonInLetterController(letterViewController))
items.add(flexibleSpaceBarButtonItem)
items.add(moreOptionsBarButtonItem)
return items
}
fileprivate func itemsForStandardLetter(_ letterViewController: POSLetterViewController) -> NSArray {
let items = NSMutableArray()
let flexibleSpaceBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
items.add(moveDocumentBarButtonItemInLetterViewController(letterViewController))
items.add(flexibleSpaceBarButtonItem)
items.add(deleteDocumentBarButtonItemInLetterViewController(letterViewController))
items.add(flexibleSpaceBarButtonItem)
items.add(renameDocumentBarButtonItemInLetterViewController(letterViewController))
items.add(flexibleSpaceBarButtonItem)
items.add(openDocumentBarButtonItemInLetterViewController(letterViewController))
return items
}
fileprivate func itemsForAttachmentThatIsInvoice(_ letterViewController: POSLetterViewController) -> NSArray {
let items = NSMutableArray()
let flexibleSpaceBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
items.add(invoiceButtonInLetterController(letterViewController))
items.add(flexibleSpaceBarButtonItem)
return items
}
}
|
apache-2.0
|
82d77c0a322b6bce57168eea682d1c3a
| 63.198347 | 242 | 0.760427 | 5.715968 | false | false | false | false |
AlexZd/SRT
|
Pod/Utils/PHAssetCollection+Helpers.swift
|
1
|
3054
|
//
// PHAssetCollection+Helpers.swift
// Ardhi
//
// Created by Alex Zdorovets on 1/4/16.
// Copyright © 2016 Solutions 4 Mobility. All rights reserved.
//
import Photos
public typealias PhotosCompletionBlock = (collection: PHAssetCollection?) -> Void
public typealias PhotosAddImageCompletionBlock = (assetPlaceholder:PHObjectPlaceholder?, error: NSError?) -> Void
extension PHAssetCollection {
public class func saveImageToAlbum(image:UIImage, albumName:String, completionBlock:PhotosAddImageCompletionBlock?) {
self.findOrCreateAlbum(albumName) { (collection) -> Void in
collection?.addImage(image, completionBlock: completionBlock)
}
}
/** Get album with name, if there is no such album it will be created */
public class func findOrCreateAlbum(name:String, completionBlock:PhotosCompletionBlock?) {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", name)
let collection = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: .Any, options: fetchOptions)
if let first = collection.firstObject as? PHAssetCollection {
completionBlock?(collection: first)
}else{
var assetCollectionPlaceholder : PHObjectPlaceholder!
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(name)
assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
dispatch_async(dispatch_get_main_queue()) {
if (success) {
let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([assetCollectionPlaceholder.localIdentifier], options: nil)
completionBlock?(collection: collectionFetchResult.firstObject as? PHAssetCollection)
}
completionBlock?(collection: nil)
}
})
}
}
/** Adds UIImage to current album */
public func addImage(image:UIImage, completionBlock:PhotosAddImageCompletionBlock?) {
var assetPlaceholder : PHObjectPlaceholder?
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
if let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self) {
albumChangeRequest.addAssets([assetPlaceholder!])
}
}) { (success, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
completionBlock?(assetPlaceholder: assetPlaceholder, error: error)
}
}
}
}
|
mit
|
54a4e84b5efe9f279eaf50e38eca5b1a
| 49.065574 | 175 | 0.680642 | 5.939689 | false | false | false | false |
natecook1000/swift
|
test/SILGen/closures.swift
|
2
|
42976
|
// RUN: %target-swift-emit-silgen -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library %s | %FileCheck %s --check-prefix=GUARANTEED
import Swift
var zero = 0
// <rdar://problem/15921334>
// CHECK-LABEL: sil hidden @$S8closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}}F : $@convention(thin) <A, R> () -> @owned @callee_guaranteed (@in_guaranteed A) -> @out R {
func return_local_generic_function_without_captures<A, R>() -> (A) -> R {
func f(_: A) -> R {
Builtin.int_trap()
}
// CHECK: [[FN:%.*]] = function_ref @$S8closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}} : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1
// CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [callee_guaranteed] [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1
// CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_guaranteed (@in_guaranteed A) -> @out R
return f
}
func return_local_generic_function_with_captures<A, R>(_ a: A) -> (A) -> R {
func f(_: A) -> R {
_ = a
}
return f
}
// CHECK-LABEL: sil hidden @$S8closures17read_only_captureyS2iF : $@convention(thin) (Int) -> Int {
func read_only_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// SEMANTIC ARC TODO: This is incorrect. We need to do the project_box on the copy.
// CHECK: [[PROJECT:%.*]] = project_box [[XBOX]]
// CHECK: store [[X]] to [trivial] [[PROJECT]]
func cap() -> Int {
return x
}
return cap()
// CHECK: [[XBOX_BORROW:%.*]] = begin_borrow [[XBOX]]
// SEMANTIC ARC TODO: See above. This needs to happen on the copy_valued box.
// CHECK: mark_function_escape [[PROJECT]]
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$S8closures17read_only_capture.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX_BORROW]])
// CHECK: end_borrow [[XBOX_BORROW]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: } // end sil function '$S8closures17read_only_captureyS2iF'
// CHECK: sil private @[[CAP_NAME]]
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: return [[X]]
// } // end sil function '[[CAP_NAME]]'
// SEMANTIC ARC TODO: This is a place where we have again project_box too early.
// CHECK-LABEL: sil hidden @$S8closures16write_to_captureyS2iF : $@convention(thin) (Int) -> Int {
func write_to_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: store [[X]] to [trivial] [[XBOX_PB]]
// CHECK: [[X2BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[X2BOX_PB:%.*]] = project_box [[X2BOX]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*Int
// CHECK: copy_addr [[ACCESS]] to [initialization] [[X2BOX_PB]]
// CHECK: [[X2BOX_BORROW:%.*]] = begin_borrow [[X2BOX]]
// SEMANTIC ARC TODO: This next mark_function_escape should be on a projection from X2BOX_BORROW.
// CHECK: mark_function_escape [[X2BOX_PB]]
var x2 = x
func scribble() {
x2 = zero
}
scribble()
// CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:\$S8closures16write_to_capture.*]] : $@convention(thin) (@guaranteed { var Int }) -> ()
// CHECK: apply [[SCRIB]]([[X2BOX_BORROW]])
// SEMANTIC ARC TODO: This should load from X2BOX_BORROW project. There is an
// issue here where after a copy_value, we need to reassign a projection in
// some way.
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[X2BOX_PB]] : $*Int
// CHECK: [[RET:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: destroy_value [[X2BOX]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
return x2
}
// CHECK: } // end sil function '$S8closures16write_to_captureyS2iF'
// CHECK: sil private @[[SCRIB_NAME]]
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[XADDR]] : $*Int
// CHECK: assign {{%[0-9]+}} to [[ACCESS]]
// CHECK: return
// CHECK: } // end sil function '[[SCRIB_NAME]]'
// CHECK-LABEL: sil hidden @$S8closures21multiple_closure_refs{{[_0-9a-zA-Z]*}}F
func multiple_closure_refs(_ x: Int) -> (() -> Int, () -> Int) {
var x = x
func cap() -> Int {
return x
}
return (cap, cap)
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$S8closures21multiple_closure_refs.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [callee_guaranteed] [[CAP]]
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$S8closures21multiple_closure_refs.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [callee_guaranteed] [[CAP]]
// CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}})
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @$S8closures18capture_local_funcySiycycSiF : $@convention(thin) (Int) -> @owned @callee_guaranteed () -> @owned @callee_guaranteed () -> Int {
func capture_local_func(_ x: Int) -> () -> () -> Int {
// CHECK: bb0([[ARG:%.*]] : @trivial $Int):
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: store [[ARG]] to [trivial] [[XBOX_PB]]
func aleph() -> Int { return x }
func beth() -> () -> Int { return aleph }
// CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:\$S8closures18capture_local_funcySiycycSiF4bethL_SiycyF]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// SEMANTIC ARC TODO: This is incorrect. This should be a project_box from XBOX_COPY.
// CHECK: mark_function_escape [[XBOX_PB]]
// CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [callee_guaranteed] [[BETH_REF]]([[XBOX_COPY]])
return beth
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[BETH_CLOSURE]]
}
// CHECK: } // end sil function '$S8closures18capture_local_funcySiycycSiF'
// CHECK: sil private @[[ALEPH_NAME:\$S8closures18capture_local_funcySiycycSiF5alephL_SiyF]] : $@convention(thin) (@guaranteed { var Int }) -> Int {
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: sil private @[[BETH_NAME]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int {
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// SEMANTIC ARC TODO: This should be on a PB from XBOX_COPY.
// CHECK: mark_function_escape [[XBOX_PB]]
// CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [callee_guaranteed] [[ALEPH_REF]]([[XBOX_COPY]])
// CHECK: return [[ALEPH_CLOSURE]]
// CHECK: } // end sil function '[[BETH_NAME]]'
// CHECK-LABEL: sil hidden @$S8closures22anon_read_only_capture{{[_0-9a-zA-Z]*}}F
func anon_read_only_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
return ({ x })()
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures22anon_read_only_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int
// -- apply expression
// CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]])
// -- cleanup
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: sil private @[[CLOSURE_NAME]]
// CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $*Int):
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: return [[X]]
// CHECK-LABEL: sil hidden @$S8closures21small_closure_capture{{[_0-9a-zA-Z]*}}F
func small_closure_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
return { x }()
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures21small_closure_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int
// -- apply expression
// CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]])
// -- cleanup
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: sil private @[[CLOSURE_NAME]]
// CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $*Int):
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: return [[X]]
// CHECK-LABEL: sil hidden @$S8closures35small_closure_capture_with_argument{{[_0-9a-zA-Z]*}}F
func small_closure_capture_with_argument(_ x: Int) -> (_ y: Int) -> Int {
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
return { x + $0 }
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @guaranteed { var Int }) -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [callee_guaranteed] [[ANON]]([[XBOX_COPY]])
// -- return
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[ANON_CLOSURE_APP]]
}
// FIXME(integers): the following checks should be updated for the new way +
// gets invoked. <rdar://problem/29939484>
// XCHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int, @guaranteed { var Int }) -> Int
// XCHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : ${ var Int }):
// XCHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// XCHECK: [[PLUS:%[0-9]+]] = function_ref @$Ss1poiS2i_SitF{{.*}}
// XCHECK: [[LHS:%[0-9]+]] = load [trivial] [[XADDR]]
// XCHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]])
// XCHECK: destroy_value [[XBOX]]
// XCHECK: return [[RET]]
// CHECK-LABEL: sil hidden @$S8closures24small_closure_no_capture{{[_0-9a-zA-Z]*}}F
func small_closure_no_capture() -> (_ y: Int) -> Int {
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures24small_closure_no_captureS2icyFS2icfU_]] : $@convention(thin) (Int) -> Int
// CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_guaranteed (Int) -> Int
// CHECK: return [[ANON_THICK]]
return { $0 }
}
// CHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int
// CHECK: bb0([[YARG:%[0-9]+]] : @trivial $Int):
// CHECK-LABEL: sil hidden @$S8closures17uncaptured_locals{{[_0-9a-zA-Z]*}}F :
func uncaptured_locals(_ x: Int) -> (Int, Int) {
var x = x
// -- locals without captures are stack-allocated
// CHECK: bb0([[XARG:%[0-9]+]] : @trivial $Int):
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XADDR]]
// CHECK: store [[XARG]] to [trivial] [[PB]]
var y = zero
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
return (x, y)
}
class SomeClass {
var x : Int = zero
init() {
x = { self.x }() // Closing over self.
}
}
// Closures within destructors <rdar://problem/15883734>
class SomeGenericClass<T> {
deinit {
var i: Int = zero
// CHECK: [[C1REF:%[0-9]+]] = function_ref @$S8closures16SomeGenericClassCfdSiyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> Int
// CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]) : $@convention(thin) (@inout_aliasable Int) -> Int
var x = { i + zero } ()
// CHECK: [[C2REF:%[0-9]+]] = function_ref @$S8closures16SomeGenericClassCfdSiyXEfU0_ : $@convention(thin) () -> Int
// CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int
var y = { zero } ()
// CHECK: [[C3REF:%[0-9]+]] = function_ref @$S8closures16SomeGenericClassCfdyyXEfU1_ : $@convention(thin) <τ_0_0> () -> ()
// CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> ()
var z = { _ = T.self } ()
}
// CHECK-LABEL: sil private @$S8closures16SomeGenericClassCfdSiyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> Int
// CHECK-LABEL: sil private @$S8closures16SomeGenericClassCfdSiyXEfU0_ : $@convention(thin) () -> Int
// CHECK-LABEL: sil private @$S8closures16SomeGenericClassCfdyyXEfU1_ : $@convention(thin) <T> () -> ()
}
// This is basically testing that the constraint system ranking
// function conversions as worse than others, and therefore performs
// the conversion within closures when possible.
class SomeSpecificClass : SomeClass {}
func takesSomeClassGenerator(_ fn : () -> SomeClass) {}
func generateWithConstant(_ x : SomeSpecificClass) {
takesSomeClassGenerator({ x })
}
// CHECK-LABEL: sil private @$S8closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CyXEfU_ : $@convention(thin) (@guaranteed SomeSpecificClass) -> @owned SomeClass {
// CHECK: bb0([[T0:%.*]] : @guaranteed $SomeSpecificClass):
// CHECK: debug_value [[T0]] : $SomeSpecificClass, let, name "x", argno 1
// CHECK: [[T0_COPY:%.*]] = copy_value [[T0]]
// CHECK: [[T0_COPY_CASTED:%.*]] = upcast [[T0_COPY]] : $SomeSpecificClass to $SomeClass
// CHECK: return [[T0_COPY_CASTED]]
// CHECK: } // end sil function '$S8closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CyXEfU_'
// Check the annoying case of capturing 'self' in a derived class 'init'
// method. We allocate a mutable box to deal with 'self' potentially being
// rebound by super.init, but 'self' is formally immutable and so is captured
// by value. <rdar://problem/15599464>
class Base {}
class SelfCapturedInInit : Base {
var foo : () -> SelfCapturedInInit
// CHECK-LABEL: sil hidden @$S8closures18SelfCapturedInInitC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit {
// CHECK: bb0([[SELF:%.*]] : @owned $SelfCapturedInInit):
//
// First create our initial value for self.
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SelfCapturedInInit }, let, name "self"
// CHECK: [[UNINIT_SELF:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_SELF_BOX:%.*]] = project_box [[UNINIT_SELF]]
// CHECK: store [[SELF]] to [init] [[PB_SELF_BOX]]
//
// Then perform the super init sequence.
// CHECK: [[TAKEN_SELF:%.*]] = load [take] [[PB_SELF_BOX]]
// CHECK: [[UPCAST_TAKEN_SELF:%.*]] = upcast [[TAKEN_SELF]]
// CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_TAKEN_SELF]]) : $@convention(method) (@owned Base) -> @owned Base
// CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $Base to $SelfCapturedInInit
// CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_SELF_BOX]]
//
// Finally put self in the closure.
// CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_SELF_BOX]]
// CHECK: [[COPIED_SELF:%.*]] = load [copy] [[PB_SELF_BOX]]
// CHECK: [[FOO_VALUE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[COPIED_SELF]]) : $@convention(thin) (@guaranteed SelfCapturedInInit) -> @owned SelfCapturedInInit
// CHECK: [[FOO_LOCATION:%.*]] = ref_element_addr [[BORROWED_SELF]]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[FOO_LOCATION]] : $*@callee_guaranteed () -> @owned SelfCapturedInInit
// CHECK: assign [[FOO_VALUE]] to [[ACCESS]]
override init() {
super.init()
foo = { self }
}
}
func takeClosure(_ fn: () -> Int) -> Int { return fn() }
class TestCaptureList {
var x = zero
func testUnowned() {
let aLet = self
takeClosure { aLet.x }
takeClosure { [unowned aLet] in aLet.x }
takeClosure { [weak aLet] in aLet!.x }
var aVar = self
takeClosure { aVar.x }
takeClosure { [unowned aVar] in aVar.x }
takeClosure { [weak aVar] in aVar!.x }
takeClosure { self.x }
takeClosure { [unowned self] in self.x }
takeClosure { [weak self] in self!.x }
takeClosure { [unowned newVal = TestCaptureList()] in newVal.x }
takeClosure { [weak newVal = TestCaptureList()] in newVal!.x }
}
}
class ClassWithIntProperty { final var x = 42 }
func closeOverLetLValue() {
let a : ClassWithIntProperty
a = ClassWithIntProperty()
takeClosure { a.x }
}
// The let property needs to be captured into a temporary stack slot so that it
// is loadable even though we capture the value.
// CHECK-LABEL: sil private @$S8closures18closeOverLetLValueyyFSiyXEfU_ : $@convention(thin) (@guaranteed ClassWithIntProperty) -> Int {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithIntProperty):
// CHECK: [[TMP_CLASS_ADDR:%.*]] = alloc_stack $ClassWithIntProperty, let, name "a", argno 1
// CHECK: [[COPY_ARG:%.*]] = copy_value [[ARG]]
// CHECK: store [[COPY_ARG]] to [init] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: [[BORROWED_LOADED_CLASS:%.*]] = load_borrow [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: [[INT_IN_CLASS_ADDR:%.*]] = ref_element_addr [[BORROWED_LOADED_CLASS]] : $ClassWithIntProperty, #ClassWithIntProperty.x
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[INT_IN_CLASS_ADDR]] : $*Int
// CHECK: [[INT_IN_CLASS:%.*]] = load [trivial] [[ACCESS]] : $*Int
// CHECK: end_borrow [[BORROWED_LOADED_CLASS]] from [[TMP_CLASS_ADDR]]
// CHECK: destroy_addr [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: dealloc_stack %1 : $*ClassWithIntProperty
// CHECK: return [[INT_IN_CLASS]]
// CHECK: } // end sil function '$S8closures18closeOverLetLValueyyFSiyXEfU_'
// GUARANTEED-LABEL: sil private @$S8closures18closeOverLetLValueyyFSiyXEfU_ : $@convention(thin) (@guaranteed ClassWithIntProperty) -> Int {
// GUARANTEED: bb0(%0 : @guaranteed $ClassWithIntProperty):
// GUARANTEED: [[TMP:%.*]] = alloc_stack $ClassWithIntProperty
// GUARANTEED: [[COPY:%.*]] = copy_value %0 : $ClassWithIntProperty
// GUARANTEED: store [[COPY]] to [init] [[TMP]] : $*ClassWithIntProperty
// GUARANTEED: [[BORROWED:%.*]] = load_borrow [[TMP]]
// GUARANTEED: end_borrow [[BORROWED]] from [[TMP]]
// GUARANTEED: destroy_addr [[TMP]]
// GUARANTEED: } // end sil function '$S8closures18closeOverLetLValueyyFSiyXEfU_'
// Use an external function so inout deshadowing cannot see its body.
@_silgen_name("takesNoEscapeClosure")
func takesNoEscapeClosure(fn : () -> Int)
struct StructWithMutatingMethod {
var x = 42
mutating func mutatingMethod() {
// This should not capture the refcount of the self shadow.
takesNoEscapeClosure { x = 42; return x }
}
}
// Check that the address of self is passed in, but not the refcount pointer.
// CHECK-LABEL: sil hidden @$S8closures24StructWithMutatingMethodV08mutatingE0{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $*StructWithMutatingMethod):
// CHECK: [[CLOSURE:%[0-9]+]] = function_ref @$S8closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int
// CHECK: partial_apply [callee_guaranteed] [[CLOSURE]](%0) : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int
// Check that the closure body only takes the pointer.
// CHECK-LABEL: sil private @$S8closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int {
// CHECK: bb0(%0 : @trivial $*StructWithMutatingMethod):
class SuperBase {
func boom() {}
}
class SuperSub : SuperBase {
override func boom() {}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1ayyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1a[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1ayyF'
func a() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]])
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func a1() {
self.boom()
super.boom()
}
a1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1byyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1b[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1byyF'
func b() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1b.*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[ARG]])
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func b1() {
// CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> ()
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase)
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
func b2() {
self.boom()
super.boom()
}
b2()
}
b1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1cyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1c[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]])
// CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]]
// CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]]
// CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]]
// CHECK: apply [[B]]()
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[PA_COPY]]
// CHECK: end_borrow [[BORROWED_PA]] from [[PA]]
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$S8closures8SuperSubC1cyyF'
func c() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> ()
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let c1 = { () -> Void in
self.boom()
super.boom()
}
c1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1dyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1d[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]])
// CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]]
// CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]]
// CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]]
// CHECK: apply [[B]]()
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[PA_COPY]]
// CHECK: end_borrow [[BORROWED_PA]] from [[PA]]
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$S8closures8SuperSubC1dyyF'
func d() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1d.*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[ARG]])
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let d1 = { () -> Void in
// CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
func d2() {
super.boom()
}
d2()
}
d1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1eyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME1:\$S8closures8SuperSubC1e[_0-9a-zA-Z]*]] : $@convention(thin)
// CHECK: = apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1eyyF'
func e() {
// CHECK: sil private @[[INNER_FUNC_NAME1]] : $@convention(thin)
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME2:\$S8closures8SuperSubC1e.*]] : $@convention(thin)
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]])
// CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]]
// CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]]
// CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]]
// CHECK: apply [[B]]() : $@callee_guaranteed () -> ()
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[PA_COPY]]
// CHECK: end_borrow [[BORROWED_PA]] from [[PA]]
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '[[INNER_FUNC_NAME1]]'
func e1() {
// CHECK: sil private @[[INNER_FUNC_NAME2]] : $@convention(thin)
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPERCAST:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPERCAST:%.*]] = begin_borrow [[ARG_COPY_SUPERCAST]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPERCAST]])
// CHECK: destroy_value [[ARG_COPY_SUPERCAST]]
// CHECK: return
// CHECK: } // end sil function '[[INNER_FUNC_NAME2]]'
let e2 = {
super.boom()
}
e2()
}
e1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1fyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1fyyFyycfU_]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]])
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$S8closures8SuperSubC1fyyF'
func f() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1fyyFyycfU_yyKXKfu_]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]])
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PA]]
// CHECK: [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[CVT]])
// CHECK: [[REABSTRACT_CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[REABSTRACT_PA]]
// CHECK: [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @$Ss2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
// CHECK: try_apply [[TRY_APPLY_AUTOCLOSURE]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
// CHECK: [[NORMAL_BB]]{{.*}}
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let f1 = {
// CHECK: sil private [transparent] @[[INNER_FUNC_2]]
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
nil ?? super.boom()
}
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1gyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1g[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1gyyF'
func g() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1g.*]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]])
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed () -> @error Error to $@noescape @callee_guaranteed () -> @error Error
// CHECK: [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[CVT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> @error Error) -> (@out (), @error Error)
// CHECK: [[REABSTRACT_CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[REABSTRACT_PA]]
// CHECK: [[TRY_APPLY_FUNC:%.*]] = function_ref @$Ss2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
// CHECK: try_apply [[TRY_APPLY_FUNC]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
// CHECK: [[NORMAL_BB]]{{.*}}
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func g1() {
// CHECK: sil private [transparent] @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
nil ?? super.boom()
}
g1()
}
}
// CHECK-LABEL: sil hidden @$S8closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> ()
// -- We enter with an assumed strong +1.
// CHECK: bb0([[SELF:%.*]] : @guaranteed $UnownedSelfNestedCapture):
// CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box ${ var @sil_unowned UnownedSelfNestedCapture }
// CHECK: [[PB:%.*]] = project_box [[OUTER_SELF_CAPTURE]]
// -- strong +2
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_COPY]] :
// -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here.
// -- strong +2, unowned +1
// CHECK: [[UNOWNED_SELF_COPY:%.*]] = copy_value [[UNOWNED_SELF]]
// CHECK: store [[UNOWNED_SELF_COPY]] to [init] [[PB]]
// SEMANTIC ARC TODO: This destroy_value should probably be /after/ the load from PB on the next line.
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[UNOWNED_SELF:%.*]] = load_borrow [[PB]]
// -- strong +2, unowned +1
// CHECK: [[SELF:%.*]] = copy_unowned_value [[UNOWNED_SELF]]
// CHECK: end_borrow [[UNOWNED_SELF]] from [[PB]]
// CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]]
// -- strong +2, unowned +2
// CHECK: [[UNOWNED_SELF2_COPY:%.*]] = copy_value [[UNOWNED_SELF2]]
// -- strong +1, unowned +2
// CHECK: destroy_value [[SELF]]
// -- closure takes unowned ownership
// CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[UNOWNED_SELF2_COPY]])
// CHECK: [[OUTER_CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[OUTER_CLOSURE]]
// -- call consumes closure
// -- strong +1, unowned +1
// CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CONVERT]]
// CHECK: [[B:%.*]] = begin_borrow [[INNER_CLOSURE]]
// CHECK: [[CONSUMED_RESULT:%.*]] = apply [[B]]()
// CHECK: destroy_value [[CONSUMED_RESULT]]
// CHECK: destroy_value [[INNER_CLOSURE]]
// -- destroy_values unowned self in box
// -- strong +1, unowned +0
// CHECK: destroy_value [[OUTER_SELF_CAPTURE]]
// -- strong +0, unowned +0
// CHECK: } // end sil function '$S8closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F'
// -- outer closure
// -- strong +0, unowned +1
// CHECK: sil private @[[OUTER_CLOSURE_FUN:\$S8closures24UnownedSelfNestedCaptureC06nestedE0yyFACycyXEfU_]] : $@convention(thin) (@guaranteed @sil_unowned UnownedSelfNestedCapture) -> @owned @callee_guaranteed () -> @owned UnownedSelfNestedCapture {
// CHECK: bb0([[CAPTURED_SELF:%.*]] : @guaranteed $@sil_unowned UnownedSelfNestedCapture):
// -- strong +0, unowned +2
// CHECK: [[CAPTURED_SELF_COPY:%.*]] = copy_value [[CAPTURED_SELF]] :
// -- closure takes ownership of unowned ref
// CHECK: [[INNER_CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[CAPTURED_SELF_COPY]])
// -- strong +0, unowned +1 (claimed by closure)
// CHECK: return [[INNER_CLOSURE]]
// CHECK: } // end sil function '[[OUTER_CLOSURE_FUN]]'
// -- inner closure
// -- strong +0, unowned +1
// CHECK: sil private @[[INNER_CLOSURE_FUN:\$S8closures24UnownedSelfNestedCaptureC06nestedE0yyFACycyXEfU_ACycfU_]] : $@convention(thin) (@guaranteed @sil_unowned UnownedSelfNestedCapture) -> @owned UnownedSelfNestedCapture {
// CHECK: bb0([[CAPTURED_SELF:%.*]] : @guaranteed $@sil_unowned UnownedSelfNestedCapture):
// -- strong +1, unowned +1
// CHECK: [[SELF:%.*]] = copy_unowned_value [[CAPTURED_SELF:%.*]] :
// -- strong +1, unowned +0 (claimed by return)
// CHECK: return [[SELF]]
// CHECK: } // end sil function '[[INNER_CLOSURE_FUN]]'
class UnownedSelfNestedCapture {
func nestedCapture() {
{[unowned self] in { self } }()()
}
}
// Check that capturing 'self' via a 'super' call also captures the generic
// signature if the base class is concrete and the derived class is generic
class ConcreteBase {
func swim() {}
}
// CHECK-LABEL: sil private @$S8closures14GenericDerivedC4swimyyFyyXEfU_ : $@convention(thin) <Ocean> (@guaranteed GenericDerived<Ocean>) -> ()
// CHECK: bb0([[ARG:%.*]] : @guaranteed $GenericDerived<Ocean>):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $GenericDerived<Ocean> to $ConcreteBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[METHOD:%.*]] = function_ref @$S8closures12ConcreteBaseC4swimyyF
// CHECK: apply [[METHOD]]([[BORROWED_ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed ConcreteBase) -> ()
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '$S8closures14GenericDerivedC4swimyyFyyXEfU_'
class GenericDerived<Ocean> : ConcreteBase {
override func swim() {
withFlotationAid {
super.swim()
}
}
func withFlotationAid(_ fn: () -> ()) {}
}
// Don't crash on this
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258() {
r25993258_helper { _, _ in () }
}
// rdar://29810997
//
// Using a let from a closure in an init was causing the type-checker
// to produce invalid AST: 'self.fn' was an l-value, but 'self' was already
// loaded to make an r-value. This was ultimately because CSApply was
// building the member reference correctly in the context of the closure,
// where 'fn' is not settable, but CSGen / CSSimplify was processing it
// in the general DC of the constraint system, i.e. the init, where
// 'fn' *is* settable.
func r29810997_helper(_ fn: (Int) -> Int) -> Int { return fn(0) }
struct r29810997 {
private let fn: (Int) -> Int
private var x: Int
init(function: @escaping (Int) -> Int) {
fn = function
x = r29810997_helper { fn($0) }
}
}
// DI will turn this into a direct capture of the specific stored property.
// CHECK-LABEL: sil hidden @$S8closures16r29810997_helperyS3iXEF : $@convention(thin) (@noescape @callee_guaranteed (Int) -> Int) -> Int
// rdar://problem/37790062
protocol P_37790062 {
associatedtype T
var elt: T { get }
}
func rdar37790062() {
struct S<T> {
init(_ a: () -> T, _ b: () -> T) {}
}
class C1 : P_37790062 {
typealias T = Int
var elt: T { return 42 }
}
class C2 : P_37790062 {
typealias T = (String, Int, Void)
var elt: T { return ("question", 42, ()) }
}
func foo() -> Int { return 42 }
func bar() -> Void {}
func baz() -> (String, Int) { return ("question", 42) }
func bzz<T>(_ a: T) -> T { return a }
func faz<T: P_37790062>(_ a: T) -> T.T { return a.elt }
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU_
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU0_
// CHECK: function_ref @$S8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC
_ = S({ foo() }, { bar() })
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU1_
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU2_
// CHECK: function_ref @$S8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC
_ = S({ baz() }, { bar() })
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU3_
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU4_
// CHECK: function_ref @$S8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC
_ = S({ bzz(("question", 42)) }, { bar() })
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU5_
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU6_
// CHECK: function_ref @$S8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC
_ = S({ bzz(String.self) }, { bar() })
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU7_
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU8_
// CHECK: function_ref @$S8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC
_ = S({ bzz(((), (()))) }, { bar() })
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU9_
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU10_
// CHECK: function_ref @$S8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC
_ = S({ bzz(C1()) }, { bar() })
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU11_
// CHECK: function_ref @$S8closures12rdar37790062yyFyyXEfU12_
// CHECK: function_ref @$S8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC
_ = S({ faz(C2()) }, { bar() })
}
|
apache-2.0
|
062421206eda187a9724dd36fe025cb6
| 49.410798 | 296 | 0.604913 | 3.372066 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Views/Common/UIHeaderTabs/UIHeaderTab.swift
|
1
|
1066
|
//
// UIHeaderTab.swift
//
// Created by Emily Ivie on 9/10/15.
// Copyright © 2015 urdnot.
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import UIKit
final public class UIHeaderTab: UIView {
@IBOutlet weak var unselectedWrapper: UIView?
@IBOutlet weak var selectedWrapper: UIView?
@IBOutlet weak var button: UIButton?
@IBOutlet weak var label1: UILabel?
@IBOutlet weak var label2: UILabel?
@IBOutlet weak var selectedUnderline: UIView?
var selected: Bool = false
var index: Int = 0
var onClick: ((Int) -> Void)?
@IBAction func onClick(_ sender: UIButton) {
onClick?(index)
}
public func setup(title: String, selected: Bool = false, index: Int = 0, onClick: ((Int) -> Void)? = nil) {
self.index = index
label1?.text = title
label2?.text = title
self.selected = selected
unselectedWrapper?.isHidden = selected
selectedWrapper?.isHidden = !selected
self.onClick = onClick
}
}
|
mit
|
80a072423da03491232ad395a7fdaf8e
| 26.307692 | 108 | 0.71831 | 3.55 | false | false | false | false |
renesto/SkypeExportSwift
|
SkypeExport/SkypeFileSystem.swift
|
1
|
8632
|
//
// SkypeFileSystem.swift
// SkypeExport
//
// Created by Aleksandar Kovacevic on 2/12/15.
// Copyright (c) 2015 Aleksandar Kovacevic. All rights reserved.
//
import Foundation
public class SkypeExporterOutput {
public func prepareMessagesForExport(messages:[(from:String, dialog_partner:String, timestamp:String, message:String)])->[[String]]{
var messageData:[[String]]=[]
messageData+=[["author",
"dialog_partner",
"timestamp",
"message"]]
for message in messages {
var singlemessage:[String]=[]
singlemessage+=[message.from]
singlemessage+=[message.dialog_partner]
if let epochsAsInt=message.timestamp.toInt() {
let epochs:Double = Double(epochsAsInt);
let formattedTimestamp=printFormattedDate(NSDate(timeIntervalSince1970: epochs))
singlemessage+=[
formattedTimestamp
]
} else {
singlemessage+=[
""
]
}
singlemessage+=[message.message]
messageData+=[singlemessage]
}
return messageData
}
public func prepareContactsForExport(contacts:[Contact])->[[String]]{
var contactData:[[String]]=[]
contactData+=[["skypename",
"given_displayname",
"fullname",
"gender",
"main_phone",
"phone_home",
"phone_mobile",
"phone_office",
"emails",
"timezone",
"type",
"nr_of_buddies"]]
for contact in contacts {
var singleContact:[String]=[]
if let sname=contact.skypename {
singleContact+=[sname]
} else {
singleContact+=[""]
}
if let dname=contact.given_displayname {
singleContact+=[dname]
} else {
singleContact+=[""]
}
if let fname=contact.fullname {
singleContact+=[fname]
} else {
singleContact+=[""]
}
if let gender=contact.gender {
singleContact+=[gender==1 ? "male": "female"]
} else {
singleContact+=[""]
}
if let mphone=contact.main_phone {
singleContact+=[mphone]
} else {
singleContact+=[""]
}
if let phome=contact.phone_home {
singleContact+=[phome]
} else {
singleContact+=[""]
}
if let pmobile=contact.phone_mobile {
singleContact+=[pmobile]
} else {
singleContact+=[""]
}
if let poffice=contact.phone_office {
singleContact+=[poffice]
} else {
singleContact+=[""]
}
if let vemail=contact.emails {
singleContact+=[vemail]
} else {
singleContact+=[""]
}
if let tzone=contact.timezone {
singleContact+=[String(tzone)]
} else {
singleContact+=[""]
}
if let typ=contact.type {
singleContact+=[typ==1 ? "skype" : "external"]
} else {
singleContact+=[""]
}
if let nbuddies=contact.nr_of_buddies {
singleContact+=[String(nbuddies)]
} else {
singleContact+=[""]
}
contactData+=[singleContact]
}
return contactData
}
//TODO - fix the double quotes when they appear in the text
public func saveToCSV(usingSelectedPath path: String, data text: [[String]], type:String) -> Bool {
var csvResult=""
for row in text {
for cell in row {
if cell == row.last {
csvResult += "\"\(cell)\""
} else {
csvResult += "\"\(cell)\":"
}
}
csvResult+="\n"
}
return csvResult.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
}
public func saveToHTML(usingSelectedPath path: String, data text: [[String]], type:String) -> Bool {
let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
/* if ((dirs) != nil) {
let dir = dirs![0]; //documents directory
let path = dir.stringByAppendingPathComponent(file);
let text = "some text"
//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}*/
var htmlResult="<html><head>"
htmlResult+="<style>"
htmlResult+="#customers {"
htmlResult+="font-family: \"Trebuchet MS\", Arial, Helvetica, sans-serif;"
htmlResult+="width: 100%;"
htmlResult+="border-collapse: collapse;"
htmlResult+="}"
htmlResult+="#customers td, #customers th {"
htmlResult+="font-size: 1em;"
htmlResult+="border: 1px solid #98bf21;"
htmlResult+="padding: 3px 7px 2px 7px;"
htmlResult+="}"
htmlResult+="#customers th {"
htmlResult+="font-size: 1.1em;"
htmlResult+="text-align: left;"
htmlResult+="padding-top: 5px;"
htmlResult+="padding-bottom: 4px;"
htmlResult+="background-color: #A7C942;"
htmlResult+="color: #ffffff;"
htmlResult+="}"
htmlResult+="#customers tr.alt td {"
htmlResult+="color: #000000;"
htmlResult+="background-color: #EAF2D3;"
htmlResult+="}"
htmlResult+="</style>"
htmlResult+="</head><body><table id='customers'>"
var i:Int=0
for row in text {
var j:Int=0
if row == text.first! {
htmlResult+="<thead><tr>"
for cell in row {
htmlResult+="<th>\(cell)</th>"
}
htmlResult+="</tr></thead><tbody>\n"
} else {
if type=="messages" {
if row[1]==row[0] {
htmlResult+="<tr class='alt'>"
} else {
htmlResult+="<tr>"
}
} else {
if i%2 == 1 {
htmlResult+="<tr class='alt'>"
} else {
htmlResult+="<tr>"
}
}
for cell in row {
htmlResult+="<td>\(cell)</td>"
}
htmlResult+="</tr>\n"
j++
}
i++
}
htmlResult += "</tbody></table></body></html>"
return htmlResult.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
}
public func getAppSupportDir() -> String? {
var error: NSError?
let userURL : NSURL? = NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomain: NSSearchPathDomainMask.AllDomainsMask, appropriateForURL: nil, create: true, error: &error)
return userURL?.path
}
public func getCurrDir() -> String? {
var error: NSError?
let userURL : NSURL? = NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.ApplicationDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true, error: &error)
return userURL?.path
}
func printFormattedDate(date: NSDate) -> String {
let dateformat = NSDateFormatter()
dateformat.timeStyle = .ShortStyle
dateformat.dateStyle = .MediumStyle
var stringDate = dateformat.stringFromDate(date)
return stringDate
}
}
|
apache-2.0
|
1a4f7789359be13f562be0e642e0f586
| 35.117155 | 230 | 0.481233 | 5.092625 | false | false | false | false |
russbishop/swift
|
test/Interpreter/SDK/objc_nsstring_bridge.swift
|
1
|
1789
|
// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
// Add a method to String to make sure a value is really a String and not
// implicitly converted from an NSString, since method lookup doesn't see through
// implicit conversions.
extension String {
func reallyAString() -> String { return self }
}
func printString(_ x: String) {
print(x)
}
func printDescription(_ o: AnyObject) {
print(o.description!.reallyAString())
}
class Pootie : NSObject {
override var description : String {
return "cole me down on the panny sty"
}
func sinePittyOnRunnyKine(_ x: String) -> String {
return "\(x). sa-da-tay"
}
}
var a:NSNumber = 2001
printDescription(a) // CHECK: 2001
var p = Pootie()
printDescription(p) // CHECK: cole me down on the panny sty
var s1:String = "wa-da-ta"
// We don't say 'var s2:NSString = "..."' in order to keep this test independent of the
// ABI of NSString.convertFromStringLiteral.
var s2s:String = "kappa-chow"
var s2 = s2s as NSString
printDescription(s2) // CHECK: kappa-chow
printDescription(p.sinePittyOnRunnyKine(s2 as String) as NSString) // CHECK: kappa-chow. sa-da-tay
var s3:String = s2.appendingPathComponent(s1).reallyAString()
printDescription(s3 as NSString) // CHECK: kappa-chow/wa-da-ta
// Unicode conversion
var s4 = NSString(string: "\u{f8ff}\u{fffd}") as String
printDescription(s4 as NSString) // CHECK: �
// NSCFConstantString conversion
var s5 : String = NSExceptionName.rangeException.rawValue as String
printDescription(s5 as NSString) // CHECK: NSRangeException
// Check conversions to AnyObject
var s6: NSString = "foo"
var ao: AnyObject = s6.copy()
var s7 = ao as! NSString
var s8 = ao as? String
// CHECK-NEXT: done
print("done")
|
apache-2.0
|
8fd2f3f2f96e17460430f58c9979f339
| 26.045455 | 98 | 0.721008 | 3.275229 | false | false | false | false |
cubixlabs/SocialGIST
|
SocialGIST/UserAuthentication/Facebook/FBConnect.swift
|
1
|
2070
|
//
// FBConnect.swift
// eGrocery
//
// Created by Shoaib on 3/20/15.
// Copyright (c) 2015 cubixlabs. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
public var FB_CONNECT:FBConnect {
get {
return FBConnect.shared;
}
} //P.E.
public class FBConnect: NSObject {
fileprivate var _userData:NSDictionary?;
public var userData:NSDictionary! {
get {
return _userData;
}
} //P.E.
//MARK: - shared
public static var shared: FBConnect = FBConnect();
public override init() {
super.init();
} //F.E.
//MARK: - login
public func login(_ completion:@escaping (_ result:NSDictionary?)->()) {
print("currentAccessToken : \(FBSDKAccessToken.current())");
if (FBSDKAccessToken.current() != nil && _userData != nil) {
completion(_userData);
//--
return;
}
let loginManager:FBSDKLoginManager = FBSDKLoginManager();
loginManager.loginBehavior = .web;//.SystemAccount;//.Native;
loginManager.logIn(withReadPermissions: ["public_profile","email"], from: nil) { (result:FBSDKLoginManagerLoginResult?, error:Error?) -> Void in
print("result : \(result) , error : \(error?.localizedDescription)");
if(( FBSDKAccessToken.current() ) != nil){
FBSDKGraphRequest(graphPath: "/me?fields=id,name,first_name,email,last_name", parameters: nil).start(completionHandler: { (connection:FBSDKGraphRequestConnection?, result:Any?, error:Error?) -> Void in
//--
self._userData = result as? NSDictionary;
completion(self._userData);
})
}
}
} //F.E.
//MARK: - logout
public func logout() {
let loginManager:FBSDKLoginManager = FBSDKLoginManager();
loginManager.logOut();
_userData = nil;
} //F.E.
} //CLS END
|
gpl-3.0
|
688a6ed10fdaa9cb302a30a35dd17ef3
| 28.15493 | 217 | 0.565217 | 4.651685 | false | false | false | false |
UnsignedInt8/LightSwordX
|
LightSwordX/Lib/Crypto.swift
|
2
|
1422
|
//
// Crypto.swift
// LightSwordX
//
// Created by Neko on 12/19/15.
// Copyright © 2015 Neko. All rights reserved.
//
import SINQ
import Foundation
import CryptoSwift
class Crypto {
static let SupportedCiphers = [
"aes-256-cfb": (info: [32, 16], blockMode: CipherBlockMode.CFB),
"aes-192-cfb": (info: [24, 16], blockMode: CipherBlockMode.CFB),
"aes-128-cfb": (info: [16, 16], blockMode: CipherBlockMode.CFB)
]
static func createCipher(algorithm: String, password: String, iv: [UInt8]? = nil) -> (cipher: AES, iv: [UInt8]) {
var tuple: (info: [Int], blockMode: CipherBlockMode)! = SupportedCiphers[algorithm.lowercaseString]
if tuple == nil {
tuple = (info: [32, 16], blockMode: CipherBlockMode.CFB)
}
var key = [UInt8](password.utf8)
if key.count > tuple.info[0] {
key = sinq(key).take(tuple.info[0]).toArray()
} else {
let longPw = String(count: (tuple.info[0] / password.length) + 1, byRepeatingString: password)!
key = [UInt8](longPw.utf8)
key = sinq(key).take(tuple.info[0]).toArray()
}
var civ: [UInt8]! = iv
if civ == nil {
civ = AES.randomIV(tuple.info[1])
}
let cipher = try! AES(key: key, iv: civ, blockMode: tuple.blockMode)
return (cipher: cipher, iv: civ)
}
}
|
gpl-2.0
|
6cb67d13f665129d187da2e18eacfae8
| 30.577778 | 117 | 0.568614 | 3.351415 | false | false | false | false |
HeartOfCarefreeHeavens/TestKitchen_pww
|
TestKitchen/TestKitchen/classes/cookbook/foodCourse/model/FoodCourseModel.swift
|
1
|
4053
|
//
// FoodCourseModel.swift
// TestKitchen
//
// Created by qianfeng on 16/8/25.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
import SwiftyJSON
class FoodCourseModel: NSObject {
var code:String?
var msg:String?
var version:String?
var timestamp:NSNumber?
var data:FoodCourseDataModel?
class func parseModel(data:NSData)->FoodCourseModel{
let model = FoodCourseModel()
let jsonData = JSON(data: data)
model.code = jsonData["code"].string
model.msg = jsonData["msg"].string
model.version = jsonData["version"].string
model.timestamp = jsonData["timestamp"].number
let subJSON = jsonData["data"]
model.data = FoodCourseDataModel.parseModel(subJSON)
return model
}
}
class FoodCourseDataModel:NSObject{
var series_id:String?
var series_name:String?
var series_title:String?
var create_time:String?
var last_update:String?
var order_no:String?
var tag:String?
var episode:NSNumber?
var series_image:String?
var share_title:String?
var share_description:String?
var share_image:String?
var album:String?
var album_logo:String?
var relate_activity:String?
var data:Array<FoodCourseSerialModel>?
var play: NSNumber?
var share_url:String?
class func parseModel(jsonData:JSON)->FoodCourseDataModel{
let model = FoodCourseDataModel()
model.series_id = jsonData["series_id"].string
model.series_name = jsonData["series_name"].string
model.series_title = jsonData["series_title"].string
model.create_time = jsonData["create_time"].string
model.last_update = jsonData["last_update"].string
model.order_no = jsonData["order_no"].string
model.tag = jsonData["tag"].string
model.episode = jsonData["episode"].number
model.series_image = jsonData["series_image"].string
model.share_title = jsonData["share_title"].string
model.share_description = jsonData["share_description"].string
model.share_image = jsonData["share_image"].string
model.album = jsonData[""].string
model.album_logo = jsonData["album_logo"].string
model.relate_activity = jsonData["relate_activity"].string
model.play = jsonData["play"].number
model.share_url = jsonData["share_url"].string
var array = Array<FoodCourseSerialModel>()
for (_,subjson) in jsonData["data"]{
let dModel = FoodCourseSerialModel.parseModel(subjson)
array.append(dModel)
}
model.data = array
return model
}
}
class FoodCourseSerialModel:NSObject{
var course_id:NSNumber?
var course_video:String?
var episode:NSNumber?
var course_name:String?
var course_subject:String?
var course_image:String?
var ischarge:String?
var price:String?
var video_watchcount:NSNumber?
var course_introduce:String?
var is_collect:NSNumber?
var is_like:NSNumber?
class func parseModel(jsonData:JSON)->FoodCourseSerialModel{
let model = FoodCourseSerialModel()
model.course_id = jsonData["course_id"].number
model.course_video = jsonData["course_video"].string
model.episode = jsonData["episode"].number
model.course_name = jsonData["course_name"].string
model.course_subject = jsonData["course_subject"].string
model.course_image = jsonData["course_image"].string
model.ischarge = jsonData["ischarge"].string
model.price = jsonData["price"].string
model.video_watchcount = jsonData["video_watchcount"].number
model.course_introduce = jsonData["course_introduce"].string
model.is_collect = jsonData[""].number
model.is_like = jsonData["is_like"].number
return model
}
}
|
mit
|
c4cc36b0719ea3ccfd2653cafd965eae
| 26.931034 | 70 | 0.63358 | 4.364224 | false | false | false | false |
dmcyk/Console
|
Sources/Console/Value.swift
|
1
|
5401
|
//
// Value.swift
// Console
//
// Created by Damian Malarczyk on 01.02.2017.
// Copyright © 2018 Damian Malarczyk. All rights reserved.
//
import Foundation
public enum ValueError: LocalizedError {
case noValue(ValueType, Value), compundIsNotTopLevelType
public var errorDescription: String? {
switch self {
case .noValue(let expected, let got):
return "noValue: expected - \(expected), got - \(got)"
case .compundIsNotTopLevelType:
return "compundIsNotTopLevelType"
}
}
}
public enum Value: CustomStringConvertible {
case int(Int)
case double(Double)
case string(String)
/// Homogeneous array value type
case array([Value], ValueType)
case bool(Bool)
public func intValue() throws -> Int {
if case .int(let value) = self {
return value
}
throw ValueError.noValue(.int, self)
}
public func doubleValue() throws -> Double {
if case .double(let value) = self {
return value
}
throw ValueError.noValue(.double, self)
}
public func arrayValue() throws -> [Value] {
if case .array(let value, _) = self {
return value
}
throw ValueError.noValue(.compound, self)
}
public func stringValue() throws -> String {
if case .string(let val) = self {
return val
}
throw ValueError.noValue(.string, self)
}
public func boolValue() throws -> Bool {
if case .bool(let val) = self {
return val
}
throw ValueError.noValue(.bool, self)
}
public var description: String {
switch self {
case .int(let val):
return "Int(\(val))"
case .double(let val):
return "Double(\(val))"
case .string(let val):
return "String(\(val))"
case .array(let val, let type):
return "Array<\(type.description)>(\(val.map { $0.string }.joined(separator: ",")))"
case .bool(let val):
return "Bool(\(val))"
}
}
public var string: String {
switch self {
case .int(let val):
return "\(val)"
case .double(let val):
return "\(val)"
case .string(let val):
return val
case .bool(let val):
return val ? "true" : "false"
case .array(let val, _):
return "(" + val.map( { $0.string }).joined(separator: ",") + ")"
}
}
public var double: Double? {
switch self {
case .int(let val):
return Double(val)
case .double(let val):
return val
case .string(let val):
return Double(val)
case .array(let value, _):
if let first = value.first, value.count == 1 {
return first.double
}
return nil
case .bool(let val):
return val ? 1 : 0
}
}
public var integer: Int? {
switch self {
case .int(let val):
return val
case .double(let val):
return Int(val)
case .string(let val):
return Int(val)
case .array(let value, _):
if let first = value.first, value.count == 1 {
return first.integer
}
return nil
case .bool(let val):
return val ? 1 : 0
}
}
public var boolean: Bool? {
switch self {
case .int(let val):
return val != 0
case .double(let val):
return val != 0
case .string(let val):
if let int = integer {
return int != 0
} else if let double = double {
return double != 0
} else {
let lowercased = val.lowercased()
if lowercased == "true" {
return true
} else if lowercased == "false" {
return false
}
return nil
}
case .bool(let val):
return val
case .array(let values, _):
if let first = values.first, values.count == 1 {
return first.boolean
}
return nil
}
}
public var type: ValueType {
switch self {
case .int:
return .int
case .double:
return .double
case .string:
return .string
case .array(_, let type):
return .array(type)
case .bool:
return .bool
}
}
}
public extension Value {
/// Parse dynamic set of values into the `Value` type
///
/// - Parameter values: if `empty` the returned `Value` will be of type `array` with `compund` ValueType
/// - Returns: `Value` with case `array`
static func dynamicArray(from values: [Value]) -> Value {
guard let firstType = values.first?.type else {
// empty array, fallback to `compund`
return .array([], .compound)
}
for value in values[1 ..< values.count] {
if value.type != firstType {
return Value.array(values, .compound)
}
}
return .array(values, firstType)
}
}
|
mit
|
5ec1b129f4aa6f6a33917ece87e326b3
| 25.470588 | 108 | 0.496111 | 4.51505 | false | false | false | false |
phimage/MomXML
|
Sources/Equatable/MomUserInfo+Equatable.swift
|
1
|
658
|
//
// MomUserInfo+Equatable.swift
// MomXML
//
// Created by anass talii on 12/06/2017.
// Copyright © 2017 phimage. All rights reserved.
//
import Foundation
extension MomUserInfo: Equatable {
public static func == (lhs: MomUserInfo, rhs: MomUserInfo) -> Bool {
if lhs.entries.count != rhs.entries.count {
return false
}
return lhs.entries.sorted { $0.key < $1.key } == rhs.entries.sorted { $0.key < $1.key }
}
}
extension MomUserInfoEntry: Equatable {
public static func == (lhs: MomUserInfoEntry, rhs: MomUserInfoEntry) -> Bool {
return lhs.key == rhs.key && lhs.value == rhs.value
}
}
|
mit
|
81aa2785dcb307fc25c7511eb7323eb2
| 25.28 | 95 | 0.628615 | 3.335025 | false | false | false | false |
firebase/firebase-ios-sdk
|
FirebaseInstallations/Source/Tests/Unit/Swift/InstallationsAPITests.swift
|
1
|
5562
|
//
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// MARK: This file is used to evaluate the experience of using Firebase APIs in Swift.
import Foundation
import FirebaseCore
import FirebaseInstallations
final class InstallationsAPITests {
func usage() {
// MARK: - Installations
// `InstallationIDDidChange` & associated notification keys
_ = NotificationCenter.default
.addObserver(
forName: .InstallationIDDidChange,
object: nil,
queue: .main
) { notification in
_ = notification.userInfo?[InstallationIDDidChangeAppNameKey]
}
// Retrieving an Installations instance
_ = Installations.installations()
if let app = FirebaseApp.app() {
_ = Installations.installations(app: app)
}
// Create or retrieve an installations ID
Installations.installations().installationID { id, error in
if let _ /* id */ = id {
// ...
} else if let _ /* error */ = error {
// ...
}
}
#if compiler(>=5.5.2) && canImport(_Concurrency)
if #available(iOS 13.0, macOS 11.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) {
// async/await is a Swift 5.5+ feature available on iOS 15+
Task {
do {
try await Installations.installations().installationID()
} catch {
// ...
}
}
}
#endif // compiler(>=5.5.2) && canImport(_Concurrency)
// Retrieves an installation auth token
Installations.installations().authToken { result, error in
if let _ /* result */ = result {
// ...
} else if let _ /* error */ = error {
// ...
}
}
#if compiler(>=5.5.2) && canImport(_Concurrency)
if #available(iOS 13.0, macOS 11.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) {
// async/await is a Swift 5.5+ feature available on iOS 15+
Task {
do {
_ = try await Installations.installations().authToken()
} catch {
// ...
}
}
}
#endif // compiler(>=5.5.2) && canImport(_Concurrency)
// Retrieves an installation auth token with forcing refresh parameter
Installations.installations().authTokenForcingRefresh(true) { result, error in
if let _ /* result */ = result {
// ...
} else if let _ /* error */ = error {
// ...
}
}
#if compiler(>=5.5.2) && canImport(_Concurrency)
if #available(iOS 13.0, macOS 11.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) {
// async/await is a Swift 5.5+ feature available on iOS 15+
Task {
do {
_ = try await Installations.installations().authTokenForcingRefresh(true)
} catch {
// ...
}
}
}
#endif // compiler(>=5.5.2) && canImport(_Concurrency)
// Delete installation data
Installations.installations().delete { error in
if let _ /* error */ = error {
// ...
}
}
#if swift(>=5.5)
if #available(iOS 13.0, macOS 11.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) {
// async/await is a Swift 5.5+ feature available on iOS 15+
Task {
do {
_ = try await Installations.installations().delete()
} catch let error as NSError
where error.domain == InstallationsErrorDomain && error.code == InstallationsErrorCode
.unknown.rawValue {
// Above is the old way to handle errors.
} catch InstallationsErrorCode.unknown {
// Above is the new way to handle errors.
} catch {
// ...
}
}
}
#endif // swift(>=5.5)
// MARK: - InstallationsAuthTokenResult
Installations.installations().authToken { result, _ in
if let result = result {
_ = result.expirationDate
_ = result.authToken
}
}
// MARK: - InstallationsErrorCode
Installations.installations().authToken { _, error in
if let error = error {
// Old error handling.
switch (error as NSError).code {
case Int(InstallationsErrorCode.unknown.rawValue):
break
case Int(InstallationsErrorCode.keychain.rawValue):
break
case Int(InstallationsErrorCode.serverUnreachable.rawValue):
break
case Int(InstallationsErrorCode.invalidConfiguration.rawValue):
break
default:
break
}
// New error handling.
switch error {
case InstallationsErrorCode.unknown:
break
case InstallationsErrorCode.keychain:
break
case InstallationsErrorCode.serverUnreachable:
break
case InstallationsErrorCode.invalidConfiguration:
break
default:
break
}
}
}
func globalStringSymbols() {
let _: String = InstallationIDDidChangeAppNameKey
let _: String = InstallationsErrorDomain
}
}
}
|
apache-2.0
|
d8813d2274d53f76b32b0ed51aa77a1c
| 29.064865 | 98 | 0.585401 | 4.456731 | false | false | false | false |
artursDerkintis/Starfly
|
Starfly/SFSettings.swift
|
1
|
8174
|
//
// SFSettings.swift
// Starfly
//
// Created by Arturs Derkintis on 9/30/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import UIKit
class SFSettings: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let stackView = UIStackView(frame: CGRect.zero)
stackView.distribution = .FillEqually
stackView.spacing = 35
let privateSwitch = SFSettingsSwitch(frame: CGRect(x: 0, y: 0, width: 150, height : 40))
privateSwitch.switcher?.tag = NSUserDefaults.standardUserDefaults().boolForKey("pr") == true ? 1 : 0
privateSwitch.switcher?.setTitle("Private", forState: UIControlState.Normal)
privateSwitch.switcher?.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("pr") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
privateSwitch.switcher?.addTarget(self, action: "privateMode:", forControlEvents: UIControlEvents.TouchDown)
stackView.addArrangedSubview(privateSwitch)
let savePasswordsSwitch = SFSettingsSwitch(frame: CGRect(x:0, y: 0, width: 150, height : 40))
savePasswordsSwitch.switcher?.tag = NSUserDefaults.standardUserDefaults().boolForKey("savePASS") == true ? 1 : 0
savePasswordsSwitch.switcher?.setTitle("Enable Fillr", forState: UIControlState.Normal)
savePasswordsSwitch.switcher?.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("savePASS") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
savePasswordsSwitch.switcher?.addTarget(self, action: "passwordMode:", forControlEvents: UIControlEvents.TouchDown)
stackView.addArrangedSubview(savePasswordsSwitch)
let showTouches = SFSettingsSwitch(frame: CGRect(x:0, y: 0, width: 150, height : 40))
showTouches.switcher?.tag = NSUserDefaults.standardUserDefaults().boolForKey("showT") == true ? 1 : 0
showTouches.switcher?.setTitle("Show touches", forState: UIControlState.Normal)
showTouches.switcher?.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("showT") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
showTouches.switcher?.addTarget(self, action: "touch:", forControlEvents: UIControlEvents.TouchDown)
stackView.addArrangedSubview(showTouches)
let restoreTabs = SFSettingsSwitch(frame: CGRect(x:0, y: 0, width: 150, height : 40))
restoreTabs.switcher?.tag = NSUserDefaults.standardUserDefaults().boolForKey("rest") == true ? 1 : 0
restoreTabs.switcher?.setTitle("Restore tabs", forState: UIControlState.Normal)
restoreTabs.switcher?.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("rest") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
restoreTabs.switcher?.addTarget(self, action: "restoreTabs:", forControlEvents: UIControlEvents.TouchDown)
stackView.addArrangedSubview(restoreTabs)
addSubview(stackView)
stackView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(15)
make.left.equalTo(15)
make.height.equalTo(40)
make.right.equalTo(self).inset(25)
}
let colorPlate = SFColorPlate(frame: CGRect.zero)
addSubview(colorPlate)
colorPlate.snp_makeConstraints { (make) -> Void in
make.left.right.bottom.equalTo(0)
make.height.equalTo(20)
}
layer.cornerRadius = 45 / 2
layer.masksToBounds = true
}
func restoreTabs(sender : UIButton){
NSUserDefaults.standardUserDefaults().setBool(sender.tag == 1 ? false : true, forKey: "rest")
sender.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("rest") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
sender.tag = NSUserDefaults.standardUserDefaults().boolForKey("rest") == true ? 1 : 0
}
func touch(sender : UIButton){
NSUserDefaults.standardUserDefaults().setBool(sender.tag == 1 ? false : true, forKey: "showT")
sender.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("showT") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
sender.tag = NSUserDefaults.standardUserDefaults().boolForKey("showT") == true ? 1 : 0
}
func privateMode(sender : UIButton){
NSUserDefaults.standardUserDefaults().setBool(sender.tag == 1 ? false : true, forKey: "pr")
sender.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("pr") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
NSNotificationCenter.defaultCenter().postNotificationName("PRIVATE", object: nil)
sender.tag = NSUserDefaults.standardUserDefaults().boolForKey("pr") == true ? 1 : 0
}
func passwordMode(sender : UIButton){
NSUserDefaults.standardUserDefaults().setBool(sender.tag == 1 ? false : true, forKey: "savePASS")
sender.backgroundColor = NSUserDefaults.standardUserDefaults().boolForKey("savePASS") == true ? UIColor(white: 0.5, alpha: 0.5) :UIColor.clearColor()
Fillr.sharedInstance().setEnabled(sender.tag == 1 ? false : true)
sender.tag = NSUserDefaults.standardUserDefaults().boolForKey("savePASS") == true ? 1 : 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SFSettingsSwitch : UIView{
var switcher : UIButton?
override init(frame: CGRect) {
super.init(frame: frame)
switcher = UIButton(type: UIButtonType.Custom)
switcher?.frame = bounds
switcher?.layer.cornerRadius = 10
switcher?.autoresizingMask = UIViewAutoresizing.FlexibleWidth
switcher?.tag = 0
switcher?.layer.borderColor = UIColor.lightGrayColor().CGColor
switcher?.layer.borderWidth = 2
switcher?.titleLabel?.font = UIFont.boldSystemFontOfSize(15)
switcher?.titleLabel!.layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor
switcher?.titleLabel!.layer.shadowOffset = CGSize(width: 0, height: lineWidth())
switcher?.titleLabel!.layer.shadowRadius = 0
switcher?.titleLabel!.layer.shadowOpacity = 1.0
switcher?.titleLabel!.layer.rasterizationScale = UIScreen.mainScreen().scale
switcher?.titleLabel!.layer.shouldRasterize = true
addSubview(switcher!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SFColorPlate: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let stackView = UIStackView(frame: CGRect.zero)
stackView.distribution = .FillEqually
stackView.spacing = 5
addSubview(stackView)
stackView.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(self.snp_bottom).inset(3)
make.left.equalTo(15)
make.right.equalTo(self.snp_right).inset(15)
make.top.equalTo(0)
}
for i in 0..<SFColors.allColors.count{
let button = UIButton(type: UIButtonType.Custom)
button.backgroundColor = SFColors.allColors[i]
button.autoresizingMask = UIViewAutoresizing.FlexibleWidth
button.addTarget(self, action: "changeColor:", forControlEvents: UIControlEvents.TouchDown)
button.tag = i
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.whiteColor().CGColor
stackView.addArrangedSubview(button)
}
}
func changeColor(sender : UIButton){
NSUserDefaults.standardUserDefaults().setColor(SFColors.allColors[sender.tag], forKey: "COLOR2")
NSNotificationCenter.defaultCenter().postNotificationName("ColorChanges", object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
61b4bfa78828b2b8f838c9979f1169b3
| 48.539394 | 180 | 0.66683 | 4.773949 | false | false | false | false |
tokyovigilante/CesiumKit
|
CesiumKit/Scene/ImageryLayer.swift
|
1
|
45802
|
//
// ImageryLayer.swift
// CesiumKit
//
// Created by Ryan Walklin on 16/08/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
import Metal
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
/**
* An imagery layer that displays tiled image data from a single imagery provider
* on a {@link Globe}.
*
* @alias ImageryLayer
* @constructor
*
* @param {ImageryProvider} imageryProvider The imagery provider to use.
*/
open class ImageryLayer {
/**
* This value is used as the default brightness for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the brightness of the imagery.
* @type {Number}
* @default 1.0
*/
let defaultBrightness: Float = 1.0
/**
* This value is used as the default contrast for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the contrast of the imagery.
* @type {Number}
* @default 1.0
*/
let defaultContrast: Float = 1.0
/**
* This value is used as the default hue for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the hue of the imagery.
* @type {Number}
* @default 0.0
*/
let defaultHue: Float = 0.0
/**
* This value is used as the default saturation for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the saturation of the imagery.
* @type {Number}
* @default 1.0
*/
let defaultSaturation: Float = 1.0
/**
* This value is used as the default gamma for the imagery layer if one is not provided during construction
* or by the imagery provider. This value does not modify the gamma of the imagery.
* @type {Number}
* @default 1.0
*/
let defaultGamma: Float = 1.0
var imageryProvider: ImageryProvider
/**
* @param {Rectangle} [options.rectangle=imageryProvider.rectangle] The rectangle of the layer. This rectangle
* can limit the visible portion of the imagery provider.
*/
fileprivate let _rectangle: Rectangle
/**
* @param {Number|Function} [options.alpha=1.0] The alpha blending value of this layer, from 0.0 to 1.0.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the alpha is required, and it is expected to return
* the alpha value to use for the tile.
*/
let alpha: (() -> Float)
/**
* @param {Number|Function} [options.brightness=1.0] The brightness of this layer. 1.0 uses the unmodified imagery
* color. Less than 1.0 makes the imagery darker while greater than 1.0 makes it brighter.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the brightness is required, and it is expected to return
* the brightness value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
*/
let brightness: (() -> Float)
/**
* @param {Number|Function} [options.contrast=1.0] The contrast of this layer. 1.0 uses the unmodified imagery color.
* Less than 1.0 reduces the contrast while greater than 1.0 increases it.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the contrast is required, and it is expected to return
* the contrast value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
*/
let contrast: (() -> Float)
/*
* @param {Number|Function} [options.hue=0.0] The hue of this layer. 0.0 uses the unmodified imagery color.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates
* of the imagery tile for which the hue is required, and it is expected to return
* the contrast value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
*/
let hue: (() -> Float)
/**
* @param {Number|Function} [options.saturation=1.0] The saturation of this layer. 1.0 uses the unmodified imagery color.
* Less than 1.0 reduces the saturation while greater than 1.0 increases it.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates
* of the imagery tile for which the saturation is required, and it is expected to return
* the contrast value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
*/
let saturation: (() -> Float)
/**
* @param {Number|Function} [options.gamma=1.0] The gamma correction to apply to this layer. 1.0 uses the unmodified imagery color.
* This can either be a simple number or a function with the signature
* <code>function(frameState, layer, x, y, level)</code>. The function is passed the
* current frame state, this layer, and the x, y, and level coordinates of the
* imagery tile for which the gamma is required, and it is expected to return
* the gamma value to use for the tile. The function is executed for every
* frame and for every tile, so it must be fast.
*/
let gamma: (() -> Float)
/**
* @param {Boolean} [options.show=true] True if the layer is shown; otherwise, false.
*/
let show: Bool
// The value of the show property on the last update.
var _show: Bool = true
/*
* @param {Number} [options.maximumAnisotropy=maximum supported] The maximum anisotropy level to use
* for texture filtering. If this parameter is not specified, the maximum anisotropy supported
* by the WebGL stack will be used. Larger values make the imagery look better in horizon
* views.
*/
let maximumAnisotropy: Int?
/*
* @param {Number} [options.minimumTerrainLevel] The minimum terrain level-of-detail at which to show this imagery layer,
* or undefined to show it at all levels. Level zero is the least-detailed level.
*/
fileprivate let _minimumTerrainLevel: Int?
/**
* @param {Number} [options.maximumTerrainLevel] The maximum terrain level-of-detail at which to show this imagery layer,
* or undefined to show it at all levels. Level zero is the least-detailed level.
*/
fileprivate let _maximumTerrainLevel: Int?
fileprivate var _imageryCache = [String: Imagery]()
lazy fileprivate var _skeletonPlaceholder: TileImagery = TileImagery(imagery: Imagery.createPlaceholder(self))
// The index of this layer in the ImageryLayerCollection.
var layerIndex = -1
//private var _requestImageError = undefined;
fileprivate var _reprojectComputeCommands = [Command]()
/**
* Gets a value indicating whether this layer is the base layer in the
* {@link ImageryLayerCollection}. The base layer is the one that underlies all
* others. It is special in that it is treated as if it has global rectangle, even if
* it actually does not, by stretching the texels at the edges over the entire
* globe.
*
* @returns {Boolean} true if this is the base layer; otherwise, false.
*/
var isBaseLayer = false
init (
imageryProvider: ImageryProvider,
rectangle: Rectangle = Rectangle.maxValue,
alpha: @escaping (() -> Float) = { return 1.0 },
brightness: @escaping (() -> Float) = { return 1.0 },
contrast: @escaping (() -> Float) = { return 1.0 },
hue: @escaping (() -> Float) = { return 0.0 },
saturation: @escaping (() -> Float) = { return 1.0 },
gamma: @escaping (() -> Float) = { return 1.0 },
show: Bool = true,
minimumTerrainLevel: Int? = nil,
maximumTerrainLevel: Int? = nil,
maximumAnisotropy: Int? = nil
) {
self.imageryProvider = imageryProvider
self._rectangle = rectangle
self.alpha = alpha
self.brightness = brightness
self.contrast = contrast
self.hue = hue
self.saturation = saturation
self.gamma = gamma
self.show = show
self._minimumTerrainLevel = minimumTerrainLevel
self._maximumTerrainLevel = maximumTerrainLevel
self.maximumAnisotropy = maximumAnisotropy
}
/**
* Computes the intersection of this layer's rectangle with the imagery provider's availability rectangle,
* producing the overall bounds of imagery that can be produced by this layer.
*
* @returns {Promise.<Rectangle>} A promise to a rectangle which defines the overall bounds of imagery that can be produced by this layer.
*
* @example
* // Zoom to an imagery layer.
* imageryLayer.getViewableRectangle().then(function (rectangle) {
* return camera.flyTo({
* destination: rectangle
* });
* });
*/
func getViewableRectangle () -> Rectangle? {
return imageryProvider.rectangle.intersection(_rectangle)
}
/**
* Create skeletons for the imagery tiles that partially or completely overlap a given terrain
* tile.
*
* @private
*
* @param {QuadtreeTile} tile The terrain tile.
* @param {TerrainProvider} terrainProvider The terrain provider associated with the terrain tile.
* @param {Number} insertionPoint The position to insert new skeletons before in the tile's imagery list.
* @returns {Boolean} true if this layer overlaps any portion of the terrain tile; otherwise, false.
*/
func createTileImagerySkeletons (_ tile: QuadtreeTile, terrainProvider: TerrainProvider, insertionPoint: Int? = nil) -> Bool {
let surfaceTile = tile.data!
if _minimumTerrainLevel != nil && tile.level < _minimumTerrainLevel {
return false
}
if _maximumTerrainLevel != nil && tile.level > _maximumTerrainLevel {
return false
}
var insertionPoint = insertionPoint
if insertionPoint == nil {
insertionPoint = surfaceTile.imagery.count
}
if (!imageryProvider.ready) {
// The imagery provider is not ready, so we can't create skeletons, yet.
// Instead, add a placeholder so that we'll know to create
// the skeletons once the provider is ready.
_skeletonPlaceholder.loadingImagery!.addReference()
surfaceTile.imagery.remove(at: insertionPoint!)
surfaceTile.imagery.insert(_skeletonPlaceholder, at: insertionPoint!)
return true
}
// Compute the rectangle of the imagery from this imageryProvider that overlaps
// the geometry tile. The ImageryProvider and ImageryLayer both have the
// opportunity to constrain the rectangle. The imagery TilingScheme's rectangle
// always fully contains the ImageryProvider's rectangle.
let imageryBounds = imageryProvider.rectangle.intersection(_rectangle)
var overlapRectangle = tile.rectangle.intersection(imageryBounds!)
var rectangle = Rectangle(west: 0.0, south: 0.0, east: 0.0, north:0.0)
if overlapRectangle != nil {
rectangle = overlapRectangle!
} else {
// There is no overlap between this terrain tile and this imagery
// provider. Unless this is the base layer, no skeletons need to be created.
// We stretch texels at the edge of the base layer over the entire globe.
if !isBaseLayer {
return false
}
let baseImageryRectangle = imageryBounds!
let baseTerrainRectangle = tile.rectangle
overlapRectangle = Rectangle(west: 0.0, south: 0.0, east: 0.0, north:0.0)
if baseTerrainRectangle.south >= baseImageryRectangle.north {
overlapRectangle!.south = baseImageryRectangle.north
overlapRectangle!.north = overlapRectangle!.south
} else if baseTerrainRectangle.north <= baseImageryRectangle.south {
overlapRectangle!.south = baseImageryRectangle.south
overlapRectangle!.north = overlapRectangle!.south
} else {
rectangle.south = max(baseTerrainRectangle.south, baseImageryRectangle.south)
rectangle.north = min(baseTerrainRectangle.north, baseImageryRectangle.north)
}
if baseTerrainRectangle.west >= baseImageryRectangle.east {
overlapRectangle!.east = baseImageryRectangle.east
overlapRectangle!.west = overlapRectangle!.east
} else if baseTerrainRectangle.east <= baseImageryRectangle.west {
overlapRectangle!.east = baseImageryRectangle.west
overlapRectangle!.west = overlapRectangle!.east
} else {
rectangle.west = max(baseTerrainRectangle.west, baseImageryRectangle.west)
rectangle.east = min(baseTerrainRectangle.east, baseImageryRectangle.east)
}
rectangle = overlapRectangle!
}
var latitudeClosestToEquator = 0.0
if (rectangle.south > 0.0) {
latitudeClosestToEquator = rectangle.south
} else if (rectangle.north < 0.0) {
latitudeClosestToEquator = rectangle.north
}
// Compute the required level in the imagery tiling scheme.
// The errorRatio should really be imagerySSE / terrainSSE rather than this hard-coded value.
// But first we need configurable imagery SSE and we need the rendering to be able to handle more
// images attached to a terrain tile than there are available texture units. So that's for the future.
let errorRatio = 1.0
let targetGeometricError = errorRatio * terrainProvider.levelMaximumGeometricError(tile.level)
var imageryLevel = levelWithMaximumTexelSpacing(targetGeometricError, latitudeClosestToEquator: latitudeClosestToEquator)
imageryLevel = max(0, imageryLevel)
let maximumLevel = imageryProvider.maximumLevel
if (imageryLevel > maximumLevel) {
imageryLevel = maximumLevel
}
if let minimumLevel = imageryProvider.minimumLevel {
if (imageryLevel < minimumLevel) {
imageryLevel = minimumLevel
}
}
let imageryTilingScheme = imageryProvider.tilingScheme
var northwestTileCoordinates = imageryTilingScheme.positionToTileXY(position: rectangle.northwest, level: imageryLevel)!
var southeastTileCoordinates = imageryTilingScheme.positionToTileXY(position: rectangle.southeast, level: imageryLevel)!
// If the southeast corner of the rectangle lies very close to the north or west side
// of the southeast tile, we don't actually need the southernmost or easternmost
// tiles.
// Similarly, if the northwest corner of the rectangle lies very close to the south or east side
// of the northwest tile, we don't actually need the northernmost or westernmost tiles.
// We define "very close" as being within 1/512 of the width of the tile.
let veryCloseX = tile.rectangle.height / 512.0
let veryCloseY = tile.rectangle.width / 512.0
let northwestTileRectangle = imageryTilingScheme.tileXYToRectangle(x: northwestTileCoordinates.x, y: northwestTileCoordinates.y, level: imageryLevel)
if (abs(northwestTileRectangle.south - tile.rectangle.north) < veryCloseY && northwestTileCoordinates.y < southeastTileCoordinates.y) {
northwestTileCoordinates.y += 1
}
if (abs(northwestTileRectangle.east - tile.rectangle.west) < veryCloseX && northwestTileCoordinates.x < southeastTileCoordinates.x) {
northwestTileCoordinates.x += 1
}
let southeastTileRectangle = imageryTilingScheme.tileXYToRectangle(x: southeastTileCoordinates.x, y: southeastTileCoordinates.y, level: imageryLevel)
if (abs(southeastTileRectangle.north - tile.rectangle.south) < veryCloseY && southeastTileCoordinates.y > northwestTileCoordinates.y) {
southeastTileCoordinates.y -= 1
}
if (abs(southeastTileRectangle.west - tile.rectangle.east) < veryCloseX && southeastTileCoordinates.x > northwestTileCoordinates.x) {
southeastTileCoordinates.x -= 1
}
// Create TileImagery instances for each imagery tile overlapping this terrain tile.
// We need to do all texture coordinate computations in the imagery tile's tiling scheme.
let terrainRectangle = tile.rectangle
var imageryRectangle = imageryTilingScheme.tileXYToRectangle(x: northwestTileCoordinates.x, y: northwestTileCoordinates.y, level: imageryLevel)
var clippedImageryRectangle = imageryRectangle.intersection(imageryBounds!)!
var minU: Double
var maxU = 0.0
var minV = 1.0
var maxV: Double
// If this is the northern-most or western-most tile in the imagery tiling scheme,
// it may not start at the northern or western edge of the terrain tile.
// Calculate where it does start.
if !isBaseLayer && abs(clippedImageryRectangle.west - tile.rectangle.west) >= veryCloseX {
maxU = min(1.0, (clippedImageryRectangle.west - terrainRectangle.west) / terrainRectangle.width)
}
if (!isBaseLayer && abs(clippedImageryRectangle.north - tile.rectangle.north) >= veryCloseY) {
minV = max(0.0, (imageryRectangle.north - terrainRectangle.south) / terrainRectangle.height)
}
let initialMinV = minV
for i in northwestTileCoordinates.x...southeastTileCoordinates.x {
minU = maxU
imageryRectangle = imageryTilingScheme.tileXYToRectangle(x: i, y: northwestTileCoordinates.y, level: imageryLevel)
clippedImageryRectangle = imageryRectangle.intersection(imageryBounds!)!
maxU = min(1.0, (clippedImageryRectangle.east - terrainRectangle.west) / terrainRectangle.width)
// If this is the eastern-most imagery tile mapped to this terrain tile,
// and there are more imagery tiles to the east of this one, the maxU
// should be 1.0 to make sure rounding errors don't make the last
// image fall shy of the edge of the terrain tile.
if i == southeastTileCoordinates.x && (isBaseLayer || abs(clippedImageryRectangle.east - tile.rectangle.east) < veryCloseX) {
maxU = 1.0
}
minV = initialMinV
for j in northwestTileCoordinates.y...southeastTileCoordinates.y {
maxV = minV
imageryRectangle = imageryTilingScheme.tileXYToRectangle(x: i, y: j, level: imageryLevel)
clippedImageryRectangle = imageryRectangle.intersection(imageryBounds!)!
minV = max(0.0, (clippedImageryRectangle.south - terrainRectangle.south) / terrainRectangle.height)
// If this is the southern-most imagery tile mapped to this terrain tile,
// and there are more imagery tiles to the south of this one, the minV
// should be 0.0 to make sure rounding errors don't make the last
// image fall shy of the edge of the terrain tile.
if j == southeastTileCoordinates.y && (isBaseLayer || abs(clippedImageryRectangle.south - tile.rectangle.south) < veryCloseY) {
minV = 0.0
}
let texCoordsRectangle = Cartesian4(x: minU, y: minV, z: maxU, w: maxV)
let imagery = getImageryFromCache(level: imageryLevel, x: i, y: j, imageryRectangle: imageryRectangle)
surfaceTile.imagery.insert(TileImagery(imagery: imagery, textureCoordinateRectangle: texCoordsRectangle), at: insertionPoint!)
insertionPoint! += 1
}
}
return true
}
/**
* Calculate the translation and scale for a particular {@link TileImagery} attached to a
* particular terrain tile.
*
* @private
*
* @param {Tile} tile The terrain tile.
* @param {TileImagery} tileImagery The imagery tile mapping.
* @returns {Cartesian4} The translation and scale where X and Y are the translation and Z and W
* are the scale.
*/
func calculateTextureTranslationAndScale (_ tile: QuadtreeTile, tileImagery: TileImagery) -> Cartesian4 {
let imageryRectangle = tileImagery.readyImagery!.rectangle!
let terrainRectangle = tile.rectangle
let terrainWidth = terrainRectangle.width
let terrainHeight = terrainRectangle.height
let scaleX = terrainWidth / imageryRectangle.width
let scaleY = terrainHeight / imageryRectangle.height
return Cartesian4(
x: scaleX * (terrainRectangle.west - imageryRectangle.west) / terrainWidth,
y: scaleY * (terrainRectangle.south - imageryRectangle.south) / terrainHeight,
z: scaleX,
w: scaleY)
}
/**
* Request a particular piece of imagery from the imagery provider. This method handles raising an
* error event if the request fails, and retrying the request if necessary.
*
* @private
*
* @param {Imagery} imagery The imagery to request.
*/
func requestImagery (_ imagery: Imagery) {
imagery.state = .transitioning
let completionBlock: ((CGImage?) -> Void) = { (image) in
if let image = image {
DispatchQueue.main.async(execute: {
imagery.image = image
imagery.credits = self.imageryProvider.tileCredits(x: imagery.x, y: imagery.y, level: imagery.level)
imagery.state = .received
})
} else {
DispatchQueue.main.async(execute: {
imagery.state = .failed
let message = "Failed to obtain image tile X: \(imagery.x) Y: \(imagery.y) Level: \(imagery.level)"
logPrint(.error, message)
})
}
}
self.imageryProvider.requestImage(x: imagery.x, y: imagery.y, level: imagery.level, completionBlock: completionBlock)
}
/**
* Create a WebGL texture for a given {@link Imagery} instance.
*
* @private
*
* @param {Context} context The rendered context to use to create textures.
* @param {Imagery} imagery The imagery for which to create a texture.
*/
func createTexture (frameState: FrameState, imagery: Imagery) {
guard let context = frameState.context else {
return
}
QueueManager.sharedInstance.resourceLoadQueue.async(execute: {
// If this imagery provider has a discard policy, use it to check if this
// image should be discarded.
if let discardPolicy = self.imageryProvider.tileDiscardPolicy {
// If the discard policy is not ready yet, transition back to the
// RECEIVED state and we'll try again next time.
if !discardPolicy.isReady {
DispatchQueue.main.async(execute: {
imagery.state = .received
})
return
}
// Mark discarded imagery tiles invalid. Parent imagery will be used instead.
if (discardPolicy.shouldDiscardImage(imagery.image!)) {
DispatchQueue.main.async(execute: {
imagery.state = .invalid
})
return
}
}
// Imagery does not need to be discarded, so upload it to GL.
let texture = Texture(context: context, options: TextureOptions(
source : .image(imagery.image!),
pixelFormat: .rgba8Unorm,
flipY: true, // CGImage
usage: .ShaderRead
)
)
logPrint(.debug, "created texture for L\(imagery.level)X\(imagery.x)Y\(imagery.y)")
DispatchQueue.main.async(execute: {
//dispatch_async(context.renderQueue, {
imagery.texture = texture
imagery.image = nil
imagery.state = ImageryState.textureLoaded
})
})
}
/**
* Enqueues a command re-projecting a texture to a {@link GeographicProjection} on the next update,
* if necessary, and generates mipmaps for the geographic texture.
*
* @private
*
* @param {FrameState} frameState The frameState.
* @param {Imagery} imagery The imagery instance to reproject.
*/
func reprojectTexture (frameState: inout FrameState, imagery: Imagery) {
let texture = imagery.texture!
let rectangle = imagery.rectangle!
let context = frameState.context
// Reproject this texture if it is not already in a geographic projection and
// the pixels are more than 1e-5 radians apart. The pixel spacing cutoff
// avoids precision problems in the reprojection transformation while making
// no noticeable difference in the georeferencing of the image.
let pixelGap: Bool = rectangle.width / Double(texture.width) > pow(10, -5)
let isGeographic = self.imageryProvider.tilingScheme is GeographicTilingScheme
if !isGeographic && pixelGap {
let computeCommand = ComputeCommand(
// Update render resources right before execution instead of now.
// This allows different ImageryLayers to share the same vao and buffers.
preExecute: { command in
self.reprojectToGeographic(command, context: context!, texture: texture, rectangle: rectangle)
},
postExecute: { outputTexture in
imagery.texture = outputTexture
self.finalizeReprojectTexture(context: context!, imagery: imagery, texture: outputTexture)
},
persists: true,
owner : self
)
_reprojectComputeCommands.append(computeCommand)
} else {
finalizeReprojectTexture(context: context!, imagery: imagery, texture: texture)
}
}
func finalizeReprojectTexture(context: Context, imagery: Imagery, texture: Texture) {
/*
// Use mipmaps if this texture has power-of-two dimensions.
if (CesiumMath.isPowerOfTwo(texture.width) && CesiumMath.isPowerOfTwo(texture.height)) {
var mipmapSampler = context.cache.imageryLayer_mipmapSampler;
if (!defined(mipmapSampler)) {
var maximumSupportedAnisotropy = ContextLimits.maximumTextureFilterAnisotropy;
mipmapSampler = context.cache.imageryLayer_mipmapSampler = new Sampler({
wrapS : TextureWrap.CLAMP_TO_EDGE,
wrapT : TextureWrap.CLAMP_TO_EDGE,
minificationFilter : TextureMinificationFilter.LINEAR_MIPMAP_LINEAR,
magnificationFilter : TextureMagnificationFilter.LINEAR,
maximumAnisotropy : Math.min(maximumSupportedAnisotropy, defaultValue(imageryLayer._maximumAnisotropy, maximumSupportedAnisotropy))
});
}
texture.generateMipmap(MipmapHint.NICEST);
texture.sampler = mipmapSampler;
} else {
var nonMipmapSampler = context.cache.imageryLayer_nonMipmapSampler;
if (!defined(nonMipmapSampler)) {
nonMipmapSampler = context.cache.imageryLayer_nonMipmapSampler = new Sampler({
wrapS : TextureWrap.CLAMP_TO_EDGE,
wrapT : TextureWrap.CLAMP_TO_EDGE,
minificationFilter : TextureMinificationFilter.LINEAR,
magnificationFilter : TextureMagnificationFilter.LINEAR
});
}
texture.sampler = nonMipmapSampler;
}
imagery.state = ImageryState.READY;*/
if false { //Math.isPowerOfTwo(texture.width) && Math.isPowerOfTwo(texture.height) {
var mipmapSampler = context.cache["imageryLayer_mipmapSampler"] as! Sampler?
if mipmapSampler == nil {
mipmapSampler = Sampler(context: context, mipMagFilter: .linear, maximumAnisotropy: context.limits.maximumTextureFilterAnisotropy)
}
// FIXME: Mipmaps
context.cache["imageryLayer_mipmapSampler"] = mipmapSampler
} else {
var nonMipmapSampler = context.cache["imageryLayer_nonMipmapSampler"] as! Sampler?
if nonMipmapSampler == nil {
nonMipmapSampler = Sampler(context: context)
context.cache["imageryLayer_nonMipmapSampler"] = nonMipmapSampler!
}
texture.sampler = nonMipmapSampler!
}
DispatchQueue.main.async(execute: {
// dispatch_async(context.renderQueue, {
imagery.state = .ready
})
}
func generateMipmaps (frameState: inout FrameState, imagery: Imagery) {
guard let context = frameState.context else {
return
}
// Use mipmaps if this texture has power-of-two dimensions.
QueueManager.sharedInstance.resourceLoadQueue.async(execute: {
let texture = imagery.texture!
if false { //Math.isPowerOfTwo(texture.width) && Math.isPowerOfTwo(texture.height) {
var mipmapSampler = context.cache["imageryLayer_mipmapSampler"] as! Sampler?
if mipmapSampler == nil {
mipmapSampler = Sampler(context: context, mipMagFilter: .linear, maximumAnisotropy: context.limits.maximumTextureFilterAnisotropy)
}
// FIXME: Mipmaps
context.cache["imageryLayer_mipmapSampler"] = mipmapSampler
} else {
var nonMipmapSampler = context.cache["imageryLayer_nonMipmapSampler"] as! Sampler?
if nonMipmapSampler == nil {
nonMipmapSampler = Sampler(context: context)
context.cache["imageryLayer_nonMipmapSampler"] = nonMipmapSampler!
}
texture.sampler = nonMipmapSampler!
}
DispatchQueue.main.async(execute: {
// dispatch_async(context.renderQueue, {
imagery.state = .ready
})
})
}
/**
* Updates frame state to execute any queued texture re-projections.
*
* @private
*
* @param {FrameState} frameState The frameState.
*/
func queueReprojectionCommands (frameState: inout FrameState) {
frameState.commandList.append(contentsOf: _reprojectComputeCommands)
_reprojectComputeCommands.removeAll()
}
/**
* Cancels re-projection commands queued for the next frame.
*
* @private
*/
func cancelReprojections () {
_reprojectComputeCommands.removeAll()
}
func getImageryFromCache (level: Int, x: Int, y: Int, imageryRectangle: Rectangle? = nil) -> Imagery {
let cacheKey = getImageryCacheKey(level: level, x: x, y: y)
var imagery = _imageryCache[cacheKey]
if imagery == nil {
imagery = Imagery(imageryLayer: self, level: level, x: x, y: y, rectangle: imageryRectangle)
_imageryCache[cacheKey] = imagery
}
imagery!.addReference()
return imagery!
}
func removeImageryFromCache (_ imagery: Imagery) {
let cacheKey = getImageryCacheKey(level: imagery.level, x: imagery.x, y: imagery.y)
_imageryCache.removeValue(forKey: cacheKey)
}
fileprivate func getImageryCacheKey(level: Int, x: Int, y: Int) -> String {
return "level\(level)x\(x)y\(y)"
}
class Reproject {
let vertexBuffer: Buffer
let vertexAttributes: [VertexAttributes]
let pipeline: RenderPipeline
let sampler: Sampler
let indexBuffer: Buffer
let indexCount: Int
init (vertexBuffer: Buffer, vertexAttributes: [VertexAttributes], pipeline: RenderPipeline, sampler: Sampler, indexBuffer: Buffer, indexCount: Int) {
self.vertexBuffer = vertexBuffer
self.vertexAttributes = vertexAttributes
self.pipeline = pipeline
self.sampler = sampler
self.indexBuffer = indexBuffer
self.indexCount = indexCount
}
deinit {
// FIXME: destroy
//if framebuffer != nil {
//this.framebuffer.destroy()
//}
//this.vertexArray.destroy();
//shaderProgram.destroy();
}
}
func reprojectToGeographic(_ command: ComputeCommand, context: Context, texture: Texture, rectangle: Rectangle) {
// This function has gone through a number of iterations, because GPUs are awesome.
//
// Originally, we had a very simple vertex shader and computed the Web Mercator texture coordinates
// per-fragment in the fragment shader. That worked well, except on mobile devices, because
// fragment shaders have limited precision on many mobile devices. The result was smearing artifacts
// at medium zoom levels because different geographic texture coordinates would be reprojected to Web
// Mercator as the same value.
//
// Our solution was to reproject to Web Mercator in the vertex shader instead of the fragment shader.
// This required far more vertex data. With fragment shader reprojection, we only needed a single quad.
// But to achieve the same precision with vertex shader reprojection, we needed a vertex for each
// output pixel. So we used a grid of 256x256 vertices, because most of our imagery
// tiles are 256x256. Fortunately the grid could be created and uploaded to the GPU just once and
// re-used for all reprojections, so the performance was virtually unchanged from our original fragment
// shader approach. See https://github.com/AnalyticalGraphicsInc/cesium/pull/714.
//
// Over a year later, we noticed (https://github.com/AnalyticalGraphicsInc/cesium/issues/2110)
// that our reprojection code was creating a rare but severe artifact on some GPUs (Intel HD 4600
// for one). The problem was that the GLSL sin function on these GPUs had a discontinuity at fine scales in
// a few places.
//
// We solved this by implementing a more reliable sin function based on the CORDIC algorithm
// (https://github.com/AnalyticalGraphicsInc/cesium/pull/2111). Even though this was a fair
// amount of code to be executing per vertex, the performance seemed to be pretty good on most GPUs.
// Unfortunately, on some GPUs, the performance was absolutely terrible
// (https://github.com/AnalyticalGraphicsInc/cesium/issues/2258).
//
// So that brings us to our current solution, the one you see here. Effectively, we compute the Web
// Mercator texture coordinates on the CPU and store the T coordinate with each vertex (the S coordinate
// is the same in Geographic and Web Mercator). To make this faster, we reduced our reprojection mesh
// to be only 2 vertices wide and 64 vertices high. We should have reduced the width to 2 sooner,
// because the extra vertices weren't buying us anything. The height of 64 means we are technically
// doing a slightly less accurate reprojection than we were before, but we can't see the difference
// so it's worth the 4x speedup.
var reproject: Reproject! = context.cache["imageryLayer_reproject"] as! Reproject!
if reproject == nil {
var positions = [Float32]()
let position0: Float = 0.0
let position1: Float = 1.0
for j in 0..<64 {
let y = 1 - Float(j) / 63.0
positions.append(position0)
positions.append(y)
positions.append(position1)
positions.append(y)
}
guard let vertexBuffer = Buffer(device: context.device, array: positions, componentDatatype: .float32, sizeInBytes: positions.sizeInBytes) else {
logPrint(.critical, "Cannot create vertex buffer")
return
}
let indices = EllipsoidTerrainProvider.getRegularGridIndices(width: 2, height: 64).map({ UInt16($0) })
guard let indexBuffer = Buffer(device: context.device, array: indices, componentDatatype: .unsignedShort, sizeInBytes: indices.sizeInBytes) else {
logPrint(.critical, "Cannot create index buffer")
return
}
let vertexAttributes = [
//position
VertexAttributes(
buffer: vertexBuffer,
bufferIndex: VertexDescriptorFirstBufferOffset,
index: 0,
format: .float2,
offset: 0,
size: MemoryLayout<Float>.size * 2,
normalize: false
),
// webMercatorT
VertexAttributes(
buffer: nil,
bufferIndex: VertexDescriptorFirstBufferOffset+1,
index: 1,
format: .float,
offset: 0,
size: MemoryLayout<Float>.size,
normalize: false
)
]
let vertexDescriptor = VertexDescriptor(attributes: vertexAttributes)
let pipeline = context.pipelineCache.getRenderPipeline(
vertexShaderSource: ShaderSource(sources: [Shaders["ReprojectWebMercatorVS"]!]),
fragmentShaderSource: ShaderSource(sources: [Shaders["ReprojectWebMercatorFS"]!]),
vertexDescriptor: vertexDescriptor,
colorMask: nil,
depthStencil: false
)
let maximumSupportedAnisotropy = context.limits.maximumTextureFilterAnisotropy
guard let sampler = Sampler(context: context, maximumAnisotropy: min(maximumSupportedAnisotropy, maximumAnisotropy ?? maximumSupportedAnisotropy)) else {
logPrint(.critical, "Cannot create sampler")
return
}
reproject = Reproject(
vertexBuffer: vertexBuffer,
vertexAttributes: vertexAttributes,
pipeline: pipeline,
sampler: sampler,
indexBuffer: indexBuffer,
indexCount: indices.count
)
context.cache["imageryLayer_reproject"] = reproject
}
texture.sampler = reproject!.sampler
let width = texture.width
let height = texture.height
let uniformMap = ImageryLayerUniformMap()
uniformMap.textureDimensions = Cartesian2(x: Double(width), y: Double(height))
uniformMap.viewportOrthographic = Matrix4.computeOrthographicOffCenter(left: 0, right: uniformMap.textureDimensions.x, bottom: 0, top: uniformMap.textureDimensions.y, near: 0.0, far: 1.0)
uniformMap.texture = texture
var sinLatitude = sin(rectangle.south)
let southMercatorY = 0.5 * log((1 + sinLatitude) / (1 - sinLatitude))
sinLatitude = sin(rectangle.north)
let northMercatorY = 0.5 * log((1 + sinLatitude) / (1 - sinLatitude))
let oneOverMercatorHeight = 1.0 / (northMercatorY - southMercatorY)
let south = rectangle.south
let north = rectangle.north
var webMercatorT = [Float]()
for webMercatorTIndex in 0..<64 {
let fraction = Double(webMercatorTIndex) / 63.0
let latitude = Math.lerp(p: south, q: north, time: fraction)
sinLatitude = sin(latitude)
let mercatorY = 0.5 * log((1.0 + sinLatitude) / (1.0 - sinLatitude))
let mercatorFraction = Float((mercatorY - southMercatorY) * oneOverMercatorHeight)
webMercatorT.append(mercatorFraction)
webMercatorT.append(mercatorFraction)
}
let webMercatorTBuffer = Buffer(device: context.device, array: webMercatorT, componentDatatype: .float32, sizeInBytes: webMercatorT.sizeInBytes)
var attributes = reproject!.vertexAttributes
attributes[1].buffer = webMercatorTBuffer
let vertexArray = VertexArray(attributes: attributes, vertexCount: 128, indexBuffer: reproject!.indexBuffer, indexCount: reproject?.indexCount)
let textureUsage: TextureUsage = [.RenderTarget, .ShaderRead]
let outputTexture = Texture(
context: context,
options: TextureOptions(
width: width,
height: height,
pixelFormat: PixelFormat(rawValue: context.view.colorPixelFormat.rawValue)!,
premultiplyAlpha: texture.premultiplyAlpha,
usage: textureUsage
)
)
outputTexture.sampler = (reproject?.sampler)!
command.pipeline = reproject?.pipeline
command.outputTexture = outputTexture
command.uniformMap = uniformMap
command.vertexArray = vertexArray
}
/**
* Gets the level with the specified world coordinate spacing between texels, or less.
*
* @param {Number} texelSpacing The texel spacing for which to find a corresponding level.
* @param {Number} latitudeClosestToEquator The latitude closest to the equator that we're concerned with.
* @returns {Number} The level with the specified texel spacing or less.
*/
func levelWithMaximumTexelSpacing(_ texelSpacing: Double, latitudeClosestToEquator: Double) -> Int {
// PERFORMANCE_IDEA: factor out the stuff that doesn't change.
let tilingScheme = imageryProvider.tilingScheme
let latitudeFactor = !(tilingScheme is GeographicTilingScheme) ? cos(latitudeClosestToEquator) : 1.0
let levelZeroMaximumTexelSpacing = tilingScheme.ellipsoid.maximumRadius * tilingScheme.rectangle.width * latitudeFactor / Double(imageryProvider.tileWidth * tilingScheme.numberOfXTilesAt(level: 0))
let twoToTheLevelPower = levelZeroMaximumTexelSpacing / texelSpacing;
let level = log(twoToTheLevelPower) / log(2)
let rounded = Int(round(level))
return rounded | 0
}
}
|
apache-2.0
|
d9e783d65effbf2e9e9e331f901ec346
| 46.512448 | 205 | 0.613226 | 4.756673 | false | false | false | false |
RxSwiftCommunity/RxTask
|
Sources/Task.swift
|
1
|
6385
|
//
// Runner.swift
// RxTask
//
// Created by Scott Hoyt on 2/18/17.
//
//
import Foundation
import RxSwift
#if os(Linux)
typealias Process = Foundation.Task
extension Process {
var isRunning: Bool {
return running
}
}
#endif
/// Event emitted by a launched `Task`.
public enum TaskEvent {
/// The `Task` has launched.
case launch(command: String)
/// The `Task` has output to `stdout`.
case stdOut(Data)
/// The `Task` has output to `stderr`.
case stdErr(Data)
/// The `Task` exited successfully.
case exit(statusCode: Int)
}
extension TaskEvent: Equatable {
/// Equates two `TaskEvent`s.
public static func == (lhs: TaskEvent, rhs: TaskEvent) -> Bool {
switch (lhs, rhs) {
case let (.launch(left), .launch(right)):
return left == right
case let (.stdOut(left), .stdOut(right)):
return left == right
case let (.stdErr(left), .stdErr(right)):
return left == right
case let (.exit(left), .exit(right)):
return left == right
default:
return false
}
}
}
/// An error encountered in the execution of a `Task`.
public enum TaskError: Error {
/// An uncaught signal was encountered.
case uncaughtSignal
/// The `Task` exited unsuccessfully.
case exit(statusCode: Int)
}
extension TaskError: Equatable {
/// Equates two `TaskError`s.
public static func == (lhs: TaskError, rhs: TaskError) -> Bool {
switch (lhs, rhs) {
case (.uncaughtSignal, .uncaughtSignal):
return true
case let (.exit(left), .exit(right)):
return left == right
default:
return false
}
}
}
/// Encapsulates launching a RxSwift powered command line task.
public struct Task {
/// The location of the executable.
let launchPath: String
/// The arguments to be passed to the executable.
let arguments: [String]
/// The working directory of the task. If `nil`, this will inherit from the parent process.
let workingDirectory: String?
/// The environment to launch the task with. If `nil`, this will inherit from the parent process.
let environment: [String: String]?
private let disposeBag = DisposeBag()
/**
Create a new task.
- parameters:
- launchPath: The location of the executable.
- arguments: The arguments to be passed to the executable.
- workingDirectory: The working directory of the task. If not used, this will inherit from the parent process.
- environment: The environment to launch the task with. If not used, this will inherit from the parent process.
*/
public init(launchPath: String, arguments: [String] = [], workingDirectory: String? = nil, environment: [String: String]? = nil) {
self.launchPath = launchPath
self.arguments = arguments
self.workingDirectory = workingDirectory
self.environment = environment
}
/**
Launch the `Task`.
- parameter stdIn: An optional `Observable` to provide `stdin` for the process. Defaults to `nil`.
*/
public func launch(stdIn: Observable<Data>? = nil) -> Observable<TaskEvent> {
let process = Process()
process.launchPath = self.launchPath
process.arguments = self.arguments
if let workingDirectory = workingDirectory { process.currentDirectoryPath = workingDirectory }
if let environment = environment { process.environment = environment }
return Observable.create { observer in
process.standardOutput = self.outPipe { observer.onNext(.stdOut($0)) }
process.standardError = self.outPipe { observer.onNext(.stdErr($0)) }
if let stdIn = stdIn {
process.standardInput = self.inPipe(stdIn: stdIn, errorHandler: observer.onError)
}
process.terminationHandler = self.terminationHandler(observer: observer)
observer.onNext(.launch(command: self.description))
process.launch()
return Disposables.create {
if process.isRunning {
process.terminate()
}
}
}
}
private func terminationHandler(observer: AnyObserver<TaskEvent>) -> (Process) -> Void {
// Handle process termination and determine if it was a normal exit
// or an error.
return { process in
switch process.terminationReason {
case .exit:
if process.terminationStatus == 0 {
observer.onNext(.exit(statusCode: Int(process.terminationStatus)))
observer.onCompleted()
} else {
observer.onError(TaskError.exit(statusCode: Int(process.terminationStatus)))
}
case .uncaughtSignal:
observer.onError(TaskError.uncaughtSignal)
}
}
}
private func outPipe(withHandler handler: @escaping (Data) -> Void) -> Pipe {
let pipe = Pipe()
pipe.fileHandleForReading.readabilityHandler = { handler($0.availableData) }
return pipe
}
private func inPipe(stdIn: Observable<Data>, errorHandler: @escaping (Error) -> Void) -> Pipe {
let pipe = Pipe()
stdIn
.subscribe(onNext: pipe.fileHandleForWriting.write)
.disposed(by: disposeBag)
return pipe
}
}
extension Task: CustomStringConvertible {
/// A `String` describing the `Task`.
public var description: String {
return ([launchPath] + arguments).joined(separator: " ")
}
}
extension Task: Equatable {
/// Whether or not two `Task`s are equal.
public static func == (lhs: Task, rhs: Task) -> Bool {
return lhs.launchPath == rhs.launchPath &&
lhs.arguments == rhs.arguments &&
lhs.workingDirectory == rhs.workingDirectory &&
envsEqual(lhs: lhs.environment, rhs: rhs.environment)
}
private static func envsEqual(lhs: [String: String]?, rhs: [String: String]?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case let (.some(left), .some(right)):
return left == right
default:
return false
}
}
}
|
mit
|
b7790d9c4069ba661573062157dd4d75
| 28.836449 | 134 | 0.602349 | 4.663988 | false | false | false | false |
306244907/Weibo
|
JLSina/JLSina/Classes/Tools(工具)/UI框架/Emoticon/View/CZEmoticonCell.swift
|
1
|
7425
|
//
// CZEmoticonCell.swift
// 表情键盘
//
// Created by 盘赢 on 2017/12/14.
// Copyright © 2017年 盘赢. All rights reserved.
//
import UIKit
//表情cell的协议
@objc protocol CZEmoticonCellDelegate: NSObjectProtocol {
/// 表情cell选中表情模型
///
/// - Parameter em: 表情模型 / nil 表示删除
func CZEmoticonCellDidSelectedEmoticon(cell: CZEmoticonCell ,em: CZEmoticon?)
}
//表情的页面cell,
//每一个cell用九宫格算法,自行添加20个表情,
//每一个cell和CollectionView一样大小
//最后一个位置,放置删除按钮
class CZEmoticonCell: UICollectionViewCell {
//代理不能用let
weak var delegate: CZEmoticonCellDelegate?
var emoticons:[CZEmoticon]? {
//当前页面表情模型数组,'最多'20个
didSet {
// print("表情包数量\(emoticons?.count)")
//1,隐藏所有按钮
for v in contentView.subviews {
v.isHidden = true
}
contentView.subviews.last?.isHidden = false
//2,遍历表情模型数组
for (i,em) in (emoticons ?? []).enumerated() {
//1,取出按钮
if let btn = contentView.subviews[i] as? UIButton {
//设置图像 - 如果图像为nil,会清空图像,避免复用
btn.setImage(em.image, for: [])
//设置emoji 的字符串 - 如果emoji为nil,会清空emoji,避免复用
btn.setTitle(em.emoji, for: [])
btn.isHidden = false
}
}
}
}
///标题选择提示视图
private lazy var tipView = CZEmoticonTipView()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 当视图从界面上删除,同样会调用此方法,newWindow == nil
override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
guard let w = newWindow else {
return
}
// 将提示视图添加到窗口上
// 提示:在 iOS 6.0 之前,很多程序员都喜欢把控件往窗口添加
// 在现在开发,如果有地方,就不要用窗口!
w.addSubview(tipView)
tipView.isHidden = true
}
//XIB加载测试
// override func awakeFromNib() {
// setupUI()
// }
//MARK: - 监听方法
/// 选中表情按钮
///
/// - Parameter button:
@objc private func selectedEmoticonButton(button: UIButton) {
//1,去 tag 0 ~ 20 ,20对应的是删除按钮
let tag = button.tag
//2,根据tag,判断是否是删除按钮,如果不是删除按钮,取得表情
var em: CZEmoticon?
if tag < (emoticons?.count)! {
em = emoticons?[tag]
}
//3,em选中的模型,如果为nil,是删除按钮
delegate?.CZEmoticonCellDidSelectedEmoticon(cell: self, em: em)
}
/// 长按手势识别 - 是一个非常重要的手势
/// 可以保证一个对象监听两种点击手势,而且不需要考虑解决手势冲突
@objc private func longGesture(gesture: UILongPressGestureRecognizer) {
//测试添加提示视图
// addSubview(tipView)
//1,获取触摸位置
let location = gesture.location(in: self)
//2,获取触摸位置对应的按钮
guard let button = buttonWithLocation(location: location) else {
tipView.isHidden = true
return
}
//3,处理手势状态
//在处理手势细节的时候,不要试图一下把所有状态都处理完毕
switch gesture.state {
case .began , .changed:
tipView.isHidden = false
//坐标系的转换 -> 将按钮参照cell坐标系,转换到window的坐标位置
let center = self.convert(button.center, to: window)
//设置提示视图的位置
tipView.center = center
//设置提示视图的表情模型
if button.tag < (emoticons?.count)! {
tipView.emoticon = emoticons?[button.tag]
}
case .ended:
tipView.isHidden = true
//执行选中按钮函数
selectedEmoticonButton(button: button)
break
case .cancelled, .failed:
tipView.isHidden = true
break
default:
break
}
print(button)
}
private func buttonWithLocation(location: CGPoint) -> UIButton? {
//遍历 contentView 所有子视图,如果子视图可见,同时在 location 确认是按钮
for btn in contentView.subviews as! [UIButton] {
//删除按钮同样需要处理
if btn.frame.contains(location) && !btn.isHidden && btn != contentView.subviews.last {
return btn
}
}
return nil
}
}
//MARK: - 设置界面
private extension CZEmoticonCell {
// - 从xib加载,cell.bounds是XIB中定义的大小,不是size的大小
// - 从纯代码创建,cell.bounds就是布局属性中设置的itemSize
func setupUI() {
//连续创建21个按钮
let rowCount = 3
let colCount = 7
//左右间距
let leftMargin: CGFloat = 8
//底部间距,为分页控件预留控件
let bottonMargin: CGFloat = 16
let w = (bounds.width - 2 * leftMargin) / CGFloat(colCount)
let h = (bounds.height - bottonMargin) / CGFloat(rowCount)
for i in 0..<21 {
let row = i / colCount
let col = i % colCount
let btn = UIButton()
//设置按钮大小
let x = leftMargin + CGFloat(col) * w
let y = CGFloat(row) * h
btn.frame = CGRect(x: x, y: y, width: w, height: h)
//设置按钮字体,lineHeight基本上和图片大小差不多
btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
contentView.addSubview(btn)
//设置按钮的tag
btn.tag = i
//添加监听方法
btn.addTarget(self, action: #selector(selectedEmoticonButton), for: .touchUpInside)
//取出末尾删除按钮
let removeButton = contentView.subviews.last as! UIButton
//设置图像
let image = UIImage.init(named: "compose_emotion_delete_highlighted", in: CZEmoticonManager.shared.bundle, compatibleWith: nil)
removeButton.setImage(image, for: [])
//添加长按手势
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture))
longPress.minimumPressDuration = 0.5
addGestureRecognizer(longPress)
}
}
}
|
mit
|
81be3c6043b3af071dc78d457446b957
| 26.785714 | 139 | 0.521369 | 4.343336 | false | false | false | false |
moysklad/ios-remap-sdk
|
Sources/MoyskladiOSRemapSDK/Utils/ObjectManager.swift
|
1
|
5311
|
//
// ObjectManager.swift
// MoyskladiOSRemapSDK
//
// Created by Anton Efimenko on 22.01.2018.
// Copyright © 2018 Andrey Parshakov. All rights reserved.
//
import Foundation
public class ObjectManager<Element> {
public private(set) var current: [Element]
public private(set) var deleted: [Element]
public private(set) var added: [Element]
public private(set) var updated: [Element]
private(set) var filtered: [Element]
let isEqual: (Element, Element) -> Bool
public init(data: [Element], isEqual: @escaping (Element, Element) -> Bool) {
current = data
filtered = current
deleted = [Element]()
added = [Element]()
updated = [Element]()
self.isEqual = isEqual
}
func contains(_ value: Element) -> Bool {
return current.contains(where: { isEqual($0, value) })
}
@discardableResult
public func append(_ value: Element) -> (Bool, count: Int) {
guard !contains(where: { isEqual($0, value) }) else { return (false, current.count) }
current.append(value)
added.append(value)
filtered = current
return (true, current.count)
}
@discardableResult
public func appendOrUpdate(_ value: Element) -> Int {
guard !append(value).0 else { return current.count }
return update(value).count
}
@discardableResult
public func update(_ value: Element) -> (Bool, count: Int) {
// если нет в списке - выходим
guard let currentIndex = firstIndex(where: { isEqual($0, value) }) else { return (false, current.count) }
if let addedIndex = added.firstIndex(where:{ isEqual($0, value) }) {
// если есть в списке добавленных, то обновляем там
added[addedIndex] = value
} else {
if let updatedIndex = updated.firstIndex(where:{ isEqual($0, value) }) {
updated[updatedIndex] = value
} else {
updated.append(value)
}
}
current[currentIndex] = value
filtered = current
return (true, current.count)
}
@discardableResult
public func remove(_ value: Element) -> (Bool, count: Int) {
guard let index = current.firstIndex(where: { isEqual($0, value) }) else { return (false, current.count) }
current.remove(at: index)
// если объект был добавлен, то удаляем его из списка добавленных
if let addedIndex = added.firstIndex(where: { isEqual($0, value) }) {
added.remove(at: addedIndex)
} else {
// если объект был изменен, то удаляем его из списка измененных
if let updatedIndex = updated.firstIndex(where: { isEqual($0, value) }) {
updated.remove(at: updatedIndex)
}
// и добавляем в список удаленных
deleted.append(value)
}
filtered = current
return (true, current.count)
}
public func filter(_ isIncluded: (Element) -> Bool) {
filtered = current.filter(isIncluded)
}
public func removeFilter() {
filtered = current
}
public func dropDeleted(count: Int) {
deleted = Array(deleted.dropFirst(count))
}
public func refreshUpdated(with data: [Element]) {
data.forEach { updatedElement in
if let currentIndex = current.firstIndex(where: { isEqual($0, updatedElement) }) {
current[currentIndex] = updatedElement
}
if let updatedIndex = updated.firstIndex(where: { isEqual($0, updatedElement) }) {
updated.remove(at: updatedIndex)
}
}
}
public func refreshAdded(with data: [Element]) {
data.forEach { updatedElement in
if let currentIndex = current.firstIndex(where: { isEqual($0, updatedElement) }) {
current[currentIndex] = updatedElement
}
if let addedIndex = added.firstIndex(where: { isEqual($0, updatedElement) }) {
added.remove(at: addedIndex)
}
}
}
public func hasChanges() -> Bool {
return deleted.count > 0 ||
added.count > 0 ||
updated.count > 0
}
public func getItems(where isIncluded: (Element) -> Bool) -> [Element] {
return current.filter(isIncluded)
}
public func copy() -> ObjectManager<Element> {
let new = ObjectManager(data: current, isEqual: isEqual)
new.filtered = filtered
new.added = added
new.updated = updated
new.deleted = deleted
return new
}
}
extension ObjectManager: Collection {
public var startIndex: Int { return filtered.startIndex }
public var endIndex: Int { return filtered.endIndex }
public func index(after i: Int) -> Int {
return filtered.index(after: i)
}
public subscript(index: Int) -> Element { get { return filtered[index] } }
}
|
mit
|
7eecb7f9fd77be0664a22863deee5319
| 31.411392 | 114 | 0.575083 | 4.369454 | false | false | false | false |
hilen/TimedSilver
|
Sources/UIKit/UIAlertController+TSExtension.swift
|
3
|
3160
|
//
// UIAlertController+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/11/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import UIKit
public extension UIAlertController {
/**
Single button alert
- parameter title: title
- parameter message: message
- parameter buttonText: buttonText can be nil, but default is "OK"
- parameter completion: completion
- returns: UIAlertController
*/
@discardableResult
class func ts_singleButtonAlertWithTitle(
_ title: String,
message: String,
buttonText: String? = "OK",
completion: (() -> Void)?) -> UIAlertController
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonText, style: .default, handler: {
(action:UIAlertAction!) -> Void in
if let completion = completion {
completion()
}
}))
alert.ts_show()
return alert
}
/**
Two button alert
- parameter title: title
- parameter message: message
- parameter buttonText: buttonText can be nil, but default is "OK"
- parameter otherButtonTitle: otherButtonTitle
- parameter completion: completion
- returns: UIAlertController
*/
@discardableResult
class func ts_doubleButtonAlertWithTitle(
_ title: String,
message: String,
buttonText: String? = "OK",
otherButtonTitle: String,
completion: (() -> Void)?) -> UIAlertController
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonText, style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: otherButtonTitle, style: .default, handler: {
(action:UIAlertAction!) -> Void in
if let completion = completion {
completion()
}
}))
alert.ts_show()
return alert
}
/**
Show UIAlertController
*/
func ts_show() {
self.ts_present(true, completion: nil)
}
@available(iOS 8.0, *)
func ts_present(_ animated: Bool, completion: (() -> Void)?) {
guard let app = UIApplication.ts_sharedApplication() else {
return
}
if let rootVC = app.keyWindow?.rootViewController {
self.ts_presentFromController(rootVC, animated: animated, completion: completion)
}
}
func ts_presentFromController(_ controller: UIViewController, animated: Bool, completion: (() -> Void)?) {
if let navVC = controller as? UINavigationController,
let visibleVC = navVC.visibleViewController {
self.ts_presentFromController(visibleVC, animated: animated, completion: completion)
} else {
controller.present(self, animated: animated, completion: completion);
}
}
func ts_dismiss() {
}
}
|
mit
|
0cc2528247b01e74ce80afa05d102364
| 29.970588 | 110 | 0.599557 | 4.966981 | false | false | false | false |
lYcHeeM/ZJImageBrowser
|
ZJImageBrowser/ZJImageBrowser/ZJImageWrapper.swift
|
1
|
1143
|
//
// ZJImageWrapper.swift
// ZJImageBrowser
//
// Created by luozhijun on 2017/7/8.
// Copyright © 2017年 RickLuo. All rights reserved.
//
import UIKit
import Photos
open class ZJImageWrapper: NSObject {
open var image : UIImage?
open var highQualityImageUrl: String = ""
open var asset : PHAsset?
open var shouldDownloadImage: Bool = true
open var progressStyle : ZJProgressViewStyle = .pie
open var placeholderImage : UIImage?
/// using for enlarging\shrinking animation
weak open var imageContainer: UIView?
public override init() {
super.init()
}
public required init(image: UIImage? = nil, highQualityImageUrl: String?, asset: PHAsset? = nil, shouldDownloadImage: Bool, placeholderImage: UIImage?, imageContainer: UIView?) {
self.image = image
self.highQualityImageUrl = highQualityImageUrl ?? ""
self.asset = asset
self.shouldDownloadImage = shouldDownloadImage
self.placeholderImage = placeholderImage
self.imageContainer = imageContainer
}
}
|
mit
|
835ebae67318eea51499834c82364903
| 31.571429 | 182 | 0.648246 | 4.615385 | false | false | false | false |
dreamsxin/swift
|
stdlib/public/core/Collection.swift
|
1
|
70964
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements, with forward
/// index traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
public protocol IndexableBase {
// FIXME(ABI)(compiler limitation): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
//
// This protocol is almost an implementation detail of the standard
// library; it is used to deduce things like the `SubSequence` and
// `Iterator` type from a minimal collection, but it is also used in
// exposed places like as a constraint on `IndexingIterator`.
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
///
/// - SeeAlso: endIndex
associatedtype Index : Comparable
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
var startIndex: Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.index(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
var endIndex: Index { get }
// The declaration of _Element and subscript here is a trick used to
// break a cyclic conformance/deduction that Swift can't handle. We
// need something other than a Collection.Iterator.Element that can
// be used as IndexingIterator<T>'s Element. Here we arrange for
// the Collection itself to have an Element type that's deducible from
// its subscript. Ideally we'd like to constrain this Element to be the same
// as Collection.Iterator.Element (see below), but we have no way of
// expressing it today.
associatedtype _Element
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
subscript(position: Index) -> _Element { get }
// WORKAROUND: rdar://25214066
/// A sequence that can represent a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence
/// Accesses the subsequence bounded by the given range.
///
/// - Parameter bounds: A range of the collection's indices. The upper and
/// lower bounds of the `bounds` range must be valid indices of the
/// collection.
subscript(bounds: Range<Index>) -> SubSequence { get }
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.lowerBound) ||
/// range.lowerBound == bounds.upperBound)
/// precondition(
/// bounds.contains(range.upperBound) ||
/// range.upperBound == bounds.upperBound)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Index) -> Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
func formIndex(after i: inout Index)
}
/// A type that provides subscript access to its elements, with forward index
/// traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
public protocol Indexable : IndexableBase {
/// A type used to represent the number of steps between two indices, where
/// one value is reachable from the other.
///
/// In Swift, *reachability* refers to the ability to produce one value from
/// the other through zero or more applications of `index(after:)`.
associatedtype IndexDistance : SignedInteger = Int
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: IndexDistance) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position. The
/// operation doesn't require going beyond the limiting `s.endIndex` value,
/// so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// `limit` has no effect if it is less than `i`. Likewise, if `n < 0`,
/// `limit` has no effect if it is greater than `i`.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index?
/// Offsets the given index by the specified distance.
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func formIndex(_ i: inout Index, offsetBy n: IndexDistance)
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. Make
/// sure the value passed as `n` does not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Bool
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> IndexDistance
}
/// A type that iterates over a collection using its indices.
///
/// The `IndexingIterator` type is the default iterator for any collection that
/// doesn't declare its own. It acts as an iterator by using a collection's
/// indices to step over each value in the collection. Most collections in the
/// standard library use `IndexingIterator` as their iterator.
///
/// By default, any custom collection type you create will inherit a
/// `makeIterator()` method that returns an `IndexingIterator` instance,
/// making it unnecessary to declare your own. When creating a custom
/// collection type, add the minimal requirements of the `Collection`
/// protocol: starting and ending indices and a subscript for accessing
/// elements. With those elements defined, the inherited `makeIterator()`
/// method satisfies the requirements of the `Sequence` protocol.
///
/// Here's an example of a type that declares the minimal requirements for a
/// collection. The `CollectionOfTwo` structure is a fixed-size collection
/// that always holds two elements of a specific type.
///
/// struct CollectionOfTwo<Element>: Collection {
/// let elements: (Element, Element)
///
/// init(_ first: Element, _ second: Element) {
/// self.elements = (first, second)
/// }
///
/// var startIndex: Int { return 0 }
/// var endIndex: Int { return 2 }
///
/// subscript(index: Int) -> Element {
/// switch index {
/// case 0: return elements.0
/// case 1: return elements.1
/// default: fatalError("Index out of bounds.")
/// }
/// }
///
/// func index(after i: Int) -> Int {
/// precondition(i < endIndex, "Can't advance beyond endIndex")
/// return i + 1
/// }
/// }
///
/// The `CollectionOfTwo` type uses the default iterator type,
/// `IndexingIterator`, because it doesn't define its own `makeIterator()`
/// method or `Iterator` associated type. This example shows how a
/// `CollectionOfTwo` instance can be created holding the values of a point,
/// and then iterated over using a `for`-`in` loop.
///
/// let point = CollectionOfTwo(15.0, 20.0)
/// for element in point {
/// print(element)
/// }
/// // Prints "15.0"
/// // Prints "20.0"
public struct IndexingIterator<
Elements : IndexableBase
// FIXME(compiler limitation):
// Elements : Collection
> : IteratorProtocol, Sequence {
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements) {
self._elements = _elements
self._position = _elements.startIndex
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns all the elements of the underlying
/// sequence in order. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// This example shows how an iterator can be used explicitly to emulate a
/// `for`-`in` loop. First, retrieve a sequence's iterator, and then call
/// the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
public mutating func next() -> Elements._Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
internal let _elements: Elements
internal var _position: Elements.Index
}
/// A sequence whose elements can be traversed multiple times,
/// nondestructively, and accessed by indexed subscript.
///
/// Collections are used extensively throughout the standard library. When
/// you use arrays, dictionaries, views of a string's contents and other
/// types, you benefit from the operations that the `Collection` protocol
/// declares and implements.
///
/// In addition to the methods that collections inherit from the `Sequence`
/// protocol, you gain access to methods that depend on accessing an element
/// at a specific position when using a collection.
///
/// For example, if you want to print only the first word in a string,
/// search for the index of the first space, and then create a subsequence up
/// to that position.
///
/// let text = "Buffalo buffalo buffalo buffalo."
/// if let firstSpace = text.characters.index(of: " ") {
/// print(String(text.characters.prefix(upTo: firstSpace)))
/// }
/// // Prints "Buffalo"
///
/// The `firstSpace` constant is an index into the `text.characters`
/// collection. `firstSpace` is the position of the first space in the
/// collection. You can store indices in variables, and pass them to
/// collection algorithms or use them later to access the corresponding
/// element. In the example above, `firstSpace` is used to extract the prefix
/// that contains elements up to that index.
///
/// You can pass only valid indices to collection operations. You can find a
/// complete set of a collection's valid indices by starting with the
/// collection's `startIndex` property and finding every successor up to, and
/// including, the `endIndex` property. All other values of the `Index` type,
/// such as the `startIndex` property of a different collection, are invalid
/// indices for this collection.
///
/// Saved indices may become invalid as a result of mutating operations; for
/// more information about index invalidation in mutable collections, see the
/// reference for the `MutableCollection` and `RangeReplaceableCollection`
/// protocols, as well as for the specific type you're using.
///
/// Accessing Individual Elements
/// =============================
///
/// You can access an element of a collection through its subscript with any
/// valid index except the collection's `endIndex` property, a "past the end"
/// index that does not correspond with any element of the collection.
///
/// Here's an example of accessing the first character in a string through its
/// subscript:
///
/// let firstChar = text.characters[text.characters.startIndex]
/// print(firstChar)
/// // Prints "B"
///
/// The `Collection` protocol declares and provides default implementations
/// for many operations that depend on elements being accessible by their
/// subscript. For example, you can also access the first character of
/// `text` using the `first` property, which has the value of the first
/// element of the collection, or `nil` if the collection is empty.
///
/// print(text.characters.first)
/// // Prints "Optional("B")"
///
/// Traversing a Collection
/// =======================
///
/// While a sequence may be consumed as it is traversed, a collection is
/// guaranteed to be multi-pass: Any element may be repeatedly accessed by
/// saving its index. Moreover, a collection's indices form a finite range
/// of the positions of the collection's elements. This guarantees the
/// safety of operations that depend on a sequence being finite, such as
/// checking to see whether a collection contains an element.
///
/// Iterating over the elements of a collection by their positions yields the
/// same elements in the same order as iterating over that collection using
/// its iterator. This example demonstrates that the `characters` view of a
/// string returns the same characters in the same order whether the view's
/// indices or the view itself is being iterated.
///
/// let word = "Swift"
/// for character in word.characters {
/// print(character)
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// for i in word.characters.indices {
/// print(word.characters[i])
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// Conforming to the Collection Protocol
/// =====================================
///
/// If you create a custom sequence that can provide repeated access to its
/// elements, conformance to the `Collection` protocol gives your custom type
/// a more useful and more efficient interface for sequence and collection
/// operations. To add `Collection` conformance to your type, declare
/// `startIndex` and `endIndex` properties, a subscript that provides at least
/// read-only access to your type's elements, and the `index(after:)` method
/// for advancing your collection's indices.
///
/// Expected Performance
/// ====================
///
/// Types that conform to `Collection` are expected to provide the
/// `startIndex` and `endIndex` properties and subscript access to elements
/// as O(1) operations. Types that are not able to guarantee that expected
/// performance must document the departure, because many collection operations
/// depend on O(1) subscripting performance for their own performance
/// guarantees.
///
/// The performance of some collection operations depends on the type of index
/// that the collection provides. For example, a random-access collection,
/// which can measure the distance between two indices in O(1) time, will be
/// able to calculate its `count` property in O(1) time. Conversely, because a
/// forward or bidirectional collection must traverse the entire collection to
/// count the number of contained elements, accessing its `count` property is
/// an O(N) operation.
public protocol Collection : Indexable, Sequence {
/// A type that can represent the number of steps between a pair of
/// indices.
associatedtype IndexDistance : SignedInteger = Int
/// A type that provides the collection's iteration interface and
/// encapsulates its iteration state.
///
/// By default, a collection conforms to the `Sequence` protocol by
/// supplying a `IndexingIterator` as its associated `Iterator`
/// type.
associatedtype Iterator : IteratorProtocol = IndexingIterator<Self>
// FIXME: Needed here so that the `Iterator` is properly deduced from
// a custom `makeIterator()` function. Otherwise we get an
// `IndexingIterator`. <rdar://problem/21539115>
/// Returns an iterator over the elements of the collection.
func makeIterator() -> Iterator
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
associatedtype SubSequence : IndexableBase, Sequence = Slice<Self>
// FIXME(compiler limitation):
// associatedtype SubSequence : Collection
// where
// Iterator.Element == SubSequence.Iterator.Element,
// SubSequence.Index == Index,
// SubSequence.Indices == Indices,
// SubSequence.SubSequence == SubSequence
//
// (<rdar://problem/20715009> Implement recursive protocol
// constraints)
//
// These constraints allow processing collections in generic code by
// repeatedly slicing them in a loop.
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
subscript(position: Index) -> Iterator.Element { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence { get }
/// A type that can represent the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : IndexableBase, Sequence = DefaultIndices<Self>
// FIXME(compiler limitation):
// associatedtype Indices : Collection
// where
// Indices.Iterator.Element == Index,
// Indices.Index == Index,
// Indices.SubSequence == Indices
// = DefaultIndices<Self>
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be non-uniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can cause an unexpected copy of the collection. To avoid the
/// unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the
/// position `end`.
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(through:)`
func prefix(upTo end: Index) -> SubSequence
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// For example:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Precondition: `start >= self.startIndex && start <= self.endIndex`
/// - Complexity: O(1)
func suffix(from start: Index) -> SubSequence
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(upTo:)`
func prefix(through position: Index) -> SubSequence
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.characters.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
var isEmpty: Bool { get }
/// The number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
var count: IndexDistance { get }
// The following requirement enables dispatching for index(of:) when
// the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found
/// or `Optional(nil)` if an element was determined to be missing;
/// otherwise, `nil`.
///
/// - Complexity: O(N).
func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index??
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
var first: Iterator.Element? { get }
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. Make
/// sure the value passed as `n` does not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: IndexDistance) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// `limit` has no effect if it is less than `i`. Likewise, if `n < 0`,
/// `limit` has no effect if it is greater than `i`.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index?
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the `BidirectionalCollection`
/// protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> IndexDistance
}
/// Default implementation for forward collections.
extension Indexable {
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inline(__always)
public func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: tests.
i = index(after: i)
}
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"out of bounds: index < startIndex")
_precondition(
index < bounds.upperBound,
"out of bounds: index >= endIndex")
}
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= range.lowerBound,
"out of bounds: range begins before startIndex")
_precondition(
range.lowerBound <= bounds.upperBound,
"out of bounds: range ends after endIndex")
_precondition(
bounds.lowerBound <= range.upperBound,
"out of bounds: range ends before bounds.lowerBound")
_precondition(
range.upperBound <= bounds.upperBound,
"out of bounds: range begins after bounds.upperBound")
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: tests.
return self._advanceForward(i, by: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// `limit` has no effect if it is less than `i`. Likewise, if `n < 0`,
/// `limit` has no effect if it is greater than `i`.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: tests.
return self._advanceForward(i, by: n, limitedBy: limit)
}
/// Offsets the given index by the specified distance.
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func formIndex(_ i: inout Index, offsetBy n: IndexDistance) {
i = index(i, offsetBy: n)
}
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. Make
/// sure the value passed as `n` does not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
public func distance(from start: Index, to end: Index) -> IndexDistance {
// FIXME: swift-3-indexing-model: tests.
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
var start = start
var count: IndexDistance = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
/// Do not use this method directly; call advanced(by: n) instead.
@inline(__always)
internal func _advanceForward(_ i: Index, by n: IndexDistance) -> Index {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
formIndex(after: &i)
}
return i
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@inline(__always)
internal
func _advanceForward(
_ i: Index, by n: IndexDistance, limitedBy limit: Index
) -> Index? {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
if i == limit {
return nil
}
formIndex(after: &i)
}
return i
}
}
/// Supply the default `makeIterator()` method for `Collection` models
/// that accept the default associated `Iterator`,
/// `IndexingIterator<Self>`.
extension Collection where Iterator == IndexingIterator<Self> {
/// Returns an iterator over the elements of the collection.
public func makeIterator() -> IndexingIterator<Self> {
return IndexingIterator(_elements: self)
}
}
/// Supply the default "slicing" `subscript` for `Collection` models
/// that accept the default associated `SubSequence`, `Slice<Self>`.
extension Collection where SubSequence == Slice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
public subscript(bounds: Range<Index>) -> Slice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
// TODO: swift-3-indexing-model - review the following
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// - Returns: The first element of the collection if the collection is
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
public mutating func popFirst() -> Iterator.Element? {
guard !isEmpty else { return nil }
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
}
/// Default implementations of core requirements
extension Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.characters.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
public var isEmpty: Bool {
return startIndex == endIndex
}
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
public var first: Iterator.Element? {
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
// so instead of testing `isEmpty` and then returning the first element,
// we'll just rely on the fact that the iterator always yields the
// first element first.
var i = makeIterator()
return i.next()
}
// TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?)
/// Returns the first element of `self`, or `nil` if `self` is empty.
///
/// - Complexity: O(1)
// public var first: Iterator.Element? {
// return isEmpty ? nil : self[startIndex]
// }
// TODO: swift-3-indexing-model - review the following
/// A value less than or equal to the number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
public var underestimatedCount: Int {
return numericCast(count)
}
/// The number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
public var count: IndexDistance {
return distance(from: startIndex, to: endIndex)
}
// TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)?
/// Customization point for `Collection.index(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(N) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: O(`count`).
public // dispatching
func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? {
return nil
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Collection
//===----------------------------------------------------------------------===//
extension Collection {
// TODO: swift-3-indexing-model - review the following
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercaseString }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.characters.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
public func map<T>(
_ transform: @noescape (Iterator.Element) throws -> T
) rethrows -> [T] {
let count: Int = numericCast(self.count)
if count == 0 {
return []
}
var result = ContiguousArray<T>()
result.reserveCapacity(count)
var i = self.startIndex
for _ in 0..<count {
result.append(try transform(self[i]))
formIndex(after: &i)
}
_expectEnd(i, self)
return Array(result)
}
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the collection.
public func dropFirst(_ n: Int) -> SubSequence {
_precondition(n >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex,
offsetBy: numericCast(n), limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off the specified number of elements
/// at the end.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let amount = Swift.max(0, numericCast(count) - n)
let end = index(startIndex,
offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence, up to the specified maximum length, containing
/// the initial elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this collection
/// with at most `maxLength` elements.
public func prefix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a prefix of negative length from a collection")
let end = index(startIndex,
offsetBy: numericCast(maxLength), limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let amount = Swift.max(0, numericCast(count) - maxLength)
let start = index(startIndex,
offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the
/// position `end`.
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Precondition: `end >= self.startIndex && end <= self.endIndex`
/// - Complexity: O(1)
/// - SeeAlso: `prefix(through:)`
public func prefix(upTo end: Index) -> SubSequence {
return self[startIndex..<end]
}
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// For example:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// - Parameter start: The index at which to start the resulting
/// subsequence. `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Precondition: `start >= self.startIndex && start <= self.endIndex`
/// - Complexity: O(1)
public func suffix(from start: Index) -> SubSequence {
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position
/// `end`.
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(upTo:)`
public func prefix(through position: Index) -> SubSequence {
return prefix(upTo: index(after: position))
}
// TODO: swift-3-indexing-model - review the following
/// Returns the longest possible subsequences of the sequence, in order, that
/// don't contain elements satisfying the given predicate. Elements that are
/// used to split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don't", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.characters.split(maxSplits: 1, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(omittingEmptySubsequences: false, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator` predicate.
/// - isSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the sequence should be
/// split at that element.
/// - Returns: An array of subsequences, split from this sequence's elements.
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
isSeparator: @noescape (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [SubSequence] = []
var subSequenceStart: Index = startIndex
func appendSubsequence(end: Index) -> Bool {
if subSequenceStart == end && omittingEmptySubsequences {
return false
}
result.append(self[subSequenceStart..<end])
return true
}
if maxSplits == 0 || isEmpty {
_ = appendSubsequence(end: endIndex)
return result
}
var subSequenceEnd = subSequenceStart
let cachedEndIndex = endIndex
while subSequenceEnd != cachedEndIndex {
if try isSeparator(self[subSequenceEnd]) {
let didAppend = appendSubsequence(end: subSequenceEnd)
formIndex(after: &subSequenceEnd)
subSequenceStart = subSequenceEnd
if didAppend && result.count == maxSplits {
break
}
continue
}
formIndex(after: &subSequenceEnd)
}
if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences {
result.append(self[subSequenceStart..<cachedEndIndex])
}
return result
}
}
// TODO: swift-3-indexing-model - review the following
extension Collection where Iterator.Element : Equatable {
/// Returns the longest possible subsequences of the sequence, in order, that
/// don't contain elements satisfying the given predicate. Elements that are
/// used to split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don't", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.characters.split(maxSplits: 1, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(omittingEmptySubsequences: false, isSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator` predicate.
/// - isSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the sequence should be
/// split at that element.
/// - Returns: An array of subsequences, split from this sequence's elements.
public func split(
separator: Iterator.Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] {
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
isSeparator: { $0 == separator })
}
}
// TODO: swift-3-indexing-model - review the following
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
/// - SeeAlso: `popFirst()`
@discardableResult
public mutating func removeFirst() -> Iterator.Element {
_precondition(!isEmpty, "can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater than
/// or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*).
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex]
}
}
// TODO: swift-3-indexing-model - review the following
extension Sequence
where Self : _ArrayProtocol, Self.Element == Self.Iterator.Element {
// A fast implementation for when you are backed by a contiguous array.
@discardableResult
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Iterator.Element>
) -> UnsafeMutablePointer<Iterator.Element> {
if let s = self._baseAddressIfContiguous {
let count = self.count
ptr.initializeFrom(s, count: count)
_fixLifetime(self._owner)
return ptr + count
} else {
var p = ptr
for x in self {
p.initialize(with: x)
p += 1
}
return p
}
}
}
extension Collection {
public func _preprocessingPass<R>(
_ preprocess: @noescape () throws -> R
) rethrows -> R? {
return try preprocess()
}
}
@available(*, unavailable, message: "Bit enum has been removed. Please use Int instead.")
public enum Bit {}
@available(*, unavailable, renamed: "IndexingIterator")
public struct IndexingGenerator<Elements : IndexableBase> {}
@available(*, unavailable, renamed: "Collection")
public typealias CollectionType = Collection
extension Collection {
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
@available(*, unavailable, renamed: "makeIterator")
public func generate() -> Iterator {
Builtin.unreachable()
}
@available(*, unavailable, message: "Removed in Swift 3. Please use underestimatedCount property.")
public func underestimateCount() -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "Please use split(maxSplits:omittingEmptySubsequences:isSeparator:) instead")
public func split(
_ maxSplit: Int = Int.max,
allowEmptySlices: Bool = false,
isSeparator: @noescape (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
Builtin.unreachable()
}
}
extension Collection where Iterator.Element : Equatable {
@available(*, unavailable, message: "Please use split(separator:maxSplits:omittingEmptySubsequences:) instead")
public func split(
_ separator: Iterator.Element,
maxSplit: Int = Int.max,
allowEmptySlices: Bool = false
) -> [SubSequence] {
Builtin.unreachable()
}
}
@available(*, unavailable, message: "PermutationGenerator has been removed in Swift 3")
public struct PermutationGenerator<C : Collection, Indices : Sequence> {}
|
apache-2.0
|
eb3c52dfd7617f6ada79fe9077c3ccc0
| 39.854347 | 115 | 0.644256 | 4.19087 | false | false | false | false |
kfarst/alarm
|
alarm/BlurViewPresenter.swift
|
1
|
1534
|
//
// BlurViewPresenter.swift
// alarm
//
// Created by Michael Lewis on 3/14/15.
// Copyright (c) 2015 Kevin Farst. All rights reserved.
//
import Foundation
// This will create a blur layer on top of the parent view.
class BlurViewPresenter {
let blurEffect: UIBlurEffect
let vibrancyEffect: UIVibrancyEffect
let blurEffectView: UIVisualEffectView
let vibrancyEffectView: UIVisualEffectView
let parentView: UIView
init(parent: UIView) {
// Stash the parent
self.parentView = parent
// Initialize the effects
blurEffect = UIBlurEffect(style: .Dark)
vibrancyEffect = UIVibrancyEffect(forBlurEffect: self.blurEffect)
// Create views on top of this controller's view
blurEffectView = UIVisualEffectView(effect: blurEffect) as UIVisualEffectView
vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
// Set up the dimensions
resetBounds()
// Set up the view relationships
blurEffectView.addSubview(vibrancyEffectView)
// Make sure the blur starts out hidden
hideBlur()
}
func showBlur() {
resetBounds()
parentView.addSubview(blurEffectView)
blurEffectView.hidden = false
}
func hideBlur() {
blurEffectView.removeFromSuperview()
blurEffectView.hidden = true
}
/* Private */
// When we show the view, frames could have changed so we want
// to reset them easily.
private func resetBounds() {
blurEffectView.frame = self.parentView.bounds
vibrancyEffectView.frame = self.parentView.bounds
}
}
|
mit
|
65a4060f2d70954ca44647464dfd5e27
| 22.6 | 81 | 0.722295 | 4.869841 | false | false | false | false |
niekang/WeiBo
|
WeiBo/Class/View/Home/WBHomeViewController.swift
|
1
|
4414
|
//
// HomeViewController.swift
// WeiBo
//
// Created by 聂康 on 2017/6/19.
// Copyright © 2017年 com.nk. All rights reserved.
//
import UIKit
import RxSwift
private let normalCellId = "WBStatusNormalCell"
private let retweetedCellId = "WBStatusRetweetedCell"
class WBHomeViewController: WBBaseTabViewController {
lazy var statusListViewModel = WBStatusListViewModel() // ViewModel 处理微博数据
let refreshControl = NKRefreshControl() /// 下拉刷新控件
let adapter = TableViewDataSource<WBStatusViewModel>()
override func viewDidLoad() {
//在判断登录状态之前 注册table 接收到登录通知之后 显示数据
setupUI()
self.configTable()
super.viewDidLoad()
}
override func loginSuccess() {
super.loginSuccess()
self.loadData()
}
@objc func loadData() {
/// 如果是下拉,显示下拉动画
refreshControl.beginRefresh()
statusListViewModel.loadWBStatusListData(isHeader: true) {[weak self] (isSuccess) in
guard let weakSelf = self else {
return
}
weakSelf.refreshControl.endRefresh()
weakSelf.adapter.dataSource = weakSelf.statusListViewModel.statusList
weakSelf.tableView.reloadData()
}
}
func loadMoreData() {
statusListViewModel.loadWBStatusListData(isHeader: false) {[weak self] (isSuccess) in
guard let weakSelf = self else {
return
}
weakSelf.adapter.dataSource = weakSelf.statusListViewModel.statusList
weakSelf.tableView.reloadData()
weakSelf.refreshControl.endRefresh()
}
}
}
extension WBHomeViewController {
func configTable() {
tableView.delegate = adapter
tableView.dataSource = adapter
adapter.configCell = {[unowned self](indexPath, statusViewModel, _, _) in
let cellId = (statusViewModel.status.retweeted_status != nil) ? retweetedCellId : normalCellId
let cell = self.tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! WBStatusCell
cell.statusViewModel = statusViewModel
return cell
}
adapter.willDisplayCell = {[unowned self](indexPath, statusViewModel, _ , _ ) in
let row = indexPath.row
/// 当滑到底部的时候加载数据
if row == (self.adapter.dataSource.count - 1){
self.loadMoreData()
}
}
}
}
extension WBHomeViewController {
func setupUI() {
if navigationItem.titleView == nil{
tableView.register(UINib(nibName: normalCellId, bundle: nil), forCellReuseIdentifier: normalCellId)
tableView.register(UINib(nibName: retweetedCellId, bundle: nil), forCellReuseIdentifier: retweetedCellId)
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 300
tableView.addSubview(refreshControl)
refreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
setupBarButtonItems()
}
NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: NSNotification.Name.init(rawValue: WBHomeVCShouldRefresh), object: nil)
}
func setupBarButtonItems() {
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(leftButtonClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightButtonClick))
let name = WBUserAccont.shared.screen_name
let btn = WBTitleButton(title: name)
navigationItem.titleView = btn
btn.addTarget(self, action: #selector(titleButtonClick(btn:)), for: .touchUpInside)
}
@objc func leftButtonClick() {
}
@objc func rightButtonClick() {
let QRCodeVC = WBQRCodeViewController()
navigationController?.pushViewController(QRCodeVC, animated: true)
}
@objc func titleButtonClick(btn:UIButton) {
btn.isSelected = !btn.isSelected
}
}
|
apache-2.0
|
2ffae82717030d163f3f228d8eb96e0b
| 30.522059 | 161 | 0.631211 | 5.240831 | false | false | false | false |
niekang/WeiBo
|
WeiBo/Class/View/Main/NewFeatureView/WBNewFeatureView.swift
|
1
|
2456
|
//
// WBNewFeatureView.swift
// WeiBo
//
// Created by 聂康 on 2017/6/24.
// Copyright © 2017年 com.nk. All rights reserved.
//
import UIKit
class WBNewFeatureView: UIView {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var enterBtn: UIButton!
@IBOutlet weak var pageControl: UIPageControl!
var enterWB: (() -> ())?
/// 从xib加载视图
///
/// - Parameter enterWB: 进入app回调
/// - Returns: 返回视图
class func newFeatureView(enterWB:(() -> ())? = nil) -> WBNewFeatureView{
let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
let welcomeView = (nib.instantiate(withOwner: nil, options: nil).first) as! WBNewFeatureView
if let enterWB = enterWB {
welcomeView.enterWB = enterWB
}
return welcomeView
}
/// 布局scrollView
override func awakeFromNib() {
let rect = UIScreen.main.bounds
for i in 0..<4 {
let imageView = UIImageView(image: UIImage(named: "new_feature_\(i + 1)"))
imageView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
scrollView.addSubview(imageView)
}
scrollView.contentSize = CGSize(width: rect.width * (4 + 1), height: rect.height)
scrollView.isPagingEnabled = true
scrollView.bounces = false
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self
enterBtn.isHidden = true
}
/// 进入微博按钮点击
@IBAction func enterBtnClick(_ sender: Any) {
removeFromSuperview()
enterWB?()
}
}
extension WBNewFeatureView:UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
/// 计算当前在哪一页
let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
if page == scrollView.subviews.count {
removeFromSuperview()
enterWB?()
}
enterBtn.isHidden = (page != scrollView.subviews.count - 1)
pageControl.currentPage = page
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x > CGFloat(scrollView.subviews.count - 1) * scrollView.bounds.width {
removeFromSuperview()
enterWB?()
}
}
}
|
apache-2.0
|
5bf28ed7797095168ac40138df443298
| 27.416667 | 106 | 0.6062 | 4.555344 | false | false | false | false |
jkandzi/Table.swift
|
Sources/Table.swift
|
1
|
2056
|
//
// Table.swift
// Table.swift
//
// Created by Justus Kandzi on 30/01/16.
// Copyright © 2016 Justus Kandzi. All rights reserved.
//
protocol PrinterType {
func put(_ string: String)
}
struct Printer: PrinterType {
func put(_ string: String) {
print(string)
}
}
public struct Table {
lazy var printer: PrinterType = {
Printer()
}()
public init() {}
public mutating func put<T>(_ data: [[T]]) {
guard let firstRow = data.first, !firstRow.isEmpty else {
printer.put("")
return
}
let borderString = borderStringForData(data)
printer.put(borderString)
data.forEach { row in
let rowString = zip(row, columns(data))
.map { String(describing: $0).padding($1.maxWidth()) }
.reduce("|") { $0 + $1 + "|" }
printer.put(rowString)
printer.put(borderString)
}
}
func borderStringForData<T>(_ data: [[T]]) -> String {
return columns(data)
.map { "-".repeated($0.maxWidth() + 2) }
.reduce("+") { $0 + $1 + "+" }
}
func columns<T>(_ data: [[T]]) -> [[T]] {
var result = [[T]]()
for i in (0..<(data.first?.count ?? 0)) {
result.append(data.map { $0[i] })
}
return result
}
}
extension Array {
func maxWidth() -> Int {
guard let maxElement = self.max(by: { a, b in
return String(describing: a).characters.count < String(describing: b).characters.count
}) else { return 0 }
return String(describing: maxElement).characters.count
}
}
extension String {
func padding(_ padding: Int) -> String {
let padding = padding + 1 - self.characters.count
guard padding >= 0 else { return self }
return " " + self + " ".repeated(padding)
}
func repeated(_ count: Int) -> String {
return Array(repeating: self, count: count).joined(separator: "")
}
}
|
mit
|
c46492abf610791ccbe6ae6cb8b8e744
| 24.6875 | 98 | 0.524088 | 3.914286 | false | false | false | false |
darwin/textyourmom
|
TextYourMom/Airport.swift
|
1
|
3619
|
typealias AirportId = Int
enum AirportPerimeter : String {
case None = "none"
case Inner = "inner"
case Outer = "outer"
}
struct Airport {
var id: AirportId = 0
var name: String = ""
var city: String = ""
var country: String = ""
var latitude: Double = 0.0
var longitude: Double = 0.0
}
class AirportsVisitorState : Equatable, Printable {
var state = [AirportId:AirportPerimeter]()
func update(id:AirportId, _ perimeter: AirportPerimeter) {
if perimeter == .None {
state[id] = nil
return
}
state[id] = perimeter
}
func itemDescription(id:AirportId, _ perimeter: AirportPerimeter) -> String {
return "\(id):\(perimeter.rawValue)"
}
var description: String {
if state.count == 0 {
return "[no man's land]"
}
var parts = [String]()
for (id, perimeter) in state {
parts.append(itemDescription(id, perimeter))
}
return ", ".join(parts)
}
}
// MARK: serialization
extension AirportsVisitorState {
var partSeparator : Character {
get { return ":" }
}
var itemSeparator : Character {
get { return "," }
}
func serialize() -> String {
var parts = [String]()
for (id, perimeter) in state {
parts.append("\(id)\(partSeparator)\(perimeter.rawValue)")
}
return String(itemSeparator).join(parts)
}
func unserialize(data: String) {
state.removeAll(keepCapacity: true)
let items = split(data) {$0 == self.itemSeparator}
for item in items {
let pieces = split(item) {$0 == self.partSeparator}
if pieces.count != 2 {
log("!!! unable to unserialize pair: \(item)")
continue
}
let id = pieces[0].toInt()
let perimeter = AirportPerimeter.init(rawValue:pieces[1])
if id != nil && perimeter != nil {
state[id!] = perimeter!
} else {
log("!!! unable to unserialize pair: \(item)")
}
}
}
}
func ==(lhs: AirportsVisitorState, rhs: AirportsVisitorState) -> Bool {
return lhs.state == rhs.state
}
struct AirportVisitChange {
var before: AirportPerimeter
var after: AirportPerimeter
}
class AirportsVisitorStateDiff : Printable {
var diff = [AirportId:AirportVisitChange]()
init(oldState: AirportsVisitorState, newState:AirportsVisitorState) {
let oldIds = $.keys(oldState.state)
let newIds = $.keys(newState.state)
for id in $.difference(oldIds, newIds) {
diff[id] = AirportVisitChange(before:oldState.state[id]!, after:.None)
}
for id in $.difference(newIds, oldIds) {
diff[id] = AirportVisitChange(before:.None, after:newState.state[id]!)
}
for id in $.intersection(newIds, oldIds) {
let change = AirportVisitChange(before:oldState.state[id]!, after:newState.state[id]!)
if change.before != change.after {
diff[id] = change
}
}
}
var description: String {
if diff.count == 0 {
return "- no change -"
}
var parts = [String]()
for (id, change) in diff {
parts.append("\(id):\(change.before.rawValue)->\(change.after.rawValue)")
}
return ", ".join(parts)
}
var empty : Bool {
return diff.count == 0
}
}
|
mit
|
bdba01426aacd695457c0c8cfeab92c7
| 26.424242 | 98 | 0.542691 | 4.313468 | false | false | false | false |
velvetroom/columbus
|
UnitTests/Model/Create/UTMCreateLocationStrategyReady.swift
|
1
|
6111
|
import XCTest
@testable import columbus
final class UTMCreateLocationStrategyReady:XCTestCase
{
private var model:MCreate?
private let kWait:TimeInterval = 1
private let kAsyncAfter:TimeInterval = 0.4
override func setUp()
{
super.setUp()
model = MCreate()
model?.changeLocationStrategy(
locationStrategyType:MCreateLocationStrategyReady.self)
}
//MARK: private
private func loadSettingsDeletePerks(
completion:@escaping(() -> ()))
{
loadSettings
{ [weak self] in
self?.deletePerks
{
completion()
}
}
}
private func loadSettings(
completion:@escaping(() -> ()))
{
let bundle:Bundle = Bundle(for:UTMCreateLoad.self)
model?.loadSettings(bundle:bundle)
{
completion()
}
}
private func deletePerks(
completion:@escaping(() -> ()))
{
model?.database?.fetch
{ [weak self] (perks:[DPerk]) in
self?.deletePerks(
perks:perks,
completion:completion)
}
}
private func deletePerks(
perks:[DPerk],
completion:@escaping(() -> ()))
{
guard
let database:Database = model?.database
else
{
return
}
for perk:DPerk in perks
{
database.delete(data:perk) { }
}
database.save
{
completion()
}
}
private func createPlan(
completion:@escaping(() -> ()))
{
model?.database?.create
{ (plan:DPlan) in
completion()
}
}
private func purchaseUnlimited(
completion:@escaping(() -> ()))
{
model?.database?.create
{ (perk:DPerk) in
perk.type = DPerkType.unlimited
perk.settings = self.model?.settings
completion()
}
}
private func nextStep(
completion:@escaping(() -> ()))
{
guard
let model:MCreate = self.model
else
{
return
}
model.locationStrategy?.nextStep(model:model)
DispatchQueue.main.asyncAfter(
deadline:DispatchTime.now() + kAsyncAfter)
{
completion()
}
}
//MARK: tests
func testDatabaseError()
{
guard
let model:MCreate = self.model
else
{
return
}
model.locationStrategy?.nextStep(model:model)
let status:MCreateStatusErrorDatabase? = model.status as? MCreateStatusErrorDatabase
XCTAssertNotNil(
status,
"status should be error database")
}
func testAvailabilityError()
{
let errorExpectation:XCTestExpectation = expectation(
description:"error expectation failed")
loadSettingsDeletePerks
{ [weak self] in
self?.createPlan
{ [weak self] in
self?.nextStep
{
errorExpectation.fulfill()
}
}
}
waitForExpectations(timeout:kWait)
{ [weak self] (error:Error?) in
let status:MCreateStatusErrorAvailability? = self?.model?.status as? MCreateStatusErrorAvailability
XCTAssertNotNil(
status,
"status should be availability error")
}
}
func testAvailable()
{
let availableExpectation:XCTestExpectation = expectation(
description:"error expectation failed")
loadSettingsDeletePerks
{ [weak self] in
self?.nextStep
{
availableExpectation.fulfill()
}
}
waitForExpectations(timeout:kWait)
{ [weak self] (error:Error?) in
XCTAssertNotNil(
self?.model?.plan,
"failed creating plan")
let mapStatus:MCreateMapStatusContracted? = self?.model?.mapStatus as? MCreateMapStatusContracted
XCTAssertNotNil(
mapStatus,
"map status should be contracted")
let status:MCreateStatusReady? = self?.model?.status as? MCreateStatusReady
XCTAssertNotNil(
status,
"status should be ready")
}
}
func testUnlimited()
{
let errorExpectation:XCTestExpectation = expectation(
description:"error expectation failed")
loadSettingsDeletePerks
{ [weak self] in
self?.createPlan
{ [weak self] in
self?.purchaseUnlimited
{ [weak self] in
self?.nextStep
{
errorExpectation.fulfill()
}
}
}
}
waitForExpectations(timeout:kWait)
{ [weak self] (error:Error?) in
XCTAssertNotNil(
self?.model?.plan,
"failed creating plan")
let mapStatus:MCreateMapStatusContracted? = self?.model?.mapStatus as? MCreateMapStatusContracted
XCTAssertNotNil(
mapStatus,
"map status should be contracted")
let status:MCreateStatusReady? = self?.model?.status as? MCreateStatusReady
XCTAssertNotNil(
status,
"status should be ready")
}
}
}
|
mit
|
da676fcfcea10ad62e1474360e5a53e3
| 23.25 | 111 | 0.471936 | 5.842256 | false | true | false | false |
pebble8888/PBKit
|
PBKit/PBGeometry.swift
|
1
|
1418
|
//
// PBGeometry.swift
// PBKit
//
// Created by pebble8888 on 2017/05/06.
// Copyright © 2017年 pebble8888. All rights reserved.
//
import CoreGraphics
public func + (p1: CGPoint, p2: CGPoint) -> CGPoint {
return CGPoint(x:p1.x + p2.x, y:p1.y + p2.y)
}
public func - (p1: CGPoint, p2: CGPoint) -> CGPoint {
return CGPoint(x:p1.x - p2.x, y:p1.y - p2.y)
}
public func * (p: CGPoint, f: CGFloat) -> CGPoint {
return CGPoint(x:p.x * f, y:p.y * f)
}
public func / (p: CGPoint, f: CGFloat) -> CGPoint {
if f == 0.0 {
return p
}
return p * (1.0/f)
}
public func + (p: CGPoint, v: CGVector) -> CGPoint {
return CGPoint(x:p.x + v.dx, y:p.y + v.dy)
}
public func - (p: CGPoint, v: CGVector) -> CGPoint {
return CGPoint(x:p.x - v.dx, y:p.y - v.dy)
}
public func * (v: CGVector, f: CGFloat) -> CGVector {
return CGVector(dx:v.dx * f, dy:v.dy * f)
}
public func / (v:CGVector, f:CGFloat) -> CGVector {
if f == 0.0 {
return v
}
return v * (1.0/f)
}
public extension CGRect {
func center() -> CGPoint {
return CGPoint(x: self.midX, y: self.midY)
}
}
public func * (rc: CGRect, f: CGFloat) -> CGRect {
return CGRect(x: rc.origin.x * f, y: rc.origin.y * f, width: rc.size.width * f, height: rc.size.height * f)
}
public func / (rc: CGRect, f: CGFloat) -> CGRect {
if f == 0.0 {
return rc
}
return rc * (1.0/f)
}
|
mit
|
78925450e388d7ec691a677dba468c0a
| 21.109375 | 111 | 0.568198 | 2.639925 | false | false | false | false |
frootloops/swift
|
test/stmt/foreach.swift
|
1
|
5960
|
// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances
// Bad containers and ranges
struct BadContainer1 {
}
func bad_containers_1(bc: BadContainer1) {
for e in bc { } // expected-error{{type 'BadContainer1' does not conform to protocol 'Sequence'}}
}
struct BadContainer2 : Sequence { // expected-error{{type 'BadContainer2' does not conform to protocol 'Sequence'}}
var generate : Int
}
func bad_containers_2(bc: BadContainer2) {
for e in bc { }
}
struct BadContainer3 : Sequence { // expected-error{{type 'BadContainer3' does not conform to protocol 'Sequence'}}
func makeIterator() { } // expected-note{{inferred type '()' (by matching requirement 'makeIterator()') is invalid: does not conform to 'IteratorProtocol'}}
}
func bad_containers_3(bc: BadContainer3) {
for e in bc { }
}
struct BadIterator1 {}
struct BadContainer4 : Sequence { // expected-error{{type 'BadContainer4' does not conform to protocol 'Sequence'}}
typealias Iterator = BadIterator1 // expected-note{{possibly intended match 'BadContainer4.Iterator' (aka 'BadIterator1') does not conform to 'IteratorProtocol'}}
func makeIterator() -> BadIterator1 { }
}
func bad_containers_4(bc: BadContainer4) {
for e in bc { }
}
// Pattern type-checking
struct GoodRange<Int> : Sequence, IteratorProtocol {
typealias Element = Int
func next() -> Int? {}
typealias Iterator = GoodRange<Int>
func makeIterator() -> GoodRange<Int> { return self }
}
struct GoodTupleIterator: Sequence, IteratorProtocol {
typealias Element = (Int, Float)
func next() -> (Int, Float)? {}
typealias Iterator = GoodTupleIterator
func makeIterator() -> GoodTupleIterator {}
}
func patterns(gir: GoodRange<Int>, gtr: GoodTupleIterator) {
var sum : Int
var sumf : Float
for i : Int in gir { sum = sum + i }
for i in gir { sum = sum + i }
for f : Float in gir { sum = sum + f } // expected-error{{'Int' is not convertible to 'Float'}}
for (i, f) : (Int, Float) in gtr { sum = sum + i }
for (i, f) in gtr {
sum = sum + i
sumf = sumf + f
sum = sum + f // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Float'}} expected-note {{expected an argument list of type '(Int, Int)'}}
}
for (i, _) : (Int, Float) in gtr { sum = sum + i }
for (i, _) : (Int, Int) in gtr { sum = sum + i } // expected-error{{'GoodTupleIterator.Element' (aka '(Int, Float)') is not convertible to '(Int, Int)'}}
for (i, f) in gtr {}
}
func slices(i_s: [Int], ias: [[Int]]) {
var sum = 0
for i in i_s { sum = sum + i }
for ia in ias {
for i in ia {
sum = sum + i
}
}
}
func discard_binding() {
for _ in [0] {}
}
struct X<T> {
var value: T
}
struct Gen<T> : IteratorProtocol {
func next() -> T? { return nil }
}
struct Seq<T> : Sequence {
func makeIterator() -> Gen<T> { return Gen() }
}
func getIntSeq() -> Seq<Int> { return Seq() }
func getOvlSeq() -> Seq<Int> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<Double> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<X<Int>> { return Seq() } // expected-note{{found this candidate}}
func getGenericSeq<T>() -> Seq<T> { return Seq() }
func getXIntSeq() -> Seq<X<Int>> { return Seq() }
func getXIntSeqIUO() -> Seq<X<Int>>! { return nil }
func testForEachInference() {
for i in getIntSeq() { }
// Overloaded sequence resolved contextually
for i: Int in getOvlSeq() { }
for d: Double in getOvlSeq() { }
// Overloaded sequence not resolved contextually
for v in getOvlSeq() { } // expected-error{{ambiguous use of 'getOvlSeq()'}}
// Generic sequence resolved contextually
for i: Int in getGenericSeq() { }
for d: Double in getGenericSeq() { }
// Inference of generic arguments in the element type from the
// sequence.
for x: X in getXIntSeq() {
let z = x.value + 1
}
for x: X in getOvlSeq() {
let z = x.value + 1
}
// Inference with implicitly unwrapped optional
for x: X in getXIntSeqIUO() {
let z = x.value + 1
}
// Range overloading.
for i: Int8 in 0..<10 { }
for i: UInt in 0...10 { }
}
func testMatchingPatterns() {
// <rdar://problem/21428712> for case parse failure
let myArray : [Int?] = []
for case .some(let x) in myArray {
_ = x
}
// <rdar://problem/21392677> for/case/in patterns aren't parsed properly
class A {}
class B : A {}
class C : A {}
let array : [A] = [A(), B(), C()]
for case (let x as B) in array {
_ = x
}
}
// <rdar://problem/21662365> QoI: diagnostic for for-each over an optional sequence isn't great
func testOptionalSequence() {
let array : [Int]?
for x in array { // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{17-17=!}}
}
}
// Crash with (invalid) for each over an existential
func testExistentialSequence(s: Sequence) { // expected-error {{protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements}}
for x in s { // expected-error {{using 'Sequence' as a concrete type conforming to protocol 'Sequence' is not supported}}
_ = x
}
}
// Conditional conformance to Sequence and IteratorProtocol.
protocol P { }
struct RepeatedSequence<T> {
var value: T
var count: Int
}
struct RepeatedIterator<T> {
var value: T
var count: Int
}
extension RepeatedIterator: IteratorProtocol where T: P {
typealias Element = T
mutating func next() -> T? {
if count == 0 { return nil }
count = count - 1
return value
}
}
extension RepeatedSequence: Sequence where T: P {
typealias Element = T
typealias Iterator = RepeatedIterator<T>
typealias SubSequence = AnySequence<T>
func makeIterator() -> RepeatedIterator<T> {
return Iterator(value: value, count: count)
}
}
extension Int : P { }
func testRepeated(ri: RepeatedSequence<Int>) {
for x in ri { _ = x }
}
|
apache-2.0
|
518a63e7fcfe37285bde7c34102bae23
| 26.214612 | 181 | 0.651846 | 3.551847 | false | false | false | false |
nextcloud/ios
|
iOSClient/Data/NCElementsJSON.swift
|
1
|
4907
|
//
// NCElementsJSON.swift
// Nextcloud
//
// Created by Marino Faggiana on 14/05/2020.
// Copyright © 2020 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
@objc class NCElementsJSON: NSObject {
@objc static let shared: NCElementsJSON = {
let instance = NCElementsJSON()
return instance
}()
@objc public let capabilitiesVersionString: Array = ["ocs", "data", "version", "string"]
@objc public let capabilitiesVersionMajor: Array = ["ocs", "data", "version", "major"]
@objc public let capabilitiesFileSharingApiEnabled: Array = ["ocs", "data", "capabilities", "files_sharing", "api_enabled"]
@objc public let capabilitiesFileSharingPubPasswdEnforced: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "password", "enforced"]
@objc public let capabilitiesFileSharingPubExpireDateEnforced: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "expire_date", "enforced"]
@objc public let capabilitiesFileSharingPubExpireDateDays: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "expire_date", "days"]
@objc public let capabilitiesFileSharingInternalExpireDateEnforced: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "expire_date_internal", "enforced"]
@objc public let capabilitiesFileSharingInternalExpireDateDays: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "expire_date_internal", "days"]
@objc public let capabilitiesFileSharingRemoteExpireDateEnforced: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "expire_date_remote", "enforced"]
@objc public let capabilitiesFileSharingRemoteExpireDateDays: Array = ["ocs", "data", "capabilities", "files_sharing", "public", "expire_date_remote", "days"]
@objc public let capabilitiesFileSharingDefaultPermissions: Array = ["ocs", "data", "capabilities", "files_sharing", "default_permissions"]
@objc public let capabilitiesFileSharingSendPasswordMail: Array = ["ocs", "data", "capabilities", "files_sharing", "sharebymail", "send_password_by_mail"]
@objc public let capabilitiesThemingColor: Array = ["ocs", "data", "capabilities", "theming", "color"]
@objc public let capabilitiesThemingColorElement: Array = ["ocs", "data", "capabilities", "theming", "color-element"]
@objc public let capabilitiesThemingColorText: Array = ["ocs", "data", "capabilities", "theming", "color-text"]
@objc public let capabilitiesThemingName: Array = ["ocs", "data", "capabilities", "theming", "name"]
@objc public let capabilitiesThemingSlogan: Array = ["ocs", "data", "capabilities", "theming", "slogan"]
@objc public let capabilitiesWebDavRoot: Array = ["ocs", "data", "capabilities", "core", "webdav-root"]
@objc public let capabilitiesE2EEEnabled: Array = ["ocs", "data", "capabilities", "end-to-end-encryption", "enabled"]
@objc public let capabilitiesE2EEApiVersion: Array = ["ocs", "data", "capabilities", "end-to-end-encryption", "api-version"]
@objc public let capabilitiesExternalSitesExists: Array = ["ocs", "data", "capabilities", "external"]
@objc public let capabilitiesRichdocumentsMimetypes: Array = ["ocs", "data", "capabilities", "richdocuments", "mimetypes"]
@objc public let capabilitiesActivity: Array = ["ocs", "data", "capabilities", "activity", "apiv2"]
@objc public let capabilitiesNotification: Array = ["ocs", "data", "capabilities", "notifications", "ocs-endpoints"]
@objc public let capabilitiesFilesUndelete: Array = ["ocs", "data", "capabilities", "files", "undelete"]
@objc public let capabilitiesFilesLockVersion: Array = ["ocs", "data", "capabilities", "files", "locking"] // NC 24
@objc public let capabilitiesFilesComments: Array = ["ocs", "data", "capabilities", "files", "comments"] // NC 20
@objc public let capabilitiesHWCEnabled: Array = ["ocs", "data", "capabilities", "handwerkcloud", "enabled"]
@objc public let capabilitiesUserStatusEnabled: Array = ["ocs", "data", "capabilities", "user_status", "enabled"]
@objc public let capabilitiesUserStatusSupportsEmoji: Array = ["ocs", "data", "capabilities", "user_status", "supports_emoji"]
}
|
gpl-3.0
|
b53aea37d68ec97310dfbfb72b9609c6
| 66.205479 | 174 | 0.708928 | 3.962843 | false | false | false | false |
RedRoma/Lexis-Database
|
LexisDatabase/LexisWord+SupplementalInformation.swift
|
1
|
5219
|
//
// LexisWord+SupplementalInformation.swift
// LexisDatabase
//
// Created by Wellington Moreno on 9/17/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import AlchemySwift
import Archeota
import Foundation
internal typealias SupplementalInformation = LexisWord.SupplementalInformation
//MARK: Supplemental Information and Functions for extracting descriptions from dictionary codes.
public extension LexisWord
{
@objc(_TtCC13LexisDatabase9LexisWord23SupplementalInformation)
class SupplementalInformation: NSObject, NSCoding
{
/**
This instance represents a situation where nothing is known about a word.
*/
static let unknown = SupplementalInformation(age: .X, subjectArea: .X, geographicalArea: .X, frequency: .X, source: .X)
public let age: Age
public let subjectArea: SubjectArea
public let geographicalArea: GeographicalArea
public let frequency: Frequency
public let source: Source
public init(age: Age, subjectArea: SubjectArea, geographicalArea: GeographicalArea, frequency: Frequency, source: Source)
{
self.age = age
self.subjectArea = subjectArea
self.geographicalArea = geographicalArea
self.frequency = frequency
self.source = source
}
public convenience required init?(coder decoder: NSCoder)
{
guard let ageString = decoder.decodeObject(forKey: Keys.age) as? String,
let age = Age.from(dictionaryCode: ageString),
let subjectAreaString = decoder.decodeObject(forKey: Keys.subjectArea) as? String,
let subjectArea = SubjectArea.from(dictionaryCode: subjectAreaString),
let geographicalAreaString = decoder.decodeObject(forKey: Keys.geopgraphicalArea) as? String,
let geographicalArea = GeographicalArea.from(dictionaryCode: geographicalAreaString),
let frequencyString = decoder.decodeObject(forKey: Keys.frequency) as? String,
let frequency = Frequency.from(dictionaryCode: frequencyString),
let sourceString = decoder.decodeObject(forKey: Keys.source) as? String,
let source = Source.from(dictionaryCode: sourceString)
else
{
LOG.warn("Failed to decode Supplemental information")
return nil
}
self.init(age: age, subjectArea: subjectArea, geographicalArea: geographicalArea, frequency: frequency, source: source)
}
public func encode(with encoder: NSCoder)
{
encoder.encode(self.age.code, forKey: Keys.age)
encoder.encode(self.subjectArea.code, forKey: Keys.subjectArea)
encoder.encode(self.geographicalArea.code, forKey: Keys.geopgraphicalArea)
encoder.encode(self.frequency.code, forKey: Keys.frequency)
encoder.encode(self.source.code, forKey: Keys.source)
}
public override func isEqual(_ object: Any?) -> Bool
{
guard let other = object as? SupplementalInformation else { return false }
return self == other
}
public override var description: String
{
return "[\(age.code)\(subjectArea.code)\(geographicalArea.code)\(frequency.code)\(source.code)]"
}
public override var hash: Int
{
return description.hashValue
}
public var humanReadableDescription: String
{
var synopsis = ""
if self.frequency != .X
{
synopsis = "Used \(frequency.description.lowercasedFirstLetter()) \(age.description.lowercasedFirstLetter()). "
}
else
{
synopsis = "Used in \(geographicalArea.description) \(age.description.lowercasedFirstLetter()). "
}
if self.subjectArea != .X
{
synopsis += "This word is primarily used in \(subjectArea.description)."
}
else
{
synopsis += "This word was used in all subject areas."
}
return synopsis
}
//Used for NSCoding
private class Keys
{
static let age = "age"
static let subjectArea = "subject_area"
static let geopgraphicalArea = "geographical_location"
static let frequency = "frequency"
static let source = "source"
}
}
}
public func ==(left: LexisWord.SupplementalInformation, right: LexisWord.SupplementalInformation) -> Bool
{
//Description is a quick and simple way to test equality
return left.description == right.description
}
//=========================================
//MARK: String Manipulations
//=========================================
fileprivate extension String
{
func lowercasedFirstLetter() -> String
{
return self.firstLetter?.lowercased() ?? ""
}
}
|
apache-2.0
|
d9f6064ad79fe9580753273f4229a3c8
| 35.48951 | 131 | 0.595631 | 5.212787 | false | false | false | false |
mapsme/omim
|
iphone/Maps/UI/PlacePage/Components/WikiDescriptionViewController.swift
|
5
|
2199
|
protocol WikiDescriptionViewControllerDelegate: AnyObject {
func didPressMore()
}
class WikiDescriptionViewController: UIViewController {
@IBOutlet var descriptionTextView: UITextView!
@IBOutlet var moreButton: UIButton!
var descriptionHtml: String? {
didSet{
updateDescription()
}
}
weak var delegate: WikiDescriptionViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
descriptionTextView.textContainerInset = .zero
updateDescription()
}
private func updateDescription() {
guard let descriptionHtml = descriptionHtml else { return }
DispatchQueue.global().async {
let font = UIFont.regular14()
let color = UIColor.blackPrimaryText()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
let attributedString: NSAttributedString
if let str = NSMutableAttributedString(htmlString: descriptionHtml, baseFont: font, paragraphStyle: paragraphStyle) {
str.addAttribute(NSAttributedString.Key.foregroundColor,
value: color,
range: NSRange(location: 0, length: str.length))
attributedString = str;
} else {
attributedString = NSAttributedString(string: descriptionHtml,
attributes: [NSAttributedString.Key.font : font,
NSAttributedString.Key.foregroundColor: color,
NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
DispatchQueue.main.async {
if attributedString.length > 500 {
self.descriptionTextView.attributedText = attributedString.attributedSubstring(from: NSRange(location: 0,
length: 500))
} else {
self.descriptionTextView.attributedText = attributedString
}
}
}
}
@IBAction func onMore(_ sender: UIButton) {
delegate?.didPressMore()
}
override func applyTheme() {
super.applyTheme()
updateDescription()
}
}
|
apache-2.0
|
cfdf9fefc8ab62727b4c574be9b83b4a
| 33.359375 | 123 | 0.616644 | 6.264957 | false | false | false | false |
STShenZhaoliang/STWeiBo
|
STWeiBo/STWeiBo/Classes/OAuth/UserAccount.swift
|
1
|
5249
|
//
// UserAccount.swift
// STWeiBo
//
// Created by ST on 15/11/16.
// Copyright © 2015年 ST. All rights reserved.
//
import UIKit
// Swift2.0 打印对象需要重写CustomStringConvertible协议中的description
class UserAccount: NSObject , NSCoding{
/// 用于调用access_token,接口获取授权后的access token。
var access_token: String?
/// access_token的生命周期,单位是秒数。
var expires_in: NSNumber?{
didSet{
// 根据过期的秒数, 生成真正地过期时间
expires_Date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
print(expires_Date)
}
}
/// 保存用户过期时间
var expires_Date: NSDate?
/// 当前授权用户的UID。
var uid:String?
/// 友好显示名称
var name: String?
/// 用户头像地址(大图),180×180像素
var avatar_large: String?
/// 用户昵称
var screen_name: String?
override init() {
}
init(dict: [String: AnyObject])
{
super.init()
// access_token = dict["access_token"] as? String
// expires_in = dict["expires_in"] as? NSNumber
// uid = dict["uid"] as? String
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
print(key)
}
// override var description: String{
// // 1.定义属性数组
// let properties = ["access_token", "expires_in", "uid", "expires_Date", "avatar_large", "screen_name"]
// // 2.根据属性数组, 将属性转换为字典
// let dict = self.dictionaryWithValuesForKeys(properties)
// // 3.将字典转换为字符串
// return "\(dict)"
// }
func loadUserInfo(finished: (account: UserAccount?, error:NSError?)->())
{
assert(access_token != nil, "没有授权")
let path = "2/users/show.json"
let params = ["access_token":access_token!, "uid":uid!]
NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) -> Void in
print(JSON)
// 1.判断字典是否有值
if let dict = JSON as? [String: AnyObject]
{
self.screen_name = dict["screen_name"] as? String
self.avatar_large = dict["avatar_large"] as? String
// 保存用户信息
// self.saveAccount()
finished(account: self, error: nil)
return
}
finished(account: nil, error: nil)
}) { (_, error) -> Void in
print(error)
finished(account: nil, error: error)
}
}
/**
返回用户是否登录
*/
class func userLogin() -> Bool
{
return UserAccount.loadAccount() != nil
}
// MARK: - 保存和读取 Keyed
/**
保存授权模型
*/
func saveAccount()
{
NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir())
}
/// 加载授权模型
static var account: UserAccount?
class func loadAccount() -> UserAccount? {
// 1.判断是否已经加载过
if account != nil
{
return account
}
// 2.加载授权模型
account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.plist".cacheDir()) as? UserAccount
// 3.判断授权信息是否过期
// 2020-09-08 03:49:39 2020-09-09 03:49:39
if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending
{
// 已经过期
return nil
}
return account
}
// MARK: - NSCoding
// 将对象写入到文件中
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeObject(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(expires_Date, forKey: "expires_Date")
aCoder.encodeObject(screen_name, forKey: "screen_name")
aCoder.encodeObject(avatar_large, forKey: "avatar_large")
aCoder.encodeObject(name, forKey: "name")
}
// 从文件中读取对象
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
uid = aDecoder.decodeObjectForKey("uid") as? String
expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
name = aDecoder.decodeObjectForKey("name") as? String
}
/// 属性列表
let properties = ["access_token", "expires_in", "uid", "name", "avatar_large"]
/// 打印对象信息
override var description: String {
return "\(self.dictionaryWithValuesForKeys(properties))"
}
}
|
mit
|
be8070b8215a0c24060589bd61a48bc4
| 27.760479 | 111 | 0.563814 | 4.213158 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
Swift/Classes/View/ConfigurationViewCell.swift
|
1
|
4776
|
//
// ConfigurationViewCell.swift
// Example
//
// Created by Slience on 2021/3/16.
//
import UIKit
class ConfigurationViewCell: UITableViewCell {
private(set) lazy var titleLabel: UILabel = {
let view = UILabel(frame: .zero)
view.font = UIFont.systemFont(ofSize: 15, weight: .regular)
view.adjustsFontSizeToFitWidth = true
if #available(iOS 13.0, *) {
view.textColor = UIColor.label
} else {
view.textColor = UIColor.black
}
view.text = ""
view.textAlignment = .left
return view
}()
private(set) lazy var tagsButton: UIButton = {
let view = UIButton(frame: .zero)
view.titleLabel?.font = UIFont.systemFont(ofSize: 11, weight: .medium)
view.setTitleColor(UIColor.systemBlue, for: .normal)
if #available(iOS 13.0, *) {
view.backgroundColor = UIColor.tertiarySystemGroupedBackground
} else {
view.backgroundColor = UIColor(red: 242.0/255.0, green: 242.0/255.0, blue: 242.0/255.0, alpha: 1.0)
}
view.setTitle("", for: .normal)
view.layer.masksToBounds = true
view.layer.cornerRadius = 2
view.contentEdgeInsets = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4)
view.isUserInteractionEnabled = false
return view
}()
private(set) lazy var contentLabel: UILabel = {
let view = UILabel(frame: .zero)
view.font = UIFont.systemFont(ofSize: 14, weight: .regular)
view.text = ""
view.numberOfLines = 2
view.adjustsFontSizeToFitWidth = true
if #available(iOS 13.0, *) {
view.textColor = UIColor.secondaryLabel
} else {
view.textColor = UIColor.gray
}
view.textAlignment = .right
return view
}()
private(set) lazy var colorView: UIView = {
let colorView = UIView.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
colorView.layer.cornerRadius = 2
colorView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
colorView.layer.shadowRadius = 2
colorView.layer.shadowOpacity = 0.5
colorView.layer.shadowOffset = CGSize(width: -1, height: 1)
return colorView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
contentView.addSubview(titleLabel)
contentView.addSubview(tagsButton)
contentView.addSubview(contentLabel)
contentView.addSubview(colorView)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.hx.x = 20
let titleLbWidth = titleLabel.text!.hx.width(ofFont: titleLabel.font, maxHeight: CGFloat(MAXFLOAT))
titleLabel.hx.width = titleLbWidth > hx.width - 50 ? hx.width - 50 : titleLbWidth
titleLabel.hx.height = titleLabel.text!.hx.height(ofFont: titleLabel.font, maxWidth: titleLabel.hx.width)
titleLabel.hx.y = hx.height * 0.5 - 2 - titleLabel.hx.height
tagsButton.hx.x = 16
tagsButton.hx.width = tagsButton.titleLabel!.text!.hx.width(
ofFont: tagsButton.titleLabel!.font,
maxHeight: CGFloat(MAXFLOAT)
) + 8
tagsButton.hx.height = tagsButton.titleLabel!.text!.hx.height(
ofFont: tagsButton.titleLabel!.font,
maxWidth: CGFloat(MAXFLOAT)
) + 4
tagsButton.hx.y = hx.height * 0.5 + 2
contentLabel.hx.width = contentLabel.text!.hx.width(ofFont: contentLabel.font, maxHeight: CGFloat(MAXFLOAT))
contentLabel.hx.height = contentLabel.text!.hx.height(
ofFont: contentLabel.font,
maxWidth: contentLabel.hx.width
)
contentLabel.hx.centerY = hx.height * 0.5
contentLabel.hx.x = hx.width - 20 - contentLabel.hx.width
colorView.hx.centerY = hx.height * 0.5
colorView.hx.x = hx.width - 10 - colorView.hx.width
}
public func setupData(_ rowType: ConfigRowTypeRule, _ content: String) {
titleLabel.text = rowType.title
tagsButton.setTitle(rowType.detailTitle, for: .normal)
contentLabel.text = content
colorView.isHidden = true
}
public func setupColorData(_ rowType: ConfigRowTypeRule, _ color: UIColor?) {
titleLabel.text = rowType.title
tagsButton.setTitle(rowType.detailTitle, for: .normal)
colorView.backgroundColor = color
contentLabel.isHidden = true
}
}
|
mit
|
fb578f0de3cd1add487a89495d7aca58
| 36.3125 | 116 | 0.621022 | 4.189474 | false | false | false | false |
n8armstrong/CalendarView
|
CalendarView/Carthage/Checkouts/SwiftMoment/SwiftMoment/MyPlayground.playground/Contents.swift
|
1
|
271
|
import SwiftMoment
let now = moment()
print(now.format())
var obj = moment([2015, 01, 19, 20, 45, 34])!
obj = obj + 4.days
obj.format("YYYY MMMM dd")
obj.fromNow()
let today = moment()
let first = moment(today).add(50.days)
let second = moment(today).add(50, .Days)
|
mit
|
f9c601c5fcd0418a8207c2b0083ef492
| 17.066667 | 45 | 0.664207 | 2.852632 | false | false | false | false |
whereuat/whereuat-ios
|
whereuat-ios/Views/KeyLocationView/KeyLocationsViewController.swift
|
1
|
3423
|
//
// KeyLocationsViewController.swift
// whereuat
//
// Created by Raymond Jacobson on 5/11/16.
// Copyright © 2016 whereuat. All rights reserved.
//
import UIKit
class KeyLocationsViewController: UIViewController, FABDelegate {
var database = Database.sharedInstance
var mainFAB: FloatingActionButton!
@IBOutlet weak var tableView: UITableView!
var keyLocations: Array<KeyLocation>!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Fetch key locations from the database
keyLocations = self.database.keyLocationTable.getAll() as! Array<KeyLocation>
self.tableView.registerClass(KeyLocationTableViewCell.self, forCellReuseIdentifier: KeyLocationTableViewCell.identifier)
self.tableView.alwaysBounceVertical = false
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, SizingConstants.tableBottomPadding, 0);
// Draw the FAB to appear on the bottom right of the screen
self.mainFAB = FloatingActionButton(color: ColorWheel.coolRed, type: FABType.KeyLocationOnly)
self.mainFAB.delegate = self
self.view.addSubview(self.mainFAB.floatingActionButton)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItems("Key Locations")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return KeyLocationTableViewCell.height
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (keyLocations != nil) {
return keyLocations!.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (keyLocations != nil) {
let cell = KeyLocationTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: KeyLocationTableViewCell.identifier)
cell.setData(keyLocations![indexPath.row])
cell.delegate = self
return cell
}
return UITableViewCell()
}
func reloadTableData() {
// Fetch key locations from the database
self.keyLocations = self.database.keyLocationTable.getAll() as! Array<KeyLocation>
self.tableView.reloadData()
}
/*
* editKeyLocation spawns a content popup with the key location name as editable
*/
func editKeyLocation(id: Int64, currentName: String) {
let alert = ContentPopup.editKeyLocationAlert(id, currentName: currentName, refreshCallback: self.reloadTableData)
self.presentViewController(alert, animated: true, completion: nil)
}
/*
* removeKeyLocation drops a key location from the database
*/
func removeKeyLocation(id: Int64) {
self.database.keyLocationTable.dropKeyLocation(id)
self.reloadTableData()
}
/*
* addKeyLocation spawns an alert with a text view and adds the key location to the database
* addKeyLocation is invoked by the floating action button
*/
func addKeyLocation() {
self.presentViewController(ContentPopup.addKeyLocationAlert(self.reloadTableData), animated: true, completion: nil)
}
}
|
apache-2.0
|
12e9555e798dfa06b0fb6bca04528854
| 34.645833 | 139 | 0.682934 | 4.952243 | false | false | false | false |
benjaminsnorris/CloudKitReactor
|
Sources/AcceptShares.swift
|
1
|
1158
|
/*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import Foundation
import Reactor
import CloudKit
public struct AcceptShares<U: State>: Command {
public var metadatas: [CKShare.Metadata]
public var completion: ((Error?) -> Void)?
public init(with metadatas: [CKShare.Metadata], completion: ((Error?) -> Void)? = nil) {
self.metadatas = metadatas
self.completion = completion
}
public func execute(state: U, core: Core<U>) {
let operation = CKAcceptSharesOperation(shareMetadatas: metadatas)
operation.perShareCompletionBlock = { metadata, share, error in
if let error = error {
core.fire(event: CloudKitShareError(error, for: metadata))
} else if let share = share {
core.fire(event: CloudKitUpdated(share))
}
}
operation.acceptSharesCompletionBlock = { error in
self.completion?(error)
}
operation.qualityOfService = .userInitiated
CKContainer.default().add(operation)
}
}
|
mit
|
ed1e380540d42da9daffa50ce4a008d2
| 28.684211 | 92 | 0.56117 | 4.014235 | false | false | false | false |
tkremenek/swift
|
validation-test/compiler_crashers_fixed/01866-swift-archetypetype-setnestedtypes.swift
|
65
|
470
|
// 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
// RUN: not %target-swift-frontend %s -typecheck
func g<T>() {
protocol c = {
}
struct A? = nil
var d = c>(A.init<f == e
|
apache-2.0
|
a58a2139b1e6b09f4edb2df21d730dcf
| 35.153846 | 79 | 0.719149 | 3.587786 | false | false | false | false |
tedinpcshool/classmaster
|
classmaster_good/Pods/InteractiveSideMenu/Sources/MenuContainerViewController.swift
|
2
|
4198
|
//
// MenuContainerViewController.swift
//
// Copyright 2017 Handsome LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
open class MenuContainerViewController: UIViewController {
public var menuViewController: MenuViewController! {
didSet {
menuViewController.menuContainerViewController = self
menuViewController.transitioningDelegate = self.navigationMenuTransitionDelegate
menuViewController.navigationMenuTransitionDelegate = self.navigationMenuTransitionDelegate
}
}
public var contentViewControllers: [MenuItemContentViewController]!
private weak var currentContentViewController: MenuItemContentViewController?
private var navigationMenuTransitionDelegate: MenuTransitioningDelegate!
open func menuTransitionOptionsBuilder() -> TransitionOptionsBuilder? {
return nil
}
override open func viewDidLoad() {
super.viewDidLoad()
navigationMenuTransitionDelegate = MenuTransitioningDelegate()
navigationMenuTransitionDelegate.interactiveTransition = MenuInteractiveTransition(
presentAction: { [weak self] in self?.presentNavigationMenu() },
dismissAction: { [weak self] in self?.dismiss(animated: true, completion: nil) },
transitionOptionsBuilder: menuTransitionOptionsBuilder()
)
let screenEdgePanRecognizer = UIScreenEdgePanGestureRecognizer(
target: navigationMenuTransitionDelegate.interactiveTransition,
action: #selector(MenuInteractiveTransition.handlePanPresentation(recognizer:))
)
screenEdgePanRecognizer.edges = .left
self.view.addGestureRecognizer(screenEdgePanRecognizer)
}
public func showMenu() {
presentNavigationMenu()
}
public func hideMenu() {
self.dismiss(animated: true, completion: nil)
}
public func selectContentViewController(_ selectedContentVC: MenuItemContentViewController) {
if let currentContentVC = self.currentContentViewController {
if currentContentVC != selectedContentVC {
currentContentVC.view.removeFromSuperview()
currentContentVC.removeFromParentViewController()
self.currentContentViewController = selectedContentVC
setCurrentView()
}
} else {
self.currentContentViewController = selectedContentVC
setCurrentView()
}
}
private func setCurrentView() {
self.addChildViewController(currentContentViewController!)
self.view.addSubview(currentContentViewController!.view)
self.view.addSubviewWithFullSizeConstraints(view: currentContentViewController!.view)
}
private func presentNavigationMenu() {
self.present(menuViewController, animated: true, completion: nil)
}
}
extension UIView {
func addSubviewWithFullSizeConstraints(view : UIView) {
insertSubviewWithFullSizeConstraints(view: view, atIndex: self.subviews.count)
}
func insertSubviewWithFullSizeConstraints(view : UIView, atIndex: Int) {
view.translatesAutoresizingMaskIntoConstraints = false
self.insertSubview(view, at: atIndex)
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": view]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": view]))
}
}
|
mit
|
b6aaa38471c792766c2dda169a1dabe7
| 38.233645 | 162 | 0.702477 | 6.110626 | false | false | false | false |
suifengqjn/swiftDemo
|
UI/UITableVIew/UITableVIew/RootViewController.swift
|
1
|
1384
|
//
// RootViewController.swift
// UITableVIew
//
// Created by qianjn on 16/7/27.
// Copyright © 2016年 SF. All rights reserved.
//
import UIKit
class RootViewController: UIViewController {
override func loadView() {
let tv = UITableView();
tv.frame = UIScreen.main().bounds
tv.delegate = self
tv.dataSource = self
view = tv
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - 懒加载
lazy var dataList:[String] = {
return ["ds", "asd", "wer", "dfr", "we", "we"]
}()
}
///官方推荐将数据源代理方法单独放到一个扩展中
///extension 相当于OC 的category
extension RootViewController: UITableViewDelegate,UITableViewDataSource
{
// MARK: - UITableVIewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellIden")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cellIden")
}
cell?.textLabel?.text = dataList[indexPath.row]
return cell!
}
}
|
apache-2.0
|
cc371cedc7c247f43cfaf26dadf1c8f2
| 22.245614 | 100 | 0.610566 | 4.584775 | false | false | false | false |
glock45/swiftX
|
Source/http/http.swift
|
1
|
7733
|
//
// http.swift
// swiftx
//
// Copyright © 2016 kolakowski. All rights reserved.
//
import Foundation
public class Request {
public enum HttpVersion { case http10, http11 }
public var httpVersion = HttpVersion.http10
public var method = ""
public var path = ""
public var query = [(String, String)]()
public var headers = [(String, String)]()
public var body = [UInt8]()
public var contentLength = 0
public func hasToken(_ token: String, forHeader headerName: String) -> Bool {
guard let (_, value) = headers.filter({ $0.0 == headerName }).first else {
return false
}
return value
.components(separatedBy: ",")
.filter({ $0.trimmingCharacters(in: .whitespaces).lowercased() == token })
.count > 0
}
}
public class Response {
public init() { }
public init(_ status: Status = Status.ok) {
self.status = status.rawValue
}
public init(_ status: Int = Status.ok.rawValue) {
self.status = status
}
public init(_ body: Array<UInt8>) {
self.body.append(contentsOf: body)
}
public init(_ body: ArraySlice<UInt8>) {
self.body.append(contentsOf: body)
}
public var status = Status.ok.rawValue
public var headers = [(String, String)]()
public var body = [UInt8]()
public var processingSuccesor: IncomingDataProcessor? = nil
}
public class TextResponse: Response {
public init(_ status: Int = Status.ok.rawValue, _ text: String) {
super.init(status)
self.headers.append(("Content-Type", "text/plain"))
self.body = [UInt8](text.utf8)
}
}
public enum Status: Int {
case `continue` = 100
case switchingProtocols = 101
case ok = 200
case created = 201
case accepted = 202
case noContent = 204
case resetContent = 205
case partialContent = 206
case movedPerm = 301
case notModified = 304
case badRequest = 400
case unauthorized = 401
case forbidden = 403
case notFound = 404
}
public class HttpIncomingDataPorcessor: Hashable, IncomingDataProcessor {
private enum State {
case waitingForHeaders
case waitingForBody
}
private var state = State.waitingForHeaders
private let socket: Int32
private var buffer = Array<UInt8>()
private var request = Request()
private let callback: ((Request) throws -> Void)
public init(_ socket: Int32, _ closure: @escaping ((Request) throws -> Void)) {
self.socket = socket
self.callback = closure
}
public static func == (lhs: HttpIncomingDataPorcessor, rhs: HttpIncomingDataPorcessor) -> Bool {
return lhs.socket == rhs.socket
}
public var hashValue: Int { return Int(self.socket) }
public func process(_ chunk: ArraySlice<UInt8>) throws {
switch self.state {
case .waitingForHeaders:
guard self.buffer.count + chunk.count < 4096 else {
throw AsyncError.parse("Headers size exceeds that limit.")
}
var iterator = chunk.makeIterator()
while let byte = iterator.next() {
if byte != UInt8.cr {
buffer.append(byte)
}
if buffer.count >= 2 && buffer[buffer.count-1] == UInt8.lf && buffer[buffer.count-2] == UInt8.lf {
self.buffer.removeLast(2)
self.request = try self.consumeHeader(buffer)
self.buffer.removeAll(keepingCapacity: true)
let left = [UInt8](iterator)
self.state = .waitingForBody
try self.process(left[0..<left.count])
break
}
}
case .waitingForBody:
guard self.request.body.count + chunk.count <= request.contentLength else {
throw AsyncError.parse("Peer sent more data then required ('Content-Length' = \(request.contentLength).")
}
request.body.append(contentsOf: chunk)
if request.body.count == request.contentLength {
self.state = .waitingForHeaders
try self.callback(request)
}
}
}
private func consumeHeader(_ data: [UInt8]) throws -> Request {
let lines = data.split(separator: UInt8.lf)
guard let requestLine = lines.first else {
throw AsyncError.httpError("No status line.")
}
let requestLineTokens = requestLine.split(separator: UInt8.space)
guard requestLineTokens.count >= 3 else {
throw AsyncError.httpError("Invalid status line.")
}
let request = Request()
if requestLineTokens[2] == [0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30] {
request.httpVersion = .http10
} else if requestLineTokens[2] == [0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31] {
request.httpVersion = .http11
} else {
throw AsyncError.parse("Invalid http version: \(requestLineTokens[2])")
}
request.headers = lines
.dropFirst()
.map { line in
let headerTokens = line.split(separator: UInt8.colon, maxSplits: 1)
if let name = headerTokens.first, let value = headerTokens.last {
if let nameString = String(bytes: name, encoding: String.Encoding.ascii),
let valueString = String(bytes: value, encoding: String.Encoding.ascii) {
return (nameString.lowercased(), valueString.trimmingCharacters(in: CharacterSet.whitespaces))
}
}
return ("", "")
}
if let (_, value) = request.headers
.filter({ $0.0 == "content-length" })
.first {
guard let contentLength = Int(value) else {
throw AsyncError.parse("Invalid 'Content-Length' header value \(value).")
}
request.contentLength = contentLength
}
guard let method = String(bytes: requestLineTokens[0], encoding: .ascii) else {
throw AsyncError.parse("Invalid 'method' value \(requestLineTokens[0]).")
}
request.method = method
guard let path = String(bytes: requestLineTokens[1], encoding: .ascii) else {
throw AsyncError.parse("Invalid 'path' value \(requestLineTokens[1]).")
}
let queryComponents = path.components(separatedBy: "?")
if queryComponents.count > 1, let first = queryComponents.first, let last = queryComponents.last {
request.path = first
request.query = last
.components(separatedBy: "&")
.reduce([(String, String)]()) { (c, s) -> [(String, String)] in
let tokens = s.components(separatedBy: "=")
if let name = tokens.first, let value = tokens.last {
if let nameDecoded = name.removingPercentEncoding, let valueDecoded = value.removingPercentEncoding {
return c + [(nameDecoded, tokens.count > 1 ? valueDecoded : "")]
}
}
return c
}
} else {
request.path = path
}
return request
}
}
|
bsd-3-clause
|
90cf41d0ae2926a7f36856759a9da671
| 31.487395 | 125 | 0.54656 | 4.688902 | false | false | false | false |
Aquaware/LaSwift
|
iOS/LaSwift/BasicMath.swift
|
1
|
14690
|
//
// BasicMath.swift
// LaSwift
//
// Created by Ikuo Kudo on 20,March,2016
// Copyright © 2016 Aquaware. All rights reserved.
//
import Darwin
import Accelerate
extension Complex {
public func copy() -> Complex {
if(self.isReal && self.isImag) {
return Complex()
}
else if self.isReal {
return Complex(imag: self.imag)
}
else if self.isImag {
return Complex(real: self.real)
}
else {
return Complex(real: self.real, imag: self.imag)
}
}
}
extension RMatrix {
public func copy() -> RMatrix {
let array = self.flat
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func sort() {
let count = self.rows * self.cols
var array = self.flat
vDSP_vsortD(&array, UInt(count), 1)
//la_release(self.la)
self.la = la_matrix_from_double_buffer( array,
la_count_t(self.rows),
la_count_t(self.cols),
la_count_t(self.cols),
la_hint_t(LA_NO_HINT),
la_attribute_t(LA_DEFAULT_ATTRIBUTES))
}
public static func rand(rows: Int, cols: Int) -> RMatrix {
let count = rows * cols
var array = [Double](count: count, repeatedValue: 0.0)
var i:__CLPK_integer = 1
var seed:Array<__CLPK_integer> = [1, 2, 3, 5]
var nn: __CLPK_integer = __CLPK_integer(count)
dlarnv_(&i, &seed, &nn, &array)
return RMatrix(array: array, rows: rows, cols: cols)
}
public func sum() -> Double {
return self.calcSum(self.flat)
}
public func sum(axis: Int) -> RMatrix {
let clousure = { (array: [Double]) -> Double in
return self.calcSum(array)
}
return calc(axis, closure: clousure)
}
public func max() -> Double {
return self.calcMax(self.flat)
}
public func max(axis: Int) -> RMatrix {
let closure = { (array: [Double]) -> Double in
return self.calcMax(array)
}
return calc(axis, closure: closure)
}
public func min() -> Double {
return self.calcMin(self.flat)
}
public func min(axis: Int) -> RMatrix {
let closure = { (array: [Double]) -> Double in
return self.calcMin(array)
}
return calc(axis, closure: closure)
}
public func mean() -> Double {
return self.calcMean(self.flat)
}
public func mean(axis: Int) -> RMatrix {
let closure = { (array: [Double]) -> Double in
return self.calcMean(array)
}
return calc(axis, closure: closure)
}
public func variance() -> Double {
assert(self.rows > 0 && self.cols > 0)
let square = (self - self.mean()) * (self - self.mean())
return square.sum() / Double(self.rows) / Double(self.cols)
}
public func std() -> Double {
return Darwin.sqrt(variance())
}
public func absolute() -> RMatrix{
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvfabs(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func sqrt() -> RMatrix{
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvsqrt(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func pow(y: RMatrix) -> RMatrix {
assert(self.rows == y.rows && self.cols == y.cols)
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvpow(&array, self.flat, y.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func exp() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvexp(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func ln() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvlog(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func log2() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvlog2(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func log10() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvlog10(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func ceil() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvceil(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func floor() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvfloor(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func round() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvnint(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func sin() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvsin(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func cos() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvcos(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func tan() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvtan(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func sinh() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvsinh(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func cosh() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvcosh(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func tanh() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvtanh(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func asinh() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvasinh(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func acosh() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvacosh(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
public func atanh() -> RMatrix {
let count = self.rows * self.cols
var array = [Double](count: count, repeatedValue: 0.0)
vvatanh(&array, self.flat, [Int32(count)])
return RMatrix(array: array, rows: self.rows, cols: self.cols)
}
// ---
private func calcSum(array: [Double]) -> Double {
var value: Double = 0.0
vDSP_sveD(array, 1, &value, vDSP_Length(array.count))
return value
}
private func calcMax(array: [Double]) -> Double {
var value: Double = 0.0
vDSP_maxvD(array, 1, &value, vDSP_Length(array.count))
return value
}
private func calcMin(array: [Double]) -> Double {
var value: Double = 0.0
vDSP_minvD(array, 1, &value, vDSP_Length(array.count))
return value
}
private func calcMean(array: [Double]) -> Double {
var value: Double = 0.0
vDSP_meanvD(array, 1, &value, vDSP_Length(array.count))
return value
}
private func calc(axis: Int, closure: ([Double]) -> Double) -> RMatrix {
var result: [Double]
if axis == 0 {
result = [Double](count: self.cols, repeatedValue: 0.0)
for i in 0 ..< self.cols {
let vector = slice(self.la, rowRange: 0..<self.rows, colRange: i..<i+1)
result[i] = closure(vector)
}
return RMatrix(array: result, rows: 1, cols: self.cols)
}
else if axis == 1 {
result = [Double](count: self.rows, repeatedValue: 0.0)
for i in 0 ..< self.rows {
let vector = slice(self.la, rowRange: i..<i, colRange: 0..<self.cols)
result[i] = closure(vector)
}
return RMatrix(array: result, rows: self.cols, cols: 1)
}
else {
return RMatrix()
}
}
private func slice(la: la_object_t, rowRange: Range<Int>, colRange: Range<Int>) -> [Double]{
let rows = rowRange.endIndex - rowRange.startIndex
let cols = colRange.endIndex - colRange.startIndex
let la = la_matrix_slice( self.la,
la_index_t(rowRange.startIndex),
la_index_t(colRange.startIndex),
1,
1,
la_count_t(rows),
la_count_t(cols) )
var array = [Double](count: rows * cols, repeatedValue: 0.0)
la_matrix_to_double_buffer(&array, la_count_t(rows * cols), la)
return array
}
}
extension Matrix {
public func copy() -> Matrix {
let real = self.real
let imag = self.imag
return Matrix(real: real, imag: imag)
}
public func sort() {
let count = self.rows * self.cols
var array = self.real.flat
vDSP_vsortD(&array, UInt(count), 1)
la_release(self.real.la)
self.real.la = la_matrix_from_double_buffer( array,
la_count_t(self.rows),
la_count_t(self.cols),
la_count_t(self.cols),
la_hint_t(LA_NO_HINT),
la_attribute_t(LA_DEFAULT_ATTRIBUTES))
}
public static func rand(rows: Int, cols: Int) -> Matrix {
let count = rows * cols
var array = [Double](count: count, repeatedValue: 0.0)
var i:__CLPK_integer = 1
var seed:Array<__CLPK_integer> = [1, 2, 3, 5]
var nn: __CLPK_integer = __CLPK_integer(count)
dlarnv_(&i, &seed, &nn, &array)
return Matrix(real: array, rows: rows, cols: cols)
}
public func sum(axis: Int) -> Matrix {
return Matrix(real: self.real.sum(axis), imag: self.imag.sum(axis))
}
public func max(axis: Int) -> Matrix {
return Matrix(real: self.real.max(axis), imag: self.imag.max(axis))
}
public func min(axis: Int) -> Matrix {
return Matrix(real: self.real.min(axis), imag: self.imag.min(axis))
}
public func mean(axis: Int) -> Matrix {
return Matrix(real: self.real.mean(axis), imag: self.imag.mean(axis))
}
public func variance() -> Double {
assert(self.rows > 0 && self.cols > 0)
return self.real.variance()
}
public func std() -> Double {
return self.real.std()
}
public func absolute() -> Matrix{
return Matrix(real:self.real.absolute())
}
public func sqrt() -> Matrix{
return Matrix(real:self.real.sqrt())
}
public func exp() -> Matrix {
return Matrix(real:self.real.exp())
}
public func ln() -> Matrix {
return Matrix(real:self.real.ln())
}
public func log2() -> Matrix {
return Matrix(real:self.real.log2())
}
public func log10() -> Matrix {
return Matrix(real:self.real.log10())
}
public func ceil() -> Matrix {
return Matrix(real:self.real.ceil())
}
public func floor() -> Matrix {
return Matrix(real:self.real.floor())
}
public func round() -> Matrix {
return Matrix(real:self.real.round())
}
public func sin() -> Matrix {
return Matrix(real:self.real.sin())
}
public func cos() -> Matrix {
return Matrix(real:self.real.cos())
}
public func tan() -> Matrix {
return Matrix(real:self.real.tan())
}
public func sinh() -> Matrix {
return Matrix(real:self.real.sinh())
}
public func cosh() -> Matrix {
return Matrix(real:self.real.cosh())
}
public func tanh() -> Matrix {
return Matrix(real:self.real.tanh())
}
public func asinh() -> Matrix {
return Matrix(real:self.real.asinh())
}
public func acosh() -> Matrix {
return Matrix(real:self.real.acosh())
}
public func atanh() -> Matrix {
return Matrix(real:self.real.atanh())
}
}
|
apache-2.0
|
3b4339c5f778f4cef4f51770b9001d1c
| 30.589247 | 96 | 0.527061 | 3.887007 | false | false | false | false |
yunhan0/ChineseChess
|
ChineseChess/Model/Pieces/Bishop.swift
|
1
|
1532
|
//
// Bishop.swift
// ChineseChess
//
// Created by Yunhan Li on 5/15/17.
// Copyright © 2017 Yunhan Li. All rights reserved.
//
import Foundation
class Bishop : Piece {
override func nextPossibleMoves(boardStates: [[Piece?]]) -> [Vector2] {
let possibleMoves: [Vector2] = [
Vector2(x: position.x - 2, y: position.y - 2),
Vector2(x: position.x - 2, y: position.y + 2),
Vector2(x: position.x + 2, y: position.y - 2),
Vector2(x: position.x + 2, y: position.y + 2)
]
var ret: [Vector2] = []
for _move in possibleMoves {
if isValidMove(_move, boardStates) {
ret.append(_move)
}
}
return ret
}
override func isValidMove(_ move: Vector2, _ boardStates: [[Piece?]]) -> Bool {
if Board.isOutOfBoard(move) {
return false
}
// Bishop can not accross the river on the board
if ( Board.getTerritoryOwner(x: move.x) != self.owner) {
return false
}
let nextState = boardStates[move.x][move.y]
if nextState != nil {
if nextState?.owner == self.owner {
return false
}
}
let minrow = min(self.position.x, move.x)
let mincol = min(self.position.y, move.y)
if (boardStates[minrow + 1][mincol + 1] == nil) {
return true
}
return false
}
}
|
mit
|
970b3e4bae5d48f439bb515decc93210
| 25.396552 | 83 | 0.497714 | 3.915601 | false | false | false | false |
wenghengcong/Coderpursue
|
BeeFun/BeeFun/View/User/BFUserDetailController.swift
|
1
|
14855
|
//
// BFUserDetailController.swift
// BeeFun
//
// Created by WengHengcong on 3/10/16.
// Copyright © 2016 JungleSong. All rights reserved.
//
import UIKit
import Moya
import Foundation
import MJRefresh
import ObjectMapper
import Kingfisher
public enum CPUserActionType: String {
case Follow = "watch"
case Repos = "star"
case Following = "fork"
}
class BFUserDetailController: BFBaseViewController {
var developerInfoV: CPDeveloperInfoView = CPDeveloperInfoView(frame: CGRect.zero)
var followBtn: UIButton = UIButton()
var developer: ObjUser?
var cellModels: [JSCellModel] = []
var actionType: CPUserActionType = .Follow
var followed: Bool = false
// MARK: - view cycle
override func viewDidLoad() {
if let username = developer!.name {
self.title = username
} else {
self.title = developer!.login!
}
super.viewDidLoad()
dvc_customView()
dvc_setupTableView()
dvc_getUserinfoRequest()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
dvc_checkUserFollowed()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
// MARK: - view
func dvc_customView() {
self.tableView.isHidden = true
self.developerInfoV.isHidden = true
self.followBtn.isHidden = true
self.rightItemImage = UIImage(named: "nav_share")
self.rightItemSelImage = UIImage(named: "nav_share")
self.rightItem?.isHidden = !ShareManager.shared.enable
self.navigationController?.setNavigationBarHidden(false, animated: false)
self.view.backgroundColor = UIColor.bfViewBackgroundColor
self.view.addSubview(developerInfoV)
self.view.addSubview(tableView)
self.view.addSubview(followBtn)
developerInfoV.frame = CGRect(x: 0, y: uiTopBarHeight, width: ScreenSize.width, height: 183.0)
let tabY = developerInfoV.bottom+15.0
let tabH = ScreenSize.height-tabY
tableView.frame = CGRect(x: 0, y: tabY, width: ScreenSize.width, height: tabH)
developerInfoV.userActionDelegate = self
followBtn.titleLabel?.font = UIFont.bfSystemFont(ofSize: 15.0)
followBtn.backgroundColor = UIColor.bfRedColor
followBtn.radius = 3.0
followBtn.addTarget(self, action: #selector(BFUserDetailController.dvc_followAction), for: UIControlEvents.touchUpInside)
let followX: CGFloat = 10.0
let followW = ScreenSize.width-2*followX
let followH: CGFloat = 40.0
let followY = ScreenSize.height-followH-57.0
followBtn.frame = CGRect(x: followX, y: followY, width: followW, height: followH)
self.dvc_updateFolloweBtn()
}
func dvc_setupTableView() {
refreshHidden = .all
self.automaticallyAdjustsScrollViewInsets = false
}
// MARK: - action
override func headerRefresh() {
super.headerRefresh()
}
override func footerRefresh() {
super.footerRefresh()
}
func dvc_updateFolloweBtn() {
if followed {
followBtn.setTitle("Unfollow".localized, for: UIControlState())
} else {
followBtn.setTitle("Follow".localized, for: UIControlState())
}
}
func dvc_updateViewContent() {
removeReloadView()
tableView.isHidden = false
developerInfoV.isHidden = false
followBtn.isHidden = false
if developer==nil {
return
}
cellModels.removeAll()
if developer!.html_url != nil {
let homeModel = JSCellModel(["type": "image", "id": "homepage", "key": "Homepage".localized, "icon": "user_home", "discolsure": "true"])
cellModels.append(homeModel)
}
if let joinTime: String = developer!.created_at {
let ind = joinTime.characters.index(joinTime.startIndex, offsetBy: 10)
let subStr = joinTime.substring(to: ind)
let join = "Joined on".localized + " "+subStr
let joinModel = JSCellModel(["type": "image", "id": "join", "key": "Join".localized, "icon": "user_time", "value": join, "discolsure": "false"])
cellModels.append(joinModel)
}
if let location: String = developer!.location {
let locModel = JSCellModel(["type": "image", "id": "location", "key": "Location".localized, "icon": "user_loc", "value": location, "discolsure": "false"])
cellModels.append(locModel)
}
if let company = developer!.company {
let companyModel = JSCellModel(["type": "image", "id": "company", "key": "Company".localized, "icon": "user_org", "value": company, "discolsure": "false"])
cellModels.append(companyModel)
}
developerInfoV.developer = developer
self.tableView.reloadData()
}
override func leftItemAction(_ sender: UIButton?) {
_ = self.navigationController?.popViewController(animated: true)
}
override func rightItemAction(_ sender: UIButton?) {
let shareContent: ShareContent = ShareContent()
shareContent.contentType = SSDKContentType.webPage
shareContent.source = .user
if let name = developer?.name {
shareContent.title = name
} else {
shareContent.title = developer?.login
}
shareContent.url = developer?.html_url ?? ""
if let bio = developer?.bio {
shareContent.content = "A Talented Developer".localized + ":\((developer?.login)!)\n" + "\(bio).\n" + "\(shareContent.url!) "+"from BeeFun App".localized+" "+"Download Here".localized + SocialAppStore
} else {
shareContent.content = "A Talented Developer".localized + ":\((developer?.login)!)\n" + "\(shareContent.url!) "+"from BeeFun App".localized+" "+"Download Here".localized + SocialAppStore
}
if let urlStr = developer?.avatar_url {
shareContent.image = urlStr as AnyObject?
ShareManager.shared.share(content: shareContent)
} else {
shareContent.image = UIImage(named: "app_logo_90")
ShareManager.shared.share(content: shareContent)
}
}
@objc func dvc_followAction() {
let follower = UserManager.shared.login ?? "Unknown User"
let befollowed = self.title ?? "Unknown User"
if followBtn.currentTitle == "Follow".localized {
self.dvc_followUserRequest()
AnswerManager.logContentView(name: "Follow", type: UserActionType.follow.rawValue, id: follower, attributes: ["follow": follower, "followed": befollowed])
} else if followBtn.currentTitle == "Unfollow".localized {
self.dvc_unfolloweUserRequest()
AnswerManager.logContentView(name: "UnFollow", type: UserActionType.unfollow.rawValue, id: follower, attributes: ["follow": follower, "followed": befollowed])
}
}
// MARK: - request
/// 是否关注该用户
func dvc_checkUserFollowed() {
if let username = developer!.login {
Provider.sharedProvider.request(.checkUserFollowing(username:username) ) { (result) -> Void in
var message = kNoDataFoundTip
switch result {
case let .success(response):
let statusCode = response.statusCode
if statusCode == BFStatusCode.noContent.rawValue {
self.followed = true
} else {
self.followed = false
}
self.dvc_updateFolloweBtn()
case .failure:
message = kNetworkErrorTip
JSMBHUDBridge.showError(message, view: self.view)
}
}
}
}
func dvc_getUserinfoRequest() {
if let username = developer!.login {
let hud = JSMBHUDBridge.showHud(view: self.view)
Provider.sharedProvider.request(.userInfo(username: username) ) { (result) -> Void in
hud.hide(animated: true)
switch result {
case let .success(response):
do {
if let result: ObjUser = Mapper<ObjUser>().map(JSONObject: try response.mapJSON() ) {
self.developer = result
self.dvc_updateViewContent()
return
} else {
}
} catch {
}
self.showReloadView()
case .failure:
self.showReloadView()
}
}
}
}
override func reconnect() {
super.reconnect()
dvc_getUserinfoRequest()
dvc_checkUserFollowed()
}
func dvc_followUserRequest() {
if let username = developer!.login {
let hud = JSMBHUDBridge.showHud(view: self.view)
Provider.sharedProvider.request(.follow(username:username) ) { (result) -> Void in
hud.hide(animated: true)
var message = kNoDataFoundTip
switch result {
case let .success(response):
let statusCode = response.statusCode
if statusCode == BFStatusCode.noContent.rawValue {
self.followed = true
JSMBHUDBridge.showSuccess("Follow Success".localized, view: self.view)
}
self.dvc_updateFolloweBtn()
case .failure:
message = kNetworkErrorTip
JSMBHUDBridge.showError(message, view: self.view)
}
}
}
}
func dvc_unfolloweUserRequest() {
if let username = developer!.login {
let hud = JSMBHUDBridge.showHud(view: self.view)
Provider.sharedProvider.request(.unfollow(username:username) ) { (result) -> Void in
hud.hide(animated: true)
var message = kNoDataFoundTip
switch result {
case let .success(response):
let statusCode = response.statusCode
if statusCode == BFStatusCode.noContent.rawValue {
self.followed = false
JSMBHUDBridge.showSuccess("UnFollow Success".localized, view: self.view)
}
self.dvc_updateFolloweBtn()
case .failure:
message = kNetworkErrorTip
JSMBHUDBridge.showError(message, view: self.view)
}
}
}
}
}
extension BFUserDetailController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return cellModels.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
let cellModel = cellModels[row]
var cell = tableView.dequeueReusableCell(withIdentifier: "BFUserTypeThirdCellIdentifier") as? JSImageCell
if cell == nil {
cell = JSCellFactory.cell(type: cellModel.type!) as? JSImageCell
}
cell?.model = cellModel
cell?.bothEndsLine(row, all: cellModels.count)
return cell!
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return nil
}
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 10))
view.backgroundColor = UIColor.bfViewBackgroundColor
return view
}
}
extension BFUserDetailController {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return 10
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
let row = indexPath.row
let cellM = cellModels[row]
if cellM.identifier == "homepage" {
JumpManager.shared.jumpWebView(url: self.developer?.html_url)
}
}
}
extension BFUserDetailController: UserProfileActionProtocol {
func viewFollowAction() {
actionType = .Follow
segueGotoViewController()
}
func viewReposAction() {
actionType = .Repos
segueGotoViewController()
}
func viewFollowingAction() {
actionType = .Following
segueGotoViewController()
}
func segueGotoViewController() {
if !UserManager.shared.isLogin {
JSMBHUDBridge.showError(kLoginFirstTip, view: self.view)
return
}
switch actionType {
case .Follow:
let uname = developer!.login
let dic: [String: String] = ["uname": uname!, "type": "follower"]
let vc = BFUserListController()
vc.hidesBottomBarWhenPushed = true
vc.dic = dic
vc.username = dic["uname"]
vc.viewType = dic["type"]
self.navigationController?.pushViewController(vc, animated: true)
case .Repos:
let uname = developer!.login
let dic: [String: String] = ["uname": uname!, "type": "myrepositories"]
let vc = BFRepoListController()
vc.hidesBottomBarWhenPushed = true
vc.dic = dic
vc.username = dic["uname"]
vc.viewType = dic["type"]
self.navigationController?.pushViewController(vc, animated: true)
case .Following:
let uname = developer!.login
let dic: [String: String] = ["uname": uname!, "type": "following"]
let vc = BFUserListController()
vc.hidesBottomBarWhenPushed = true
vc.dic = dic
vc.username = dic["uname"]
vc.viewType = dic["type"]
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
mit
|
f37e5040e0740a90190cf8ebe4b69ee7
| 32.881279 | 214 | 0.572844 | 4.848089 | false | false | false | false |
hstdt/GodEye
|
Carthage/Checkouts/SystemEye/SystemEye/Classes/Network.swift
|
1
|
4008
|
//
// Network.swift
// Pods
//
// Created by zixun on 17/1/20.
//
//
import Foundation
import CoreTelephony
open class Network: NSObject {
//--------------------------------------------------------------------------
// MARK: OPEN PROPERTY
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// MARK: CTCarrier
//--------------------------------------------------------------------------
/// mobile carrier name
open static var carrierName: String? {
get {
return self.carrier?.carrierName
}
}
/// mobile carrier country
open static var carrierCountry: String? {
get {
let currentCountry = Locale.current as NSLocale
return currentCountry.object(forKey: NSLocale.Key.countryCode) as? String
}
}
/// mobile carrier country code
open static var carrierMobileCountryCode: String? {
get {
return self.carrier?.mobileCountryCode
}
}
/// get the carrier iso country code
open static var carrierISOCountryCode: String? {
get {
return self.carrier?.isoCountryCode
}
}
/// get the carrier mobile network code
open static var carrierMobileNetworkCode: String? {
get {
return self.carrier?.mobileNetworkCode
}
}
open static var carrierAllowVOIP: Bool {
get {
return self.carrier?.allowsVOIP ?? false
}
}
//--------------------------------------------------------------------------
// MARK: WIFI
//--------------------------------------------------------------------------
open static var isConnectedToWifi: Bool {
get {
guard let address = self.wifiIPAddress else {
return false
}
guard address.characters.count <= 0 else {
return false
}
return true
}
}
open static var wifiIPAddress: String? {
get {
return NetObjc.wifiIPAddress()
}
}
open static var wifiNetmaskAddress: String? {
get {
return NetObjc.wifiNetmaskAddress()
}
}
//--------------------------------------------------------------------------
// MARK: CELL
//--------------------------------------------------------------------------
open static var isConnectedToCell: Bool {
get {
guard let address = self.cellIPAddress else {
return false
}
guard address.characters.count <= 0 else {
return false
}
return true
}
}
open static var cellIPAddress: String? {
get {
return NetObjc.cellIPAddress()
}
}
open static var cellNetmaskAddress: String? {
get {
return NetObjc.cellNetmaskAddress()
}
}
//--------------------------------------------------------------------------
// MARK: NETWORK FLOW
//--------------------------------------------------------------------------
open static func flow() -> (wifiSend: UInt32,
wifiReceived: UInt32,
wwanSend: UInt32,
wwanReceived: UInt32) {
let flow = NetObjc.flow()
return (flow.wifiSend,flow.wifiReceived,flow.wwanSend,flow.wwanReceived)
}
//--------------------------------------------------------------------------
// MARK: PRIVATE PROPERTY
//--------------------------------------------------------------------------
private static var carrier: CTCarrier? {
get {
return CTTelephonyNetworkInfo().subscriberCellularProvider
}
}
}
|
mit
|
c19c750ea89638cf466bb05f3e620813
| 27.225352 | 85 | 0.39496 | 6.311811 | false | false | false | false |
Raizlabs/ios-template
|
PRODUCTNAME/app/Pods/BonMot/Sources/UIKit/StyleableUIElement.swift
|
1
|
9699
|
//
// StyleableUIElement.swift
// BonMot
//
// Created by Brian King on 8/11/16.
// Copyright © 2016 Raizlabs. All rights reserved.
//
import UIKit
extension UILabel {
/// The name of a style in the global `NamedStyles` registry. The getter
/// always returns `nil`, and should not be used.
@IBInspectable
public var bonMotStyleName: String? {
get { return nil }
set { bonMotStyle = StyleableUIElementHelpers.lookUpSharedStyle(for: newValue, font: font) }
}
/// A string style. Stored via associated objects.
public final var bonMotStyle: StringStyle? {
get { return StyleableUIElementHelpers.getAssociatedStyle(from: self) }
set {
StyleableUIElementHelpers.setAssociatedStyle(on: self, style: newValue)
styledText = text
}
}
/// Update this property to style the incoming text via the `bonMotStyle`
/// and set it as the receiver's `attributedText`.
@objc(bon_styledText)
public var styledText: String? {
get { return attributedText?.string }
set { attributedText = StyleableUIElementHelpers.styledAttributedString(from: newValue, style: bonMotStyle, traitCollection: traitCollection) }
}
}
extension UITextField {
/// The name of a style in the global `NamedStyles` registry. The getter
/// always returns `nil`, and should not be used.
///
/// - note: The style is applied to both the `attributedText` and
/// `defaultTextAttributes`. If you plan on styling them differently, use
/// attributed strings directly.
@IBInspectable
public var bonMotStyleName: String? {
get { return nil }
set {
guard let font = font else { fatalError("Unable to get the font. This is unexpected, see UIKitTests.testTextFieldPropertyBehavior") }
bonMotStyle = StyleableUIElementHelpers.lookUpSharedStyle(for: newValue, font: font)
}
}
/// A string style. Stored via associated objects.
/// - note: The style is applied to both the `attributedText` and
/// `attributedPlaceholder`. If you plan on styling them differently, use
/// attributed strings directly.
public final var bonMotStyle: StringStyle? {
get { return StyleableUIElementHelpers.getAssociatedStyle(from: self) }
set {
StyleableUIElementHelpers.setAssociatedStyle(on: self, style: newValue)
styledText = text
let attributes = (bonMotStyle?.attributes(adaptedTo: traitCollection) ?? [:])
#if swift(>=4.2)
defaultTextAttributes = attributes
#else
defaultTextAttributes = attributes.withStringKeys
#endif
}
}
/// Update this property to style the incoming text via the `bonMotStyle`
/// and set it as the receiver's `attributedText`.
@objc(bon_styledText)
public var styledText: String? {
get { return attributedText?.string }
set {
let styledText = StyleableUIElementHelpers.styledAttributedString(from: newValue, style: bonMotStyle, traitCollection: traitCollection)
// Set the font first to avoid a bug that causes UITextField to hang
if let styledText = styledText {
if styledText.length > 0 {
font = styledText.attribute(.font, at: 0, effectiveRange: nil) as? UIFont
}
}
attributedText = styledText
}
}
}
extension UITextView {
/// The name of a style in the global `NamedStyles` registry. The getter
/// always returns `nil`, and should not be used.
///
/// - note: The style is applied to both the `attributedText` and
/// `typingAttributes`. If you plan on styling them differently, use
/// attributed strings directly.
@IBInspectable
public var bonMotStyleName: String? {
get { return nil }
set {
let font: UIFont
if let configuredFont = self.font {
font = configuredFont
}
else {
// If the text property is not and has not been set, the font property is nil. Use the platform specific default values here
// See UIKitTests.testTextFieldPropertyBehavior
#if os(iOS)
font = UIFont.systemFont(ofSize: 12)
#elseif os(tvOS)
font = UIFont.systemFont(ofSize: 38)
#else
fatalError("Unsupported Mystery Platform")
#endif
}
bonMotStyle = StyleableUIElementHelpers.lookUpSharedStyle(for: newValue, font: font)
}
}
/// A string style. Stored via associated objects.
/// - note: The style is applied to both the `attributedText` and
/// `typingAtributes`. If you plan on styling them differently, use
/// attributed strings directly.
public final var bonMotStyle: StringStyle? {
get { return StyleableUIElementHelpers.getAssociatedStyle(from: self) }
set {
StyleableUIElementHelpers.setAssociatedStyle(on: self, style: newValue)
#if swift(>=4.2)
typingAttributes = newValue?.attributes(adaptedTo: traitCollection) ?? typingAttributes
#else
typingAttributes = newValue?.attributes(adaptedTo: traitCollection).withStringKeys ?? typingAttributes
#endif
styledText = text
}
}
/// Update this property to style the incoming text via the `bonMotStyle`
/// and set it as the receiver's `attributedText`.
@objc(bon_styledText)
public var styledText: String? {
get { return attributedText?.string }
set {
attributedText = StyleableUIElementHelpers.styledAttributedString(from: newValue, style: bonMotStyle, traitCollection: traitCollection)
}
}
}
extension UIButton {
/// The name of a style in the global `NamedStyles` registry. The getter
/// always returns `nil`, and should not be used.
@IBInspectable
public var bonMotStyleName: String? {
get { return nil }
set {
guard let font = titleLabel?.font else { fatalError("Unable to get the font. This is unexpected; see UIKitTests.testTextFieldPropertyBehavior") }
bonMotStyle = StyleableUIElementHelpers.lookUpSharedStyle(for: newValue, font: font)
}
}
/// A string style. Stored via associated objects.
public final var bonMotStyle: StringStyle? {
get { return StyleableUIElementHelpers.getAssociatedStyle(from: self) }
set {
StyleableUIElementHelpers.setAssociatedStyle(on: self, style: newValue)
styledText = titleLabel?.text
}
}
/// Update this property to style the incoming text via the `bonMotStyle`
/// and set it as the receiver's attributed text for the "normal" state.
@objc(bon_styledText)
public var styledText: String? {
get { return titleLabel?.text }
set {
let styledText = StyleableUIElementHelpers.styledAttributedString(from: newValue, style: bonMotStyle, traitCollection: traitCollection)
setAttributedTitle(styledText, for: .normal)
}
}
}
/// Helper for the bonMotStyle associated objects.
private var containerHandle: UInt8 = 0
private enum StyleableUIElementHelpers {
static func getAssociatedStyle(from object: AnyObject) -> StringStyle? {
let adaptiveFunctionContainer = objc_getAssociatedObject(object, &containerHandle) as? StringStyleHolder
return adaptiveFunctionContainer?.style
}
static func setAssociatedStyle(on object: AnyObject, style: StringStyle?) {
var adaptiveFunction: StringStyleHolder?
if let bonMotStyle = style {
adaptiveFunction = StringStyleHolder(style: bonMotStyle)
}
objc_setAssociatedObject(
object, &containerHandle,
adaptiveFunction,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
static func styledAttributedString(from string: String?, style: StringStyle?, traitCollection: UITraitCollection) -> NSAttributedString? {
guard let string = string else { return nil }
let attributedString = (style ?? StringStyle()).attributedString(from: string)
return attributedString.adapted(to: traitCollection)
}
static func lookUpSharedStyle(for name: String?, font: UIFont) -> StringStyle? {
guard let name = name, let style = NamedStyles.shared.style(forName: name) else {
return nil
}
// Create a style with the font and then add the named style.
// This will provide a font if one is not specified in the style.
return StringStyle(.font(font)).byAdding(stringStyle: style)
}
}
@objc(BONStringStyleHolder)
internal class StringStyleHolder: NSObject {
let style: StringStyle
init(style: StringStyle) {
self.style = style
}
}
extension Dictionary where Key: RawRepresentable, Key.RawValue == String {
var withStringKeys: [String: Value] {
var newDict: [String: Value] = [:]
for (key, value) in self {
newDict[key.rawValue] = value
}
return newDict
}
}
extension Dictionary where Key == String {
func withTypedKeys<KeyType>() -> [KeyType: Value] where KeyType: RawRepresentable, KeyType.RawValue == String {
var newDict: [KeyType: Value] = [:]
for (key, value) in self {
if let newKey = KeyType(rawValue: key) {
newDict[newKey] = value
}
}
return newDict
}
}
|
mit
|
835607c36264a3bd7def859d66f87662
| 35.874525 | 157 | 0.642091 | 4.880725 | false | false | false | false |
lhc70000/iina
|
iina/FileGroup.swift
|
1
|
4818
|
//
// FileGroup.swift
// iina
//
// Created by lhc on 20/5/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
fileprivate let charSetGroups: [CharacterSet] = [.decimalDigits, .letters]
fileprivate let subsystem = Logger.Subsystem(rawValue: "fgroup")
class FileInfo: Hashable {
var url: URL
var path: String
var filename: String
var ext: String
var nameInSeries: String?
var characters: [Character]
var dist: [FileInfo: UInt] = [:]
var minDist: [FileInfo] = []
var relatedSubs: [FileInfo] = []
var priorityStringOccurances = 0
var isMatched = false
var prefix: String { // prefix detected by FileGroup
didSet {
if prefix.count < self.characters.count {
suffix = String(filename[filename.index(filename.startIndex, offsetBy: prefix.count)...])
getNameInSeries()
} else {
prefix = ""
suffix = self.filename
}
}
}
var suffix: String // filename - prefix
init(_ url: URL) {
self.url = url
self.path = url.path
self.ext = url.pathExtension
self.filename = url.deletingPathExtension().lastPathComponent
self.characters = [Character](self.filename)
self.prefix = ""
self.suffix = self.filename
}
private func getNameInSeries() {
// e.g. "abc_" "ch01_xxx" -> "ch01"
var firstDigit = false
let name = suffix.unicodeScalars.prefix {
if CharacterSet.decimalDigits.contains($0) {
if !firstDigit {
firstDigit = true
}
} else {
if firstDigit {
return false
}
}
return true
}
self.nameInSeries = String(name)
}
var hashValue: Int {
return path.hashValue
}
static func == (lhs: FileInfo, rhs: FileInfo) -> Bool {
return lhs.path == rhs.path
}
}
class FileGroup {
var prefix: String
var contents: [FileInfo]
var groups: [FileGroup]
private let chineseNumbers: [Character] = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]
static func group(files: [FileInfo]) -> FileGroup {
Logger.log("Start grouping \(files.count) files", subsystem: subsystem)
let group = FileGroup(prefix: "", contents: files)
group.tryGroupFiles()
return group
}
init(prefix: String, contents: [FileInfo] = []) {
self.prefix = prefix
self.contents = contents
self.groups = []
}
private func tryGroupFiles() {
Logger.log("Try group files, prefix=\(prefix), count=\(contents.count)", level: .verbose, subsystem: subsystem)
guard contents.count >= 3 else {
Logger.log("Contents count < 3, skipped", level: .verbose, subsystem: subsystem)
return
}
var tempGroup: [String: [FileInfo]] = [:]
var currChars: [(Character, String)] = []
var i = prefix.count
while tempGroup.count < 2 {
var lastPrefix = ""
for finfo in contents {
// if reached string end
if i >= finfo.characters.count {
tempGroup[prefix, default: []].append(finfo)
currChars.append(("/", prefix))
continue
}
let c = finfo.characters[i]
var p = prefix
p.append(c)
lastPrefix = p
if tempGroup[p] == nil {
tempGroup[p] = []
currChars.append((c, p))
}
tempGroup[p]!.append(finfo)
}
// if all items have the same prefix
if tempGroup.count == 1 {
prefix = lastPrefix
tempGroup.removeAll()
currChars.removeAll()
}
i += 1
}
let maxSubGroupCount = tempGroup.reduce(0, { max($0, $1.value.count) })
if stopGrouping(currChars) || maxSubGroupCount < 3 {
Logger.log("Stop groupping, maxSubGroup=\(maxSubGroupCount)", level: .verbose, subsystem: subsystem)
contents.forEach { $0.prefix = self.prefix }
} else {
Logger.log("Continue grouping, groups=\(tempGroup.count), chars=\(currChars)", level: .verbose, subsystem: subsystem)
groups = tempGroup.map { FileGroup(prefix: $0.0, contents: $0.1) }
// continue
for g in groups {
g.tryGroupFiles()
}
}
}
func flatten() -> [String: [FileInfo]] {
var result: [String: [FileInfo]] = [:]
var search: ((FileGroup) -> Void)!
search = { group in
if group.groups.count > 0 {
for g in group.groups {
search(g)
}
} else {
result[group.prefix] = group.contents
}
}
search(self)
return result
}
private func stopGrouping(_ chars: [(Character, String)]) -> Bool {
var chineseNumberCount = 0
for (c, _) in chars {
if c >= "0" && c <= "9" { return true }
// chinese characters
if chineseNumbers.contains(c) { chineseNumberCount += 1 }
if chineseNumberCount >= 3 { return true }
}
return false
}
}
|
gpl-3.0
|
495c41b5ada4150bb6e2ca3eddfcf1cf
| 25.638889 | 123 | 0.594369 | 3.817675 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.