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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nathawes/swift
|
test/SPI/run_spi_client.swift
|
21
|
1202
|
/// Compile an SPI lib and client
// RUN: %empty-directory(%t)
/// Compile the lib with SPI decls
// RUN: %target-build-swift-dylib(%t/%target-library-name(SPIHelper)) %S/Inputs/spi_helper.swift -emit-module -emit-module-path %t/SPIHelper.swiftmodule -module-name SPIHelper -enable-library-evolution
// RUN: %target-codesign %t/%target-library-name(SPIHelper)
/// Client with SPI access
// RUN: %target-swiftc_driver -I %t -L %t %s -o %t/spi_client -lSPIHelper %target-rpath(%t)
// RUN: %target-codesign %t/spi_client
// RUN: %target-run %t/spi_client %t/%target-library-name(SPIHelper) > %t/output
// RUN: %FileCheck %s < %t/output
// REQUIRES: executable_test
@_spi(HelperSPI) import SPIHelper
publicFunc()
// CHECK: publicFunc
spiFunc()
// CHECK: spiFunc
var c = SPIClass()
// CHECK: SPIClass.init
c.spiMethod()
// CHECK: SPIClass.spiMethod
c.spiVar = "write"
print(c.spiVar)
// CHECK: write
var s = SPIStruct()
// CHECK: SPIStruct.init
s.spiMethod()
// CHECK: SPIStruct.spiMethod
s.spiVar = "write"
print(s.spiVar)
// CHECK: write
var e = SPIEnum()
// CHECK: SPIEnum.init
e.spiMethod()
// CHECK: SPIEnum.spiMethod
var ps = PublicStruct()
ps.spiMethod()
// CHECK: PublicStruct.spiMethod
|
apache-2.0
|
b88fd2586d0c742a60a06486b6018570
| 23.530612 | 201 | 0.705491 | 3.050761 | false | false | false | false |
crazypoo/PTools
|
Pods/JXSegmentedView/Sources/Indicator/JXSegmentedIndicatorParams.swift
|
1
|
2364
|
//
// JXSegmentedIndicatorParamsModel.swift
// JXSegmentedView
//
// Created by jiaxin on 2018/12/26.
// Copyright © 2018 jiaxin. All rights reserved.
//
import Foundation
import UIKit
/**
指示器传递的数据模型,不同情况会对不同的属性赋值,根据不同情况的api说明确认。
为什么会通过model传递数据,因为指示器处理逻辑以后会扩展不同的使用场景,会新增参数。如果不通过model传递,就会在api新增参数,一旦修改api修改的地方就特别多了,而且会影响到之前自定义实现的开发者。
*/
public struct JXSegmentedIndicatorSelectedParams {
public let currentSelectedIndex: Int
public let currentSelectedItemFrame: CGRect
public let selectedType: JXSegmentedViewItemSelectedType
public let currentItemContentWidth: CGFloat
/// collectionView的contentSize
public var collectionViewContentSize: CGSize?
public init(currentSelectedIndex: Int, currentSelectedItemFrame: CGRect, selectedType: JXSegmentedViewItemSelectedType, currentItemContentWidth: CGFloat, collectionViewContentSize: CGSize?) {
self.currentSelectedIndex = currentSelectedIndex
self.currentSelectedItemFrame = currentSelectedItemFrame
self.selectedType = selectedType
self.currentItemContentWidth = currentItemContentWidth
self.collectionViewContentSize = collectionViewContentSize
}
}
public struct JXSegmentedIndicatorTransitionParams {
public let currentSelectedIndex: Int
public let leftIndex: Int
public let leftItemFrame: CGRect
public let rightIndex: Int
public let rightItemFrame: CGRect
public let leftItemContentWidth: CGFloat
public let rightItemContentWidth: CGFloat
public let percent: CGFloat
public init(currentSelectedIndex: Int, leftIndex: Int, leftItemFrame: CGRect, leftItemContentWidth: CGFloat, rightIndex: Int, rightItemFrame: CGRect, rightItemContentWidth: CGFloat, percent: CGFloat) {
self.currentSelectedIndex = currentSelectedIndex
self.leftIndex = leftIndex
self.leftItemFrame = leftItemFrame
self.leftItemContentWidth = leftItemContentWidth
self.rightIndex = rightIndex
self.rightItemFrame = rightItemFrame
self.rightItemContentWidth = rightItemContentWidth
self.percent = percent
}
}
|
mit
|
aa23c4a83eb01b64bf5a1284caa8c982
| 39.596154 | 205 | 0.778778 | 4.943794 | false | false | false | false |
qihuang2/Game3
|
Game3/Entity/CurrentSceneHUDSprite.swift
|
1
|
2242
|
//
// CurrentSceneHUDSprite.swift
// Game2
//
// Created by Qi Feng Huang on 7/3/15.
// Copyright (c) 2015 Qi Feng Huang. All rights reserved.
//
import SpriteKit
//
// USED TO SHOW WHICH SET OF LEVELS THE PLAYER IS VIEWING
//
class CurrentSceneHUDSprite: SKSpriteNode {
private var spriteArray:[SKShapeNode] = [SKShapeNode]()
private var currentlyActiveCircle:Int
private let CIRCLE_RADIUS:CGFloat = 10
private let CIRCLE_PLUS_SPACE:CGFloat = 40
private let ACTIVE_COLOR:UIColor = COLORS_USED.ORANGE //orange when on scene
private let INACTIVE_COLOR:UIColor = COLORS_USED.LIGHT_GREY //grey when now on scene
init(numberOfScenes:Int, activeCircle: Int){
self.currentlyActiveCircle = activeCircle
super.init(texture: nil, color: UIColor.clearColor(), size: CGSize(width: CIRCLE_PLUS_SPACE * CGFloat(numberOfScenes), height: CIRCLE_PLUS_SPACE * CGFloat(numberOfScenes)))
setUpShapes(numberOfScenes)
activateCircle(activeCircle)
}
private func setUpShapes(numOfCircles: Int){
let backgroundWidth:CGFloat = CIRCLE_PLUS_SPACE * CGFloat(numOfCircles)
let midpoint = backgroundWidth / 2
for sqNum in 0..<numOfCircles{
let circle:SKShapeNode = SKShapeNode(circleOfRadius: CIRCLE_RADIUS)
circle.fillColor = INACTIVE_COLOR
circle.lineWidth = 0
self.addChild(circle)
circle.position = CGPoint(x: -midpoint + (CIRCLE_PLUS_SPACE/2) + (CGFloat(sqNum) * CIRCLE_PLUS_SPACE), y: 0)
spriteArray.append(circle)
}
}
private func activateCircle(index: Int){
self.spriteArray[index].fillColor = ACTIVE_COLOR
self.spriteArray[index].setScale(1.2)
}
private func deactiveCircle(index: Int){
self.spriteArray[index].fillColor = INACTIVE_COLOR
self.spriteArray[index].setScale(1)
}
func changeActivatedCircle(index: Int){
deactiveCircle(currentlyActiveCircle)
self.currentlyActiveCircle = index
activateCircle(index)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
b45672bdda26a3392bee17a02c9d6f9c
| 31.492754 | 180 | 0.661463 | 4.106227 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
SwiftGL-Demo/Source/iOS/StrokeSelecter.swift
|
1
|
2633
|
//
// StrokeSelecter.swift
// SwiftGL
//
// Created by jerry on 2016/5/8.
// Copyright © 2016年 Jerry Chan. All rights reserved.
//
import SwiftGL
import GLFramework
class StrokeSelecter {
var area:GLRect!
var selectRectView:SelectRectView!
var originalClip:PaintClip!
var selectingClip:PaintClip!
var selectedStrokes:[PaintStroke] = []
var isSelectingClip:Bool = false
init()
{
selectingClip = PaintClip(name: "selecting", branchAt: 0)
selectingClip.strokeDelegate = PaintViewController.instance
}
convenience init(selectRectView:SelectRectView)
{
self.init()
self.selectRectView = selectRectView
}
var lastPoint:Vec2!
var selectingPolyPoints:[Vec2]!
func startSelectPolygon()
{
selectingPolyPoints = []
}
func addSelectPoint(_ point:Vec2)
{
DLog("\(point)")
selectingPolyPoints.append(point)
//testStrokes(point)
}
func selectStrokesInPolygon()->[PaintStroke]
{
return selectStrokesInPolygon(selectingPolyPoints)
}
//select strokes from a polygon area
func selectStrokesInPolygon(_ points:[Vec2])->[PaintStroke]
{
selectedStrokes = []
area = nil
DLog("\(points)")
for stroke in originalClip.strokes {
DLog("\(stroke.bound)")
if stroke.bound.center.isInsidePolygon(points)
{
selectedStrokes.append(stroke)
expand(stroke)
}
}
if area != nil
{
selectRectView.redraw(area)
}
selectingClip.strokes = selectedStrokes
return selectedStrokes
}
func testStrokes(_ point:Vec2)->[PaintStroke]
{
let strokes = originalClip.selectStrokes(point)
selectedStrokes = strokes
return strokes
}
func expand(_ stroke:PaintStroke)
{
DLog("\(stroke.bound)")
if area == nil
{
area = stroke.bound
}
else
{
area.union(stroke.bound)
}
}
func exitSelectionMode()
{
selectedStrokes = []
}
}
extension Vec2 {
func isInsidePolygon(_ vertices: [Vec2]) -> Bool {
guard !vertices.isEmpty else { return false }
var j = vertices.last!, c = false
for i in vertices {
let a = (i.y > y) != (j.y > y)
let b = (x < (j.x - i.x) * (y - i.y) / (j.y - i.y) + i.x)
if a && b { c = !c }
j = i
}
return c
}
}
|
mit
|
72242c19dcb42e1f5d8a29ea4c53e878
| 22.693694 | 69 | 0.547148 | 4.304419 | false | false | false | false |
rugheid/Swift-MathEagle
|
MathEagle/Functions/ArrayGenerators.swift
|
1
|
960
|
//
// ArrayGenerators.swift
// MathEagle
//
// Created by Rugen Heidbuchel on 31/05/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
import Foundation
/**
Returns an array of the given length. The first element is the given initial value.
Following elements will be incremented by increment.
- parameter length: The number of elements the array should have.
- parameter initialValue: The first value of the array. Default 0.
- parameter increment: The difference between two adjecent elements. Default 1.
:example: rampedArray(length: 4, initialValue: 2, increment: 3) will return
[2, 5, 8, 11]
*/
public func rampedArray <T: ExpressibleByIntegerLiteral & Addable> (length: Int, initialValue: T = 0, increment: T = 1) -> [T] {
var array = [T]()
var element = initialValue
for _ in 0 ..< length {
array.append(element)
element = element + increment
}
return array
}
|
mit
|
76c6f5fa03634309de3382dd43943a8d
| 26.428571 | 128 | 0.682292 | 3.983402 | false | false | false | false |
MrZoidberg/metapp
|
metapp/Pods/RealmSwift/RealmSwift/RealmCollection.swift
|
20
|
61349
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
#if swift(>=3.0)
/**
An iterator for a `RealmCollection` instance.
*/
public final class RLMIterator<T: Object>: IteratorProtocol {
private var i: UInt = 0
private let generatorBase: NSFastEnumerationIterator
init(collection: RLMCollection) {
generatorBase = NSFastEnumerationIterator(collection)
}
/// Advance to the next element and return it, or `nil` if no next element exists.
public func next() -> T? { // swiftlint:disable:this valid_docs
let accessor = generatorBase.next() as! T?
if let accessor = accessor {
RLMInitializeSwiftAccessorGenerics(accessor)
}
return accessor
}
}
/**
A `RealmCollectionChange` value encapsulates information about changes to collections
that are reported by Realm notifications.
The change information is available in two formats: a simple array of row
indices in the collection for each type of change, and an array of index paths
in a requested section suitable for passing directly to `UITableView`'s batch
update methods.
The arrays of indices in the `.Update` case follow `UITableView`'s batching
conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths.
For example, for a simple one-section table view, you can do the following:
```swift
self.notificationToken = results.addNotificationBlock { changes in
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
self.tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the TableView
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.endUpdates()
break
case .error(let err):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(err)")
break
}
}
```
*/
public enum RealmCollectionChange<T> {
/**
`.initial` indicates that the initial run of the query has completed (if applicable), and the collection can now be
used without performing any blocking work.
*/
case initial(T)
/**
`.update` indicates that a write transaction has been committed which either changed which objects
are in the collection, and/or modified one or more of the objects in the collection.
All three of the change arrays are always sorted in ascending order.
- parameter deletions: The indices in the previous version of the collection which were removed from this one.
- parameter insertions: The indices in the new collection which were added in this version.
- parameter modifications: The indices of the objects in the new collection which were modified in this version.
*/
case update(T, deletions: [Int], insertions: [Int], modifications: [Int])
/**
If an error occurs, notification blocks are called one time with a `.error` result and an `NSError` containing
details about the error. This can only currently happen if the Realm is opened on a background worker thread to
calculate the change set.
*/
case error(Error)
static func fromObjc(value: T, change: RLMCollectionChange?, error: Error?) -> RealmCollectionChange {
if let error = error {
return .error(error)
}
if let change = change {
return .update(value,
deletions: change.deletions as [Int],
insertions: change.insertions as [Int],
modifications: change.modifications as [Int])
}
return .initial(value)
}
}
/**
A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
*/
public protocol RealmCollection: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible {
/// The type of the objects contained in the collection.
associatedtype Element: Object
// MARK: Properties
/// The Realm which manages the collection, or `nil` for unmanaged collections.
var realm: Realm? { get }
/**
Indicates if the collection can no longer be accessed.
The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection.
*/
var isInvalidated: Bool { get }
/// The number of objects in the collection.
var count: Int { get }
/// A human-readable description of the objects contained in the collection.
var description: String { get }
// MARK: Index Retrieval
/**
Returns the index of an object in the collection, or `nil` if the object is not present.
- parameter object: An object.
*/
func index(of object: Element) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate to use to filter the objects.
*/
func index(matching predicate: NSPredicate) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func index(matching predicateFormat: String, _ args: Any...) -> Int?
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element>
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate to use to filter the objects.
*/
func filter(_ predicate: NSPredicate) -> Results<Element>
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byProperty: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter property: The name of the property to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted(byProperty property: String, ascending: Bool) -> Results<Element>
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byProperty:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func min<U: MinMaxType>(ofProperty property: String) -> U?
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func max<U: MinMaxType>(ofProperty property: String) -> U?
/**
Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
*/
func sum<U: AddableType>(ofProperty property: String) -> U
/**
Returns the sum of the values of a given property over all the objects in the collection.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
func average<U: AddableType>(ofProperty property: String) -> U?
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
func value(forKey key: String) -> Any?
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
func value(forKeyPath keyPath: String) -> Any?
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
func setValue(_ value: Any?, forKey key: String)
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken
/// :nodoc:
func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
}
private class _AnyRealmCollectionBase<T: Object> {
typealias Wrapper = AnyRealmCollection<Element>
typealias Element = T
var realm: Realm? { fatalError() }
var isInvalidated: Bool { fatalError() }
var count: Int { fatalError() }
var description: String { fatalError() }
func index(of object: Element) -> Int? { fatalError() }
func index(matching predicate: NSPredicate) -> Int? { fatalError() }
func index(matching predicateFormat: String, _ args: Any...) -> Int? { fatalError() }
func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { fatalError() }
func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() }
func sorted(byProperty property: String, ascending: Bool) -> Results<Element> { fatalError() }
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor {
fatalError()
}
func min<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() }
func max<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() }
func sum<U: AddableType>(ofProperty property: String) -> U { fatalError() }
func average<U: AddableType>(ofProperty property: String) -> U? { fatalError() }
subscript(position: Int) -> Element { fatalError() }
func makeIterator() -> RLMIterator<T> { fatalError() }
var startIndex: Int { fatalError() }
var endIndex: Int { fatalError() }
func value(forKey key: String) -> Any? { fatalError() }
func value(forKeyPath keyPath: String) -> Any? { fatalError() }
func setValue(_ value: Any?, forKey key: String) { fatalError() }
func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { fatalError() }
}
private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> {
let base: C
init(base: C) {
self.base = base
}
// MARK: Properties
override var realm: Realm? { return base.realm }
override var isInvalidated: Bool { return base.isInvalidated }
override var count: Int { return base.count }
override var description: String { return base.description }
// MARK: Index Retrieval
override func index(of object: C.Element) -> Int? { return base.index(of: object) }
override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
override func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
override func filter(_ predicateFormat: String, _ args: Any...) -> Results<C.Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
// MARK: Sorting
override func sorted(byProperty property: String, ascending: Bool) -> Results<C.Element> {
return base.sorted(byProperty: property, ascending: ascending)
}
override func sorted<S: Sequence>
(by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor {
return base.sorted(by: sortDescriptors)
}
// MARK: Aggregate Operations
override func min<U: MinMaxType>(ofProperty property: String) -> U? {
return base.min(ofProperty: property)
}
override func max<U: MinMaxType>(ofProperty property: String) -> U? {
return base.max(ofProperty: property)
}
override func sum<U: AddableType>(ofProperty property: String) -> U {
return base.sum(ofProperty: property)
}
override func average<U: AddableType>(ofProperty property: String) -> U? {
return base.average(ofProperty: property)
}
// MARK: Sequence Support
override subscript(position: Int) -> C.Element {
// FIXME: it should be possible to avoid this force-casting
return unsafeBitCast(base[position as! C.Index], to: C.Element.self)
}
override func makeIterator() -> RLMIterator<Element> {
// FIXME: it should be possible to avoid this force-casting
return base.makeIterator() as! RLMIterator<Element>
}
// MARK: Collection Support
override var startIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.startIndex as! Int
}
override var endIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.endIndex as! Int
}
// MARK: Key-Value Coding
override func value(forKey key: String) -> Any? { return base.value(forKey: key) }
override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/// :nodoc:
override func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { return base._addNotificationBlock(block) }
}
/**
A type-erased `RealmCollection`.
Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type.
*/
public final class AnyRealmCollection<T: Object>: RealmCollection {
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// The type of the objects contained in the collection.
public typealias Element = T
private let base: _AnyRealmCollectionBase<T>
/// Creates an `AnyRealmCollection` wrapping `base`.
public init<C: RealmCollection>(_ base: C) where C.Element == T {
self.base = _AnyRealmCollection(base: base)
}
// MARK: Properties
/// The Realm which manages the collection, or `nil` if the collection is unmanaged.
public var realm: Realm? { return base.realm }
/**
Indicates if the collection can no longer be accessed.
The collection can no longer be accessed if `invalidate()` is called on the containing `realm`.
*/
public var isInvalidated: Bool { return base.isInvalidated }
/// The number of objects in the collection.
public var count: Int { return base.count }
/// A human-readable description of the objects contained in the collection.
public var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
- parameter object: An object.
*/
public func index(of object: Element) -> Int? { return base.index(of: object) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate with which to filter the objects.
- returns: A `Results` containing objects that match the given predicate.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byProperty: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter property: The name of the property to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byProperty property: String, ascending: Bool) -> Results<Element> {
return base.sorted(byProperty: property, ascending: ascending)
}
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byProperty:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return base.sorted(by: sortDescriptors)
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<U: MinMaxType>(ofProperty property: String) -> U? {
return base.min(ofProperty: property)
}
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func max<U: MinMaxType>(ofProperty property: String) -> U? {
return base.max(ofProperty: property)
}
/**
Returns the sum of the values of a given property over all the objects in the collection.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<U: AddableType>(ofProperty property: String) -> U { return base.sum(ofProperty: property) }
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<U: AddableType>(ofProperty property: String) -> U? { return base.average(ofProperty: property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: The index.
*/
public subscript(position: Int) -> T { return base[position] }
/// Returns a `RLMIterator` that yields successive elements in the collection.
public func makeIterator() -> RLMIterator<T> { return base.makeIterator() }
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return base.startIndex }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return base.endIndex }
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
public func value(forKey key: String) -> Any? { return base.value(forKey: key) }
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The value to set the property to.
- parameter key: The name of the property whose value should be set on each object.
*/
public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> ())
-> NotificationToken { return base._addNotificationBlock(block) }
/// :nodoc:
public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> ())
-> NotificationToken { return base._addNotificationBlock(block) }
}
// MARK: Unavailable
extension AnyRealmCollection {
@available(*, unavailable, renamed: "isInvalidated")
public var invalidated: Bool { fatalError() }
@available(*, unavailable, renamed: "index(matching:)")
public func index(of predicate: NSPredicate) -> Int? { fatalError() }
@available(*, unavailable, renamed: "index(matching:_:)")
public func index(of predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() }
@available(*, unavailable, renamed: "sorted(byProperty:ascending:)")
public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() }
@available(*, unavailable, renamed: "sorted(by:)")
public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor {
fatalError()
}
@available(*, unavailable, renamed: "min(ofProperty:)")
public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() }
@available(*, unavailable, renamed: "max(ofProperty:)")
public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() }
@available(*, unavailable, renamed: "sum(ofProperty:)")
public func sum<U: AddableType>(_ property: String) -> U { fatalError() }
@available(*, unavailable, renamed: "average(ofProperty:)")
public func average<U: AddableType>(_ property: String) -> U? { fatalError() }
}
#else
/**
An iterator for a `RealmCollectionType` instance.
*/
public final class RLMGenerator<T: Object>: GeneratorType {
private let generatorBase: NSFastGenerator
internal init(collection: RLMCollection) {
generatorBase = NSFastGenerator(collection)
}
/// Advance to the next element and return it, or `nil` if no next element exists.
public func next() -> T? { // swiftlint:disable:this valid_docs
let accessor = generatorBase.next() as! T?
if let accessor = accessor {
RLMInitializeSwiftAccessorGenerics(accessor)
}
return accessor
}
}
/**
A `RealmCollectionChange` value encapsulates information about changes to collections
that are reported by Realm notifications.
The change information is available in two formats: a simple array of row
indices in the collection for each type of change, and an array of index paths
in a requested section suitable for passing directly to `UITableView`'s batch
update methods.
The arrays of indices in the `.Update` case follow `UITableView`'s batching
conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths.
For example, for a simple one-section table view, you can do the following:
```swift
self.notificationToken = results.addNotificationBlock { changes in
switch changes {
case .Initial:
// Results are now populated and can be accessed without blocking the UI
self.tableView.reloadData()
break
case .Update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the TableView
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.endUpdates()
break
case .Error(let err):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(err)")
break
}
}
```
*/
public enum RealmCollectionChange<T> {
/// `.Initial` indicates that the initial run of the query has completed (if applicable), and the
/// collection can now be used without performing any blocking work.
case Initial(T)
/// `.Update` indicates that a write transaction has been committed which either changed which objects
/// are in the collection, and/or modified one or more of the objects in the collection.
///
/// All three of the change arrays are always sorted in ascending order.
///
/// - parameter deletions: The indices in the previous version of the collection
/// which were removed from this one.
/// - parameter insertions: The indices in the new collection which were added in
/// this version.
/// - parameter modifications: The indices of the objects in the new collection which
/// were modified in this version.
case Update(T, deletions: [Int], insertions: [Int], modifications: [Int])
/// If an error occurs, notification blocks are called one time with a
/// `.Error` result and an `NSError` containing details about the error. This can only currently happen if the
/// Realm is opened on a background worker thread to calculate the change set.
case Error(NSError)
static func fromObjc(value: T, change: RLMCollectionChange?, error: NSError?) -> RealmCollectionChange {
if let error = error {
return .Error(error)
}
if let change = change {
return .Update(value,
deletions: change.deletions as! [Int],
insertions: change.insertions as! [Int],
modifications: change.modifications as! [Int])
}
return .Initial(value)
}
}
/**
A homogenous collection of `Object`s which can be retrieved, filtered, sorted,
and operated upon.
*/
public protocol RealmCollectionType: CollectionType, CustomStringConvertible {
/// The type of the objects contained in the collection.
associatedtype Element: Object
// MARK: Properties
/// The Realm which manages the collection, or `nil` for unmanaged collections.
var realm: Realm? { get }
/// Indicates if the collection can no longer be accessed.
///
/// The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection.
var invalidated: Bool { get }
/// The number of objects in the collection.
var count: Int { get }
/// A human-readable description of the objects contained in the collection.
var description: String { get }
// MARK: Index Retrieval
/**
Returns the index of an object in the collection, or `nil` if the object is not present.
- parameter object: An object.
*/
func indexOf(object: Element) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate to use to filter the objects.
*/
func indexOf(predicate: NSPredicate) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int?
// MARK: Filtering
/**
Returns all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element>
/**
Returns all objects matching the given predicate in the collection.
- parameter predicate: The predicate to use to filter the objects.
*/
func filter(predicate: NSPredicate) -> Results<Element>
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byProperty: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter property: The name of the property to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted(byProperty: String, ascending: Bool) -> Results<Element>
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byProperty:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element>
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func min<U: MinMaxType>(property: String) -> U?
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func max<U: MinMaxType>(property: String) -> U?
/**
Returns the sum of the values of a given property over all the objects represented by the collection.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
func sum<U: AddableType>(property: String) -> U
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
func average<U: AddableType>(property: String) -> U?
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
func valueForKey(key: String) -> AnyObject?
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
func valueForKeyPath(keyPath: String) -> AnyObject?
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
func setValue(value: AnyObject?, forKey key: String)
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then
called again after each write transaction which changes either any of the
objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the
collection, which of the objects were added, removed, or modified during each write transaction. See the
`RealmCollectionChange` documentation for more information on the change information supplied and an example of how
to use it to update a `UITableView`.
At the time when the block is called, the collection will be fully
evaluated and up-to-date, and as long as you do not perform a write
transaction on the same thread or explicitly call `realm.refresh()`,
accessing it will never perform blocking work.
Notifications are delivered via the standard run loop, and so can't be
delivered while the run loop is blocked by other activity. When
notifications can't be delivered instantly, multiple notifications may be
coalesced into a single notification. This can include the notification
with the initial collection. For example, the following code performs a write
transaction immediately after adding the notification block, so there is no
opportunity for the initial notification to be delivered first. As a
result, the initial notification will reflect the state of the Realm after
the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { changes in
switch changes {
case .Initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .Update:
// Will not be hit in this example
break
case .Error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- warning: This method cannot be called during a write transaction, or when
the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func addNotificationBlock(block: (RealmCollectionChange<Self>) -> Void) -> NotificationToken
/// :nodoc:
func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
}
private class _AnyRealmCollectionBase<T: Object> {
typealias Wrapper = AnyRealmCollection<Element>
typealias Element = T
var realm: Realm? { fatalError() }
var invalidated: Bool { fatalError() }
var count: Int { fatalError() }
var description: String { fatalError() }
func indexOf(object: Element) -> Int? { fatalError() }
func indexOf(predicate: NSPredicate) -> Int? { fatalError() }
func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() }
func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { fatalError() }
func filter(predicate: NSPredicate) -> Results<Element> { fatalError() }
func sorted(property: String, ascending: Bool) -> Results<Element> { fatalError() }
func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> {
fatalError()
}
func min<U: MinMaxType>(property: String) -> U? { fatalError() }
func max<U: MinMaxType>(property: String) -> U? { fatalError() }
func sum<U: AddableType>(property: String) -> U { fatalError() }
func average<U: AddableType>(property: String) -> U? { fatalError() }
subscript(index: Int) -> Element { fatalError() }
func generate() -> RLMGenerator<T> { fatalError() }
var startIndex: Int { fatalError() }
var endIndex: Int { fatalError() }
func valueForKey(key: String) -> AnyObject? { fatalError() }
func valueForKeyPath(keyPath: String) -> AnyObject? { fatalError() }
func setValue(value: AnyObject?, forKey key: String) { fatalError() }
func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { fatalError() }
}
private final class _AnyRealmCollection<C: RealmCollectionType>: _AnyRealmCollectionBase<C.Element> {
let base: C
init(base: C) {
self.base = base
}
override var realm: Realm? { return base.realm }
override var invalidated: Bool { return base.invalidated }
override var count: Int { return base.count }
override var description: String { return base.description }
// MARK: Index Retrieval
override func indexOf(object: C.Element) -> Int? { return base.indexOf(object) }
override func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) }
override func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? {
return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
override func filter(predicateFormat: String, _ args: AnyObject...) -> Results<C.Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
override func filter(predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
// MARK: Sorting
override func sorted(property: String, ascending: Bool) -> Results<C.Element> {
return base.sorted(property, ascending: ascending)
}
override func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>
(sortDescriptors: S) -> Results<C.Element> {
return base.sorted(sortDescriptors)
}
// MARK: Aggregate Operations
override func min<U: MinMaxType>(property: String) -> U? { return base.min(property) }
override func max<U: MinMaxType>(property: String) -> U? { return base.max(property) }
override func sum<U: AddableType>(property: String) -> U { return base.sum(property) }
override func average<U: AddableType>(property: String) -> U? { return base.average(property) }
// MARK: Sequence Support
override subscript(index: Int) -> C.Element {
// FIXME: it should be possible to avoid this force-casting
return unsafeBitCast(base[index as! C.Index], C.Element.self)
}
override func generate() -> RLMGenerator<Element> {
// FIXME: it should be possible to avoid this force-casting
return base.generate() as! RLMGenerator<Element>
}
// MARK: Collection Support
override var startIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.startIndex as! Int
}
override var endIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.endIndex as! Int
}
// MARK: Key-Value Coding
override func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) }
override func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) }
override func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/// :nodoc:
override func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { return base._addNotificationBlock(block) }
}
/**
A type-erased `RealmCollectionType`.
Instances of `RealmCollectionType` forward operations to an opaque underlying collection having the same `Element`
type.
*/
public final class AnyRealmCollection<T: Object>: RealmCollectionType {
/// The type of the objects contained in the collection.
public typealias Element = T
private let base: _AnyRealmCollectionBase<T>
/// Creates an `AnyRealmCollection` wrapping `base`.
public init<C: RealmCollectionType where C.Element == T>(_ base: C) {
self.base = _AnyRealmCollection(base: base)
}
// MARK: Properties
/// The Realm which manages this collection, or `nil` if the collection is unmanaged.
public var realm: Realm? { return base.realm }
/// Indicates if the collection can no longer be accessed.
///
/// The collection can no longer be accessed if `invalidate()` is called on the containing `realm`.
public var invalidated: Bool { return base.invalidated }
/// The number of objects in the collection.
public var count: Int { return base.count }
/// A human-readable description of the objects contained in the collection.
public var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
- parameter object: An object.
*/
public func indexOf(object: Element) -> Int? { return base.indexOf(object) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? {
return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate with which to filter the objects.
*/
public func filter(predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call `students.sorted("age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating
point, integer, and string types.
- parameter property: The name of the property to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(property: String, ascending: Bool) -> Results<Element> {
return base.sorted(property, ascending: ascending)
}
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating
point, integer, and string types.
- see: `sorted(_:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>
(sortDescriptors: S) -> Results<Element> {
return base.sorted(sortDescriptors)
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<U: MinMaxType>(property: String) -> U? { return base.min(property) }
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func max<U: MinMaxType>(property: String) -> U? { return base.max(property) }
/**
Returns the sum of the values of a given property over all the objects in the collection.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<U: AddableType>(property: String) -> U { return base.sum(property) }
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<U: AddableType>(property: String) -> U? { return base.average(property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: An index to retrieve or set an object from.
*/
public subscript(index: Int) -> T { return base[index] }
/// Returns an `RLMGenerator` that yields successive elements in the collection.
public func generate() -> RLMGenerator<T> { return base.generate() }
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to `endIndex` in an empty collection.
public var startIndex: Int { return base.startIndex }
/// The collection's "past the end" position.
/// `endIndex` is not a valid argument to `subscript`, and is always reachable from `startIndex` by
/// zero or more applications of `successor()`.
public var endIndex: Int { return base.endIndex }
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
public func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) }
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
public func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) }
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The value to set the property to.
- parameter key: The name of the property whose value should be set on each object.
*/
public func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then
called again after each write transaction which changes either any of the
objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the
collection, which of the objects were added, removed, or modified during each write transaction. See the
`RealmCollectionChange` documentation for more information on the change information supplied and an example of how
to use it to update a `UITableView`.
At the time when the block is called, the collection will be fully
evaluated and up-to-date, and as long as you do not perform a write
transaction on the same thread or explicitly call `realm.refresh()`,
accessing it will never perform blocking work.
Notifications are delivered via the standard run loop, and so can't be
delivered while the run loop is blocked by other activity. When
notifications can't be delivered instantly, multiple notifications may be
coalesced into a single notification. This can include the notification
with the initial collection.
For example, the following code performs a write
transaction immediately after adding the notification block, so there is no
opportunity for the initial notification to be delivered first. As a
result, the initial notification will reflect the state of the Realm after
the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { changes in
switch changes {
case .Initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .Update:
// Will not be hit in this example
break
case .Error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> ())
-> NotificationToken { return base._addNotificationBlock(block) }
/// :nodoc:
public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> ())
-> NotificationToken { return base._addNotificationBlock(block) }
}
#endif
|
mpl-2.0
|
105df3a87fecddff23ad7c8d86ce1e4e
| 38.759559 | 132 | 0.680467 | 4.791019 | false | false | false | false |
ustwo/formvalidator-swift
|
Tests/Unit Tests/Validators/URLShorthandValidatorTests.swift
|
1
|
1059
|
//
// URLShorthandValidatorTests.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 14/01/2016.
// Copyright © 2016 ustwo. All rights reserved.
//
import XCTest
@testable import FormValidatorSwift
final class URLShorthandValidatorTests: XCTestCase {
// MARK: - Properties
let validator = URLShorthandValidator()
// MARK: - Test Success
func testURLShorthandValidator_Success() {
// Given
let testInput = "example.com"
let expectedResult: [Condition]? = nil
// Test
AssertValidator(validator, testInput: testInput, expectedResult: expectedResult)
}
// MARK: - Test Failure
func testURLShorthandValidator_Failure() {
// Given
let testInput = "http://example"
let expectedResult: [Condition]? = validator.conditions
// Test
AssertValidator(validator, testInput: testInput, expectedResult: expectedResult)
}
}
|
mit
|
07b3ab59599df45399ef934e6609ccc6
| 22.511111 | 88 | 0.597353 | 5.160976 | false | true | false | false |
kstaring/swift
|
validation-test/compiler_crashers_fixed/25966-llvm-densemap-swift-normalprotocolconformance.swift
|
11
|
1504
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
}
( ")enum S<a
struct B
Void{
var a: A : A
protocol c : A
}
class var e : a {
protocol a : a {
struct B<String
in
}struct B<T where k : A
func a
func a=e
protocol P {
func f<h = object {
protocol c B
a Foundation
}
protocol a {
class A? = compose("
}
{
class A : a
class d
class B<String, C>("
class d>()
typealias e : a: a :d
protocol P {
struct A
class A {
struct B
func a {
class A<T.e
func a {
}
struct b<d
}
}
class B
protocol a {
var "
case c,
let end = compose("
}
in
}
case c
typealias e : A
extension g:Boolean{
class A {}
extension NSFileManager {
return E.c{ enum b {
}
typealias e = compose()enum C {
{struct A
var d {
{
func a :Boolean{
let b{struct B<T:C>()
let h : A {
case c
}
protocol P {
}
struct c {
}
{
protocol A {
}
}
return E.e
func a {
}
atic var d {
class B<T where T? {{
protocol a {
class B< {
}
class A {
enum S<b{
class A {
}
}}
}
Void{{
if
struct c,
func c{ enum S<h : a
typealias e : A {
class d}
struct b: a {enum b = F>() {
}
}
( "
func a {
class A : A
func a:Boolean{
var f = compose(n: Dictionary<String, C>())
struct b: A
protocol A {
class A {
static let f = e
}
let end = [
|
apache-2.0
|
5dfa682c8a347a4e021435c1576e419e
| 12.309735 | 78 | 0.647606 | 2.70018 | false | false | false | false |
roehrdor/diagnoseit-ios-mobile-agent
|
DiskMetric.swift
|
1
|
2385
|
/*
Copyright (c) 2017 Oliver Roehrdanz
Copyright (c) 2017 Matteo Sassano
Copyright (c) 2017 Christopher Voelker
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 DiskMetric: NSObject {
class var totalDiskSpaceInBytes: Int64 {
get {
do {
let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String)
let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value
return space!
} catch {
return 0
}
}
}
class var freeDiskSpaceInBytes: Int64 {
get {
do {
let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String)
let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value
return freeSpace!
} catch {
return 0
}
}
}
class var usedDiskSpaceInBytes: Int64 {
get {
let usedSpace = totalDiskSpaceInBytes - freeDiskSpaceInBytes
return usedSpace
}
}
class func getUsedDiskPercentage() -> Double {
return Double(DiskMetric.usedDiskSpaceInBytes) / Double(DiskMetric.totalDiskSpaceInBytes)
}
}
|
mit
|
3e4def96005a7280994c5beadc3fbb2f
| 36.857143 | 123 | 0.681761 | 5.096154 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Models/CoreData/Game Rows/GameItems.swift
|
1
|
2029
|
//
// GameItems.swift
// MEGameTracker
//
// Created by Emily Ivie on 11/13/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
extension Item: GameRowStorable {
/// (CodableCoreDataManageable Protocol)
/// Type of the core data entity.
public typealias EntityType = GameItems
/// (GameRowStorable Protocol)
/// Corresponding data entity for this game entity.
public typealias DataRowType = DataItem
/// (CodableCoreDataManageable Protocol)
/// Sets core data values to match struct values (specific).
public func setAdditionalColumnsOnSave(
coreItem: EntityType
) {
// only save searchable columns
setDateModifiableColumnsOnSave(coreItem: coreItem) //TODO
coreItem.id = id
coreItem.gameSequenceUuid = gameSequenceUuid?.uuidString
coreItem.isAcquired = isAcquired ? 1 : 0
coreItem.acquiredDate = acquiredDate
coreItem.isSavedToCloud = isSavedToCloud ? 1 : 0
coreItem.dataParent = generalData.entity(context: coreItem.managedObjectContext)
}
/// (GameRowStorable X Eventsable Protocol)
/// Create a new game entity value for the game uuid given using the data value given.
public static func create(
using data: DataRowType,
with manager: CodableCoreDataManageable?
) -> Item {
var item = Item(id: data.id, generalData: data)
item.events = item.getEvents(gameSequenceUuid: item.gameSequenceUuid, with: manager)
return item
}
/// (GameRowStorable Protocol)
public mutating func migrateId(id newId: String) {
id = newId
generalData.migrateId(id: newId)
}
}
extension Item {
// MARK: Additional Convenience Methods
/// Get all items from the specified game version.
public static func getAll(
gameVersion: GameVersion,
with manager: CodableCoreDataManageable? = nil
) -> [Item] {
return getAllFromData(with: manager) { fetchRequest in
fetchRequest.predicate = NSPredicate(
format: "(%K == %@)",
#keyPath(DataItems.gameVersion), gameVersion.stringValue
)
}
}
}
|
mit
|
485582f181184ac16a258464ffece664
| 27.56338 | 92 | 0.725838 | 4.121951 | false | false | false | false |
san2ride/TIY-Assignments
|
18.a/MovieAppSwift/MovieTableViewController.swift
|
1
|
7222
|
//
// MovieTableViewController.swift
// MovieAppSwift
//
// Created by don't touch me on 6/15/16.
// Copyright © 2016 trvl, LLC. All rights reserved.
//
import UIKit
class MovieTableViewController: UITableViewController {
typealias JSONDictionary = [String:AnyObject]
typealias JSONArray = [JSONDictionary]
var moviesArray = [Movie]()
var currentMuvi: Movie?
override func viewDidLoad() {
super.viewDidLoad()
if let filePath = NSBundle.mainBundle().URLForResource("popular", withExtension: "json") {
if let data = NSData(contentsOfURL: filePath) {
do {
if let jsonDict = try
NSJSONSerialization.JSONObjectWithData(data, options: []) as?
JSONDictionary {
print(jsonDict)
if let resultsArray = jsonDict["results"] as? JSONArray {
for dict in resultsArray {
let theMovie = Movie()
if let posterPath = dict["poster_path"] as? String {
theMovie.posterPath = posterPath
} else {
print("Could not parse the poster path")
}
if let adult = dict["adult"] as? Bool {
theMovie.adult = adult
} else {
print("Could not parse the adult")
}
if let overview = dict["overview"] as? String {
theMovie.overview = overview
} else {
print("Could not parse overview string")
}
if let releaseDate = dict["release_date"] as? String {
theMovie.releaseDate = releaseDate
} else {
print("Could not parse the releaseDate")
}
if let muviId = dict["id"] as? Int {
theMovie.muviId = muviId
} else {
print("Could not parse Id string")
}
if let originalTitle = dict["original_title"] as? String {
theMovie.originalTitle = originalTitle
} else {
print("Could not parse the originalTitle")
}
if let originalLanguage = dict["original_language"] as? String {
theMovie.originalLanguage = originalLanguage
} else {
print("Could not parse originalLanguage string")
}
if let title = dict["title"] as? String {
theMovie.title = title
} else {
print("Could not parse title string")
}
if let backdropPath = dict["backdrop_path"] as? String {
theMovie.backdropPath = backdropPath
} else {
print("Could not parse title string")
}
if let popularity = dict["popularity"] as? Double {
theMovie.popularity = popularity
} else {
print("Could not parse the popularity")
}
if let voteCount = dict["vote_count"] as? Int {
theMovie.voteCount = voteCount
} else {
print("Could not parse voteCount string")
}
if let video = dict["video"] as? Bool {
theMovie.video = video
} else {
print("Could not parse the video")
}
if let voteAverage = dict["vote_average"] as? Double {
theMovie.voteAverage = voteAverage
} else {
print("Could not parse the poster path")
}
moviesArray.append(theMovie)
}
}
}
} catch {
print("Something went wrong parsing the data")
}
}
for theMovie in moviesArray {
print(theMovie.title)
}
}
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.moviesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! muviTableViewCell
let movie = self.moviesArray[indexPath.row]
cell.muviLabel.text = movie.title
cell.muviImageView.image = UIImage(named: movie.posterPath)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.currentMuvi = self.moviesArray[indexPath.row]
self.performSegueWithIdentifier("PosterSegue", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController as? PosterViewController
controller?.theMovie = self.currentMuvi
}
}
|
mit
|
c7be5c7a9253e395f6e58d1c54cf1c6e
| 38.895028 | 118 | 0.377095 | 7.569182 | false | false | false | false |
alexking124/Picture-Map
|
Picture Map/Pin.swift
|
1
|
1810
|
//
// Pin.swift
// Picture Map
//
// Created by Tigger on 7/14/16.
// Copyright © 2016 Alex King. All rights reserved.
//
import CoreLocation
import Foundation
import Firebase
class Pin {
var latitude: CLLocationDegrees = 0
var longitude: CLLocationDegrees = 0
var imagePath: String = ""
var title: String = ""
var description: String = ""
var identifier: String = ""
var dateTaken: NSNumber = NSNumber.init(value: Date.distantPast.timeIntervalSinceReferenceDate)
init() {}
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String:Any]
self.latitude = snapshotValue["latitude"] as! CLLocationDegrees
self.longitude = snapshotValue["longitude"] as! CLLocationDegrees
self.imagePath = snapshotValue["imagePath"] as! String
self.title = snapshotValue["title"] as! String
self.description = snapshotValue["description"] as! String
if let date = snapshotValue["date"] as? NSNumber {
self.dateTaken = date
}
self.identifier = snapshot.key
}
func getDate() -> Date {
return Date(timeIntervalSinceReferenceDate: dateTaken.doubleValue)
}
func changeDate(_ date: Date) {
dateTaken = NSNumber.init(value: date.timeIntervalSinceReferenceDate)
}
func metadataDictionary() -> Dictionary<String, Any> {
let pinMetadata = ["identifier": identifier,
"latitude": latitude,
"longitude": longitude,
"imagePath": imagePath,
"title": title,
"description": description,
"date": dateTaken] as [String : Any]
return pinMetadata
}
}
|
mit
|
04b0fcfeb218d8e0565fe2483fd6a6fb
| 31.303571 | 99 | 0.598673 | 5.025 | false | false | false | false |
square/Valet
|
Sources/Valet/Internal/Keychain.swift
|
1
|
14286
|
// Created by Dan Federman and Eric Muller on 9/16/17.
// Copyright © 2017 Square, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
internal final class Keychain {
// MARK: Private Static Properties
private static let canaryKey = "VAL_KeychainCanaryUsername"
private static let canaryValue = "VAL_KeychainCanaryPassword"
// MARK: Keychain Accessibility
internal static func canAccess(attributes: [String : AnyHashable]) -> Bool {
func isCanaryValueInKeychain() -> Bool {
do {
let retrievedCanaryValue = try string(forKey: canaryKey, options: attributes)
return retrievedCanaryValue == canaryValue
} catch {
return false
}
}
if isCanaryValueInKeychain() {
return true
} else {
var secItemQuery = attributes
secItemQuery[kSecAttrAccount as String] = canaryKey
secItemQuery[kSecValueData as String] = Data(canaryValue.utf8)
try? SecItem.add(attributes: secItemQuery)
return isCanaryValueInKeychain()
}
}
// MARK: Getters
internal static func string(forKey key: String, options: [String : AnyHashable]) throws -> String {
let data = try object(forKey: key, options: options)
if let string = String(data: data, encoding: .utf8) {
return string
} else {
throw KeychainError.itemNotFound
}
}
internal static func object(forKey key: String, options: [String : AnyHashable]) throws -> Data {
guard !key.isEmpty else {
throw KeychainError.emptyKey
}
var secItemQuery = options
secItemQuery[kSecAttrAccount as String] = key
secItemQuery[kSecMatchLimit as String] = kSecMatchLimitOne
secItemQuery[kSecReturnData as String] = true
return try SecItem.copy(matching: secItemQuery)
}
// MARK: Setters
internal static func setString(_ string: String, forKey key: String, options: [String: AnyHashable]) throws {
let data = Data(string.utf8)
try setObject(data, forKey: key, options: options)
}
internal static func setObject(_ object: Data, forKey key: String, options: [String: AnyHashable]) throws {
guard !key.isEmpty else {
throw KeychainError.emptyKey
}
guard !object.isEmpty else {
throw KeychainError.emptyValue
}
var secItemQuery = options
secItemQuery[kSecAttrAccount as String] = key
#if os(macOS)
// Never update an existing keychain item on OS X, since the existing item could have unauthorized apps in the Access Control List. Fixes zero-day Keychain vuln found here: https://drive.google.com/file/d/0BxxXk1d3yyuZOFlsdkNMSGswSGs/view
try SecItem.deleteItems(matching: secItemQuery)
secItemQuery[kSecValueData as String] = object
try SecItem.add(attributes: secItemQuery)
#else
if performCopy(forKey: key, options: options) == errSecSuccess {
try SecItem.update(attributes: [kSecValueData as String: object], forItemsMatching: secItemQuery)
} else {
secItemQuery[kSecValueData as String] = object
try SecItem.add(attributes: secItemQuery)
}
#endif
}
// MARK: Removal
internal static func removeObject(forKey key: String, options: [String : AnyHashable]) throws {
guard !key.isEmpty else {
throw KeychainError.emptyKey
}
var secItemQuery = options
secItemQuery[kSecAttrAccount as String] = key
try SecItem.deleteItems(matching: secItemQuery)
}
internal static func removeAllObjects(matching options: [String : AnyHashable]) throws {
try SecItem.deleteItems(matching: options)
}
// MARK: Contains
internal static func performCopy(forKey key: String, options: [String : AnyHashable]) -> OSStatus {
guard !key.isEmpty else {
return errSecParam
}
var secItemQuery = options
secItemQuery[kSecAttrAccount as String] = key
return SecItem.performCopy(matching: secItemQuery)
}
// MARK: AllObjects
internal static func allKeys(options: [String: AnyHashable]) throws -> Set<String> {
var secItemQuery = options
secItemQuery[kSecMatchLimit as String] = kSecMatchLimitAll
secItemQuery[kSecReturnAttributes as String] = true
do {
let collection: Any = try SecItem.copy(matching: secItemQuery)
if let singleMatch = collection as? [String: AnyHashable], let singleKey = singleMatch[kSecAttrAccount as String] as? String, singleKey != canaryKey {
return Set([singleKey])
} else if let multipleMatches = collection as? [[String: AnyHashable]] {
return Set(multipleMatches.compactMap({ attributes in
let key = attributes[kSecAttrAccount as String] as? String
return key != canaryKey ? key : nil
}))
} else {
return Set()
}
} catch KeychainError.itemNotFound {
// Nothing was found. That's fine.
return Set()
} catch {
// This isn't a recoverable error. Throw.
throw error
}
}
// MARK: Migration
internal static func migrateObjects(matching query: [String : AnyHashable], into destinationAttributes: [String : AnyHashable], compactMap: (MigratableKeyValuePair<AnyHashable>) throws -> MigratableKeyValuePair<String>?) throws {
guard !query.isEmpty else {
// Migration requires secItemQuery to contain values.
throw MigrationError.invalidQuery
}
guard query[kSecMatchLimit as String] as? String as CFString? != kSecMatchLimitOne else {
// Migration requires kSecMatchLimit to be set to kSecMatchLimitAll.
throw MigrationError.invalidQuery
}
guard query[kSecReturnData as String] as? Bool != true else {
// kSecReturnData is not supported in a migration query.
throw MigrationError.invalidQuery
}
guard query[kSecReturnAttributes as String] as? Bool != false else {
// Migration requires kSecReturnAttributes to be set to kCFBooleanTrue.
throw MigrationError.invalidQuery
}
guard query[kSecReturnRef as String] as? Bool != true else {
// kSecReturnRef is not supported in a migration query.
throw MigrationError.invalidQuery
}
guard query[kSecReturnPersistentRef as String] as? Bool != false else {
// Migration requires kSecReturnPersistentRef to be set to kCFBooleanTrue.
throw MigrationError.invalidQuery
}
guard query[kSecClass as String] as? String as CFString? == kSecClassGenericPassword else {
// Migration requires kSecClass to be set to kSecClassGenericPassword to avoid data loss.
throw MigrationError.invalidQuery
}
guard query[kSecAttrAccessControl as String] == nil else {
// kSecAttrAccessControl is not supported in a migration query. Keychain items can not be migrated en masse from the Secure Enclave.
throw MigrationError.invalidQuery
}
var secItemQuery = query
secItemQuery[kSecMatchLimit as String] = kSecMatchLimitAll
secItemQuery[kSecReturnAttributes as String] = true
secItemQuery[kSecReturnData as String] = false
secItemQuery[kSecReturnRef as String] = false
secItemQuery[kSecReturnPersistentRef as String] = true
let collection: Any = try SecItem.copy(matching: secItemQuery)
let retrievedItemsToMigrate: [[String: AnyHashable]]
if let singleMatch = collection as? [String : AnyHashable] {
retrievedItemsToMigrate = [singleMatch]
} else if let multipleMatches = collection as? [[String: AnyHashable]] {
retrievedItemsToMigrate = multipleMatches
} else {
throw MigrationError.dataToMigrateInvalid
}
// Now that we have the persistent refs with attributes, get the data associated with each keychain entry.
var retrievedItemsToMigrateWithData = [[String : AnyHashable]]()
for retrievedItem in retrievedItemsToMigrate {
guard let retrievedPersistentRef = retrievedItem[kSecValuePersistentRef as String] else {
throw KeychainError.couldNotAccessKeychain
}
let retrieveDataQuery: [String : AnyHashable] = [
kSecValuePersistentRef as String : retrievedPersistentRef,
kSecReturnData as String : true
]
do {
let data: Data = try SecItem.copy(matching: retrieveDataQuery)
guard !data.isEmpty else {
throw MigrationError.dataToMigrateInvalid
}
var retrievedItemToMigrateWithData = retrievedItem
retrievedItemToMigrateWithData[kSecValueData as String] = data
retrievedItemsToMigrateWithData.append(retrievedItemToMigrateWithData)
} catch KeychainError.itemNotFound {
// It is possible for metadata-only items to exist in the keychain that do not have data associated with them. Ignore this entry.
continue
} catch {
throw error
}
}
// Sanity check that we are capable of migrating the data.
var keyValuePairsToMigrate = [String: Data]()
for keychainEntry in retrievedItemsToMigrateWithData {
guard let key = keychainEntry[kSecAttrAccount as String] else {
throw MigrationError.keyToMigrateInvalid
}
guard key as? String != Keychain.canaryKey else {
// We don't care about this key. Move along.
continue
}
guard let data = keychainEntry[kSecValueData as String] as? Data else {
// This state should be impossible, per Apple's documentation for `kSecValueData`.
throw MigrationError.dataToMigrateInvalid
}
guard let migratablePair = try compactMap(MigratableKeyValuePair<AnyHashable>(key: key, value: data)) else {
// We don't care about this key. Move along.
continue
}
guard !migratablePair.key.isEmpty else {
throw MigrationError.keyToMigrateInvalid
}
guard keyValuePairsToMigrate[migratablePair.key] == nil else {
throw MigrationError.duplicateKeyToMigrate
}
guard !migratablePair.value.isEmpty else {
throw MigrationError.dataToMigrateInvalid
}
if Keychain.performCopy(forKey: migratablePair.key, options: destinationAttributes) == errSecItemNotFound {
keyValuePairsToMigrate[migratablePair.key] = migratablePair.value
} else {
throw MigrationError.keyToMigrateAlreadyExistsInValet
}
}
// Capture the keys in the destination prior to migration beginning.
let keysInKeychainPreMigration = Set(try Keychain.allKeys(options: destinationAttributes))
// All looks good. Time to actually migrate.
for keyValuePair in keyValuePairsToMigrate {
do {
try Keychain.setObject(keyValuePair.value, forKey: keyValuePair.key, options: destinationAttributes)
} catch {
revertMigration(into: destinationAttributes, keysInKeychainPreMigration: keysInKeychainPreMigration)
throw error
}
}
}
internal static func migrateObjects(matching query: [String : AnyHashable], into destinationAttributes: [String : AnyHashable], removeOnCompletion: Bool) throws {
// Capture the keys in the destination prior to migration beginning.
let keysInKeychainPreMigration = Set(try Keychain.allKeys(options: destinationAttributes))
// Attempt migration.
try migrateObjects(matching: query, into: destinationAttributes) { keychainKeyValuePair in
guard let key = keychainKeyValuePair.key as? String else {
throw MigrationError.keyToMigrateInvalid
}
return MigratableKeyValuePair(key: key, value: keychainKeyValuePair.value)
}
// Remove data if requested.
if removeOnCompletion {
do {
try Keychain.removeAllObjects(matching: query)
} catch {
revertMigration(into: destinationAttributes, keysInKeychainPreMigration: keysInKeychainPreMigration)
throw MigrationError.removalFailed
}
// We're done!
}
}
internal static func revertMigration(into destinationAttributes: [String : AnyHashable], keysInKeychainPreMigration: Set<String>) {
if let allKeysPostPotentiallyPartialMigration = try? Keychain.allKeys(options: destinationAttributes) {
let migratedKeys = allKeysPostPotentiallyPartialMigration.subtracting(keysInKeychainPreMigration)
migratedKeys.forEach { migratedKey in
try? Keychain.removeObject(forKey: migratedKey, options: destinationAttributes)
}
}
}
}
|
apache-2.0
|
b8cc7489c2f43d06ba51273cf4df17e6
| 39.341808 | 246 | 0.634759 | 5.287301 | false | false | false | false |
CharlinFeng/Reflect
|
Reflect/Reflect/Reflect.swift
|
1
|
2582
|
//
// Reflect.swift
// Reflect
//
// Created by 冯成林 on 15/8/19.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
class Reflect: NSObject, NSCoding{
lazy var mirror: Mirror = {Mirror(reflecting: self)}()
required override init(){}
public convenience required init?(coder aDecoder: NSCoder) {
self.init()
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
assert(type.check(), "[Charlin Feng]: Property '\(name)' type can not be a '\(type.realType.rawValue)' Type,Please use 'NSNumber' instead!")
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
self.setValue(aDecoder.decodeObject(forKey: name), forKeyPath: name)
}
}else{
self.setValue(aDecoder.decodeObject(forKey: name), forKeyPath: name)
}
}
}
public func encode(with aCoder: NSCoder){
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
aCoder.encode(value as? AnyObject, forKey: name)
}
}else{
if type.isArray {
if type.isReflect {
aCoder.encode(value as? NSArray, forKey: name)
}else {
aCoder.encode(value as? AnyObject, forKey: name)
}
}else {
var v = "\(value)".replacingOccurrencesOfString(target: "Optional(", withString: "").replacingOccurrencesOfString(target: ")", withString: "")
v = v.replacingOccurrencesOfString(target: "\"", withString: "")
aCoder.encode(v, forKey: name)
}
}
}
}
func parseOver(){}
}
|
mit
|
ed933cf44ec253612c9fde1cf91fbf9c
| 27.21978 | 162 | 0.474299 | 5.944444 | false | false | false | false |
asp2insp/Twittercism
|
Twittercism/MentionsViewController.swift
|
1
|
2138
|
//
// MentionsViewController.swift
// Twittercism
//
// Created by Josiah Gaskin on 5/31/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import Foundation
import UIKit
let MENTIONS = Getter(keyPath: ["mentions"])
class MentionsViewController : UITableViewController {
var reactor : Reactor!
var keys : [UInt] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "Tweet", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "tweet")
self.refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "fetchMentions", forControlEvents: UIControlEvents.ValueChanged)
reactor = TwitterApi.sharedInstance.reactor
TwitterApi.loadMentions()
self.title = "Mentions"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
keys.append(reactor.observe(TWEETS, handler: { (newState) -> () in
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
}))
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
reactor.unobserve(keys)
}
func fetchMentions() {
TwitterApi.loadMentions()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reactor.evaluate(MENTIONS).count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tweet", forIndexPath: indexPath) as! TweetView
cell.tweet = reactor.evaluate(MENTIONS.extendKeyPath([indexPath.row]))
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 180
}
}
|
mit
|
688ad0bcbc152292a5056e9c5086319e
| 32.421875 | 121 | 0.681478 | 5.164251 | false | false | false | false |
firebase/quickstart-ios
|
firestore/FirestoreSwiftUIExample/ViewModels/RestaurantViewModel.swift
|
1
|
3402
|
//
// RestaurantViewModel.swift
// FirestoreSwiftUIExample
//
// Copyright (c) 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import FirebaseFirestore
import Combine
class RestaurantViewModel: ObservableObject {
var restaurant: Restaurant
@Published var reviews = [Review]()
private var db = Firestore.firestore()
private var listener: ListenerRegistration?
init(restaurant: Restaurant) {
self.restaurant = restaurant
}
deinit {
unsubscribe()
}
func add(review: Review) {
db.runTransaction({ (transaction, errorPointer) -> Any? in
let restaurantRef = self.restaurant.reference!
let restaurantDocument: DocumentSnapshot
do {
try restaurantDocument = transaction.getDocument(restaurantRef)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let ratingCount = restaurantDocument.data()?["numRatings"] as? Int else {
errorPointer?.pointee = self.getNSError(document: restaurantDocument)
return nil
}
guard let averageRating = restaurantDocument.data()?["avgRating"] as? Float else {
errorPointer?.pointee = self.getNSError(document: restaurantDocument)
return nil
}
let newAverage = (Float(ratingCount) * averageRating + Float(review.rating))
/ Float(ratingCount + 1)
transaction.setData([
"numRatings": ratingCount + 1,
"avgRating": newAverage,
], forDocument: restaurantRef, merge: true)
let reviewDocument = self.restaurant.ratingsCollection!.document()
do {
_ = try transaction.setData(from: review, forDocument: reviewDocument)
} catch {
fatalError("Unable to add review: \(error.localizedDescription).")
}
return nil
}) { object, error in
if let error = error {
print("Transaction failed: \(error)")
}
}
}
func unsubscribe() {
if listener != nil {
listener?.remove()
listener = nil
}
}
func subscribe() {
if listener == nil {
listener = restaurant.ratingsCollection?.addSnapshotListener {
[weak self] querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
guard let self = self else { return }
self.reviews = documents.compactMap { document in
do {
return try document.data(as: Review.self)
} catch {
print(error)
return nil
}
}
}
}
}
func getNSError(document: DocumentSnapshot) -> NSError {
return NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve value from snapshot \(document)",
]
)
}
}
|
apache-2.0
|
1944f53b3dee599a0964822219bc42ec
| 27.35 | 88 | 0.644033 | 4.578735 | false | false | false | false |
hhsolar/MemoryMaster-iOS
|
MemoryMaster/Controller/LibraryViewController.swift
|
1
|
12019
|
//
// LibraryViewController.swift
// MemoryMaster
//
// Created by apple on 1/10/2017.
// Copyright © 2017 greatwall. All rights reserved.
//
import UIKit
import CoreData
private let cellReuseIdentifier = "LibraryTableViewCell"
class LibraryViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var allNoteButton: UIButton!
@IBOutlet weak var qaNoteButton: UIButton!
@IBOutlet weak var singleNoteButton: UIButton!
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
}
}
let topView = UIView()
let nothingFoundLabel = UILabel()
// public api
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
var fetchedResultsController: NSFetchedResultsController<BasicNoteInfo>?
let searchController = UISearchController(searchResultsController: nil)
var lastType = ""
var selectedCellIndex: IndexPath?
var showFlag: NoteType = .all
fileprivate let playSound = SystemAudioPlayer()
func updateUI(noteType: NoteType, searchKeyWord: String?) {
if let context = container?.viewContext {
let request: NSFetchRequest<BasicNoteInfo> = BasicNoteInfo.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(
key: "name",
ascending: true,
selector: #selector(NSString.localizedCaseInsensitiveCompare(_:))
)]
if let searchKeyWord = searchKeyWord, searchKeyWord != "" {
if noteType != NoteType.all {
request.predicate = NSPredicate(format: "type == %@ && name CONTAINS[c] %@", noteType.rawValue, searchKeyWord)
} else {
request.predicate = NSPredicate(format: "name CONTAINS[c] %@", searchKeyWord)
}
} else if noteType != NoteType.all {
request.predicate = NSPredicate(format: "type == %@", noteType.rawValue)
}
fetchedResultsController = NSFetchedResultsController<BasicNoteInfo>(
fetchRequest: request,
managedObjectContext: context,
sectionNameKeyPath: nil,
cacheName: nil
)
fetchedResultsController?.delegate = self
try? fetchedResultsController?.performFetch()
tableView.reloadData()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewWillAppear(_ animated: Bool) {
super .viewWillAppear(animated)
updateUI(noteType: showFlag, searchKeyWord: nil)
}
@IBAction func showAllNote(_ sender: UIButton) {
showFlag = NoteType.all
allNoteButton.setImage(UIImage(named: "all_icon_click.png"), for: .normal)
qaNoteButton.setImage(UIImage(named: "qa_icon_unclick.png"), for: .normal)
singleNoteButton.setImage(UIImage(named: "single_icon_unclick.png"), for: .normal)
updateUI(noteType: showFlag, searchKeyWord: nil)
}
@IBAction func showQANote(_ sender: UIButton) {
showFlag = NoteType.qa
allNoteButton.setImage(UIImage(named: "all_icon_unclick.png"), for: .normal)
qaNoteButton.setImage(UIImage(named: "qa_icon_click.png"), for: .normal)
singleNoteButton.setImage(UIImage(named: "single_icon_unclick.png"), for: .normal)
updateUI(noteType: showFlag, searchKeyWord: nil)
}
@IBAction func showSingleNote(_ sender: UIButton) {
showFlag = NoteType.single
allNoteButton.setImage(UIImage(named: "all_icon_unclick.png"), for: .normal)
qaNoteButton.setImage(UIImage(named: "qa_icon_unclick.png"), for: .normal)
singleNoteButton.setImage(UIImage(named: "single_icon_click.png"), for: .normal)
updateUI(noteType: showFlag, searchKeyWord: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(returnKeyBoard))
swipeRecognizer.direction = .down
swipeRecognizer.numberOfTouchesRequired = 1
tableView.addGestureRecognizer(swipeRecognizer)
swipeRecognizer.delegate = self
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
// eliminate black line above searchBar
searchController.searchBar.isTranslucent = false
searchController.searchBar.backgroundImage = UIImage()
// set searchBar textField to round corner
let searchField = searchController.searchBar.value(forKey: "searchField") as? UITextField
searchField?.layer.cornerRadius = 14
searchField?.layer.masksToBounds = true
searchController.searchBar.delegate = self
searchController.searchBar.tintColor = UIColor.white
searchController.searchBar.barTintColor = CustomColor.deepBlue
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
private func setupUI()
{
topView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: CustomSize.barHeight + CustomSize.statusBarHeight)
topView.backgroundColor = CustomColor.medianBlue
view.addSubview(topView)
view.sendSubview(toBack: topView)
nothingFoundLabel.frame = CGRect(x: 0, y: 44, width: UIScreen.main.bounds.width, height: 44)
nothingFoundLabel.text = "Nothing Found"
nothingFoundLabel.textColor = CustomColor.wordGray
nothingFoundLabel.textAlignment = .center
tableView.addSubview(nothingFoundLabel)
allNoteButton.setImage(UIImage(named: "all_icon_click.png"), for: .normal)
singleNoteButton.setImage(UIImage(named: "single_icon_unclick.png"), for: .normal)
qaNoteButton.setImage(UIImage(named: "qa_icon_unclick.png"), for: .normal)
addButton.tintColor = UIColor.white
tableView.rowHeight = 44
let nib = UINib(nibName: cellReuseIdentifier, bundle: nil)
tableView.register(nib, forCellReuseIdentifier: cellReuseIdentifier)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ToNoteViewController" {
let controller = segue.destination as! NoteViewController
controller.container = self.container
if let card = fetchedResultsController?.object(at: selectedCellIndex!) {
let passCard = MyBasicNoteInfo(id: Int(card.id), time: card.createTime as Date, type: card.type, name: card.name, numberOfCard: Int(card.numberOfCard))
controller.passedInNoteInfo = passCard
controller.container = container
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
@objc func returnKeyBoard(byReactionTo swipeRecognizer: UISwipeGestureRecognizer) {
if swipeRecognizer.state == .ended {
if searchController.searchBar.isFirstResponder {
searchController.searchBar.resignFirstResponder()
searchController.searchBar.setShowsCancelButton(false, animated: true)
}
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if searchController.searchBar.isFirstResponder {
tableView.isScrollEnabled = false
return true
} else {
tableView.isScrollEnabled = true
return false
}
}
@IBAction func addButtonClicked(_ sender: UIButton) {
playSound.playClickSound(SystemSound.buttonClick)
}
}
extension LibraryViewController: UISearchResultsUpdating, UISearchBarDelegate {
func updateSearchResults(for searchController: UISearchController) {
updateUI(noteType: showFlag, searchKeyWord: searchController.searchBar.text)
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
return true
}
}
extension LibraryViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return fetchedResultsController?.sections?.count ?? 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let sections = fetchedResultsController?.sections, sections.count > 0 {
if sections[section].numberOfObjects == 0 {
nothingFoundLabel.isHidden = false
} else {
nothingFoundLabel.isHidden = true
}
return sections[section].numberOfObjects
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LibraryTableViewCell", for: indexPath) as! LibraryTableViewCell
if let card = fetchedResultsController?.object(at: indexPath) {
cell.awakeFromNib()
cell.updateCell(with: card, lastCardType: lastType)
lastType = card.type
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCellIndex = indexPath
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "ToNoteViewController", sender: indexPath)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let note: BasicNoteInfo! = fetchedResultsController?.object(at: indexPath)
for i in 0..<Int(note.numberOfCard) {
CardContent.removeCardContent(with: note.name, at: i, in: note.type)
}
let context = container?.viewContext
BookMark.remove(matching: note.id, in: context!)
context?.delete(note)
try? context?.save()
}
}
}
extension LibraryViewController: NSFetchedResultsControllerDelegate {
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert: tableView.insertSections([sectionIndex], with: .fade)
case .delete: tableView.deleteSections([sectionIndex], with: .fade)
default: break
}
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .fade)
case .move:
tableView.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
|
mit
|
849c0be53b2d13ce1becdf00146d6e4d
| 40.441379 | 216 | 0.660343 | 5.298942 | false | false | false | false |
ripventura/VCUIKit
|
VCUIKit/Classes/VCTheme/VCPlaceholderView.swift
|
1
|
5245
|
//
// VCPlaceholderView.swift
// VCUIKit
//
// Created by Vitor Cesco on 01/03/18.
//
import Foundation
open class VCPlaceholderView: VCView {
open var placeHolderDrawableView : VCDrawableView = VCDrawableView()
open var placeHolderActivityIndicatorView : VCActivityIndicatorView = VCActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
open var placeHolderTitleLabel : VCLabel = VCLabel()
open var placeHolderTextLabel : VCLabel = VCLabel()
open var placeHolderActionButton : VCButton = VCButton()
var actionHandler: (() -> Void)?
open var isEnabled: Bool {
get {
return !self.isHidden
}
set(newValue) {
self.isHidden = !newValue
}
}
/** Updates the placeholders */
open func update(enable: Bool,
title: String? = nil,
text: String? = nil,
drawer: VCDrawerProtocol? = nil,
activity: Bool = false,
buttonTitle: String? = nil) {
self.isEnabled = enable
self.placeHolderTitleLabel.text = title
self.placeHolderTextLabel.text = text
self.placeHolderDrawableView.drawer = drawer
if activity {
self.placeHolderActivityIndicatorView.startAnimating()
} else {
self.placeHolderActivityIndicatorView.stopAnimating()
}
self.placeHolderActionButton.setTitle(buttonTitle, for: .normal)
self.placeHolderActionButton.isHidden = buttonTitle == nil
}
/** Sets up the PlaceholderView */
open func setup(actionHandler: @escaping (() -> Void)) {
self.actionHandler = actionHandler
self.backgroundColor = .clear
self.placeHolderTitleLabel = VCLabel(frame: CGRectDefault)
self.placeHolderTitleLabel.textAlignment = .center
self.placeHolderTitleLabel.numberOfLines = 0
self.addSubview(self.placeHolderTitleLabel)
placeHolderTitleLabel.snp.makeConstraints({make in
make.left.equalTo(self).offset(48)
make.right.equalTo(self).offset(-48)
make.centerY.equalToSuperview()
make.height.greaterThanOrEqualTo(25)
})
self.placeHolderDrawableView.backgroundColor = .clear
self.addSubview(self.placeHolderDrawableView)
placeHolderDrawableView.snp.makeConstraints({make in
make.centerX.equalTo(self)
make.bottom.equalTo(self.placeHolderTitleLabel.snp.top).offset(-20)
make.size.equalTo(sharedAppearanceManager.appearance.placeholderViewImageSize)
})
self.addSubview(self.placeHolderActivityIndicatorView)
self.placeHolderActivityIndicatorView.hidesWhenStopped = true
placeHolderActivityIndicatorView.snp.makeConstraints({make in
make.centerX.equalTo(self.placeHolderDrawableView)
make.centerY.equalTo(self.placeHolderDrawableView)
})
self.placeHolderTextLabel = VCLabel(frame: CGRectDefault)
self.placeHolderTextLabel.textAlignment = .center
self.placeHolderTextLabel.numberOfLines = 0
self.addSubview(self.placeHolderTextLabel)
placeHolderTextLabel.snp.makeConstraints({make in
make.left.equalTo(self.placeHolderTitleLabel)
make.right.equalTo(self.placeHolderTitleLabel)
make.top.equalTo(self.placeHolderTitleLabel.snp.bottom)
make.height.greaterThanOrEqualTo(40)
})
self.placeHolderActionButton = VCButton(frame: CGRectDefault)
self.addSubview(self.placeHolderActionButton)
self.placeHolderActionButton.addTarget(self, action: #selector(self.actionButtonPressed), for: .touchUpInside)
placeHolderActionButton.snp.makeConstraints({make in
make.left.equalTo(self.placeHolderTitleLabel)
make.right.equalTo(self.placeHolderTitleLabel)
make.height.equalTo(40)
make.top.equalTo(self.placeHolderTextLabel.snp.bottom).offset(8)
})
self.isEnabled = false
}
@objc fileprivate func actionButtonPressed() {
self.actionHandler?()
}
override open func applyAppearance() {
self.placeHolderTextLabel.textColor = sharedAppearanceManager.appearance.placeholderViewTextColor
self.placeHolderTextLabel.font = sharedAppearanceManager.appearance.placeholderViewTextFont
self.placeHolderTitleLabel.textColor = sharedAppearanceManager.appearance.placeholderViewTitleColor
self.placeHolderTitleLabel.font = sharedAppearanceManager.appearance.placeholderViewTitleFont
self.placeHolderDrawableView.snp.updateConstraints({make in
make.size.equalTo(sharedAppearanceManager.appearance.placeholderViewImageSize)
})
self.placeHolderActionButton.tintColor = sharedAppearanceManager.appearance.placeholderViewButtonTintColor
self.placeHolderActionButton.titleLabel?.font = sharedAppearanceManager.appearance.placeholderViewButtonFont
self.placeHolderActivityIndicatorView.applyAppearance()
}
}
|
mit
|
0502f07d66aba8f7f8bb44cf521d317b
| 41.298387 | 162 | 0.682364 | 5.429607 | false | false | false | false |
Maslor/swift-cannon
|
swift-cannon/GameViewController.swift
|
1
|
1408
|
//
// GameViewController.swift
// swift-cannon
//
// Created by Gabriel Freire on 11/02/16.
// Copyright (c) 2016 maslor. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene"){
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
unlicense
|
d5a38dbc8e6cdd590ba248813fc3fffc
| 25.566038 | 94 | 0.603693 | 5.565217 | false | false | false | false |
RayTao/CoreAnimation_Collection
|
CoreAnimation_Collection/CALayerViewController.swift
|
1
|
1046
|
//
// CALayerViewController.swift
// CoreAnimation_Collection
//
// Created by ray on 15/12/12.
// Copyright © 2015年 ray. All rights reserved.
//
import UIKit
class CALayerViewController: UIViewController {
let layerView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//create sublayer
layerView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
layerView.center = self.view.center
layerView.backgroundColor = UIColor.white
self.view.addSubview(layerView)
let blueLayer = CALayer()
blueLayer.frame = CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0);
blueLayer.backgroundColor = UIColor.blue.cgColor;
//add it to our view
layerView.layer.addSublayer(blueLayer);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
510bcd50452bb661a799af2d345314bb
| 25.075 | 80 | 0.629914 | 4.49569 | false | false | false | false |
Fenrikur/ef-app_ios
|
Eurofurence/Director/RestorationIdentifierOrderingPolicy.swift
|
1
|
1067
|
import UIKit
class RestorationIdentifierOrderingPolicy: ModuleOrderingPolicy {
private let userDefaults = UserDefaults.standard
private struct Keys {
static let tabOrderKey = "EFModuleRestorationIdentifiers"
}
func order(modules: [UIViewController]) -> [UIViewController] {
guard let order = userDefaults.stringArray(forKey: Keys.tabOrderKey) else { return modules }
return modules.sorted(by: { (first, second) -> Bool in
guard let firstIdentifier = first.restorationIdentifier,
let secondIdentifier = second.restorationIdentifier,
let firstIndex = order.firstIndex(of: firstIdentifier),
let secondIndex = order.firstIndex(of: secondIdentifier) else { return false }
return firstIndex < secondIndex
})
}
func saveOrder(_ modules: [UIViewController]) {
let restorationIdentifiers = modules.compactMap({ $0.restorationIdentifier })
userDefaults.setValue(restorationIdentifiers, forKey: Keys.tabOrderKey)
}
}
|
mit
|
24b094410b5810073cf0f4816cadacc7
| 37.107143 | 100 | 0.686036 | 5.282178 | false | false | false | false |
ale84/ABLE
|
ABLE/PeripheralManager.swift
|
1
|
11205
|
//
// Created by Alessio Orlando on 15/05/17.
// Copyright © 2019 Alessio Orlando. All rights reserved.
//
import Foundation
import CoreBluetooth
public class PeripheralManager: NSObject {
public var bluetoothStateUpdate: BluetoothStateUpdate?
public var readRequestCallback: ReadRequestCallback?
public var writeRequestsCallback: WriteRequestsCallback?
public var state: ManagerState {
return cbPeripheralManager.managerState
}
public var isAdvertising: Bool {
return cbPeripheralManager.isAdvertising
}
private (set) var cbPeripheralManager: CBPeripheralManagerType
private var waitForStateAttempts: Set<WaitForStateAttempt> = []
private var addServiceCompletion: AddServiceCompletion?
private var startAdvertisingCompletion: StartAdvertisingCompletion?
private var readyToUpdateCallback: ReadyToUpdateSubscribersCallback?
private var addServiceAttempts: Set<AddServiceAttempt> = []
private var cbPeripheralManagerDelegateProxy: CBPeripheralManagerDelegateProxy?
public init(with peripheralManager: CBPeripheralManagerType,
queue: DispatchQueue?,
options: [String : Any]? = nil,
stateUpdate: BluetoothStateUpdate? = nil) {
cbPeripheralManager = peripheralManager
bluetoothStateUpdate = stateUpdate
super.init()
cbPeripheralManager.cbDelegate = self
}
public convenience init(queue: DispatchQueue?,
options: [String : Any]? = nil,
stateUpdate: BluetoothStateUpdate? = nil) {
let manager = CBPeripheralManager(delegate: nil, queue: queue, options: options)
self.init(with: manager, queue: queue, options: options, stateUpdate: stateUpdate)
self.cbPeripheralManagerDelegateProxy = CBPeripheralManagerDelegateProxy(withTarget: self)
manager.delegate = cbPeripheralManagerDelegateProxy
}
public func waitForPoweredOn(withTimeout timeout: TimeInterval = 3, completion: @escaping WaitForStateCompletion) {
wait(for: .poweredOn, timeout: timeout, completion: completion)
}
public func wait(for state: ManagerState, timeout: TimeInterval = 3, completion: @escaping WaitForStateCompletion) {
if state == self.state {
completion(state)
return
}
let timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(handleWaitStateTimeoutReached(_:)), userInfo: nil, repeats: false)
let waitForStateAttempt = WaitForStateAttempt(state: state, completion: completion, timer: timer)
waitForStateAttempts.update(with: waitForStateAttempt)
}
public func add(_ service: CBMutableService, completion: @escaping AddServiceCompletion) {
let addServiceAttempt = AddServiceAttempt(service: service, completion: completion)
addServiceAttempts.update(with: addServiceAttempt)
cbPeripheralManager.add(service)
}
public func remove(_ service: CBMutableService) {
cbPeripheralManager.remove(service)
}
public func removeAllServices() {
cbPeripheralManager.removeAllServices()
}
public func startAdvertising(_ advertisementData: [String : Any]?, completion: @escaping StartAdvertisingCompletion) {
startAdvertisingCompletion = completion
cbPeripheralManager.startAdvertising(advertisementData)
}
public func startAdvertising(with localName: String? = nil, UUIDs: [CBUUID]? = nil, completion: @escaping StartAdvertisingCompletion) {
var advertisementData: [String : Any] = [:]
if let localName = localName {
advertisementData[CBAdvertisementDataLocalNameKey] = localName
}
if let UUIDs = UUIDs {
advertisementData[CBAdvertisementDataServiceUUIDsKey] = UUIDs
}
startAdvertising(advertisementData, completion: completion)
}
public func stopAdvertising() {
cbPeripheralManager.stopAdvertising()
}
public func updateValue(_ value: Data, for characteristic: CBMutableCharacteristic, onSubscribedCentrals centrals: [CBCentral]?, readyToUpdateCallback: @escaping ReadyToUpdateSubscribersCallback) -> Bool {
self.readyToUpdateCallback = readyToUpdateCallback
return cbPeripheralManager.updateValue(value, for: characteristic, onSubscribedCentrals: centrals)
}
public func respond(to request: CBATTRequest, withResult result: CBATTError.Code) {
cbPeripheralManager.respond(to: request, withResult: result)
}
public func setDesiredConnectionLatency(_ latency: CBPeripheralManagerConnectionLatency, for central: CBCentral) {
cbPeripheralManager.setDesiredConnectionLatency(latency, for: central)
}
// MARK: Utilities
private func getWaitForStateAttempt(for timer: Timer) -> WaitForStateAttempt? {
return waitForStateAttempts.filter { $0.timer == timer }.last
}
}
// MARK: Timers handling.
extension PeripheralManager {
@objc private func handleWaitStateTimeoutReached(_ timer: Timer) {
Logger.debug("ble wait for state timeout reached.")
if let attempt = getWaitForStateAttempt(for: timer), attempt.isValid {
attempt.invalidate()
attempt.completion(state)
waitForStateAttempts.remove(attempt)
Logger.debug("Invalidated wait for state attempt: \(attempt).")
Logger.debug("Wait for state attempts: \(waitForStateAttempts).")
}
}
}
// MARK: CBPeripheralManager delegate.
extension PeripheralManager: CBPeripheralManagerDelegateType {
public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManagerType) {
Logger.debug("peripheral manager updated state: \(state)")
var toRemove: Set<WaitForStateAttempt> = []
waitForStateAttempts.filter({ $0.isValid && $0.state == state }).forEach {
Logger.debug("Wait for state attempt success.")
$0.completion(state)
$0.invalidate()
toRemove.insert($0)
Logger.debug("Invalidated wait for state attempt: \($0).")
}
waitForStateAttempts.subtract(toRemove)
bluetoothStateUpdate?(state)
NotificationCenter.default.post(name: PeripheralManagerNotification.stateChanged.notificationName,
object: self,
userInfo: ["state": state])
Logger.debug("Wait for state attempts: \(waitForStateAttempts).")
}
public func peripheralManager(_ peripheral: CBPeripheralManagerType, didAdd service: CBServiceType, error: Error?) {
if let attempt = addServiceAttempts.filter({ $0.service.uuid.uuidString == service.uuid.uuidString }).first {
if let error = error {
attempt.completion(.failure(PeripheralManagerError.cbError(error)))
}
else {
let service = Service(with: service)
attempt.completion(.success(service))
}
addServiceAttempts.remove(attempt)
}
}
public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManagerType, error: Error?) {
if let error = error {
startAdvertisingCompletion?(.failure(PeripheralManagerError.cbError(error)))
}
else {
startAdvertisingCompletion?(.success(()))
}
}
public func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManagerType) {
readyToUpdateCallback?()
}
public func peripheralManager(_ peripheral: CBPeripheralManagerType, didReceiveRead request: CBATTRequest) {
readRequestCallback?(request)
}
public func peripheralManager(_ peripheral: CBPeripheralManagerType, didReceiveWrite requests: [CBATTRequest]) {
writeRequestsCallback?(requests)
}
public func peripheralManager(_ peripheral: CBPeripheralManagerType, willRestoreState dict: [String : Any]) { }
public func peripheralManager(_ peripheral: CBPeripheralManagerType, central: CBCentral, didSubscribeTo characteristic: CBCharacteristicType) { }
public func peripheralManager(_ peripheral: CBPeripheralManagerType, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristicType) { }
public func peripheralManager(_ peripheral: CBPeripheralManagerType, didOpen channel: CBL2CAPChannel?, error: Error?) { }
public func peripheralManager(_ peripheral: CBPeripheralManagerType, didPublishL2CAPChannel PSM: CBL2CAPPSM, error: Error?) { }
public func peripheralManager(_ peripheral: CBPeripheralManagerType, didUnpublishL2CAPChannel PSM: CBL2CAPPSM, error: Error?) { }
}
// MARK: Public Support.
public extension PeripheralManager {
enum PeripheralManagerError: Error {
case cbError(Error)
}
enum PeripheralManagerNotification: String {
case stateChanged = "it.able.peripheralmanager.statechangednotification"
var notificationName: Notification.Name {
return Notification.Name(rawValue)
}
}
enum ManagerNotification: String {
case bluetoothStateChanged = "it.able.centralmanager.bluetoothstatechangednotification"
var notificationName: Notification.Name {
return Notification.Name(rawValue)
}
}
}
// MARK: Private Support.
private extension PeripheralManager {
struct WaitForStateAttempt: Hashable {
var state: ManagerState
var completion: WaitForStateCompletion
var timer: Timer
var isValid: Bool {
return timer.isValid
}
func invalidate() {
timer.invalidate()
}
static func == (lhs: WaitForStateAttempt, rhs: WaitForStateAttempt) -> Bool {
return lhs.timer == rhs.timer
}
func hash(into hasher: inout Hasher) {
hasher.combine(timer.hashValue)
}
}
struct AddServiceAttempt: Hashable {
private (set) var service: CBMutableService
private (set) var completion: AddServiceCompletion
static func == (lhs: AddServiceAttempt, rhs: AddServiceAttempt) -> Bool {
return lhs.hashValue == rhs.hashValue
}
func hash(into hasher: inout Hasher) {
hasher.combine(service.hashValue)
}
}
}
// MARK: Aliases.
public extension PeripheralManager {
typealias BluetoothStateUpdate = ((ManagerState) -> Void)
typealias WaitForStateCompletion = ((ManagerState) -> (Void))
typealias AddServiceCompletion = ((Result<Service, PeripheralManagerError>) -> Void)
typealias StartAdvertisingCompletion = ((Result<Void, PeripheralManagerError>) -> (Void))
typealias ReadyToUpdateSubscribersCallback = (() -> Void)
typealias ReadRequestCallback = ((CBATTRequest) -> Void)
typealias WriteRequestsCallback = (([CBATTRequest]) -> Void)
}
|
mit
|
2715c3bc452a799ce20919188674aa0a
| 39.157706 | 209 | 0.677794 | 5.489466 | false | false | false | false |
Pacific3/P3UIKit
|
Sources/Operations/Observers/P3NetworkActivityObserver.swift
|
1
|
2559
|
//
// P3NetworkActivityObserver.swift
// P3UIKit
//
// Created by Oscar Swanros on 6/17/16.
// Copyright © 2016 Pacific3. All rights reserved.
//
#if os(iOS)
public struct P3NetworkActivityObserver: P3OperationObserver {
public init() { }
public func operationDidStart(operation: Operation) {
p3_executeOnMainThread {
NetworkIndicatorManager.sharedManager.networkActivityDidStart()
}
}
public func operationDidFinish(operation: Operation, errors: [NSError]) {
p3_executeOnMainThread {
NetworkIndicatorManager.sharedManager.networkActivityDidEnd()
}
}
public func operation(operation: Operation, didProduceOperation newOperation: Operation) { }
public func operationDidCancel(operation: Operation) {
p3_executeOnMainThread {
NetworkIndicatorManager.sharedManager.networkActivityDidEnd()
}
}
}
private class NetworkIndicatorManager {
static let sharedManager = NetworkIndicatorManager()
private var activiyCount = 0
private var visibilityTimer: Timer?
func networkActivityDidStart() {
assert(Thread.isMainThread, "Only on main thread!")
activiyCount += 1
updateNetworkActivityIndicatorVisibility()
}
func networkActivityDidEnd() {
assert(Thread.isMainThread, "Only on main thread!")
activiyCount -= 1
updateNetworkActivityIndicatorVisibility()
}
private func updateNetworkActivityIndicatorVisibility() {
if activiyCount > 0 {
showIndicator()
} else {
visibilityTimer = Timer(interval: 1.0) {
self.hideIndicator()
}
}
}
private func showIndicator() {
visibilityTimer?.cancel()
visibilityTimer = nil
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
private func hideIndicator() {
visibilityTimer?.cancel()
visibilityTimer = nil
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
private class Timer {
var isCancelled = false
init(interval: TimeInterval, handler: @escaping () -> Void) {
let when = DispatchTime.now() + interval
DispatchQueue.main.asyncAfter(deadline: when) { [weak self] in
if self?.isCancelled == false {
handler()
}
}
}
func cancel() {
isCancelled = true
}
}
#endif
|
mit
|
51ee9ea1fae93943625a8b82439f9858
| 25.102041 | 96 | 0.623925 | 5.307054 | false | false | false | false |
MakeSchool/Swift-Playgrounds
|
P0-Var-And-Let.playground/Contents.swift
|
4
|
2224
|
/*:
# Welcome to Swift!
This is the first in a series of short tutorials designed to get you up to speed with Swift-specific topics. You all have seen at least one programming language before, so these tutorials are going to focus on things that are new or special to Swift. We love Swift and hope you will too!
*/
/*:
# Variables
Variables associate a name to a value. Here's how you would declare a variable in Swift:
*/
var height = 6
/*:
We just declared a variable called `height` and set its initial value to `6`. Let's try changing that value.
*/
height = 10
height
/*:
If you look at the right side of your screen, you will see the value of `height` has changed to 10. As long as you define a variable with the keyword `var`, you can change its value later on.
*/
/*:
# Constants
Unlike variables, constants can not be changed. You can declare a constant using the word `let`:
*/
let pi = 3.14 // Mmm, pi.
/*:
Suppose we want to try to bend the rules of mathematics and change the value of pi. Try changing `pi` by uncommenting the following line. You can uncomment it by deleting the `//`
*/
// pi = 2
/*:
Notice that you get an error on that line. This is because you cannot change the value of a constant. Clicking on the error sign would show you the following:
`Cannot assign to 'let' value 'pi'`
If you've declared a variable using `let`, you will not be able to change its value later on.
To get rid of the error, comment it again by adding `//` to the beginning of that line.
*/
/*:
## Naming Variables and Constants
When naming variables and constants, most Swift programmers use a convention called CamelCase. Here's how you can follow it:
*/
// Correct
var yourHeight = 5
let upcomingAppVersion = 1.1
// Wrong
var YourHeight = 6
let Upcomingappversion = 1.1
/*:
The rules are as follows:
* Start the first word in the variable name with a lowercase letter.
* Start any subsequent word with an uppercase letter.
*/
/*:
For more details on what we covered in this tutorial, please visit [Apple's Variables and Constants guide.](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID310)
*/
|
mit
|
48c4e911f3b584993c42008523cc4a16
| 30.323944 | 287 | 0.740108 | 3.834483 | false | false | false | false |
randymarsh77/scope
|
Sources/Scope/Scope.swift
|
1
|
388
|
import IDisposable
public typealias DisposeFunc = () -> ()
public class Scope: IDisposable {
var disposeFunc: DisposeFunc? = nil
public init(dispose: DisposeFunc?) {
disposeFunc = dispose
}
public func dispose() {
disposeFunc?()
disposeFunc = nil
}
public func transfer() -> Scope {
let newScope = Scope(dispose: disposeFunc)
disposeFunc = nil
return newScope
}
}
|
mit
|
802039425de87cd340ca1450205c5f4d
| 16.636364 | 44 | 0.698454 | 3.495495 | false | false | false | false |
asp2insp/Nuclear-Swift
|
NuclearTests/ImmutableTests.swift
|
1
|
8226
|
//
// ImmutableTests.swift
// Nuclear
//
// Created by Josiah Gaskin on 5/5/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import UIKit
import XCTest
class ImmutableTests: XCTestCase {
override func setUp() {
super.setUp()
}
// Test contains
func testContainsValueArray() {
let state = Immutable.toState([0, 1, 2, 3, "true", false, 5])
XCTAssertTrue(state.containsValue(3), "")
XCTAssertTrue(state.containsValue("true"), "")
XCTAssertTrue(state.containsValue(false), "")
XCTAssertFalse(state.containsValue(-1), "")
}
func testContainsValueMap() {
let state = Immutable.toState(["items": ["eggs", "milk"], "total": 5])
XCTAssertTrue(state.containsValue(5), "")
XCTAssertFalse(state.containsValue("items"), "")
}
func testContainsKeyMap() {
let state = Immutable.toState(["items": ["eggs", "milk"], "total": 5])
XCTAssertTrue(state.containsKey("items"), "")
XCTAssertTrue(state.containsKey("total"), "")
XCTAssertFalse(state.containsKey("hello"), "")
}
// Test dirty marks
func testSetInMarksAsDirty() {
var state = Immutable.toState([:])
state = state.setIn(["a", 5], withValue: Immutable.toState(75))
XCTAssertTrue(state.getIn(["a", 5]) === state.getIn(["a", 5]), "Identity failed on same value")
XCTAssertTrue(state.getIn(["a", 2]) === state.getIn(["a", 2]), "Identity failed on None")
// Test replace
state = state.setIn(["b", 10], withValue: Immutable.toState(30))
let oldValue = state.getIn(["a", 5])
let oldRoot = state
let oldArray = state.getIn(["a"])
let oldUntouched = state.getIn(["b", 10])
state = state.setIn(["a", 5], withValue: Immutable.toState(88))
XCTAssertFalse(oldValue === state.getIn(["a", 5]), "Updated value should have different tag")
XCTAssertFalse(oldArray === state.getIn(["a"]), "Array with updated child should have different tag")
XCTAssertFalse(oldRoot === state, "Map with updated child should have different tag")
XCTAssertTrue(oldUntouched === state.getIn(["b", 10]), "")
}
// Test mutators
func testSetIn() {
var state = Immutable.toState([:])
state = state.setIn(["a", 0, "b"], withValue: Immutable.toState("Hello!"))
XCTAssertEqual("(Map {a : (Array [(Map {b : (Value)})])})", state.description(), "")
XCTAssertEqual("Hello!", Immutable.fromState(state.getIn(["a", 0, "b"])) as! String, "")
// Test auto fill arrays increment
state = state.setIn(["a", 5], withValue: Immutable.toState(75))
XCTAssertEqual("(Map {a : (Array [(Map {b : (Value)}), (None), (None), (None), (None), (Value)])})", state.description(), "")
XCTAssertEqual(75, Immutable.fromState(state.getIn(["a", 5])) as! Int, "")
// Test replace
state = state.setIn(["a", 5], withValue: Immutable.toState(88))
XCTAssertEqual(88, Immutable.fromState(state.getIn(["a", 5])) as! Int, "")
}
// Test mapping transformation
func testMap() {
let state = Immutable.toState([0, 1, 2, 3, 4, 5])
let plusThree = state.map({(int, index) in
return Immutable.toState(int.toSwift() as! Int + 3)
})
let native = plusThree.toSwift() as! [Any?]
for var i = 0; i < 5; i++ {
XCTAssertEqual(i+3, native[i] as! Int, "")
}
}
// Test reducing transformation
func testReduce() {
let state = Immutable.toState([0, 1, 2, 3, 4, 5])
let summed = state.reduce(Immutable.toState(0), f: {(sum, one) in
let a = sum.toSwift() as! Int
let b = one.toSwift() as! Int
return Immutable.toState(a + b)
})
XCTAssertEqual(15, summed.toSwift() as! Int, "")
}
// Test helper functions that convert back from state
func testFromStateNested() {
let state = Immutable.toState(["shopping_cart": ["items": ["eggs", "milk"], "total": 5]])
let native = Immutable.fromState(state) as! [String:Any?]
let cart = native["shopping_cart"] as! [String:Any?]
let items = cart["items"] as! [Any?]
XCTAssertEqual(5, cart["total"] as! Int, "")
XCTAssertEqual("eggs", items[0] as! String, "")
XCTAssertEqual("milk", items[1] as! String, "")
}
func testConvertBackFromArray() {
let state = Immutable.convertArray([0, 1, 2, 3])
let native = Immutable.convertArrayBack(state)
XCTAssertEqual(4, native.count, "There should be 4 items in the round-tripped array")
for var i = 0; i < 3; i++ {
XCTAssertEqual(i, native[i] as! Int, "")
}
}
func testConvertBackFromMap() {
let state = Immutable.convertMap(["hello":"world", "eggs":12])
let native = Immutable.convertMapBack(state)
XCTAssertEqual(2, native.count, "There should be 2 items in the round-tripped array")
XCTAssertEqual("world", native["hello"] as! String, "")
XCTAssertEqual(12, native["eggs"] as! Int, "")
}
// Test comparison by tag, and marking as dirty
func testTagging() {
let a = Immutable.State.Value(5, 2)
let b = Immutable.State.Value(5, 3)
XCTAssertFalse(a === b, "States should be compared by tag not by value")
XCTAssertTrue(a === a, "States should be self-identical")
}
// Test deep conversion to state
func testDeepNestedToState() {
let a = ["shopping_cart": ["items": ["eggs", "milk"], "total": 5]]
let stateRep = Immutable.toState(a)
let expected = "(Map {shopping_cart : (Map {items : (Array [(Value), (Value)]), total : (Value)})})"
XCTAssertEqual(expected, stateRep.description(), "")
}
// Test simple conversion to state
func testValueToState() {
let a = 5
let stateRep = Immutable.toState(a)
XCTAssertEqual( "(Value)", stateRep.description(), "")
let b = "hello"
let stateRep2 = Immutable.toState(b)
XCTAssertEqual("(Value)", stateRep2.description(), "")
}
// Test deep conversion to state
func testMapToState() {
let a = ["total": 5]
let stateRep = Immutable.toState(a)
let expected = "(Map {total : (Value)})"
XCTAssertEqual(expected, stateRep.description(), "")
}
// Test deep conversion to state
func testArrayToState() {
let a = ["eggs", "milk"]
let stateRep = Immutable.toState(a)
let expected = "(Array [(Value), (Value)])"
XCTAssertEqual(expected, stateRep.description(), "")
let b = [1, 2, 3]
let stateRep2 = Immutable.toState(b)
let expected2 = "(Array [(Value), (Value), (Value)])"
XCTAssertEqual(expected2, stateRep2.description(), "")
}
// Test helper functions that convert to state
func testConvertArray() {
let a = ["eggs", "milk", 45]
let stateRep = Immutable.State.Array(Immutable.convertArray(a), 4)
let expected = "(Array [(Value), (Value), (Value)])"
XCTAssertEqual(expected, stateRep.description(), "")
}
// Test helper functions that convert to state
func testConvertMap() {
let a = ["eggs":10, "milk":"one"]
let stateRep = Immutable.State.Map(Immutable.convertMap(a), 3)
let expected = "(Map {eggs : (Value), milk : (Value)})"
XCTAssertEqual(expected, stateRep.description(), "")
}
// Ensure that our to string works since we'll be basing everything else on it
func testDescription() {
XCTAssertEqual("(Value)", Immutable.State.Value(3, 1).description(), "")
XCTAssertEqual("(Array [(Value)])", Immutable.State.Array([Immutable.State.Value(3, 1)], 2).description(), "")
XCTAssertEqual("(Map {hello : (Value)})", Immutable.State.Map(["hello":Immutable.State.Value(3, 1)], 2).description(), "")
}
}
|
mit
|
fe3bc16447c2fb918cc44c5e2ee90654
| 37.624413 | 133 | 0.574155 | 4.177755 | false | true | false | false |
ahcode0919/swift-design-patterns
|
swift-design-patterns/swift-design-patterns/Models/Vehicle/Wheel.swift
|
1
|
545
|
//
// Wheel.swift
// swift-design-patterns
//
// Created by Aaron Hinton on 10/28/17.
// Copyright © 2017 No Name Software. All rights reserved.
//
import Foundation
enum Wheel: Equatable {
case offroad(size: WheelSize), touring(size: WheelSize)
static func ==(lhs: Wheel, rhs: Wheel) -> Bool {
switch (lhs, rhs) {
case let (.offroad(l), .offroad(r)):
return l == r
case let (.touring(l), .touring(r)):
return l == r
default:
return false
}
}
}
|
mit
|
b4faaefee1730972c13773e099ffecfa
| 21.666667 | 59 | 0.553309 | 3.555556 | false | false | false | false |
dreamsxin/swift
|
stdlib/public/core/Boolean.swift
|
3
|
7864
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Boolean
//===----------------------------------------------------------------------===//
/// Performs a logical NOT operation on a Boolean value.
///
/// The logical NOT operator (`!`) inverts a Boolean value. If the value is
/// `true`, the result of the operation is `false`; if the value is `false`,
/// the result is `true`. For example:
///
/// var printedMessage = false
///
/// if !printedMessage {
/// print("You look nice today!")
/// printedMessage = true
/// }
/// // Prints "You look nice today!"
///
/// - Parameter a: The Boolean value to negate.
public prefix func !<T : Boolean>(a: T) -> Bool {
return !a.boolValue
}
/// Performs a logical AND operation on two Boolean values.
///
/// The logical AND operator (`&&`) combines two Boolean values and returns
/// `true` if both of the values are `true`. If either of the values is
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `true`. For example:
///
/// let measurements = [7.44, 6.51, 4.74, 5.88, 6.27, 6.12, 7.76]
/// let sum = measurements.reduce(0, combine: +)
///
/// if measurements.count > 0 && sum / Double(measurements.count) < 6.5 {
/// print("Average measurement is less than 6.5")
/// }
/// // Prints "Average measurement is less than 6.5"
///
/// In this example, `lhs` tests whether `measurements.count` is greater than
/// zero. Evaluation of the `&&` operator is one of the following:
///
/// - When `measurements.count` is equal to zero, `lhs` evaluates to `false`
/// and `rhs` is not evaluated, preventing a divide-by-zero error in the
/// expression `sum / Double(measurements.count)`. The result of the
/// operation is `false`.
/// - When `measurements.count` is greater than zero, `lhs` evaluates to `true`
/// and `rhs` is evaluated. The result of evaluating `rhs` is the result of
/// the `&&` operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
@inline(__always)
public func && <T : Boolean, U : Boolean>(
lhs: T, rhs: @autoclosure () throws -> U
) rethrows -> Bool {
return lhs.boolValue ? try rhs().boolValue : false
}
/// Performs a logical OR operation on two Boolean values.
///
/// The logical OR operator (`||`) combines two Boolean values and returns
/// `true` if at least one of the values is `true`. If both values are
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `false`. For example:
///
/// let majorErrors: Set = ["No first name", "No last name", ...]
/// let error = ""
///
/// if error.isEmpty || !majorErrors.contains(error) {
/// print("No major errors detected")
/// } else {
/// print("Major error: \(error)")
/// }
/// // Prints "No major errors detected")
///
/// In this example, `lhs` tests whether `error` is an empty string. Evaluation
/// of the `||` operator is one of the following:
///
/// - When `error` is an empty string, `lhs` evaluates to `true` and `rhs` is
/// not evaluated, skipping the call to `majorErrors.contains(_:)`. The
/// result of the operation is `true`.
/// - When `error` is not an empty string, `lhs` evaluates to `false` and `rhs`
/// is evaluated. The result of evaluating `rhs` is the result of the `||`
/// operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
@inline(__always)
public func || <T : Boolean, U : Boolean>(
lhs: T, rhs: @autoclosure () throws -> U
) rethrows -> Bool {
return lhs.boolValue ? true : try rhs().boolValue
}
/// Performs a logical AND operation on two Boolean values.
///
/// The logical AND operator (`&&`) combines two Boolean values and returns
/// `true` if both of the values are `true`. If either of the values is
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `true`. For example:
///
/// let measurements = [7.44, 6.51, 4.74, 5.88, 6.27, 6.12, 7.76]
/// let sum = measurements.reduce(0, combine: +)
///
/// if measurements.count > 0 && sum / Double(measurements.count) < 6.5 {
/// print("Average measurement is less than 6.5")
/// }
/// // Prints "Average measurement is less than 6.5"
///
/// In this example, `lhs` tests whether `measurements.count` is greater than
/// zero. Evaluation of the `&&` operator is one of the following:
///
/// - When `measurements.count` is equal to zero, `lhs` evaluates to `false`
/// and `rhs` is not evaluated, preventing a divide-by-zero error in the
/// expression `sum / Double(measurements.count)`. The result of the
/// operation is `false`.
/// - When `measurements.count` is greater than zero, `lhs` evaluates to `true`
/// and `rhs` is evaluated. The result of evaluating `rhs` is the result of
/// the `&&` operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
// FIXME: We can't make the above @_transparent due to
// rdar://problem/19418937, so here are some @_transparent overloads
// for Bool. We've done the same for ObjCBool.
@_transparent
public func && <T : Boolean>(
lhs: T, rhs: @autoclosure () throws -> Bool
) rethrows -> Bool {
return lhs.boolValue ? try rhs().boolValue : false
}
/// Performs a logical OR operation on two Boolean values.
///
/// The logical OR operator (`||`) combines two Boolean values and returns
/// `true` if at least one of the values is `true`. If both values are
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `false`. For example:
///
/// let majorErrors: Set = ["No first name", "No last name", ...]
/// let error = ""
///
/// if error.isEmpty || !majorErrors.contains(error) {
/// print("No major errors detected")
/// } else {
/// print("Major error: \(error)")
/// }
/// // Prints "No major errors detected")
///
/// In this example, `lhs` tests whether `error` is an empty string. Evaluation
/// of the `||` operator is one of the following:
///
/// - When `error` is an empty string, `lhs` evaluates to `true` and `rhs` is
/// not evaluated, skipping the call to `majorErrors.contains(_:)`. The
/// result of the operation is `true`.
/// - When `error` is not an empty string, `lhs` evaluates to `false` and `rhs`
/// is evaluated. The result of evaluating `rhs` is the result of the `||`
/// operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
@_transparent
public func || <T : Boolean>(
lhs: T, rhs: @autoclosure () throws -> Bool
) rethrows -> Bool {
return lhs.boolValue ? true : try rhs().boolValue
}
|
apache-2.0
|
27e0b8483a604cde105da01dcb338617
| 39.746114 | 80 | 0.622711 | 3.750119 | false | false | false | false |
hongxinhope/TBRepeatPicker
|
TBRepeatPicker/TBRPCollectionItem.swift
|
1
|
2593
|
//
// TBRPCollectionItem.swift
// TBRepeatPicker
//
// Created by hongxin on 15/9/25.
// Copyright © 2015年 Teambition. All rights reserved.
//
import UIKit
private let lineWidth: CGFloat = 0.5
class TBRPCollectionItem: UICollectionViewCell {
// MARK: - Public properties
var textLabel: UILabel?
var showTopLine = true
var showBottomLine = true
var showLeftLine = true
var showRightLine = true
// MARK: - Private properties
private let topLine = CALayer()
private let bottomLine = CALayer()
private let leftLine = CALayer()
private let rightLine = CALayer()
// MARK: - View life cycle
override init(frame: CGRect) {
super.init(frame: frame)
textLabel = UILabel(frame: CGRectMake(lineWidth, lineWidth, bounds.size.width - 2 * lineWidth, bounds.size.height - 2 * lineWidth))
textLabel?.textAlignment = .Center
backgroundView = textLabel
// add separator line
topLine.frame = CGRectMake(0, 0, bounds.size.width, lineWidth)
topLine.backgroundColor = separatorColor()
bottomLine.frame = CGRectMake(0, bounds.size.height - lineWidth, bounds.size.width, lineWidth)
bottomLine.backgroundColor = separatorColor()
leftLine.frame = CGRectMake(0, 0, lineWidth, bounds.size.height)
leftLine.backgroundColor = separatorColor()
rightLine.frame = CGRectMake(bounds.size.width - lineWidth, 0, lineWidth, bounds.size.height)
rightLine.backgroundColor = separatorColor()
layer.addSublayer(topLine)
layer.addSublayer(bottomLine)
layer.addSublayer(leftLine)
layer.addSublayer(rightLine)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
topLine.hidden = !showTopLine
bottomLine.hidden = !showBottomLine
leftLine.hidden = !showLeftLine
rightLine.hidden = !showRightLine
}
// MARK: - Helper
private func separatorColor() -> CGColorRef {
return UIColor.init(white: 187.0 / 255.0, alpha: 1.0).CGColor
}
func setItemSelected(selected: Bool) {
if selected == true {
textLabel?.backgroundColor = tintColor
textLabel?.textColor = UIColor.whiteColor()
} else {
textLabel?.backgroundColor = UIColor.whiteColor()
textLabel?.textColor = UIColor.blackColor()
}
}
}
|
mit
|
e63c69c8db17d5b99b0b983a547624ad
| 30.975309 | 139 | 0.637452 | 4.769797 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Models/Base/ModelHandler.swift
|
1
|
1263
|
//
// ModelHandler.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 13/01/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
protocol ModelHandler {
func add(_ values: JSON, realm: Realm)
func update(_ values: JSON, realm: Realm)
func remove(_ values: JSON, realm: Realm)
}
extension ModelHandler where Self: BaseModel {
static func handle(msg: ResponseMessage, primaryKey: String, values: JSON) {
Realm.execute({ (realm) in
var object: Self!
if let existentObject = realm.object(ofType: Self.self, forPrimaryKey: primaryKey as AnyObject) {
object = existentObject
}
if object == nil {
object = Self()
object.setValue(primaryKey, forKey: Self.primaryKey() ?? "")
}
switch msg {
case .added, .inserted:
object.add(values, realm: realm)
case .changed:
object.update(values, realm: realm)
case .removed:
object.remove(values, realm: realm)
default:
object.update(values, realm: realm)
}
})
}
}
|
mit
|
52ca150bbfb9380c10306df4f7875904
| 27.044444 | 109 | 0.569731 | 4.491103 | false | false | false | false |
KhunLam/Swift_weibo
|
LKSwift_weibo/LKSwift_weibo/Classes/Module/Oauth/Controller/LKOauthViewController.swift
|
1
|
6071
|
//
// LKOauthViewController.swift
// LKSwift_weibo
//
// Created by lamkhun on 15/10/29.
// Copyright © 2015年 lamKhun. All rights reserved.
//
import UIKit
import SVProgressHUD
class LKOauthViewController: UIViewController {
//MARK: -------------------私有属性-------------------
//MARK: -------------------对外属性-------------------
//MARK: -------------------私有方法-------------------
/// 关闭控制器
func close() {
// 退出控制器
dismissViewControllerAnimated(true, completion: nil)
// 关闭正在加载
SVProgressHUD.dismiss()
}
// /// 自动填充账号密码
// func autoFill() {
// let js = "document.getElementById('userId').value='账号';" + "document.getElementById('passwd').value='密码';"
// // webView执行js代码
// webView.stringByEvaluatingJavaScriptFromString(js)
// }
// MARK: - 懒加载
private lazy var webView = UIWebView()
//MARK: -------------------对外方法-------------------
override func loadView() {
view = webView
// 设置代理
webView.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// 设导航栏退出按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
/// 自动填充账号密码
// navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
// 加载网页
let request = NSURLRequest(URL: LKNetworkTools.sharedInstance.oauthRUL())
webView.loadRequest(request)
}
}
// MARK: - 扩展 CZOauthViewController 实现 UIWebViewDelegate 协议
extension LKOauthViewController: UIWebViewDelegate {
/// 开始加载请求
func webViewDidStartLoad(webView: UIWebView){
// 显示正在加载
// showWithStatus 不主动关闭,会一直显示
SVProgressHUD.showWithStatus("正在玩命加载...", maskType: SVProgressHUDMaskType.Black)
}
/// 加载请求完毕
func webViewDidFinishLoad(webView: UIWebView){
// 关闭正在加载
SVProgressHUD.dismiss()
}
/// 询问是否加载 request
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
// 得到的就是 OAtuhURL授权地址
// 若 点击授权 就会得到 回调地址+ code
//urlString:Optional("http://www.baidu.com/?code=6c57029d0c97236b3ac44efe22336561")
let urlString = request.URL!.absoluteString
print("urlString:\(urlString)")
// 加载的不是回调地址
if !urlString.hasPrefix(LKNetworkTools.sharedInstance.redirect_uri) {
return true // 直接返回 可以加载
}
// 判断点击的是 确定(加载) 还是 取消(拦截) 通过是否http://www.baidu.com/? 后是否 紧接 code=
// http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
// http://www.baidu.com/?code=6c57029d0c97236b3ac44efe22336561
if let query = request.URL?.query {
print("query:\(query)")//打印的 就是 没了http://www.baidu.com/? 的
// 定义开头 是就是点击确定
let codeString = "code="
if query.hasPrefix(codeString) {
// 确定
// code=6c57029d0c97236b3ac44efe22336561
// 转成NSString
let nsQuery = query as NSString
//截取后面的code值6c57029d0c97236b3ac44efe22336561 不要code=
let code = nsQuery.substringFromIndex(codeString.characters.count)
print("code: \(code)")
//通过code值 获取access token
loadAccessToken(code)
} else {
// 取消
}
}
return false
}
/// 加载失败回调
func webView(webView: UIWebView, didFailLoadWithError error: NSError?){
// 关闭正在加载
SVProgressHUD.dismiss()
}
/**
调用网络工具类去加载加载access token
- parameter code: code
*/
func loadAccessToken(code: String){
LKNetworkTools.sharedInstance.loadAccessToken(code)
{ (result, error) -> () in
// 如果 出错了 就提示
if error != nil || result == nil {
self.netError("网络不给力...")
return
}
print("result: \(result)")
// 将数据 给模型
let account = LKUserAccount(dict: result!)
// 保存到沙盒
account.saveAccount()
// 加载用户数据
account.loadUserInfo({ (error) -> () in
if error != nil {
print("加载用户数据出错: \(error)")
self.netError("加载用户数据出错...")
return
}
print("account:\(LKUserAccount.loadAccount())")
self.close()
// 切换控制器 ---> false 进入 欢迎界面
(UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(false)
})
}
}
//MARK: - 出错了 提示 方法
private func netError(message: String) {
SVProgressHUD.showErrorWithStatus(message, maskType: SVProgressHUDMaskType.Black)
// 延迟关闭. dispatch_after 没有提示,可以拖oc的dispatch_after来修改
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
self.close()
})
}
}
|
apache-2.0
|
ce3f96070bc314670768c04b71070526
| 31.660606 | 151 | 0.552524 | 4.391198 | false | false | false | false |
jcfausto/transit-app
|
TransitApp/TransitApp/Stop.swift
|
1
|
1284
|
//
// Stop.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 24/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import Foundation
import Unbox
struct Stop {
var name: String?
var longitude: Double
var latitude: Double
var time: NSDate
init(name: String, latitude: Double, longitude: Double, time: NSDate){
self.name = name
self.latitude = latitude
self.longitude = longitude
self.time = time
}
}
// MARK: extensions
extension Stop: Unboxable {
init(unboxer: Unboxer) {
self.name = unboxer.unbox("name")
self.latitude = unboxer.unbox("lat")
self.longitude = unboxer.unbox("lng")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
self.time = unboxer.unbox("datetime", formatter: DateFormatter.sharedInstance.formatterForJsonConversion)
}
}
// MARK: equatable
extension Stop: Equatable {}
func ==(lhs: Stop, rhs: Stop) -> Bool {
let areEqual = lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
return areEqual
}
|
mit
|
1aabc092fbb6ee8dee8dcacb7fc7b057
| 24.176471 | 113 | 0.655495 | 4.112179 | false | false | false | false |
NUKisZ/TestKitchen_1606
|
TestKitchen/TestKitchen/classes/cookbook/recommend/model/CBRecommendModel.swift
|
1
|
4788
|
//
// CBRecommendModel.swift
// TestKitchen
//
// Created by NUK on 16/8/16.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
import SwiftyJSON
class CBRecommendModel: NSObject {
var code:NSNumber?
var msg:Bool?
var version:String?
var timestamp:NSNumber?
var data:CBRecommendDataModel?
class func parseModel(data:NSData)->CBRecommendModel{
let model = CBRecommendModel()
let jsonData = JSON(data: data)
model.code = jsonData["code"].number
model.msg = jsonData["msg"].bool
model.version = jsonData["version"].string
model.timestamp = jsonData["timestamp"].number
let dataDict = jsonData["data"]
model.data = CBRecommendDataModel.parseModel(dataDict)
return model
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
class CBRecommendDataModel: NSObject {
var banner:Array<CBRecommendBannerModel>?
var widgetList:Array<CBRecommendWidgetListModel>?
class func parseModel(jsonData:JSON)->CBRecommendDataModel {
let model = CBRecommendDataModel()
let bannerArray = jsonData["banner"]
var bArray = Array<CBRecommendBannerModel>()
for (_,subjson) in bannerArray{
//subjson是转换成CBRecommendBannerModel类型的对象
let bannerModel = CBRecommendBannerModel.parseModel(subjson)
bArray.append(bannerModel)
}
model.banner = bArray
let listArray = jsonData["widgetList"]
var wlArray = Array<CBRecommendWidgetListModel>()
for (_,subjson) in listArray{
//subjson是转换成CBRecommendWidgetListModel类型的对象
let wlModel = CBRecommendWidgetListModel.parseModel(subjson)
wlArray.append(wlModel)
}
model.widgetList = wlArray
return model
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
class CBRecommendBannerModel: NSObject {
var banner_id:NSNumber?
var banner_title:String?
var banner_picture:String?
var banner_link:String?
var is_link:NSNumber?
var refer_key:NSNumber?
var type_id:NSNumber?
class func parseModel(jsonData:JSON)-> CBRecommendBannerModel{
let model = CBRecommendBannerModel()
model.banner_id = jsonData["banner_id"].number
model.banner_title = jsonData["banner_title"].string
model.banner_picture = jsonData["banner_picture"].string
model.banner_link = jsonData["banner_link"].string
model.is_link = jsonData["is_link"].number
model.refer_key = jsonData["refer_key"].number
model.type_id = jsonData["type_id"].number
return model
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
class CBRecommendWidgetListModel: NSObject {
var widget_id:NSNumber?
var widget_type:NSNumber?
var title:String?
var title_link:String?
var desc:String?
var widget_data:Array<CBRecommendWidgetDataModel>?
class func parseModel(jsonData:JSON)->CBRecommendWidgetListModel{
let model = CBRecommendWidgetListModel()
model.widget_id = jsonData["widget_id"].number
model.widget_type = jsonData["widget_type"].number
model.title = jsonData["title"].string
model.title_link = jsonData["title_link"].string
model.desc = jsonData["desc"].string
let dataArray = jsonData["widget_data"]
var wdArray = Array<CBRecommendWidgetDataModel>()
for (_,subjson) in dataArray{
//subjson是转换成CBRecommendWidgetDataModel类型的对象
let wdModel = CBRecommendWidgetDataModel.parseModel(subjson)
wdArray.append(wdModel)
}
model.widget_data = wdArray
return model
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
class CBRecommendWidgetDataModel: NSObject {
var id:NSNumber?
var type:String?
var content:String?
var link:String?
class func parseModel(jsonData:JSON)->CBRecommendWidgetDataModel{
let model = CBRecommendWidgetDataModel()
model.id = jsonData["id"].number
model.type = jsonData["type"].string
model.content = jsonData["content"].string
model.link = jsonData["link"].string
return model
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
|
mit
|
af2ce3ca7966f5053735b2d5ec36b769
| 25.430168 | 76 | 0.624181 | 4.769153 | false | false | false | false |
hsusmita/SHRichTextEditorTools
|
SHRichTextEditorTools/Source/Core/Extensions/UITextView+IndentationHelper.swift
|
1
|
4449
|
//
// UITextView+IndentationHelper.swift
// SHRichTextEditorTools
//
// Created by Susmita Horrow on 20/02/17.
// Copyright © 2017 hsusmita. All rights reserved.
//
import Foundation
import UIKit
public protocol IndentationEnabled {
var indentationString: String { get }
var indentationStringWithoutNewline: String { get }
}
extension IndentationEnabled {
public var indentationString: String {
return "\n\t • "
}
public var indentationStringWithoutNewline: String {
return "\t • "
}
}
public protocol IndentationProtocol {
func addIndentation(at index: Int)
func removeIndentation(at index: Int)
func toggleIndentation(at index: Int)
func indentationRange(at index: Int) -> NSRange?
func indentationPresent(at index: Int) -> Bool
}
extension UITextView: IndentationEnabled {}
extension UITextView: IndentationProtocol {
public func addIndentation(at index: Int) {
let attributedStringToAppend: NSMutableAttributedString = NSMutableAttributedString(string: indentationString)
let contentOffset = self.contentOffset
let selectedRange = selectedTextRange
attributedStringToAppend.addAttribute(NSAttributedString.Key.font,
value: self.attributedText.font(at: index) ?? font!,
range: NSRange(location: 0, length: attributedStringToAppend.length))
let updatedText: NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
updatedText.insert(attributedStringToAppend, at: index)
attributedText = updatedText
if let currentSelectedRange = selectedRange,
let start = position(from: currentSelectedRange.start, offset: attributedStringToAppend.length),
let end = position(from: currentSelectedRange.end, offset: attributedStringToAppend.length) {
selectedTextRange = textRange(from: start, to: end)
}
setContentOffset(contentOffset, animated: false)
self.delegate?.textViewDidChange?(self)
}
public func removeIndentation(at index: Int) {
guard let range = indentationRange(at: index) else {
return
}
let selectedRange = selectedTextRange
let updatedText: NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
updatedText.replaceCharacters(in: range, with: "")
attributedText = updatedText
if let currentSelectedRange = selectedRange,
let start = position(from: currentSelectedRange.start, offset: -indentationString.count),
let end = position(from: currentSelectedRange.end, offset: -indentationString.count) {
selectedTextRange = textRange(from: start, to: end)
}
setContentOffset(contentOffset, animated: false)
self.delegate?.textViewDidChange?(self)
}
public func toggleIndentation(at index: Int) {
guard let index = currentCursorPosition else {
return
}
if let _ = indentationRange(at: index) {
removeIndentation(at: index)
} else {
addIndentation(at: index)
}
}
public func indentationRange(at index: Int) -> NSRange? {
guard index < text.count else {
return nil
}
var lineRange = NSMakeRange(NSNotFound, 0)
layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
guard lineRange.location < attributedText.length else {
return nil
}
let rangeOfText = (text as NSString).substring(with: lineRange)
let indentationRange = (rangeOfText as NSString).range(of: indentationStringWithoutNewline)
if indentationRange.length == 0 {
return nil
} else {
return NSRange(location: lineRange.location - 1, length: indentationString.count)
}
}
public func indentationPresent(at index: Int) -> Bool {
guard let startOfLineIndex = startOfLineIndex, index > startOfLineIndex, index < text.count else {
return false
}
let range = NSRange(location: startOfLineIndex, length: index - startOfLineIndex)
let substring = (text as NSString).substring(with: range)
return substring.contains(indentationStringWithoutNewline)
}
func addIndentationAtStartOfLine() {
if let startOfLineIndex = startOfLineIndex {
addIndentation(at: startOfLineIndex)
}
}
func removeIndentationFromStartOfLine() {
if let startOfLineIndex = startOfLineIndex {
removeIndentation(at: startOfLineIndex)
}
}
func toggleIndentation() {
guard let index = currentCursorPosition else {
return
}
if indentationPresent(at: index) {
removeIndentationFromStartOfLine()
} else {
addIndentationAtStartOfLine()
}
}
}
|
mit
|
7fe7f5a12c9fdcc0357bbdc15b44aed2
| 31.437956 | 112 | 0.74865 | 4.168856 | false | false | false | false |
xwu/swift
|
test/expr/closure/closures.swift
|
1
|
35317
|
// RUN: %target-typecheck-verify-swift
var func6 : (_ fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{53-53= _ in}}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0
// expected-error@-1 {{cannot convert value of type 'Double' to closure result type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{27-27=()}} // expected-note {{Remove '=' to make 'closure7' a computed property}}{{20-22=}}
var capturedVariable = 1
var closure8 = { [capturedVariable] in
capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}}
}
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(_ a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6({$0 + $1}) // Closure with two named anonymous arguments
func6({($0) + $1}) // Closure with sequence expr inferred type
func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}}
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
// expected-error@-1 {{cannot convert value of type '(Int) -> Int' to expected argument type '()'}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11) // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}}
funcdecl1(123, 444)
// Calls.
4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6({ a, b -> Int in a+b})
// Return type inference.
func6({ a,b in a+b })
// Infer incompatible type.
func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments.
func6({ _,_ in 4 })
func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, Int) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(_ x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(_ p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(_ a: Any) -> Int { return 1 }
assert(f0(1) == 1)
var selfRef = { selfRef() }
// expected-note@-1 2{{through reference here}}
// expected-error@-2 {{circular reference}}
var nestedSelfRef = {
var recursive = { nestedSelfRef() }
// expected-warning@-1 {{variable 'recursive' was never mutated; consider changing to 'let' constant}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
func f(_: String) {}
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}}
var a4 = { (z: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
var a5 = { (_: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}}
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
}
func doStuff(_ fn : @escaping () -> Int) {}
func doVoidStuff(_ fn : @escaping () -> ()) {}
func doVoidStuffNonEscaping(_ fn: () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base or an explicit capture.
doVoidStuff({ self.x += 1 })
doVoidStuff({ [self] in x += 1 })
doVoidStuff({ [self = self] in x += 1 })
doVoidStuff({ [unowned self] in x += 1 })
doVoidStuff({ [unowned(unsafe) self] in x += 1 })
doVoidStuff({ [unowned self = self] in x += 1 })
doStuff({ [self] in x+1 })
doStuff({ [self = self] in x+1 })
doStuff({ self.x+1 })
doStuff({ [unowned self] in x+1 })
doStuff({ [unowned(unsafe) self] in x+1 })
doStuff({ [unowned self = self] in x+1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff({ doStuff({ x+1 })}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{28-28= [self] in}} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{19-19=self.}}
doVoidStuff({ _ = "\(x)"}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff({ [y = self] in x += 1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{33-33=self.}}
doStuff({ [y = self] in x+1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in x += 1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in x+1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in x += 1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in x+1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
// Methods follow the same rules as properties, uses of 'self' without capturing must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff { () -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{35-35=self.}}
doVoidStuff { [y = self] in _ = method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{37-37=self.}}
doStuff({ [y = self] in method() }) // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in _ = method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in _ = method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff { _ = self.method() }
doVoidStuff { [self] in _ = method() }
doVoidStuff { [self = self] in _ = method() }
doVoidStuff({ [unowned self] in _ = method() })
doVoidStuff({ [unowned(unsafe) self] in _ = method() })
doVoidStuff({ [unowned self = self] in _ = method() })
doStuff { self.method() }
doStuff { [self] in method() }
doStuff({ [self = self] in method() })
doStuff({ [unowned self] in method() })
doStuff({ [unowned(unsafe) self] in method() })
doStuff({ [unowned self = self] in method() })
// When there's no space between the opening brace and the first expression, insert it
doStuff {method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in }} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
doVoidStuff {_ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doVoidStuff {() -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{34-34=self.}}
// With an empty capture list, insertion should should be suggested without a comma
doStuff { [] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{21-21=self.}}
doStuff { [ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doStuff { [ /* This space intentionally left blank. */ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{65-65=self.}}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}}
doStuff { [ // Nothing in this capture list!
]
in
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{9-9=self.}}
}
// An inserted capture list should be on the same line as the opening brace, immediately following it.
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+2 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
// Note: Trailing whitespace on the following line is intentional and should not be removed!
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff { // We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {// We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// String interpolation should offer the diagnosis and fix-its at the expected locations
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
doVoidStuff { _ = "\(x+1)" } // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
// If we already have a capture list, self should be added to the list
let y = 1
doStuff { [y] in method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doStuff { [ // expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
y // expected-warning {{capture 'y' was never used}}
] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{23-23= [self] in }} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
// If the implicit self is of value type, no diagnostic should be produced.
struct ImplicitSelfAllowedInStruct {
var x = 42
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ x += 1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
enum ImplicitSelfAllowedInEnum {
case foo
var x: Int { 42 }
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
class SomeClass {
var field : SomeClass?
func foo() -> Int {}
}
func testCaptureBehavior(_ ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{invalid redeclaration of 'v1'}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
// FIXME: We should probably offer a fix-it to the field capture error and suppress the 'implicit self' error. https://bugs.swift.org/browse/SR-11634
doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note {{reference 'self.' explicitly}} {{36-36=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 { // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{top-level statement cannot begin with a closure expression}}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> (Int) -> Int {
return { x in
class A {
let d : Int = 0
}
return 0
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(_ f: () -> ()) {}
var i: Int = 1
// expected-warning @+1 {{expression of type 'Int' is unused}}
takesVoidFunc({i})
// expected-warning @+1 {{expression of type 'Int' is unused}}
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = { // expected-error {{cannot infer return type for closure with multiple statements; add explicit type to disambiguate}} {{16-16= () -> <#Result#> in }}
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(_ fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(_ a: () -> T) {}
func genericTwo<T>(_ a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{cannot find type 'Undeclared' in scope}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0 // expected-warning {{variable 'width' was never mutated}}
var height = 0 // expected-warning {{variable 'height' was never mutated}}
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{cannot find type 'asdf' in scope}} expected-warning {{variable 'bufs' was never used}}
[UInt8](repeating: 0, count: width*height)
}
}
// <rdar://problem/25993258>
// Don't crash if we infer a closure argument to have a tuple type containing inouts.
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258a() {
r25993258_helper { x in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
func r25993258b() {
r25993258_helper { _ in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// We have to map the captured var type into the right generic environment.
class GenericClass<T> {}
func lvalueCapture<T>(c: GenericClass<T>) {
var cc = c
weak var wc = c
func innerGeneric<U>(_: U) {
_ = cc
_ = wc
cc = wc!
}
}
// Don't expose @lvalue-ness in diagnostics.
let closure = { // expected-error {{cannot infer return type for closure with multiple statements; add explicit type to disambiguate}} {{16-16= () -> <#Result#> in }}
var helper = true
return helper
}
// SR-9839
func SR9839(_ x: @escaping @convention(block) () -> Void) {}
func id<T>(_ x: T) -> T {
return x
}
var qux: () -> Void = {}
SR9839(qux)
SR9839(id(qux)) // expected-error {{conflicting arguments to generic parameter 'T' ('() -> Void' vs. '@convention(block) () -> Void')}}
func forceUnwrap<T>(_ x: T?) -> T {
return x!
}
var qux1: (() -> Void)? = {}
SR9839(qux1!)
SR9839(forceUnwrap(qux1))
// rdar://problem/65155671 - crash referencing parameter of outer closure
func rdar65155671(x: Int) {
{ a in
_ = { [a] in a }
}(x)
}
func sr3186<T, U>(_ f: (@escaping (@escaping (T) -> U) -> ((T) -> U))) -> ((T) -> U) {
return { x in return f(sr3186(f))(x) }
}
class SR3186 {
init() {
// expected-warning@+1{{capture 'self' was never used}}
let v = sr3186 { f in { [unowned self, f] x in x != 1000 ? f(x + 1) : "success" } }(0)
print("\(v)")
}
}
// Apply the explicit 'self' rule even if it referrs to a capture, if
// we're inside a nested closure
class SR14120 {
func operation() {}
func test1() {
doVoidStuff { [self] in
operation()
}
}
func test2() {
doVoidStuff { [self] in
doVoidStuff {
// expected-warning@+3 {{call to method 'operation' in closure requires explicit use of 'self'}}
// expected-note@-2 {{capture 'self' explicitly to enable implicit 'self' in this closure}}
// expected-note@+1 {{reference 'self.' explicitly}}
operation()
}
}
}
func test3() {
doVoidStuff { [self] in
doVoidStuff { [self] in
operation()
}
}
}
func test4() {
doVoidStuff { [self] in
doVoidStuff {
self.operation()
}
}
}
func test5() {
doVoidStuff { [self] in
doVoidStuffNonEscaping {
operation()
}
}
}
func test6() {
doVoidStuff { [self] in
doVoidStuff { [self] in
doVoidStuff {
// expected-warning@+3 {{call to method 'operation' in closure requires explicit use of 'self'}}
// expected-note@-2 {{capture 'self' explicitly to enable implicit 'self' in this closure}}
// expected-note@+1 {{reference 'self.' explicitly}}
operation()
}
}
}
}
}
// SR-14678
func call<T>(_ : Int, _ f: () -> (T, Int)) -> (T, Int) {
f()
}
func testSR14678() -> (Int, Int) {
call(1) { // expected-error {{cannot convert return expression of type '((), Int)' to return type '(Int, Int)'}}
(print("hello"), 0)
}
}
func testSR14678_Optional() -> (Int, Int)? {
call(1) { // expected-error {{cannot convert return expression of type '((), Int)' to return type '(Int, Int)'}}
(print("hello"), 0)
}
}
// SR-13239
func callit<T>(_ f: () -> T) -> T {
f()
}
func callitArgs<T>(_ : Int, _ f: () -> T) -> T {
f()
}
func callitArgsFn<T>(_ : Int, _ f: () -> () -> T) -> T {
f()()
}
func callitGenericArg<T>(_ a: T, _ f: () -> T) -> T {
f()
}
func callitTuple<T>(_ : Int, _ f: () -> (T, Int)) -> T {
f().0
}
func callitVariadic<T>(_ fs: () -> T...) -> T {
fs.first!()
}
func testSR13239_Tuple() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitTuple(1) { // expected-note@:18{{generic parameter 'T' inferred as '()' from closure return expression}}
(print("hello"), 0)
}
}
func testSR13239() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callit { // expected-note@:10{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
}
}
func testSR13239_Args() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitArgs(1) { // expected-note@:17{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
}
}
func testSR13239_ArgsFn() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitArgsFn(1) { // expected-note@:19{{generic parameter 'T' inferred as '()' from closure return expression}}
{ print("hello") }
}
}
func testSR13239MultiExpr() -> Int {
callit {
print("hello")
return print("hello") // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
func testSR13239_GenericArg() -> Int {
// Generic argument is inferred as Int from first argument literal, so no conflict in this case.
callitGenericArg(1) {
print("hello") // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
}
}
func testSR13239_Variadic() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitVariadic({ // expected-note@:18{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
})
}
func testSR13239_Variadic_Twos() -> Int {
// expected-error@+1{{cannot convert return expression of type '()' to return type 'Int'}}
callitVariadic({
print("hello")
}, {
print("hello")
})
}
// rdar://82545600: this should just be a warning until Swift 6
public class TestImplicitCaptureOfExplicitCaptureOfSelfInEscapingClosure {
var property = false
private init() {
doVoidStuff { [unowned self] in
doVoidStuff {}
doVoidStuff { // expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}}
doVoidStuff {}
property = false // expected-warning {{reference to property 'property' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note {{reference 'self.' explicitly}}
}
}
}
}
|
apache-2.0
|
e09c41c92b5bbba4654de83d4c75df3e
| 48.672293 | 426 | 0.651471 | 3.71797 | false | false | false | false |
mapzen/ios
|
SampleApp/StylePickerVC.swift
|
1
|
6908
|
//
// StylePickerVC.swift
// ios-sdk
//
// Created by Matt Smollinger on 10/3/17.
// Copyright © 2017 Mapzen. All rights reserved.
//
import UIKit
import Mapzen_ios_sdk
class StylePickerVC: UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet var styleSheetPicker: UIPickerView!
@IBOutlet var colorPicker: UIPickerView!
@IBOutlet var levelOfDetailText: UITextField!
@IBOutlet var labelDensityText: UITextField!
@IBOutlet var transitOverlaySwitch: UISwitch!
@IBOutlet var bikeOverlaySwitch: UISwitch!
@IBOutlet var walkingOverlaySwitch: UISwitch!
weak var mapController : SampleMapViewController?
var currentSelectedStyle: StyleSheet = BubbleWrapStyle()
var currentColor: String = ""
var currentLabelLevel: Int = 0
var currentDetailLevel: Int = 0
var availableStyles : [ String : StyleSheet ] = ["Bubble Wrap" : BubbleWrapStyle(),
"Cinnabar" : CinnabarStyle(),
"Refill" : RefillStyle(),
"Walkabout" : WalkaboutStyle(),
"Zinc" : ZincStyle()]
//MARK:- Internal Funcs
func transitOverlaySwitchChanged(switchState: UISwitch) {
mapController?.showTransitOverlay = switchState.isOn
}
func bikeOverlaySwitchChanged(switchState: UISwitch) {
if switchState.isOn {
walkingOverlaySwitch.setOn(false, animated: true)
mapController?.showWalkingPathOverlay = false
}
mapController?.showBikeOverlay = switchState.isOn
}
func walkingOverlaySwitchChanged(switchState: UISwitch) {
if switchState.isOn {
bikeOverlaySwitch.setOn(false, animated: true)
mapController?.showBikeOverlay = false
}
mapController?.showWalkingPathOverlay = switchState.isOn
}
func setUIStateForStyle(styleSheet: StyleSheet) {
colorPicker.reloadAllComponents()
if styleSheet.availableDetailLevels > 0 {
levelOfDetailText.text = String(styleSheet.detailLevel)
levelOfDetailText.isEnabled = true
} else {
levelOfDetailText.text = "N/A"
levelOfDetailText.isEnabled = false
}
if styleSheet.availableLabelLevels > 0 {
labelDensityText.text = String(styleSheet.labelLevel)
labelDensityText.isEnabled = true
} else {
labelDensityText.text = "N/A"
labelDensityText.isEnabled = false
}
}
//MARK:- Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
transitOverlaySwitch.setOn(mapController!.showTransitOverlay, animated: true)
transitOverlaySwitch.addTarget(self, action: #selector(transitOverlaySwitchChanged(switchState:)), for: .valueChanged)
bikeOverlaySwitch.setOn(mapController!.showBikeOverlay, animated: true)
bikeOverlaySwitch.addTarget(self, action: #selector(bikeOverlaySwitchChanged(switchState:)), for: .valueChanged)
walkingOverlaySwitch.setOn(mapController!.showWalkingPathOverlay, animated: true)
walkingOverlaySwitch.addTarget(self, action: #selector(walkingOverlaySwitchChanged(switchState:)), for: .valueChanged)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
currentSelectedStyle = appDelegate.selectedMapStyle
currentColor = currentSelectedStyle.currentColor
currentDetailLevel = currentSelectedStyle.detailLevel
currentLabelLevel = currentSelectedStyle.labelLevel
setUIStateForStyle(styleSheet: currentSelectedStyle)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let values = Array(availableStyles.values)
//Set the style picker to the correct current style
let index = values.index { (style) -> Bool in
style.relativePath == currentSelectedStyle.relativePath
}
if let unwrappedIndex = index {
styleSheetPicker.selectRow(unwrappedIndex, inComponent: 0, animated: false)
}
//Set the color picker to the correct current color (assuming we have one)
if currentSelectedStyle.availableColors.count > 0 &&
!currentSelectedStyle.currentColor.isEmpty {
if let colorIndex = currentSelectedStyle.availableColors.index(of: currentSelectedStyle.currentColor) {
colorPicker.selectRow(colorIndex, inComponent: 0, animated: false)
}
}
}
func saveTextField(_ textField: UITextField) {
guard let text = textField.text, var level = Int(text) else { return }
if level > currentSelectedStyle.availableLabelLevels { level = currentSelectedStyle.availableLabelLevels }
if level < 0 { level = 0 }
if textField == levelOfDetailText {
currentSelectedStyle.detailLevel = level
}
if textField == labelDensityText {
currentSelectedStyle.labelLevel = level
}
}
//MARK:- Interface Builder
@IBAction func savePressed(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
saveTextField(labelDensityText)
saveTextField(levelOfDetailText)
appDelegate.selectedMapStyle = currentSelectedStyle
self.dismiss(animated: true, completion: nil)
}
@IBAction func cancelPressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
//MARK:- Picker View
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == styleSheetPicker {
return availableStyles.count
}
if pickerView == colorPicker {
let styleKeys = Array(availableStyles.keys)
if currentSelectedStyle.availableColors.count > 0 &&
styleKeys[styleSheetPicker.selectedRow(inComponent: 0)] != "Zinc"{
// We want to return 1 in the event we have no colors to show "No Colors" so just need this
return currentSelectedStyle.availableColors.count
}
}
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let styleKeys = Array(availableStyles.keys)
if pickerView == styleSheetPicker {
return styleKeys[row]
}
if pickerView == colorPicker {
if currentSelectedStyle.availableColors.count == 0 ||
styleKeys[styleSheetPicker.selectedRow(inComponent: 0)] == "Zinc" {
return "N/A"
}
return currentSelectedStyle.availableColors[row]
}
return "???"
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == styleSheetPicker {
let keys = Array(availableStyles.keys)
let style = availableStyles[keys[row]]
guard let unwrappedStyle = style else { return }
currentSelectedStyle = unwrappedStyle
setUIStateForStyle(styleSheet: unwrappedStyle)
}
if pickerView == colorPicker {
if currentSelectedStyle.availableColors.count == 0 { return }
currentSelectedStyle.currentColor = currentSelectedStyle.availableColors[row]
}
}
}
|
apache-2.0
|
e177d4155e3fcec4c0aafeabc05951b3
| 34.060914 | 122 | 0.718836 | 4.676371 | false | false | false | false |
devpunk/velvet_room
|
Source/Model/Vita/MVitaXmlItemMetadata.swift
|
1
|
3017
|
import Foundation
import XmlHero
extension MVitaXmlItem
{
//MARK: private
private class func factoryMetadataModel(
directories:[DVitaItemDirectory]) -> [String:Any]
{
var modelSaveData:[[String:Any]] = []
for directory:DVitaItemDirectory in directories
{
let index:Int = modelSaveData.count
guard
let saveDataItem:[String:Any] = factorySaveData(
directory:directory,
index:index)
else
{
continue
}
modelSaveData.append(saveDataItem)
}
let model:[String:Any] = [
MVitaXml.kKeyObjectMetadata:modelSaveData]
return model
}
private class func factorySaveData(
directory:DVitaItemDirectory,
index:Int) -> [String:Any]?
{
guard
let modelContent:[String:Any] = factoryContentModel(
directory:directory,
index:index)
else
{
return nil
}
let modelSaveData:[String:Any] = [
MVitaXml.kKeySaveData:modelContent]
return modelSaveData
}
private class func factoryContentModel(
directory:DVitaItemDirectory,
index:Int) -> [String:Any]?
{
guard
let saveDataTitle:String = directory.sfoSavedDataTitle,
let title:String = directory.sfoTitle,
let dirName:String = directory.identifier?.identifier,
let detail:String = directory.sfoSavedDataDetail
else
{
return nil
}
let dateModified:String = factoryDateModified(
directory:directory)
let model:[String:Any] = [
MVitaXml.kKeySaveDataTitle:saveDataTitle,
MVitaXml.kKeyDateModified:dateModified,
MVitaXml.kKeySize:directory.size,
MVitaXml.kKeyTitle:title,
MVitaXml.kKeyDirName:dirName,
MVitaXml.kKeyDetail:detail,
MVitaXml.kKeyIndex:index]
return model
}
private class func factoryDateModified(
directory:DVitaItemDirectory) -> String
{
let dateModified:Date = Date(
timeIntervalSince1970:directory.dateModified)
let dateModifiedString:String = MVitaPtpDate.factoryString(
date:dateModified)
return dateModifiedString
}
//MARK: internal
class func factoryXml(
directories:[DVitaItemDirectory],
completion:@escaping((Data?) -> ()))
{
let model:[String:Any] = factoryMetadataModel(
directories:directories)
Xml.data(object:model)
{ (data:Data?, error:XmlError?) in
completion(data)
}
}
}
|
mit
|
7f5316f9f04be7ba4fa285ba01fb4c06
| 25.234783 | 67 | 0.537289 | 5.079125 | false | false | false | false |
zyhndesign/DesignCourse
|
DesignCourse/DesignCourse/controls/BackButton.swift
|
1
|
883
|
//
// BackButton.swift
// DesignCourse
//
// Created by lotusprize on 15/10/14.
// Copyright © 2015年 geekTeam. All rights reserved.
//
import UIKit
class BackButton: UIButton {
override func drawRect(rect: CGRect) {
/*
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(3, 3)
self.layer.shadowRadius = 1.0
self.layer.shadowOpacity = 0.4
*/
//let circlePath:CGMutablePathRef = CGPathCreateMutable()
//CGPathAddEllipseInRect(circlePath, nil, self.bounds)
//self.layer.shadowPath = circlePath
let searchIconLayer:CALayer = CALayer()
searchIconLayer.frame = CGRectMake(11, 11, 24, 24)
searchIconLayer.contents = UIImage(named: "rightArrow")?.CGImage
self.layer.addSublayer(searchIconLayer)
}
}
|
apache-2.0
|
b8f2db238a0b286619acd3c905be82cd
| 27.387097 | 72 | 0.636364 | 4.4 | false | false | false | false |
madcato/LongPomo
|
LongPomo/Shared/Resources/UI/AppColors.swift
|
1
|
1800
|
//
// AppColors.swift
// LongPomo
//
// Created by Daniel Vela on 22/05/2017.
// Copyright © 2017 Daniel Vela. All rights reserved.
//
let backgroundColorRed = 0.0
let backgroundColorGreen = 0.0
let backgroundColorBlue = 0.0
let backgroundColorAlpha = 0.0
let secondaryColorRed = 0.2
let secondaryColorGreen = 0.2
let secondaryColorBlue = 0.2
let secondaryColorAlpha = 1.0
let accentColorRed = 0.0
let accentColorGreen = 0.6
let accentColorBlue = 1.0
let accentColorAlpha = 1.0
let primaryColorRed = 1.0
let primaryColorGreen = 1.0
let primaryColorBlue = 0.0
let primaryColorAlpha = 1.0
import UIKit
typealias Color = UIColor
class AppColors {
static var backgroundColor = Color(red: CGFloat(backgroundColorRed),
green: CGFloat(backgroundColorGreen),
blue: CGFloat(backgroundColorBlue),
alpha: CGFloat(backgroundColorAlpha))
static var secondaryColor = Color(red: CGFloat(secondaryColorRed),
green: CGFloat(secondaryColorGreen),
blue: CGFloat(secondaryColorBlue),
alpha: CGFloat(secondaryColorAlpha))
static var accentColor = Color(red: CGFloat(accentColorRed),
green: CGFloat(accentColorGreen),
blue: CGFloat(accentColorBlue),
alpha: CGFloat(accentColorAlpha))
static var primaryColor = Color(red: CGFloat(primaryColorRed),
green: CGFloat(primaryColorGreen),
blue: CGFloat(primaryColorBlue),
alpha: CGFloat(primaryColorAlpha))
}
|
mit
|
99dd6677c6d055d3f1b4f616823f5b50
| 36.479167 | 76 | 0.587549 | 5.244898 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer
|
GeekSpeak Show Timer/BreakCount-3/Timer+Types.swift
|
2
|
8370
|
import UIKit
// TODO: Refactor and abstract out the following hard coded time.
// These structs and enums were a quick and dirty way to get the
// Timer up and running. This should be abstrated out and use
// some sort of configuration file that allows the timer to have
// user definded Phases, Durations, soft and hard segment times and
// break times.
extension Timer {
// MARK: - Enums
enum CountingState: String, CustomStringConvertible {
case Ready = "Ready"
case Counting = "Counting"
case Paused = "Paused"
case PausedAfterComplete = "PausedAfterComplete"
case CountingAfterComplete = "CountingAfterComplete"
var description: String {
return self.rawValue
}
}
enum ShowPhase: String, CustomStringConvertible {
case PreShow = "PreShow"
case Section1 = "Section1"
case Break1 = "Break1"
case Section2 = "Section2"
case Break2 = "Break2"
case Section3 = "Section3"
case PostShow = "PostShow"
var description: String {
return self.rawValue
}
}
// ShowTiming
struct ShowTiming {
var durations = Durations()
var timeElapsed = TimeElapsed()
var phase = ShowPhase.PreShow
var formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
formatter.maximumIntegerDigits = 2
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 0
formatter.negativePrefix = ""
return formatter
}()
var totalShowTimeElapsed: TimeInterval {
return timeElapsed.totalShowTime
}
var totalShowTimeRemaining: TimeInterval {
return durations.totalShowTime - timeElapsed.totalShowTime
}
var elapsed: TimeInterval {
get {
switch phase {
case .PreShow: return timeElapsed.preShow
case .Section1: return timeElapsed.section1
case .Break1: return timeElapsed.break1
case .Section2: return timeElapsed.section2
case .Break2: return timeElapsed.break2
case .Section3: return timeElapsed.section3
case .PostShow: return timeElapsed.postShow
}
}
set(newElapsed) {
switch phase {
case .PreShow: timeElapsed.preShow = newElapsed
case .Section1: timeElapsed.section1 = newElapsed
case .Break1: timeElapsed.break1 = newElapsed
case .Section2: timeElapsed.section2 = newElapsed
case .Break2: timeElapsed.break2 = newElapsed
case .Section3: timeElapsed.section3 = newElapsed
case .PostShow: timeElapsed.postShow = newElapsed
}
}
}
var duration: TimeInterval {
get {
switch phase {
case .PreShow: return durations.preShow
case .Section1: return durations.section1
case .Break1: return durations.break1
case .Section2: return durations.section2
case .Break2: return durations.break2
case .Section3: return durations.section3
case .PostShow: return TimeInterval(0.0)
}
}
set(newDuration) {
switch phase {
case .PreShow: durations.preShow = newDuration
case .Section1: durations.section1 = newDuration
case .Break1: durations.break1 = newDuration
case .Section2: durations.section2 = newDuration
case .Break2: durations.break2 = newDuration
case .Section3: durations.section3 = newDuration
case .PostShow: break
}
}
}
var remaining: TimeInterval {
return max(duration - elapsed, 0)
}
@discardableResult mutating func incrementPhase() -> ShowPhase {
switch phase {
case .PreShow:
phase = .Section1
case .Section1:
// Before moving to the next phase of the show,
// get the difference between the planned duration and the elapsed time
// and add that to the next show section.
let difference = duration - elapsed
durations.section1 -= difference
durations.section2 += difference
phase = .Break1
case .Break1:
phase = .Section2
case .Section2:
// Before moving to the next phase of the show,
// get the difference between the planned duration and the elapsed time
// and add that to the next show section.
let difference = duration - elapsed
durations.section2 -= difference
durations.section3 += difference
phase = .Break2
case .Break2:
phase = .Section3
case .Section3:
phase = .PostShow
case .PostShow:
break
}
return phase
}
func asString(_ interval: TimeInterval) -> String {
let roundedInterval = Int(interval)
let seconds = roundedInterval % 60
let minutes = (roundedInterval / 60) % 60
let intervalNumber = NSNumber(value: interval * TimeInterval(100))
let subSeconds = formatter.string(from: intervalNumber)!
return String(format: "%02d:%02d:\(subSeconds)", minutes, seconds)
}
func asShortString(_ interval: TimeInterval) -> String {
let roundedInterval = Int(interval)
let seconds = roundedInterval % 60
let minutes = (roundedInterval / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
}
// Durations
struct Durations {
var preShow: TimeInterval = 0
var section1: TimeInterval = 0
var break1: TimeInterval = 0
var section2: TimeInterval = 0
var break2: TimeInterval = 0
var section3: TimeInterval = 0
/**
Setup struct with timer durations
- returns: Timer Duractions Struct
-note: Until a real preferences mechenism is built for the
Lyle: The Pledge Drive Durations are currently active.
Remember to switch them back to the standard "useGeekSpeakDurations()"
*/
init() {
// useGeekSpeakDurations()
useGeekSpeakPledgeDriveDurations()
}
var totalShowTime: TimeInterval {
return section1 + section2 + section3
}
func advancePhaseOnCompletion(_ phase: ShowPhase) -> Bool {
switch phase {
case .PreShow,
.Break1,
.Break2,
.Section3:
return true
case .Section1,
.Section2,
.PostShow:
return false
}
}
mutating func useDemoDurations() {
preShow = 2.0
section1 = 30.0
break1 = 2.0
section2 = 30.0
break2 = 2.0
section3 = 30.0
}
/**
The timings used for GeekSpeak before KUSP changed format (51 minutes)
*/
mutating func useOldGeekSpeakDurations() {
preShow = 1.0 * oneMinute
section1 = 14.0 * oneMinute
break1 = 1.0 * oneMinute
section2 = 19.0 * oneMinute
break2 = 1.0 * oneMinute
section3 = 18.0 * oneMinute
}
/**
The current timings used for GeekSpeak after KUSP changed format (57 minutes)
*/
mutating func useGeekSpeakDurations() {
preShow = 1.0 * oneMinute
section1 = 19.0 * oneMinute
break1 = 1.0 * oneMinute
section2 = 19.0 * oneMinute
break2 = 1.0 * oneMinute
section3 = 19.0 * oneMinute
}
/**
timings used for GeekSpeak pledge drives after KUSP changed format (40 minutes)
Lyle: change durations for pledge drive here.
*/
mutating func useGeekSpeakPledgeDriveDurations() {
preShow = 1.0 * oneMinute
section1 = 13.0 * oneMinute
break1 = 1.0 * oneMinute
section2 = 14.0 * oneMinute
break2 = 1.0 * oneMinute
section3 = 13.0 * oneMinute
}
}
// TimeElapsed
struct TimeElapsed {
var preShow: TimeInterval = 0.0
var section1: TimeInterval = 0.0
var break1: TimeInterval = 0.0
var section2: TimeInterval = 0.0
var break2: TimeInterval = 0.0
var section3: TimeInterval = 0.0
var postShow: TimeInterval = 0.0
var totalShowTime: TimeInterval {
return section1 + section2 + section3
}
}
} // Timer Extention
|
mit
|
eed3398f7da8e21cc847156eb111334f
| 28.575972 | 84 | 0.608961 | 4.442675 | false | false | false | false |
WeltN24/Carlos
|
Tests/CarlosTests/StringTransformerTests.swift
|
1
|
2076
|
import Foundation
import Nimble
import Quick
import Carlos
import Combine
final class StringTransformerTests: QuickSpec {
override func spec() {
describe("String transformer") {
var transformer: StringTransformer!
var error: Error!
var cancellable: AnyCancellable?
beforeEach {
transformer = StringTransformer(encoding: .utf8)
}
afterEach {
cancellable?.cancel()
cancellable = nil
}
context("when transforming NSData to String") {
var result: String!
context("when the NSData is a valid string") {
let stringSample = "this is a sample string"
beforeEach {
cancellable = transformer.transform((stringSample.data(using: .utf8) as NSData?)!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not return nil") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected String") {
expect(result).toEventually(equal(stringSample))
}
}
}
context("when transforming String to NSData") {
var result: NSData?
let expectedString = "this is the expected string value"
beforeEach {
cancellable = transformer.inverseTransform(expectedString)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should return the expected data") {
expect(result).toEventually(equal(expectedString.data(using: .utf8) as NSData?))
}
}
}
}
}
|
mit
|
14985131d3ee0b821720e8d08df2d1c4
| 25.615385 | 94 | 0.563102 | 5.100737 | false | false | false | false |
brunophilipe/Noto
|
Noto/Application/EditorTheme.swift
|
1
|
11818
|
//
// EditorTheme.swift
// Noto
//
// Created by Bruno Philipe on 23/02/2017.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Cocoa
protocol EditorTheme: class
{
var name: String { get }
var editorForeground: NSColor { get }
var editorBackground: NSColor { get }
var lineNumbersForeground: NSColor { get }
var lineNumbersBackground: NSColor { get }
var preferenceName: String? { get }
var invisiblesForeground: NSColor { get }
}
private let kThemeNameKey = "name"
private let kThemeEditorBackgroundKey = "editor_background"
private let kThemeLineNumbersBackgroundKey = "lines_background"
private let kThemeEditorForegroundKey = "editor_foreground"
private let kThemeLineNumbersForegroundKey = "lines_foreground"
private let kThemeNativeNamePrefix = "native:"
private let kThemeUserNamePrefix = "user:"
extension EditorTheme
{
fileprivate static var userThemeKeys: [String]
{
return [
kThemeEditorBackgroundKey,
kThemeLineNumbersBackgroundKey,
kThemeEditorForegroundKey,
kThemeLineNumbersForegroundKey
]
}
fileprivate var serialized: [String: AnyObject]
{
return [
kThemeNameKey: name as NSString,
kThemeEditorBackgroundKey: editorBackground,
kThemeLineNumbersBackgroundKey: lineNumbersBackground,
kThemeEditorForegroundKey: editorForeground,
kThemeLineNumbersForegroundKey: lineNumbersForeground
]
}
func make(fromSerialized dict: [String: AnyObject]) -> EditorTheme
{
return UserEditorTheme(fromSerialized: dict)
}
static func installedThemes() -> (native: [EditorTheme], user: [EditorTheme])
{
let nativeThemes: [EditorTheme] = [
LightEditorTheme(),
DarkEditorTheme()
]
var userThemes: [EditorTheme] = []
if let themesDirectoryURL = URLForUserThemesDirectory()
{
if let fileURLs = try? FileManager.default.contentsOfDirectory(at: themesDirectoryURL,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles])
{
for fileURL in fileURLs
{
if fileURL.pathExtension == "plist", let theme = UserEditorTheme(fromFile: fileURL)
{
userThemes.append(theme)
}
}
}
}
return (nativeThemes, userThemes)
}
static func URLForUserThemesDirectory() -> URL?
{
if let appSupportDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last
{
let themeDirectory = appSupportDirectory.appendingPathComponent("Noto/Themes/")
do
{
try FileManager.default.createDirectory(at: themeDirectory, withIntermediateDirectories: true, attributes: nil)
}
catch let error
{
NSLog("Could not create Themes directory: \(themeDirectory). Please check permissions. Error: \(error)")
}
return themeDirectory
}
return nil
}
public static func getWithPreferenceName(_ name: String) -> EditorTheme?
{
if name.hasPrefix(kThemeNativeNamePrefix)
{
let themeName = name[name.index(name.startIndex, offsetBy: kThemeNativeNamePrefix.count) ..< name.endIndex]
switch themeName
{
case "Light":
return LightEditorTheme()
case "Dark":
return DarkEditorTheme()
default:
return nil
}
}
else if name.hasPrefix(kThemeUserNamePrefix)
{
let themeFilePath = String(name[name.index(name.startIndex, offsetBy: kThemeUserNamePrefix.count) ..< name.endIndex])
if FileManager.default.fileExists(atPath: themeFilePath)
{
return UserEditorTheme(fromFile: URL(fileURLWithPath: themeFilePath))
}
else
{
return nil
}
}
else
{
return nil
}
}
}
fileprivate extension NSColor
{
var invisibles: NSColor
{
return withAlphaComponent(0.2)
}
}
class ConcreteEditorTheme: NSObject, EditorTheme
{
init(name: String, editorForeground: NSColor, editorBackground: NSColor, lineNumbersForeground: NSColor, lineNumbersBackground: NSColor)
{
self.name = name
self.editorForeground = editorForeground
self.editorBackground = editorBackground
self.lineNumbersForeground = lineNumbersForeground
self.lineNumbersBackground = lineNumbersBackground
}
fileprivate(set) var name: String
/// Color to be used for invisible characters rendering. It is based on the foreground
lazy var invisiblesForeground: NSColor = editorForeground.invisibles
@objc dynamic var editorForeground: NSColor
@objc dynamic var editorBackground: NSColor
@objc dynamic var lineNumbersForeground: NSColor
@objc dynamic var lineNumbersBackground: NSColor
@objc dynamic var willDeallocate: Bool = false
var preferenceName: String?
{
return "\(kThemeNativeNamePrefix)\(name)"
}
func makeCustom() -> EditorTheme?
{
return UserEditorTheme(customizingTheme: self)
}
}
class UserEditorTheme : ConcreteEditorTheme
{
fileprivate init(fromSerialized dict: [String: AnyObject])
{
super.init(name: (dict[kThemeNameKey] as? String) ?? "(Unamed)",
editorForeground: (dict[kThemeEditorForegroundKey] as? NSColor) ?? #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),
editorBackground: (dict[kThemeEditorBackgroundKey] as? NSColor) ?? #colorLiteral(red: 0.9921568627, green: 0.9921568627, blue: 0.9921568627, alpha: 1),
lineNumbersForeground: (dict[kThemeLineNumbersForegroundKey] as? NSColor) ?? #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1),
lineNumbersBackground: (dict[kThemeLineNumbersBackgroundKey] as? NSColor) ?? #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1))
}
fileprivate var fileWriterOldURL: URL? = nil
fileprivate var fileWriterTimer: Timer? = nil
fileprivate var fileURL: URL?
{
if let themesDirectory = UserEditorTheme.URLForUserThemesDirectory()
{
return themesDirectory.appendingPathComponent(name).appendingPathExtension("plist")
}
else
{
return nil
}
}
convenience init(customizingTheme originalTheme: EditorTheme)
{
self.init(fromSerialized: originalTheme.serialized)
name = originalTheme.name.appending(" (Custom)")
}
convenience init?(fromFile fileURL: URL)
{
if fileURL.isFileURL,
let data = try? Data(contentsOf: fileURL),
var themeDictionary = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String : AnyObject]
{
for itemKey in UserEditorTheme.userThemeKeys
{
if themeDictionary[itemKey] == nil
{
return nil
}
if let data = themeDictionary[itemKey] as? Data
{
themeDictionary[itemKey] = NSColor.fromData(data) ?? NSColor.white
}
else if let intValue = themeDictionary[itemKey] as? UInt
{
themeDictionary[itemKey] = NSColor(rgb: intValue)
}
}
self.init(fromSerialized: themeDictionary)
name = fileURL.deletingPathExtension().lastPathComponent
}
else
{
return nil
}
}
var isCustomization: Bool
{
return name.hasSuffix("(Custom)")
}
override var preferenceName: String?
{
if let fileURL = self.fileURL
{
return "\(kThemeUserNamePrefix)\(fileURL.path)"
}
return nil
}
override func didChangeValue(forKey key: String)
{
super.didChangeValue(forKey: key)
if !["name", "willDeallocate"].contains(key)
{
writeToFile(immediatelly: false)
}
}
func renameTheme(newName: String) -> Bool
{
if let oldUrl = fileURL
{
fileWriterOldURL = oldUrl
name = newName
return moveThemeFile()
}
return false
}
func deleteTheme() -> Bool
{
return deleteThemeFile()
}
}
extension UserEditorTheme
{
func writeToFile(immediatelly: Bool)
{
if immediatelly
{
writeToFileNow()
fileWriterTimer?.invalidate()
fileWriterTimer = nil
}
else
{
if let timer = self.fileWriterTimer
{
timer.fireDate = Date().addingTimeInterval(3)
}
else
{
fileWriterTimer = Timer.scheduledTimer(withTimeInterval: 3, repeats: false)
{
(timer) in
self.writeToFileNow()
self.fileWriterTimer = nil
}
}
}
}
func exportThemeTo(url targetUrl: URL)
{
writeToFileNow(url: targetUrl)
}
private func writeToFileNow(url targetUrl: URL? = nil)
{
if let url = targetUrl ?? self.fileURL
{
let serialized = self.serialized
let dict = (serialized as NSDictionary).mutableCopy() as! NSMutableDictionary
for settingKey in serialized.keys
{
if let color = dict[settingKey] as? NSColor
{
dict.setValue(color.data, forKey: settingKey)
}
}
do
{
try PropertyListSerialization.data(fromPropertyList: dict,
format: .binary,
options: 0).write(to: url,
options: .atomicWrite)
print("Now 1")
}
catch
{
print("Now 2")
dict.write(to: url, atomically: true)
}
}
}
fileprivate func moveThemeFile() -> Bool
{
if let oldURL = fileWriterOldURL, let newURL = fileURL
{
do
{
try FileManager.default.moveItem(at: oldURL, to: newURL)
fileWriterOldURL = nil
// We have to write now so we update the theme name.
writeToFileNow()
return true
}
catch let error
{
NSLog("Error! Could not rename theme file! \(error)")
return false
}
}
return false
}
fileprivate func deleteThemeFile() -> Bool
{
if let url = fileURL
{
do
{
try FileManager.default.removeItem(at: url)
return true
}
catch let error
{
NSLog("Error! Could not delete theme file! \(error)")
}
}
return false
}
}
class NativeEditorTheme: ConcreteEditorTheme
{
override var preferenceName: String?
{
return "\(kThemeNativeNamePrefix)\(name)"
}
}
class LightEditorTheme: NativeEditorTheme
{
init()
{
super.init(name: "Light",
editorForeground: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),
editorBackground: #colorLiteral(red: 0.9921568627, green: 0.9921568627, blue: 0.9921568627, alpha: 1),
lineNumbersForeground: #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1),
lineNumbersBackground: #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1))
}
}
class DarkEditorTheme: NativeEditorTheme
{
init()
{
super.init(name: "Dark",
editorForeground: #colorLiteral(red: 0.8588235294, green: 0.8588235294, blue: 0.8588235294, alpha: 1),
editorBackground: #colorLiteral(red: 0.2156862745, green: 0.2156862745, blue: 0.2156862745, alpha: 1),
lineNumbersForeground: #colorLiteral(red: 0.4549019608, green: 0.4549019608, blue: 0.4549019608, alpha: 1),
lineNumbersBackground: #colorLiteral(red: 0.1647058824, green: 0.1647058824, blue: 0.1647058824, alpha: 1))
}
}
class PrintingEditorTheme: NativeEditorTheme
{
init()
{
super.init(name: "Print",
editorForeground: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),
editorBackground: #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1),
lineNumbersForeground: #colorLiteral(red: 0.6642242074, green: 0.6642400622, blue: 0.6642315388, alpha: 1),
lineNumbersBackground: #colorLiteral(red: 0.9688121676, green: 0.9688346982, blue: 0.9688225389, alpha: 1))
}
}
|
gpl-3.0
|
eba02a5ea4fc1a594ef347b3e3743cb3
| 24.089172 | 168 | 0.693831 | 3.555054 | false | false | false | false |
wireapp/wire-ios-data-model
|
Source/Model/Message/ZMClientMessage+GenericMessage.swift
|
1
|
3471
|
//
// Wire
// Copyright (C) 2020 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
extension ZMClientMessage {
public var underlyingMessage: GenericMessage? {
guard !isZombieObject else {
return nil
}
if cachedUnderlyingMessage == nil {
cachedUnderlyingMessage = underlyingMessageMergedFromDataSet()
}
return cachedUnderlyingMessage
}
private func underlyingMessageMergedFromDataSet() -> GenericMessage? {
let filteredData = dataSet.lazy
.compactMap { ($0 as? ZMGenericMessageData)?.underlyingMessage }
.filter { $0.knownMessage && $0.imageAssetData == nil }
.compactMap { try? $0.serializedData() }
guard !Array(filteredData).isEmpty else {
return nil
}
var message = GenericMessage()
filteredData.forEach {
try? message.merge(serializedData: $0)
}
return message
}
/// Set the underlying protobuf message data.
///
/// - Parameter message: The protobuf message object to be associated with this client message.
/// - Throws `ProcessingError` if the protobuf data can't be processed.
public func setUnderlyingMessage(_ message: GenericMessage) throws {
let messageData = try mergeWithExistingData(message)
if nonce == .none, let messageID = messageData.underlyingMessage?.messageID {
nonce = UUID(uuidString: messageID)
}
updateCategoryCache()
setLocallyModifiedKeys([#keyPath(ZMClientMessage.dataSet)])
}
@discardableResult
func mergeWithExistingData(_ message: GenericMessage) throws -> ZMGenericMessageData {
cachedUnderlyingMessage = nil
let existingMessageData = dataSet
.compactMap { $0 as? ZMGenericMessageData }
.first
guard let messageData = existingMessageData else {
return try createNewGenericMessageData(with: message)
}
do {
try messageData.setGenericMessage(message)
} catch {
throw ProcessingError.failedToProcessMessageData(reason: error.localizedDescription)
}
return messageData
}
private func createNewGenericMessageData(with message: GenericMessage) throws -> ZMGenericMessageData {
guard let moc = managedObjectContext else {
throw ProcessingError.missingManagedObjectContext
}
let messageData = ZMGenericMessageData.insertNewObject(in: moc)
do {
try messageData.setGenericMessage(message)
messageData.message = self
return messageData
} catch {
moc.delete(messageData)
throw ProcessingError.failedToProcessMessageData(reason: error.localizedDescription)
}
}
}
|
gpl-3.0
|
ee5b4fe32f8a8f8352c36f01151026d6
| 32.375 | 107 | 0.665514 | 5.275076 | false | false | false | false |
jfosterdavis/FlashcardHero
|
FlashcardHero/QuizletSetSearchResult.swift
|
1
|
13742
|
//
// QuizletSetSearchResult.swift
// FlashcardHero
//
// Created by Jacob Foster Davis on 10/31/16.
// Copyright © 2016 Zero Mu, LLC. All rights reserved.
//
import Foundation
struct QuizletSetSearchResult {
/******************************************************/
/*******************///MARK: Properties
/******************************************************/
var access_type : Int?
var can_edit: Bool?
var created_by: String?
var created_date : Int?
var creator_id : Int?
var description: String?
var editable: String?
var has_access: Bool?
var has_images: Bool?
var id : Int?
var lang_definitions : String?
var lang_terms : String?
var modified_date : Int?
var password_edit: Bool?
var password_use: Bool?
var published_date : Int?
var subjects : NSArray?
var title: String?
var url: String?
var term_count: Int?
var visibility : String?
//TODO: support creator
var creator : [String:Any]?
/******************************************************/
/*******************///MARK: Error Checking Properties
/******************************************************/
let expectedKeys : [String] = ["access_type", "can_edit", "created_by", "created_date", "creator_id", "description", "editable", "has_access", "has_images", "id", "lang_definitions", "lang_terms", "modified_date", "password_edit", "password_use", "published_date", "subjects", "term_count", "title", "url", "visibility", "creator"]
enum QuizletSetSearchKeyError: Error {
case badInputKeys(keys: [String]) //couldn't convert incoming dictionary keys to a set of Strings
case inputMismatchKeys(key: String) //incoming keys don't match expected keys
}
enum QuizletSetSearchAssignmentError: Error {
case badInputValues(property: String)
case inputValueOutOfExpectedRange(expected: String, actual: Double)
}
/******************************************************/
/*******************///MARK: init
/******************************************************/
init?(fromDataSet data: [String:Any]) throws {
//print("\nAttempting to initialize StudentInformation Object from data set")
//try to stuff the data into the properties of this instance, or return nil if it doesn't work
//check the keys first
do {
try checkInputKeys(data)
} catch QuizletSetSearchKeyError.badInputKeys (let keys){
print("\nERROR: Data appears to be malformed. BadInputKeys:")
print(keys)
return nil
} catch QuizletSetSearchKeyError.inputMismatchKeys(let key) {
print("\nERROR: InputMismatchKeys. Data appears to be malformed. This key: ")
print(key)
print("Do not match the expected keys: ")
print(expectedKeys)
return nil
} catch {
print("\nQUIZLET PARSING ERROR: Unknown error when calling checkInputKeys")
return nil
}
//keys look good, now try to assign the values to the struct
do {
try attemptToAssignValues(data)
//print("Successfully initialized a StudentInformation object\n")
} catch QuizletSetSearchAssignmentError.badInputValues(let propertyName) {
print("\nQUIZLET PARSING ERROR: QuizletSetSearchAssignmentError: bad input when parsing ")
print(propertyName)
return nil
} catch QuizletSetSearchAssignmentError.inputValueOutOfExpectedRange(let expected, let actual) {
print("\nQUIZLET PARSING ERROR: A value was out of the expected range when calling attemptToAssignValues. Expected: \"" + expected + "\" Actual: " + String(actual))
return nil
}catch {
print("\nQUIZLET PARSING ERROR: Unknown error when calling attemptToAssignValues")
return nil
}
}
//init withiout a data set
init() {
//placeholder to allow struct to be initialized without input parameters
}
/******************************************************/
/*******************///MARK: Input Checking
/******************************************************/
/**
Verifies that the keys input match the expected keys
- Parameters:
- data: a `[String:AnyObject]` containing key-value pairs that match `expectedKeys`
- Returns:
- True: if keys match
- Throws:
- `QuizletSetSearchKeyError.BadInputKeys` if input keys can't be made into a set
- `QuizletSetSearchKeyError.InputMismatchKeys` if input keys don't match `expectedKeys`
*/
func checkInputKeys(_ data: [String:Any]) throws {
//guard check one: Put the incoming keys into a set
//let keysToCheck = [String](data.keys) as? [String]
//print("About to check these keys against expected: " + String(keysToCheck))
//check to see if incoming keys can be placed into a set of strings
// guard let incomingKeys : Set<String> = keysToCheck.map(Set.init) else {
// throw QuizletSetSearchKeyError.badInputKeys(keys: [String](data.keys))
// }
//compare the new set with the expectedKeys
for key in data.keys {
if expectedKeys.contains(key) {
//print("found \(key) in \(expectedKeys)")
} else {
throw QuizletSetSearchKeyError.inputMismatchKeys(key: key)
}
}
}
/**
Attempts to take a `[String:AnyObject]` and assign it to all of the properties of this struct
- Parameters:
- data: a `[String:AnyObject]` containing key-value pairs that match `expectedKeys`
- Returns:
- True: if all values are assigned successfully
- Throws:
- `QuizletSetSearchAssignmentError.BadInputValues` if input doesn't have a key in the `expectedKeys` Set
- `QuizletSetSearchAssignmentError.inputValueOutOfExpectedRange` if input value at a key that has an expected range is out of range
*/
private mutating func attemptToAssignValues(_ data: [String:Any]) throws {
//go through each item and attempt to assign it to the struct
//print("\nAbout to assign values from the following object: ")
//print(data)
for (key, value) in data {
switch key {
case "access_type":
if let value = value as? Int {
access_type = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "access_type")
}
case "can_edit":
if let value = value as? Int , value == 0 {
can_edit = false
} else if let value = value as? Int , value == 1 {
can_edit = true
} else if String(describing: value) == "1" {
can_edit = true
} else if String(describing: value) == "0" {
can_edit = false
}else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "can_edit")
}
case "creator_id":
if let value = value as? Int {
creator_id = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "creator_id")
}
case "created_date":
if let value = value as? Int {
created_date = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "created_date")
}
case "editable":
if let value = value as? String {
editable = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "editable")
}
case "has_access":
//print("looking at has_access. value is \"\(value)\"")
if let value = value as? Int , value == 0 {
has_access = false
} else if let value = value as? Int , value == 1 {
has_access = true
} else if String(describing: value) == "1" {
has_access = true
} else if String(describing: value) == "0" {
has_access = false
}else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "has_access")
}
case "id":
if let value = value as? Int {
id = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "id")
}
case "has_images":
if let value = value as? Int , value == 0 {
has_images = false
} else if let value = value as? Int , value == 1 {
has_images = true
} else if String(describing: value) == "1" {
has_images = true
} else if String(describing: value) == "0" {
has_images = false
}else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "has_images")
}
case "lang_definitions":
if let value = value as? String {
lang_definitions = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "lang_definitions")
}
case "lang_terms":
if let value = value as? String {
lang_terms = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "lang_terms")
}
case "modified_date":
if let value = value as? Int {
modified_date = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "modified_date")
}
case "password_use":
if let value = value as? Int , value == 0 {
password_use = false
} else if let value = value as? Int , value == 1 {
password_use = true
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "password_use")
}
case "password_edit":
if let value = value as? Int , value == 0 {
password_edit = false
} else if let value = value as? Int , value == 1 {
password_edit = true
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "password_edit")
}
case "published_date":
if let value = value as? Int {
published_date = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "published_date")
}
case "subjects":
if let value = value as? NSArray {
subjects = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "subjects")
}
case "created_by":
if let value = value as? String {
created_by = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "created_by")
}
case "description":
if let value = value as? String {
description = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "description")
}
case "title":
if let value = value as? String {
title = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "title")
}
case "url":
if let value = value as? String {
url = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "url")
}
case "term_count":
if let value = value as? Int {
term_count = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "term_count")
}
case "visibility":
if let value = value as? String {
visibility = value
} else {
throw QuizletSetSearchAssignmentError.badInputValues(property: "visibility")
}
case "creator":
if let value = value as? [String:Any] {
creator = value
} else {
//TODO: handle image error
//throw QuizletGetTermResultAssignmentError.badInputValues(property: "rank")
}
default:
//unknown input. Should all be ints or strings
print("Unknown input when initializing FlickrPhoto. Key: \(key), Value: \(value)")
}
}
} //end of attemptToAssignValues
}
|
apache-2.0
|
bcd9d4313557ae0d6bb09651b0cd695c
| 41.150307 | 336 | 0.513645 | 5.121506 | false | false | false | false |
hacktoolkit/htk-ios-RottenTomatoes
|
RottenTomatoes/MoviesViewController.swift
|
1
|
4119
|
//
// MoviesViewController.swift
// rottentomatoes
//
// Created by Jonathan Tsai on 9/14/14.
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import UIKit
class MoviesViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var movieTableView: UITableView!
@IBOutlet weak var moviesSearchBar: UISearchBar!
var movies: [RottenTomatoesMovie]!
var visibleMovies: [RottenTomatoesMovie]!
var movieType: RottenTomatoesApiMovieType?
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to Refresh")
refreshControl.addTarget(self, action: "tableRefreshCallback:", forControlEvents: UIControlEvents.ValueChanged)
self.movieTableView!.addSubview(refreshControl)
self.reloadData()
}
func setMovieType(movieType: RottenTomatoesApiMovieType) {
self.movieType = movieType
}
func reloadData(showHud: Bool = true, refreshControl: UIRefreshControl? = nil) {
if showHud {
var hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// hud.mode = MBProgressHUDModeAnnularDeterminate;
hud.labelText = "Loading"
}
RottenTomatoesClient.getMovies(self.movieType ?? RottenTomatoesApiMovieType.Movies) {
(movies: [RottenTomatoesMovie]) -> () in
self.movies = movies
self.visibleMovies = movies
if showHud {
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
refreshControl?.endRefreshing()
self.movieTableView.reloadData()
}
}
func tableRefreshCallback(refreshControl: UIRefreshControl) {
reloadData(showHud: false, refreshControl: refreshControl)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numRows = self.visibleMovies?.count ?? 0
return numRows
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let movieTableViewCell = movieTableView.dequeueReusableCellWithIdentifier("com.hacktoolkit.rottentomatoes.movieCell") as MovieTableViewCell
let movie = self.visibleMovies[indexPath.row]
movieTableViewCell.formatWithMovie(movie)
return movieTableViewCell
}
// Can use this function if implementing the protocol UITableViewDelegate
//
// func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// let movieDetailsViewController = MovieDetailsViewController(nibName: nil, bundle: nil)
//
// self.navigationController?.pushViewController(movieDetailsViewController, animated: true)
// }
func updateVisibleMovies(filterTitle substring: String) {
if substring == "" {
self.visibleMovies = self.movies
} else {
self.visibleMovies = self.movies.filter {
(movie: RottenTomatoesMovie) -> Bool in
let rangeValue = (movie.title as NSString).rangeOfString(substring, options: NSStringCompareOptions.CaseInsensitiveSearch)
let shouldInclude = rangeValue.location != NSNotFound
return shouldInclude
}
}
self.movieTableView.reloadData()
}
// UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
updateVisibleMovies(filterTitle: searchText)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let movieDetailsViewController = segue.destinationViewController as? MovieDetailsViewController {
if let movieCell = sender as? MovieTableViewCell {
movieDetailsViewController.setMovieCellSender(movieCell)
}
}
}
}
|
mit
|
433b883952817a703dd806fae2a945b6
| 37.495327 | 147 | 0.685361 | 5.314839 | false | false | false | false |
ryanglobus/Augustus
|
Augustus/Augustus/AUEventView.swift
|
1
|
4736
|
//
// AUEventView.swift
// Augustus
//
// Created by Ryan Globus on 7/29/15.
// Copyright (c) 2015 Ryan Globus. All rights reserved.
//
import Cocoa
class AUEventView: NSView {
static let eventMargin: CGFloat = 5
fileprivate let log = AULog.instance
let withRightBorder: Bool
var auDelegate: AUEventViewDelegate? {
didSet { self.didSetAuDelegate() }
}
fileprivate var bottomConstraint_: NSLayoutConstraint?
fileprivate var eventViews: [AUEventField] = [] // TODO rename
var events: [AUEvent] {
didSet { self.didSetEvents(oldValue) }
}
init(withRightBorder: Bool = true) {
self.withRightBorder = withRightBorder
self.events = []
super.init(frame: NSRect())
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func didSetEvents(_ oldValue: [AUEvent]) {
let sortedEvents = self.events.sorted() {(lhs: AUEvent, rhs: AUEvent) -> Bool in
var compareResult = ComparisonResult.orderedSame
if let lhsCreationDate = lhs.creationDate, let rhsCreationDate = rhs.creationDate {
compareResult = lhsCreationDate.compare(rhsCreationDate as Date)
}
if compareResult == .orderedSame {
compareResult = lhs.description.compare(rhs.description)
}
return compareResult == .orderedAscending
}
for eventView in self.eventViews {
eventView.removeFromSuperview()
}
self.eventViews = []
var previousEventField_: AUEventField? = nil
for event in sortedEvents {
let eventField = AUEventField(event: event)
eventField.auDelegate = self.auDelegate
self.eventViews.append(eventField)
self.addSubview(eventField)
self.addEventFieldConstraints(eventField, previousEventField_: previousEventField_)
previousEventField_ = eventField
}
if let bottomConstraint = self.bottomConstraint_ {
self.removeConstraint(bottomConstraint)
}
if let lastEventField = previousEventField_ {
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .greaterThanOrEqual, toItem: lastEventField, attribute: .bottom, multiplier: 1, constant: 0)
self.addConstraint(bottomConstraint)
self.bottomConstraint_ = bottomConstraint
}
self.needsDisplay = true
}
fileprivate func didSetAuDelegate() {
for eventField in self.eventViews {
eventField.auDelegate = self.auDelegate
}
}
fileprivate func addEventFieldConstraints(_ eventField: AUEventField, previousEventField_: AUEventField?) {
let topConstraint: NSLayoutConstraint
if let previousEventField = previousEventField_ {
topConstraint = NSLayoutConstraint(item: eventField, attribute: .top, relatedBy: .equal, toItem: previousEventField, attribute: .bottom, multiplier: 1, constant: 20)
} else {
topConstraint = NSLayoutConstraint(item: eventField, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
}
let leftConstraint = NSLayoutConstraint(item: eventField, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: eventField, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)
eventField.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints([leftConstraint, rightConstraint, topConstraint])
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if self.withRightBorder {
self.drawBorders()
}
}
override func mouseDown(with theEvent: NSEvent) {
if theEvent.clickCount == 2 {
self.auDelegate?.requestNewEventForEventView?(self)
} else {
self.auDelegate?.selectEventView?(self)
}
}
fileprivate func drawBorders() {
let path = NSBezierPath()
// border to the right
path.move(to: NSPoint(x: self.frame.width, y: 0))
path.line(to: NSPoint(x: self.frame.width, y: self.frame.height))
path.lineWidth = 2
path.stroke()
}
}
@objc protocol AUEventViewDelegate: AUEventFieldDelegate {
@objc optional func selectEventView(_ eventView: AUEventView)
@objc optional func requestNewEventForEventView(_ eventView: AUEventView)
}
|
gpl-2.0
|
aef6059204299e34c0886ae8a6534422
| 36.888 | 189 | 0.645059 | 4.750251 | false | false | false | false |
myandy/shi_ios
|
shishi/Network/Plugin/NetworkLogger.swift
|
1
|
4105
|
import Foundation
import Moya
import Result
//import ISRemoveNull
/// Logs network activity (outgoing requests and incoming responses).
class NetworkLogger: PluginType {
typealias Comparison = (TargetType) -> Bool
let whitelist: Comparison
let blacklist: Comparison
init(whitelist: @escaping Comparison = { _ -> Bool in return true }, blacklist: @escaping Comparison = { _ -> Bool in return true }) {
self.whitelist = whitelist
self.blacklist = blacklist
}
func willSendRequest(_ request: RequestType, target: TargetType) {
// If the target is in the blacklist, don't log it.
guard blacklist(target) == false else { return }
if let params = target.parameters{
let paramsString = jsonStringWithDic(parameters: params as [String : AnyObject]!)
log.debug("Sending request: \(request.request?.url?.absoluteString ?? String()), params:\(paramsString)")
}
else {
log.debug("Sending request: \(request.request?.url?.absoluteString ?? String())")
}
if let head = request.request?.allHTTPHeaderFields {
log.debug("head: \(head)")
}
if let body = request.request?.httpBody {
if let bodyString = NSString(data:body, encoding:String.Encoding.utf8.rawValue) as? String {
log.debug("body: \(bodyString)")
}
else{
log.debug("bodyData LENGTH: \(body.count)")
}
}
}
func didReceiveResponse(_ result: Result<Moya.Response, Moya.MoyaError>, target: TargetType) {
// If the target is in the blacklist, don't log it.
guard blacklist(target) == false else { return }
switch result {
case .success(let response):
if 200..<400 ~= response.statusCode {
// If the status code is OK, and if it's not in our whitelist, then don't worry about logging its response body.
//let dataString = jsonStringWithDic(response.dataDicByRemovingNull() as! [String : AnyObject])
var dataString:String!
do {
dataString = try response.mapString()
}
catch {
dataString = (NSString(data: response.data,
encoding: String.Encoding.utf8.rawValue) as! String)
}
log.debug("Received Success response(\(response.statusCode)) from \(response.response?.url?.absoluteString ?? String()), data:\(dataString)")
}
else {
let dataString = NSString(data: response.data,
encoding: String.Encoding.utf8.rawValue) as! String
log.warning("Received error response(\(response.statusCode)) from \(response.response?.url?.absoluteString ?? String()), data:\(dataString)")
}
case .failure(let error):
// Otherwise, log everything.baogei
//logger.log("Received networking error: \(error.nsError)")
log.error("Received networking error: \(error)")
}
}
//字典转JSON字符串
func jsonStringWithDic(parameters: [String: AnyObject]!)->String?{
// guard let parameters = parameters as? [String: String] else {
// return ""
// }
for (_, value) in parameters {
if value is NSData {
return "can not serialization params"
}
}
do {
let theJSONData = try JSONSerialization.data(
withJSONObject: parameters,
options: JSONSerialization.WritingOptions.prettyPrinted)
return NSString(data: theJSONData,
encoding: String.Encoding.utf8.rawValue) as? String
}
catch let error as NSError {
log.error("Failed to load: \(error.localizedDescription)")
}
catch let error {
log.error("Failed to load: \(error)")
}
return ""
}
}
|
apache-2.0
|
835389d54c9a9e42268e0d3353dc46d2
| 37.613208 | 157 | 0.56731 | 5.084472 | false | false | false | false |
skedgo/tripkit-ios
|
Examples/TripKitUIExample/Autocompleter/InMemoryHistoryManager+Home.swift
|
1
|
1720
|
//
// InMemoryHistoryManager+Home.swift
// TripKitUIExample
//
// Created by Adrian Schönig on 17/3/2022.
// Copyright © 2022 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import UIKit
import RxCocoa
import TripKitUI
extension InMemoryHistoryManager.History: TKUIHomeComponentItem {
var identity: String {
"\(date)"
}
}
extension InMemoryHistoryManager: TKUIHomeComponentViewModel {
static func buildInstance(from inputs: TKUIHomeComponentInput) -> InMemoryHistoryManager {
let manager = Self.shared
manager.selection = inputs.itemSelected.compactMap { $0 as? History }
return manager
}
var identity: String {
return "home-history"
}
var homeCardSection: Driver<TKUIHomeComponentContent> {
return history
.asDriver(onErrorJustReturn: [])
.map { items in
TKUIHomeComponentContent(
items: items,
header: .init(
title: "Search history",
action: (
"Clear all", {
self.history.onNext([])
return .success
}
)
)
)
}
}
func cell(for item: TKUIHomeComponentItem, at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell? {
guard let history = item as? History else { return nil }
let cell = tableView.dequeueReusableCell(withIdentifier: "home-history") ?? UITableViewCell(style: .default, reuseIdentifier: "home-history")
cell.textLabel?.text = history.annotation.title ?? "Location"
return cell
}
var nextAction: Signal<TKUIHomeCard.ComponentAction> {
selection.map {
.handleSelection(.annotation($0.annotation), component: self)
}
}
}
|
apache-2.0
|
b08527df95f4f7c2c18c53d33ec219c6
| 25.430769 | 145 | 0.653667 | 4.497382 | false | false | false | false |
michaelvu812/MVGCD
|
MVGCD/MVGCD.swift
|
1
|
6504
|
//
// MVGCD.swift
// MVGCD
//
// Created by Michael on 24/6/14.
// Copyright (c) 2014 Michael Vu. All rights reserved.
//
import Foundation
let MVGCDQueueSpecificKey:CString = "MVGCDQueueSpecificKey"
class MVGCD {
class func execOnce(block: dispatch_block_t!) {
struct Static {
static var predicate:dispatch_once_t = 0
}
dispatch_once(&Static.predicate, block)
}
@required init() {
}
}
class MVGCDQueue {
let queue: dispatch_queue_t
convenience init() {
self.init(queue: dispatch_queue_create(MVGCDQueueSpecificKey, DISPATCH_QUEUE_SERIAL))
}
init(queue: dispatch_queue_t) {
self.queue = queue
}
class var mainQueue: MVGCDQueue {
return MVGCDQueue(queue: dispatch_get_main_queue())
}
class var defaultQueue: MVGCDQueue {
return MVGCDQueue(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
}
class var highPriorityQueue: MVGCDQueue {
return MVGCDQueue(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0))
}
class var lowPriorityQueue: MVGCDQueue {
return MVGCDQueue(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0))
}
class var backgroundQueue: MVGCDQueue {
return MVGCDQueue(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
}
class func initSerial() -> MVGCDQueue {
return MVGCDQueue(queue: dispatch_queue_create(MVGCDQueueSpecificKey, DISPATCH_QUEUE_SERIAL))
}
class func initConcurrent() -> MVGCDQueue {
return MVGCDQueue(queue: dispatch_queue_create(MVGCDQueueSpecificKey, DISPATCH_QUEUE_CONCURRENT))
}
func sync(block: dispatch_block_t) {
dispatch_sync(self.queue, block)
}
func async(block: dispatch_block_t) {
dispatch_async(self.queue, block)
}
func after(block: dispatch_block_t, afterDelay seconds: Double) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, self.queue, block)
}
func afterDate(block: dispatch_block_t, afterDelay date: NSDate) {
after(block, afterDelay: date.timeIntervalSinceNow)
}
func apply(block: ((UInt) -> Void), iterationCount count: UInt) {
dispatch_apply(count, self.queue, block)
}
func barrierAsync(block: dispatch_block_t) {
dispatch_barrier_async(self.queue, block)
}
func barrierSync(block: dispatch_block_t) {
dispatch_barrier_sync(self.queue, block)
}
func suspend() {
dispatch_suspend(self.queue)
}
func resume() {
dispatch_resume(self.queue)
}
func lable() -> CString {
return dispatch_queue_get_label(self.queue)
}
func setTarget(object:dispatch_object_t) {
dispatch_set_target_queue(object, self.queue)
}
func runMain() {
dispatch_main()
}
}
class MVGCDGroup {
let group: dispatch_group_t
convenience init() {
self.init(group: dispatch_group_create())
}
init(group: dispatch_group_t) {
self.group = group
}
func async(block: dispatch_block_t, withQueue queue: MVGCDQueue) {
dispatch_group_async(self.group, queue.queue, block)
}
func enter() {
return dispatch_group_enter(self.group)
}
func leave() {
return dispatch_group_leave(self.group)
}
func notify(block: dispatch_block_t, withQueue queue: MVGCDQueue) {
dispatch_group_notify(self.group, queue.queue, block)
}
func wait() {
dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER)
}
func wait(seconds: Double) -> Bool {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
return dispatch_group_wait(self.group, time) == 0
}
func waitDate(date: NSDate) -> Bool {
return wait(date.timeIntervalSinceNow)
}
}
class MVGCDSemaphore {
let semaphore: dispatch_semaphore_t
convenience init() {
self.init(value: 0)
}
convenience init(value: CLong) {
self.init(semaphore: dispatch_semaphore_create(value))
}
init(semaphore: dispatch_semaphore_t) {
self.semaphore = semaphore
}
func signal() -> Bool {
return dispatch_semaphore_signal(self.semaphore) != 0
}
func wait() {
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER)
}
func wait(seconds: Double) -> Bool {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
return dispatch_semaphore_wait(self.semaphore, time) == 0
}
func waitDate(date: NSDate) -> Bool {
return wait(date.timeIntervalSinceNow)
}
}
class MVGCDSource {
let source: dispatch_source_t
convenience init(type: dispatch_source_type_t, handle: UInt, mask: CUnsignedLong, queue: dispatch_queue_t?) {
self.init(source: dispatch_source_create(type, handle, mask, queue!))
}
init(source: dispatch_source_t) {
self.source = source
}
func resume() {
dispatch_resume(self.source)
}
func cancel() {
dispatch_source_cancel(self.source);
}
func isCancelled() -> Bool {
return (dispatch_source_testcancel(self.source) != 0)
}
func setRegistrationHandler(block: dispatch_block_t) {
dispatch_source_set_registration_handler(self.source, block)
}
func setCancelHandler(block: dispatch_block_t) {
dispatch_source_set_cancel_handler(self.source, block)
}
func setEventHandler(block: dispatch_block_t) {
dispatch_source_set_event_handler(self.source, block)
}
func handle() -> UInt {
return dispatch_source_get_handle(self.source)
}
func mask() -> CUnsignedLong {
return dispatch_source_get_mask(self.source)
}
func data() -> CUnsignedLong {
return dispatch_source_get_data(self.source)
}
func mergeData(value:CUnsignedLong) {
dispatch_source_merge_data(self.source, value)
}
func setTimer(seconds: Double, interval:UInt64, leeway:UInt64) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_source_set_timer(self.source, time, interval / NSEC_PER_SEC, leeway / NSEC_PER_SEC);
}
func setTimer(date: NSDate, interval:UInt64, leeway:UInt64) {
setTimer(date.timeIntervalSinceNow, interval: interval, leeway: leeway)
}
}
|
mit
|
a62da4cda4936f3c185e343f7a03e0e0
| 31.363184 | 113 | 0.647601 | 3.703872 | false | false | false | false |
rheinfabrik/Heimdall.swift
|
Heimdallr/OAuthAccessToken.swift
|
2
|
3426
|
import Foundation
/// An access token is used for authorizing requests to the resource endpoint.
@objc
public class OAuthAccessToken: NSObject {
/// The access token.
public let accessToken: String
/// The acess token's type (e.g., Bearer).
public let tokenType: String
/// The access token's expiration date.
public let expiresAt: Date?
/// The refresh token.
public let refreshToken: String?
/// Initializes a new access token.
///
/// - parameter accessToken: The access token.
/// - parameter tokenType: The access token's type.
/// - parameter expiresAt: The access token's expiration date.
/// - parameter refreshToken: The refresh token.
///
/// - returns: A new access token initialized with access token, type,
/// expiration date and refresh token.
public init(accessToken: String, tokenType: String, expiresAt: Date? = nil, refreshToken: String? = nil) {
self.accessToken = accessToken
self.tokenType = tokenType
self.expiresAt = expiresAt
self.refreshToken = refreshToken
}
/// Copies the access token, using new values if provided.
///
/// - parameter accessToken: The new access token.
/// - parameter tokenType: The new access token's type.
/// - parameter expiresAt: The new access token's expiration date.
/// - parameter refreshToken: The new refresh token.
///
/// - returns: A new access token with this access token's values for
/// properties where new ones are not provided.
public func copy(accessToken: String? = nil, tokenType: String? = nil, expiresAt: Date?? = nil, refreshToken: String?? = nil) -> OAuthAccessToken {
return OAuthAccessToken(accessToken: accessToken ?? self.accessToken,
tokenType: tokenType ?? self.tokenType,
expiresAt: expiresAt ?? self.expiresAt,
refreshToken: refreshToken ?? self.refreshToken)
}
}
public func == (lhs: OAuthAccessToken, rhs: OAuthAccessToken) -> Bool {
return lhs.accessToken == rhs.accessToken
&& lhs.tokenType == rhs.tokenType
&& lhs.expiresAt == rhs.expiresAt
&& lhs.refreshToken == rhs.refreshToken
}
extension OAuthAccessToken {
public class func decode(_ json: [String: AnyObject]) -> OAuthAccessToken? {
func toDate(_ timeIntervalSinceNow: TimeInterval?) -> Date? {
return timeIntervalSinceNow.map { timeIntervalSinceNow in
Date(timeIntervalSinceNow: timeIntervalSinceNow)
}
}
guard let accessToken = json["access_token"] as? String,
let tokenType = json["token_type"] as? String else {
return nil
}
let expiresAt = (json["expires_in"] as? TimeInterval).flatMap(toDate)
let refreshToken = json["refresh_token"] as? String
return OAuthAccessToken(accessToken: accessToken, tokenType: tokenType,
expiresAt: expiresAt, refreshToken: refreshToken)
}
public class func decode(data: Data) -> OAuthAccessToken? {
guard let json = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)),
let jsonDictionary = json as? [String: AnyObject] else {
return nil
}
return decode(jsonDictionary)
}
}
|
apache-2.0
|
0a0c605ff8db0d545e88c322411ad5bc
| 38.837209 | 151 | 0.638938 | 5.121076 | false | false | false | false |
svdo/ReRxSwift
|
Pods/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift
|
7
|
3686
|
#if canImport(Darwin)
import class Foundation.NSObject
// swiftlint:disable line_length
public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) throws -> Bool
public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) throws -> Bool
// swiftlint:enable line_length
@available(*, deprecated, message: "Use NMBPredicate instead")
public class NMBObjCMatcher: NSObject, NMBMatcher {
// swiftlint:disable identifier_name
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
// swiftlint:enable identifier_name
let canMatchNil: Bool
public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) {
self.canMatchNil = canMatchNil
self._match = matcher
self._doesNotMatch = notMatcher
}
public convenience init(matcher: @escaping MatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in
return try !matcher(actualExpression, failureMessage)
}))
}
public convenience init(matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in
return try matcher(actualExpression, failureMessage, false)
}), notMatcher: ({ actualExpression, failureMessage in
return try matcher(actualExpression, failureMessage, true)
}))
}
private func canMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
do {
if !canMatchNil {
if try actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return false
}
}
} catch let error {
failureMessage.actualValue = "an unexpected error thrown: \(error)"
return false
}
return true
}
public func matches(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result: Bool
do {
result = try _match(expr, failureMessage)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
public func doesNotMatch(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result: Bool
do {
result = try _doesNotMatch(expr, failureMessage)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
}
#endif
|
mit
|
878e005352b0e1e9922eefe17181497d
| 37.8 | 151 | 0.651926 | 5.485119 | false | false | false | false |
jedlewison/AsyncOpKit
|
AsyncOpTypes.swift
|
1
|
3771
|
//
// AsyncOpTypes.swift
//
// Created by Jed Lewison
// Copyright (c) 2015 Magic App Factory. MIT License.
import Foundation
public enum AsyncOpResult<ValueType> {
case Succeeded(ValueType)
case Failed(ErrorType)
case Cancelled
init(asyncOpValue: AsyncOpValue<ValueType>) {
switch asyncOpValue {
case .Some(let value):
self = .Succeeded(value)
case .None(let asyncOpError):
switch asyncOpError {
case .NoValue:
self = .Failed(AsyncOpError.NoResultBecauseOperationNotFinished)
case .Cancelled:
self = .Cancelled
case .Failed(let error):
self = .Failed(error)
}
}
}
var succeeded: Bool {
switch self {
case .Succeeded:
return true
default:
return false
}
}
}
extension AsyncOp {
public var result: AsyncOpResult<OutputType> {
return AsyncOpResult(asyncOpValue: output)
}
}
public protocol AsyncVoidConvertible: NilLiteralConvertible {
init(asyncVoid: AsyncVoid)
}
extension AsyncVoidConvertible {
public init(nilLiteral: ()) {
self.init(asyncVoid: .Void)
}
}
public enum AsyncVoid: AsyncVoidConvertible {
case Void
public init(asyncVoid: AsyncVoid) {
self = .Void
}
}
public protocol AsyncOpResultStatusProvider {
var resultStatus: AsyncOpResultStatus { get }
}
public enum AsyncOpResultStatus {
case Pending
case Succeeded
case Cancelled
case Failed
}
public protocol AsyncOpInputProvider {
associatedtype ProvidedInputValueType
func provideAsyncOpInput() -> AsyncOpValue<ProvidedInputValueType>
}
public enum AsyncOpValue<ValueType>: AsyncOpInputProvider {
case None(AsyncOpValueErrorType)
case Some(ValueType)
public typealias ProvidedInputValueType = ValueType
public func provideAsyncOpInput() -> AsyncOpValue<ProvidedInputValueType> {
return self
}
}
public enum AsyncOpValueErrorType: ErrorType {
case NoValue
case Cancelled
case Failed(ErrorType)
}
extension AsyncOpValue {
public func getValue() throws -> ValueType {
switch self {
case .None:
throw AsyncOpValueErrorType.NoValue
case .Some(let value):
return value
}
}
public var value: ValueType? {
switch self {
case .None:
return nil
case .Some(let value):
return value
}
}
public var noneError: AsyncOpValueErrorType? {
switch self {
case .None(let error):
return error
case .Some:
return nil
}
}
}
extension AsyncOpValueErrorType {
public var cancelled: Bool {
switch self {
case .Cancelled:
return true
default:
return false
}
}
public var failed: Bool {
switch self {
case .Failed:
return true
default:
return false
}
}
public var failureError: ErrorType? {
switch self {
case .Failed(let error):
return error
default:
return nil
}
}
}
public enum AsyncOpError: ErrorType {
case Unspecified
case NoResultBecauseOperationNotFinished
case UnimplementedOperation
case Multiple([ErrorType])
case PreconditionFailure
}
public enum AsyncOpPreconditionInstruction {
case Continue
case Cancel
case Fail(ErrorType)
init(errors: [ErrorType]) {
if errors.count == 1 {
self = .Fail(errors[0])
} else {
self = .Fail(AsyncOpError.Multiple(errors))
}
}
}
|
mit
|
e0e760f48f1e16f2b2001db5044ab97a
| 19.95 | 80 | 0.604349 | 4.803822 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift
|
TLTranstionLib-swift/Classes/Animator/TLFromLeftAnimator.swift
|
1
|
6236
|
//
// TLFromLeftAnimator.swift
// Pods
//
// Created by Andrew on 16/5/31.
//
//
import UIKit
public class TLFromLeftAnimator: TLBaseAnimator {
var snapshots:NSMutableArray!
let TAGKEY = 9999
// func snapshots() -> NSMutableArray {
// if(snapshots==nil){
// snapshots = NSMutableArray()
// }
// return snapshots
//
// }
public override init() {
super.init()
if(snapshots == nil){
snapshots = NSMutableArray()
}
}
/**
执行动画
- parameter transitionContext: 上下文
*/
public override func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let model = TransitionModel(context: transitionContext)
print(self.operaiton)
if(self.isPositiveAnimation == true){
pushOpreation(model, context: transitionContext)
}else{
popOpreation(model, context: transitionContext)
}
}
/**
结论
当执行 model.containerView.addSubview(model.toView)这行代码的时候
model.fromView的概念就会消失,就是没有fromView了。
如果屏幕截图 不管是用 fromView还是toView截图,最后得到的截图都是TOView的屏幕截图。
- parameter model: <#model description#>
- parameter context: <#context description#>
*/
func popOpreation(model:TransitionModel,context:UIViewControllerContextTransitioning) -> Void {
let keyWindow = model.fromView.window
let baseView = keyWindow?.subviews.first
var result : TLSnapshotModel?
for var i = self.snapshots.count-1;i>=0;i-- {
let snapshot = self.snapshots[i] as! TLSnapshotModel
if(snapshot.viewConcroller == model.toViewController){
result = snapshot
break
}
}
if(result != nil){
let index = self.snapshots.indexOfObject(result!)
self.snapshots.removeObjectsInRange(NSMakeRange(index, self.snapshots.count-index))
}
if(result != nil){
//获取之前的屏幕截图
let snapshotView = result?.snapshotView
let maskView = snapshotView?.viewWithTag(TAGKEY)
if snapshotView != nil{
keyWindow?.addSubview(snapshotView!)
keyWindow?.bringSubviewToFront(baseView!)
}
let originalFrame = baseView?.frame
var newFrame = baseView?.frame
newFrame?.origin.x = (newFrame?.origin.x)! + (newFrame?.size.width)!
UIView.animateWithDuration(self.animatorDuration, animations: {
maskView?.alpha = 0
snapshotView?.layer.transform = CATransform3DIdentity
baseView?.frame = newFrame!
}, completion: { (finished) in
baseView?.frame = originalFrame!
model.containerView.addSubview(model.toView)
snapshotView?.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled())
})
}
}
func pushOpreation(model:TransitionModel,context:UIViewControllerContextTransitioning) -> Void {
let keyWindow = model.fromView.window
var baseView = keyWindow?.subviews.first
//获取屏幕快照
var snapshotView:UIView?
//如果是UINavigation的push操作
if self.showType == .push {
snapshotView = baseView?.snapshotViewAfterScreenUpdates(false)
}else if self.showType == .present{
//那就一定是使用UIViewController的 Present方式
snapshotView = baseView?.snapshotViewAfterScreenUpdates(true)
}
snapshotView?.frame = (baseView?.frame)!
// let maskView = UIView(frame: (snapshotView?.bounds)!)
// maskView.alpha = 0
// maskView.tag = TAGKEY
// snapshotView?.addSubview(maskView)
if snapshotView != nil{
keyWindow?.addSubview(snapshotView!)
keyWindow?.bringSubviewToFront(baseView!)
}
let originalFrame = baseView?.frame
var newFrame = baseView?.frame
newFrame?.origin.x = (newFrame?.origin.x)! + (newFrame?.size.width)!
baseView?.frame = newFrame!
var transform : CATransform3D = CATransform3DIdentity
transform.m34 = -1.0 / 750
transform = CATransform3DTranslate(transform, 0, 0, -50)
UIView.animateWithDuration(self.animatorDuration, animations: {
baseView?.frame = originalFrame!
snapshotView?.layer.transform = transform
//添加目标视图
model.containerView.addSubview(model.toView)
// maskView.alpha = 0.35
}) { (finished) in
snapshotView?.removeFromSuperview()
var snapShot:TLSnapshotModel?
for sp in self.snapshots {
let spShot = sp as! TLSnapshotModel
if(spShot.viewConcroller == model.fromViewController){
snapShot = spShot
break;
}
}
if(snapShot != nil){
//设置屏幕快照
snapShot?.snapshotView = snapshotView
}else{
snapShot = TLSnapshotModel()
snapShot?.snapshotView=snapshotView
snapShot?.viewConcroller = model.fromViewController
self.snapshots.addObject(snapShot!)
}
context.completeTransition(!context.transitionWasCancelled())
}
}
}
|
mit
|
1a6e93c934f1e494814ed33de3b59bf3
| 28.529412 | 101 | 0.533865 | 5.582947 | false | false | false | false |
huonw/swift
|
test/decl/protocol/special/coding/class_codable_non_strong_vars.swift
|
40
|
1767
|
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Classes with Codable properties (with non-strong ownership) should get
// derived conformance to Codable.
class NonStrongClass : Codable {
class NestedClass : Codable {
init() {}
}
weak var x: NestedClass? = NestedClass()
// expected-warning@-1 {{instance will be immediately deallocated because property 'x' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'x' declared here}}
unowned var y: NestedClass = NestedClass()
// expected-warning@-1 {{instance will be immediately deallocated because property 'y' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'y' declared here}}
static var z: String = "foo"
// These lines have to be within the NonStrongClass type because CodingKeys
// should be private.
func foo() {
// They should receive a synthesized CodingKeys enum.
let _ = NonStrongClass.CodingKeys.self
// The enum should have a case for each of the vars.
let _ = NonStrongClass.CodingKeys.x
let _ = NonStrongClass.CodingKeys.y
// Static vars should not be part of the CodingKeys enum.
let _ = NonStrongClass.CodingKeys.z // expected-error {{type 'NonStrongClass.CodingKeys' has no member 'z'}}
}
}
// They should receive synthesized init(from:) and an encode(to:).
let _ = NonStrongClass.init(from:)
let _ = NonStrongClass.encode(to:)
// The synthesized CodingKeys type should not be accessible from outside the
// class.
let _ = NonStrongClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
|
apache-2.0
|
76c529a74c14374c7476399e4c154d9a
| 40.093023 | 123 | 0.718166 | 4.217184 | false | false | false | false |
chicio/HackerRank
|
DataStructures/TreeHeightofaBinaryTree.swift
|
1
|
1565
|
//
// TreeHeightofaBinaryTree.swift
// HackerRank
//
// Created by Fabrizio Duroni on 13/12/2016.
//
// https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree
import Foundation
class Node {
var data: Int
var left: Node?
var right: Node?
init(d : Int) {
data = d
}
}
class Tree {
func insert(root: Node?, data: Int) -> Node? {
if root == nil {
return Node(d: data)
}
if data <= (root?.data)! {
root?.left = insert(root: root?.left, data: data)
} else {
root?.right = insert(root: root?.right, data: data)
}
return root
}
/*!
I just noted that i already solved
this challenge in 30 days of code, but here I created
a more elegant solution :).
- param root: root node.
- return the tree height.
*/
func getHeight(root: Node?) -> Int {
var countLeft = 0
var countRight = 0
if let left = root?.left {
countLeft = 1 + getHeight(root: left)
}
if let right = root?.right {
countRight = 1 + getHeight(root: right)
}
return countLeft > countRight ? countLeft : countRight
}
}
var root: Node?
var tree = Tree()
var t = Int(readLine()!)!
while t > 0 {
root = tree.insert(root: root, data: Int(readLine()!)!)
t = t - 1
}
print(tree.getHeight(root: root))
|
mit
|
d01ca8e4e56f7eea4845502a46c8eb26
| 18.320988 | 70 | 0.497764 | 3.972081 | false | false | false | false |
vsqweHCL/DouYuZB
|
DouYuZB/DouYuZB/Classs/Home/Controller/RecommendViewController.swift
|
1
|
7971
|
//
// RecommendViewController.swift
// DouYuZB
//
// Created by HCL黄 on 16/11/16.
// Copyright © 2016年 HCL黄. All rights reserved.
//
import UIKit
private let kItemMargin: CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin) / 2
private let kNormalItemH = kItemW * 3 / 4
private let kPrettyItemH = kItemW * 4 / 3
private let kHeaderViewH: CGFloat = 50
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90.0
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
private let kHeaderViewID = "kHeaderViewID"
class RecommendViewController: BaseViewController {
// MARK:- 懒加载
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH+kGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
// 解决最小间距全部挤到中间
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
// 注册
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionViewNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionViewPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
// collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
// MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
// 设置UI界面
setupUI()
// 发送网络请求
loadData()
}
}
// MARK:- 发送网络请求
extension RecommendViewController
{
fileprivate func loadData() {
// 请求推荐数据
recommendVM.requestData {
// 1.展示推荐书籍
self.collectionView.reloadData()
// 2.将数据传递给GameView
var groups = self.recommendVM.anchorGroups
// 先移除前两组数据
groups.removeFirst()
groups.removeFirst()
// 添加更多
let moreGroup = AnchorGroup(dict: ["" : "" as NSObject])
moreGroup.tag_name = "更多"
groups.append(moreGroup)
// 将数据传递给gameView
self.gameView.groups = groups
self.loadDataFinshed()
}
// 请求轮播数据
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
// MARK:- 设置UI界面内容
extension RecommendViewController
{
override func setupUI() {
// 1.给父类中的内容View的引用进行复制
contentView = collectionView
// 1.将UICollectionView添加到控制器view
view.addSubview(collectionView)
// 2.将cycleView添加到UICollectionView中
collectionView.addSubview(cycleView)
// 将gameView添加到UICollectionView中
collectionView.addSubview(gameView)
// 3.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH+kGameViewH, 0, 0, 0)
super.setupUI()
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendViewController: UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recommendVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recommendVM.anchorGroups[section]
return group.anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 0.取出模型
let group = recommendVM.anchorGroups[indexPath.section]
let anchor = group.anchors[indexPath.item]
// 1.获取cell
if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionViewPrettyCell
cell.anchor = anchor
return cell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionViewNormalCell
cell.anchor = anchor
return cell
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出section的HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.取出模型
let group = recommendVM.anchorGroups[indexPath.section]
headerView.group = group
return headerView
}
}
// MARK:- 遵守UICollectionView的代理协议协议
extension RecommendViewController: UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let group = recommendVM.anchorGroups[indexPath.section]
let anchor = group.anchors[indexPath.item]
// 2.判断是秀场房间还是普通房间
anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc()
}
private func presentShowRoomVc() {
let showRoomVc = RoomShowViewController()
present(showRoomVc, animated: true, completion: nil)
}
private func pushNormalRoomVc() {
let normalRoomVc = RoomNormalViewController()
navigationController?.pushViewController(normalRoomVc, animated: true)
}
}
// MARK:- 遵守UICollectionView的代理协议
extension RecommendViewController: UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
|
mit
|
f35224840f056899e3b334e66297e890
| 34.596244 | 186 | 0.669744 | 5.787786 | false | false | false | false |
zhiquan911/chance_btc_wallet
|
chance_btc_wallet/chance_btc_wallet/extension/UIView+extension.swift
|
1
|
6278
|
//
// UIView+extension.swift
// light_guide
//
// Created by Chance on 15/10/16.
// Copyright © 2015年 wetasty. All rights reserved.
//
import Foundation
import UIKit
//MARK:全局方法
extension UIView {
//读取nib文件
class func loadFromNibNamed(_ nibNamed: String, bundle : Bundle? = nil) -> UIView? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
}
// MARK: - 动画
extension UIView {
//不停360旋转
func rotate360Degrees(_ duration: CFTimeInterval = 5, completionDelegate: AnyObject? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.toValue = CGFloat(M_PI * 2.0)
rotateAnimation.duration = duration
rotateAnimation.isCumulative = true
rotateAnimation.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
self.layer.add(rotateAnimation, forKey: "rotationAnimation")
}
//停止360旋转
func stopRotate360Degrees() {
self.layer.removeAnimation(forKey: "rotationAnimation")
}
//左右振动
func shakeLeftRightAnimation() {
let animation = CAKeyframeAnimation()
animation.keyPath = "position.x"
animation.values = [0, 10, -10, 10, 0]
animation.keyTimes = [0, NSNumber(value: 1 / 6.0), NSNumber(value: 3 / 6.0), NSNumber(value: 5 / 6.0), 1]
animation.duration = 0.4;
animation.isAdditive = true;
self.layer.add(animation, forKey: "shake")
}
//上下振动
func shakeUpDownAnimation(_ range: Float = 10) {
let animation = CAKeyframeAnimation()
animation.keyPath = "position.y"
animation.values = [0, range, -range, range, 0]
animation.keyTimes = [0, NSNumber(value: 1 / 6.0), NSNumber(value: 3 / 6.0), NSNumber(value: 5 / 6.0), 1]
animation.duration = 0.8;
animation.isAdditive = true;
self.layer.add(animation, forKey: "shake")
}
}
// MARK: - 形状坐标相关
extension UIView {
var x: CGFloat {
set {
var frame = self.frame;
frame.origin.x = newValue;
self.frame = frame;
}
get {
return self.frame.origin.x
}
}
var y: CGFloat {
set {
var frame = self.frame;
frame.origin.y = newValue;
self.frame = frame;
}
get {
return self.frame.origin.y
}
}
var centerX: CGFloat {
set {
var center = self.center;
center.x = newValue;
self.center = center;
}
get {
return self.center.x
}
}
var centerY: CGFloat {
set {
var center = self.center;
center.y = newValue;
self.center = center;
}
get {
return self.center.y
}
}
var width: CGFloat {
set {
var frame = self.frame;
frame.size.width = newValue;
self.frame = frame;
}
get {
return self.frame.size.width
}
}
var height: CGFloat {
set {
var frame = self.frame;
frame.size.height = newValue;
self.frame = frame;
}
get {
return self.frame.size.height
}
}
var size: CGSize {
set {
var frame = self.frame;
frame.size = newValue;
self.frame = frame;
}
get {
return self.frame.size
}
}
}
// MARK: - 角标红点定制
extension UIView {
var badgeViewTag: Int {
return 777
}
/**
显示小红点
- parameter index: 位置
*/
func showBadge(_ x: CGFloat? = nil, y: CGFloat? = nil, width: CGFloat = 10, height: CGFloat = 10) {
//移除之前的小红点
self.removeBadge()
//新建小红点
let badgeView = UIView()
badgeView.tag = self.badgeViewTag;
badgeView.layer.cornerRadius = 5;//圆形
badgeView.layer.masksToBounds = true
badgeView.backgroundColor = UIColor.red //颜色:红色
let frame = self.frame;
//确定小红点的位置
var x = x
if x == nil {
x = 0
x = frame.size.width + width
}
var y = y
if y == nil {
y = 0
y = (frame.size.height - height) / 2
}
badgeView.frame = CGRect(x: CGFloat(x!), y: CGFloat(y!), width: width, height: height);//圆形大小为10
self.addSubview(badgeView)
}
/**
隐藏小红点
- parameter index: 位置
*/
func hideBadge() {
//移除小红点
self.removeBadge()
}
/**
移除小红点
- parameter index:
*/
func removeBadge() {
//按照tag值进行移除
for subView in self.subviews {
if (subView.tag == self.badgeViewTag) {
subView.removeFromSuperview()
}
}
}
}
// MARK: - 使用原生的UIMenu式弹出自定义菜单栏
extension UIView {
/// 弹出UIMenu式菜单
///
/// - Parameters:
/// - items: 菜单项
/// - containerView: 弹出显示菜单时所在范围的容器(View)
func showUIMenu(items: [UIMenuItem], containerView: UIView) {
//已经是第一响应就消除
if containerView.isFirstResponder {
containerView.resignFirstResponder()
}
//把自己设置为第一响应才能弹出菜单
containerView.becomeFirstResponder()
let menuController = UIMenuController.shared
menuController.menuItems = items
//设置 menu 的 frame和父 view
guard let newFrame = self.superview?.convert(self.frame, to: containerView) else {
return
}
menuController.setTargetRect(newFrame, in: containerView)
menuController.setMenuVisible(true, animated: true)
}
}
|
mit
|
d97065c892490206d9f289b4d435e5ae
| 23.109756 | 113 | 0.524532 | 4.203402 | false | false | false | false |
kesun421/firefox-ios
|
Client/Frontend/AuthenticationManager/PasscodeViews.swift
|
1
|
6987
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SnapKit
private struct PasscodeUX {
static let TitleVerticalSpacing: CGFloat = 32
static let DigitSize: CGFloat = 30
static let TopMargin: CGFloat = 80
static let PasscodeFieldSize: CGSize = CGSize(width: 160, height: 32)
}
@objc protocol PasscodeInputViewDelegate: class {
func passcodeInputView(_ inputView: PasscodeInputView, didFinishEnteringCode code: String)
}
/// A custom, keyboard-able view that displays the blank/filled digits when entrering a passcode.
class PasscodeInputView: UIView, UIKeyInput {
weak var delegate: PasscodeInputViewDelegate?
var digitFont: UIFont = UIConstants.PasscodeEntryFont
let blankCharacter: Character = "-"
let filledCharacter: Character = "•"
fileprivate let passcodeSize: Int
fileprivate var inputtedCode: String = ""
fileprivate var blankDigitString: NSAttributedString {
return NSAttributedString(string: "\(blankCharacter)", attributes: [NSFontAttributeName: digitFont])
}
fileprivate var filledDigitString: NSAttributedString {
return NSAttributedString(string: "\(filledCharacter)", attributes: [NSFontAttributeName: digitFont])
}
@objc var keyboardType: UIKeyboardType = .numberPad
init(frame: CGRect, passcodeSize: Int) {
self.passcodeSize = passcodeSize
super.init(frame: frame)
isOpaque = false
}
convenience init(passcodeSize: Int) {
self.init(frame: CGRect.zero, passcodeSize: passcodeSize)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var canBecomeFirstResponder: Bool {
return true
}
func resetCode() {
inputtedCode = ""
setNeedsDisplay()
}
@objc var hasText: Bool {
return inputtedCode.characters.count > 0
}
@objc func insertText(_ text: String) {
guard inputtedCode.characters.count < passcodeSize else {
return
}
inputtedCode += text
setNeedsDisplay()
if inputtedCode.characters.count == passcodeSize {
delegate?.passcodeInputView(self, didFinishEnteringCode: inputtedCode)
}
}
// Required for implementing UIKeyInput
@objc func deleteBackward() {
guard inputtedCode.characters.count > 0 else {
return
}
inputtedCode.remove(at: inputtedCode.characters.index(before: inputtedCode.endIndex))
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let circleSize = CGSize(width: 14, height: 14)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setLineWidth(1)
context.setStrokeColor(UIConstants.PasscodeDotColor.cgColor)
context.setFillColor(UIConstants.PasscodeDotColor.cgColor)
(0..<passcodeSize).forEach { index in
let offset = floor(rect.width / CGFloat(passcodeSize))
var circleRect = CGRect(origin: CGPoint.zero, size: circleSize)
circleRect.center = CGPoint(x: (offset * CGFloat(index + 1)) - offset / 2, y: rect.height / 2)
if index < inputtedCode.characters.count {
context.fillEllipse(in: circleRect)
} else {
context.strokeEllipse(in: circleRect)
}
}
}
}
/// A pane that gets displayed inside the PasscodeViewController that displays a title and a passcode input field.
class PasscodePane: UIView {
let codeInputView: PasscodeInputView
var codeViewCenterConstraint: Constraint?
var containerCenterConstraint: Constraint?
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIConstants.DefaultChromeFont
label.isAccessibilityElement = true
return label
}()
fileprivate let centerContainer = UIView()
override func accessibilityElementCount() -> Int {
return 1
}
override func accessibilityElement(at index: Int) -> Any? {
switch index {
case 0: return titleLabel
default: return nil
}
}
init(title: String? = nil, passcodeSize: Int = 4) {
codeInputView = PasscodeInputView(passcodeSize: passcodeSize)
super.init(frame: CGRect.zero)
backgroundColor = UIConstants.TableViewHeaderBackgroundColor
titleLabel.text = title
centerContainer.addSubview(titleLabel)
centerContainer.addSubview(codeInputView)
addSubview(centerContainer)
centerContainer.snp.makeConstraints { make in
make.centerX.equalTo(self)
containerCenterConstraint = make.centerY.equalTo(self).constraint
}
titleLabel.snp.makeConstraints { make in
make.centerX.equalTo(centerContainer)
make.top.equalTo(centerContainer)
make.bottom.equalTo(codeInputView.snp.top).offset(-PasscodeUX.TitleVerticalSpacing)
}
codeInputView.snp.makeConstraints { make in
codeViewCenterConstraint = make.centerX.equalTo(centerContainer).constraint
make.bottom.equalTo(centerContainer)
make.size.equalTo(PasscodeUX.PasscodeFieldSize)
}
layoutIfNeeded()
NotificationCenter.default.addObserver(self, selector: #selector(PasscodePane.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(PasscodePane.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
func shakePasscode() {
UIView.animate(withDuration: 0.1, animations: {
self.codeViewCenterConstraint?.update(offset: -10)
self.layoutIfNeeded()
}, completion: { complete in
UIView.animate(withDuration: 0.1, animations: {
self.codeViewCenterConstraint?.update(offset: 0)
self.layoutIfNeeded()
})
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func keyboardWillShow(_ sender: Notification) {
guard let keyboardFrame = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {
return
}
UIView.animate(withDuration: 0.1, animations: {
self.containerCenterConstraint?.update(offset: -keyboardFrame.height/2)
self.layoutIfNeeded()
})
}
func keyboardWillHide(_ sender: Notification) {
UIView.animate(withDuration: 0.1, animations: {
self.containerCenterConstraint?.update(offset: 0)
self.layoutIfNeeded()
})
}
}
|
mpl-2.0
|
53e1e86974413d2cb7d0616c102f8325
| 32.907767 | 167 | 0.662563 | 5.01796 | false | false | false | false |
Tanglo/VergeOfStrife
|
Vos Map Maker/VoSMapDocument.swift
|
1
|
5564
|
//
// VoSMapDocument
// Vos Map Maker
//
// Created by Lee Walsh on 30/03/2015.
// Copyright (c) 2015 Lee David Walsh. All rights reserved.
//
import Cocoa
class VoSMapDocument: NSDocument {
var map = VoSMap()
var mapView: VoSMapView?
@IBOutlet var scrollView: NSScrollView?
@IBOutlet var tileWidthField: NSTextField?
@IBOutlet var tileHeightField: NSTextField?
override init() {
super.init()
// Add your subclass-specific initialization here.
map = VoSMap()
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
let (rows,columns) = map.grid.gridSize()
mapView = VoSMapView(frame: NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height))
scrollView!.documentView = mapView
tileWidthField!.doubleValue = map.tileSize.width
tileHeightField!.doubleValue = map.tileSize.height
}
override class func autosavesInPlace() -> Bool {
return true
}
override var windowNibName: String? {
// Returns the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
return "VoSMapDocument"
}
override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return NSKeyedArchiver.archivedDataWithRootObject(map)
}
override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
// let testData = NSData() //data
// println("before: \(map.someVar)")
let newMap: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(data) //testData)
if let testMap = newMap as? VoSMap {
map = newMap! as! VoSMap
// println("after: \(map.someVar)")
return true
}
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return false
}
@IBAction func importMapFromCSV(sender: AnyObject) {
let importOpenPanel = NSOpenPanel()
importOpenPanel.canChooseDirectories = false
importOpenPanel.canChooseFiles = true
importOpenPanel.allowsMultipleSelection = false
importOpenPanel.allowedFileTypes = ["csv", "CSV"]
let result = importOpenPanel.runModal()
if result == NSModalResponseOK {
var outError: NSError?
let mapString: String? = String(contentsOfFile: importOpenPanel.URL!.path!, encoding: NSUTF8StringEncoding, error: &outError)
if (mapString != nil) {
map.importMapFromString(mapString!)
updateMapView()
} else {
let errorAlert = NSAlert(error: outError!)
errorAlert.runModal()
}
}
}
func updateMapView() {
let (rows,columns) = map.grid.gridSize()
mapView!.frame = NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height)
mapView!.needsDisplay = true
}
@IBAction func saveAsPdf(sender: AnyObject){
let savePanel = NSSavePanel()
savePanel.allowedFileTypes = ["pdf", "PDF"]
let saveResult = savePanel.runModal()
if saveResult == NSModalResponseOK {
let pdfData = mapView!.dataWithPDFInsideRect(mapView!.frame)
let success = pdfData.writeToURL(savePanel.URL!, atomically: true)
}
}
override func printOperationWithSettings(printSettings: [NSObject : AnyObject], error outError: NSErrorPointer) -> NSPrintOperation? {
let printOp = NSPrintOperation(view: mapView!)
printOp.printPanel.options = printOp.printPanel.options | NSPrintPanelOptions.ShowsPageSetupAccessory
return printOp
}
@IBAction func updateTileSize(sender: AnyObject){
if sender as? NSTextField == tileWidthField {
map.tileSize.width = sender.doubleValue
} else if sender as? NSTextField == tileHeightField {
map.tileSize.height = sender.doubleValue
}
let (rows,columns) = map.grid.gridSize()
mapView!.frame = NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height)
mapView!.needsDisplay = true
}
}
|
mit
|
e0279e7adcd9ed177f101f113e14f39b
| 44.983471 | 198 | 0.667685 | 4.636667 | false | false | false | false |
oliverkulpakko/ATMs
|
Watch Extension/InterfaceController.swift
|
1
|
1851
|
//
// InterfaceController.swift
// Watch Extension
//
// Created by Oliver Kulpakko on 25/12/2018.
// Copyright © 2018 East Studios. All rights reserved.
//
import WatchKit
import Foundation
import CoreLocation
class InterfaceController: WKInterfaceController {
override func awake(withContext context: Any?) {
super.awake(withContext: context)
statusLabel.setText("main.status.fetching-location".localized)
locationManager.delegate = self
locationManager.requestLocation()
}
var locationManager = CLLocationManager()
func presentAtms(_ atms: [ATM], location: CLLocation) {
let namesAndContexts: [(name: String, context: AnyObject)] = atms.map {
let context = ($0, location) as AnyObject
return (name: "ATMInterfaceController", context: context)
}
WKInterfaceController.reloadRootControllers(withNamesAndContexts: namesAndContexts)
}
@IBOutlet var statusLabel: WKInterfaceLabel!
}
extension InterfaceController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
return
}
statusLabel.setText("main.status.fetching-atms".localized)
RemoteService.shared.fetchATMs(completion: { result in
switch result {
case .success(let atms):
let atms = Array(atms.sortedByLocation(location, nearbyThreshold: 10_000).prefix(10))
DispatchQueue.main.async {
self.presentAtms(atms, location: location)
}
case .failure(let error):
self.statusLabel.setText(error.localizedDescription)
}
})
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
statusLabel.setText(error.localizedDescription)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
}
}
|
mit
|
89c11ce9ddbc73012d78c76b6591227c
| 26.205882 | 107 | 0.752973 | 4.176072 | false | false | false | false |
nerdyc/Squeal
|
Tests/UpdateHelpersSpec.swift
|
1
|
2453
|
import Quick
import Nimble
import Squeal
class UpdateHelpersSpec: QuickSpec {
override func spec() {
var database : Database!
var result : Int?
beforeEach {
database = Database()
try! database.execute("CREATE TABLE contacts (contactId INTEGER PRIMARY KEY, name TEXT, email TEXT)")
try! database.insertInto("contacts", values:["name": "Amelia", "email":"[email protected]"])
try! database.insertInto("contacts", values:["name": "Brian", "email":"[email protected]"])
try! database.insertInto("contacts", values:["name": "Cara", "email":"[email protected]"])
}
afterEach {
database = nil
result = nil
}
describe(".update(tableName:set:whereExpr:parameters:error:)") {
beforeEach {
result = try! database.update("contacts",
set: ["name":"Bobby", "email":"[email protected]"],
whereExpr: "name IS ?",
parameters:["Brian"])
}
it("updates the values in the database") {
expect(result).to(equal(1))
let names = try! database.selectFrom("contacts") { $0["name"] as! String }
expect(names).to(equal(["Amelia", "Bobby", "Cara"]))
let emails = try! database.selectFrom("contacts") { $0["email"] as! String }
expect(emails).to(equal(["[email protected]", "[email protected]", "[email protected]"]))
}
}
describe(".update(tableName:rowIds:values:error:)") {
beforeEach {
result = try! database.update("contacts",
rowIds: [1, 3],
values: ["name":"Bobby"])
}
it("updates the values in the database") {
let values = try! database.selectFrom("contacts",
orderBy:"_ROWID_") { $0["name"] as! String }
expect(result).to(equal(2))
expect(values).to(equal(["Bobby", "Brian", "Bobby"]))
}
}
}
}
|
mit
|
d2cbceb7e4d486052ab88e70c5e3a4a9
| 37.936508 | 113 | 0.446392 | 4.995927 | false | true | false | false |
trill-lang/trill
|
Sources/AST/Statements.swift
|
2
|
5741
|
///
/// Statements.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import Foundation
import Source
public class Stmt: ASTNode {}
public class ReturnStmt: Stmt { // return <expr>;
public let value: Expr
public init(value: Expr, sourceRange: SourceRange? = nil) {
self.value = value
super.init(sourceRange: sourceRange)
}
}
public enum VarKind: Equatable {
case local(FuncDecl)
case global
case property(TypeDecl)
case implicitSelf(FuncDecl, TypeDecl)
public static func ==(lhs: VarKind, rhs: VarKind) -> Bool {
switch (lhs, rhs) {
case (.local(let fn), .local(let fn2)):
return fn === fn2
case (.global, .global):
return true
case (.property(let t), .property(let t2)):
return t === t2
case (.implicitSelf(let fn, let ty), .implicitSelf(let fn2, let ty2)):
return fn === fn2 && ty === ty2
default: return false
}
}
}
public class VarAssignDecl: Decl {
public let rhs: Expr?
public let name: Identifier
public var typeRef: TypeRefExpr?
public var kind: VarKind
public var mutable: Bool
public init?(name: Identifier,
typeRef: TypeRefExpr?,
kind: VarKind = .global,
rhs: Expr? = nil,
modifiers: [DeclModifier] = [],
mutable: Bool = true,
sourceRange: SourceRange? = nil) {
guard rhs != nil || typeRef != nil else { return nil }
self.rhs = rhs
self.typeRef = typeRef
self.mutable = mutable
self.name = name
self.kind = kind
super.init(type: typeRef?.type ?? .void,
modifiers: modifiers,
sourceRange: sourceRange)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["type"] = typeRef?.type.description
superAttrs["name"] = name.name
superAttrs["kind"] = {
switch kind {
case .local: return "local"
case .global: return "global"
case .implicitSelf: return "implicit_self"
case .property: return "property"
}
}()
superAttrs["mutable"] = mutable
return superAttrs
}
}
public class CompoundStmt: Stmt {
public let stmts: [Stmt]
public var hasReturn = false
public init(stmts: [Stmt], sourceRange: SourceRange? = nil) {
self.stmts = stmts
super.init(sourceRange: sourceRange)
}
}
public class BranchStmt: Stmt {
public let condition: Expr
public let body: CompoundStmt
public init(condition: Expr, body: CompoundStmt, sourceRange: SourceRange? = nil) {
self.condition = condition
self.body = body
super.init(sourceRange: sourceRange)
}
}
public class IfStmt: Stmt {
public let blocks: [(Expr, CompoundStmt)]
public let elseBody: CompoundStmt?
public init(blocks: [(Expr, CompoundStmt)], elseBody: CompoundStmt?, sourceRange: SourceRange? = nil) {
self.blocks = blocks
self.elseBody = elseBody
super.init(sourceRange: sourceRange)
}
}
public class WhileStmt: BranchStmt {}
public class ForStmt: Stmt {
public let initializer: Stmt?
public let condition: Expr?
public let incrementer: Stmt?
public let body: CompoundStmt
public init(initializer: Stmt?,
condition: Expr?,
incrementer: Stmt?,
body: CompoundStmt,
sourceRange: SourceRange? = nil) {
self.initializer = initializer
self.condition = condition
self.incrementer = incrementer
self.body = body
super.init(sourceRange: sourceRange)
}
}
public class SwitchStmt: Stmt {
public let value: Expr
public let cases: [CaseStmt]
public let defaultBody: CompoundStmt?
public init(value: Expr, cases: [CaseStmt], defaultBody: CompoundStmt? = nil, sourceRange: SourceRange? = nil) {
self.value = value
self.cases = cases
self.defaultBody = defaultBody
super.init(sourceRange: sourceRange)
}
}
public class CaseStmt: Stmt {
public let constant: Expr
public let body: CompoundStmt
public init(constant: Expr, body: CompoundStmt, sourceRange: SourceRange? = nil) {
self.constant = constant
self.body = body
super.init(sourceRange: sourceRange)
}
}
public class BreakStmt: Stmt {}
public class ContinueStmt: Stmt {}
public class ExtensionDecl: Decl {
public let methods: [MethodDecl]
public let staticMethods: [MethodDecl]
public let subscripts: [SubscriptDecl]
public let typeRef: TypeRefExpr
public var typeDecl: TypeDecl?
public init(type: TypeRefExpr,
methods: [MethodDecl],
staticMethods: [MethodDecl],
subscripts: [SubscriptDecl],
sourceRange: SourceRange? = nil) {
self.methods = methods
self.subscripts = subscripts
self.staticMethods = staticMethods
self.typeRef = type
super.init(type: type.type, modifiers: [], sourceRange: sourceRange)
}
}
public class ExprStmt: Stmt {
public let expr: Expr
public init(expr: Expr) {
self.expr = expr
super.init(sourceRange: expr.sourceRange)
}
}
public class DeclStmt: Stmt {
public let decl: Decl
public init(decl: Decl) {
self.decl = decl
super.init(sourceRange: decl.sourceRange)
}
}
public class PoundDiagnosticStmt: Stmt {
public let isError: Bool
public let content: StringExpr
public init(isError: Bool, content: StringExpr,
sourceRange: SourceRange? = nil) {
self.isError = isError
self.content = content
super.init(sourceRange: sourceRange)
}
public var text: String {
return content.text
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["text"] = text
superAttrs["kind"] = isError ? "error" : "warning"
return superAttrs
}
}
|
mit
|
d1eba493c8d46e8fec148901a98807a5
| 25.578704 | 114 | 0.671312 | 3.97301 | false | false | false | false |
DanielOYC/Tools
|
Category/UIImage+CircleImage.swift
|
1
|
1915
|
//
// UIImage+CircleImage.swift
// TestAnimation
//
// Created by daniel on 2017/9/3.
// Copyright © 2017年 daniel. All rights reserved.
//
import UIKit
extension UIImage {
//获得圆角图片
class func circleImage(original: UIImage, clicpBounds: CGRect) -> UIImage {
//开始绘图上下文
UIGraphicsBeginImageContextWithOptions(clicpBounds.size, false, 0.0)
//添加裁切路径
let bounds = CGRect(x: 0, y: 0, width: clicpBounds.width, height: clicpBounds.height)
let path = UIBezierPath(ovalIn: clicpBounds)
path.addClip()
//绘制图片
original.draw(in: bounds)
let tempImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tempImage!
}
//获得带圆环的圆角图片
class func circleImageWithRing(original: UIImage, clicpBounds: CGRect, ringWidth: CGFloat, ringColor: UIColor) -> UIImage {
//设置上下文尺寸
let imageW = clicpBounds.width
let contextW = imageW + 2 * ringWidth
let contextSize = CGSize(width: contextW, height: contextW)
//开始绘图上下文
UIGraphicsBeginImageContextWithOptions(contextSize, false, 0.0)
//绘制圆环
let ringBounds = CGRect(x: 0, y: 0, width: contextW, height: contextW)
let ringPath = UIBezierPath(ovalIn: ringBounds)
ringColor.set()
ringPath.fill()
//添加裁切路径
let imageBounds = CGRect(x: ringWidth, y: ringWidth, width: imageW, height: imageW)
let path = UIBezierPath(ovalIn: imageBounds)
path.addClip()
//绘制图片
original.draw(in: imageBounds)
let tempImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tempImage!
}
}
|
mit
|
9c6dc02ebe5c42b0bea5cb2d17b6302f
| 29.338983 | 128 | 0.626257 | 4.272076 | false | false | false | false |
esttorhe/RxSwift
|
RxSwift/RxSwift/DataStructures/Bag.swift
|
1
|
1763
|
//
// Bag.swift
// Rx
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
private struct BagPrivate {
static let maxElements = Bag<Void>.KeyType.max - 1 // this is guarding from theoretical endless loop
}
public struct Bag<T> : SequenceType, CustomStringConvertible {
typealias Generator = AnyGenerator<T>
public typealias KeyType = Int
private var map: [KeyType: T] = Dictionary(minimumCapacity: 5)
private var nextKey: KeyType = 0
public init() {
}
public var description : String {
get {
return "\(map.count) elements \(self.map)"
}
}
public var count: Int {
get {
return map.count
}
}
public mutating func put(x: T) -> KeyType {
if map.count >= BagPrivate.maxElements {
rxFatalError("Too many elements")
}
while map[nextKey] != nil {
nextKey = nextKey &+ 1
}
map[nextKey] = x
return nextKey
}
public func generate() -> AnyGenerator<T> {
var dictionaryGenerator = map.generate()
return anyGenerator {
let next = dictionaryGenerator.next()
if let (_, value) = next {
return value
}
else {
return nil
}
}
}
public var all: [T]
{
get {
return self.map.values.array
}
}
public mutating func removeAll() {
map.removeAll(keepCapacity: false)
}
public mutating func removeKey(key: KeyType) -> T? {
return map.removeValueForKey(key)
}
}
|
mit
|
dda949a72067096b58bc871f384a478d
| 20.777778 | 104 | 0.533749 | 4.591146 | false | false | false | false |
Entalpi/SwiftJSON
|
SwiftJSON.playground/Contents.swift
|
1
|
2985
|
//: Playground - noun: a place where people can play
// MARK: - JSON Handling
/// Allows you to iterate over members of classes, structs.
func iterate<T>(t: T, block: (name: String, value: Any, parent: MirrorType, indexInParent: Int) -> Void) {
let mirror = reflect(t)
for i in 0..<mirror.count {
block(name: mirror[i].0, value: mirror[i].1.value, parent: mirror, indexInParent: i)
}
}
/// Recursive helper for JSON method
private func helperJSON<T>(t: T, moreContent: Bool) -> String {
var json = "{\n"
iterate(t, { (name, value, parent, index) -> Void in
let mirror = reflect(value)
if mirror.count > 1 {
json += "\"\(value)\":"
let moreMembers = index < parent.count - 1 ? true : false
json += helperJSON(value, moreMembers)
} else {
json += "\"\(name)\" : \"\(value)\""
if index != parent.count - 1 {
json += ",\n"
}
}
})
json += "\n}"
if moreContent { json += "," }
return json
}
/// Generates a JSON string from any type T (like structs, classes, objects).
func JSON<T>(t: T) -> String {
return helperJSON(t, false)
}
// MARK: - Enums
enum Heating: String, Reflectable {
case Direct = "DIRECT"
case District = "DISTRICT"
case AirHeatPump = "AIR_HEATPUMP"
case HeatPump = "HEATPUMP"
case None = ""
func getMirror() -> MirrorType {
return self.rawValue.getMirror()
}
}
enum House: String, Reflectable {
case Villa = "VILLA"
case Apartment = "APARTMENT"
case RowHouse = "ROWHOUSE"
func getMirror() -> MirrorType {
return self.rawValue.getMirror()
}
}
enum ProviderContractType: String, Reflectable {
case Fixed = "FIXED"
case Mixed = "MIXED"
case Hourly = "HOURLY"
func getMirror() -> MirrorType {
return self.rawValue.getMirror()
}
}
// MARK: - Structs
struct UserInformation {
let username: String
let password: String
let email: String
let facility: Facility
}
struct ProviderContract {
var provider_id: Int
var contract_type: ProviderContractType
var fee: Int
var price: Double?
}
struct Facility {
var id: String
var construction_year: Int?
var area: Int
var provider_contract: ProviderContract
var street: String
var heating: Heating?
var facility_type: House
var postal_code: Int
var occupants: Int
}
let providerContract = ProviderContract(provider_id: 1, contract_type: ProviderContractType.Hourly, fee: 25, price: 1.37)
let facility = Facility(id: "id", construction_year: 1994, area: 90, provider_contract: providerContract, street: "Infinity Loop 1", heating: Heating.HeatPump, facility_type: House.Apartment, postal_code: 12345, occupants: 2)
let userInfo = UserInformation(username: "username", password: "password", email: "[email protected]", facility: facility)
println(JSON(userInfo))
|
mit
|
f68eb4777f884ad6341c0d5df27bcf2e
| 28.27451 | 225 | 0.623451 | 3.712687 | false | false | false | false |
cloudinary/cloudinary_ios
|
Cloudinary/Classes/Core/CLDResponsiveParams.swift
|
1
|
3156
|
//
// CLDResponsiveParams.swift
//
// Copyright (c) 2018 Cloudinary (http://cloudinary.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
@objcMembers open class CLDResponsiveParams: NSObject {
public static let defaultStepSize = 50
public static let defaultMaxDimension = 350
public static let defaultMinDimension = 50
public static let defaultReloadOnSizeChange = false
internal let autoWidth: Bool
internal let autoHeight: Bool
internal let cropMode: CLDTransformation.CLDCrop?
internal let gravity: CLDTransformation.CLDGravity?
internal var shouldReloadOnSizeChange = defaultReloadOnSizeChange
internal var stepSizePoints = defaultStepSize
internal var maxDimensionPoints = defaultMaxDimension
internal var minDimensionPoints = defaultMinDimension
// MARK: - Init
public init(autoWidth: Bool, autoHeight: Bool, cropMode: CLDTransformation.CLDCrop?, gravity: CLDTransformation.CLDGravity?) {
self.autoWidth = autoWidth
self.autoHeight = autoHeight
self.cropMode = cropMode
self.gravity = gravity
}
// MARK: - Presets
public static func fit () -> CLDResponsiveParams {
return CLDResponsiveParams(autoWidth: true, autoHeight: true, cropMode: CLDTransformation.CLDCrop.fit, gravity: nil)
}
public static func autoFill () -> CLDResponsiveParams {
return CLDResponsiveParams(autoWidth: true, autoHeight: true, cropMode: CLDTransformation.CLDCrop.fill, gravity: CLDTransformation.CLDGravity.auto)
}
// MARK: - Setters
public func setStepSize(_ stepSize:Int) -> Self {
self.stepSizePoints = stepSize
return self
}
public func setMaxDimension(_ maxDimension:Int) -> Self {
self.maxDimensionPoints = maxDimension
return self
}
public func setMinDimension(_ minDimension:Int) -> Self {
self.minDimensionPoints = minDimension
return self
}
public func setReloadOnSizeChange(_ reload: Bool) -> Self {
self.shouldReloadOnSizeChange = reload
return self
}
}
|
mit
|
74deb150a43042a1e2b8c5e552800bd1
| 37.487805 | 155 | 0.727186 | 4.641176 | false | false | false | false |
ProjectTorch/iOS
|
Torch-iOS/Protocols/TorManager.swift
|
1
|
2306
|
import Foundation
import CPAProxy
class TorManager {
var cpaProxyManager: CPAProxyManager!
var urlSession: URLSession!
func startProxy (completion: @escaping CPABootstrapCompletionBlock, progress: @escaping CPABootstrapProgressBlock)
{
let cpaProxyBundleURL: URL? = Bundle(for: CPAProxyManager.self).url(forResource: "CPAProxy", withExtension: "bundle")
let cpaProxyBundle = Bundle(url: cpaProxyBundleURL!)
let torrcPath: String? = cpaProxyBundle?.path(forResource: "torrc", ofType: nil)
let geoipPath: String? = cpaProxyBundle?.path(forResource: "geoip", ofType: nil)
let documentsDirectory: String? = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let torDataDir: String = URL(fileURLWithPath: documentsDirectory!).appendingPathComponent("tor").absoluteString
let configuration = CPAConfiguration(torrcPath: torrcPath, geoipPath: geoipPath, torDataDirectoryPath: torDataDir)
self.cpaProxyManager = CPAProxyManager.proxy(with: configuration)
self.cpaProxyManager?.setup(
completion: completion,
progress: progress
)
return
}
func urlSessionSetup (withSOCKSHost SOCKSHost: String, socksPort SOCKSPort: Int)
{
let configuration = URLSessionConfiguration.ephemeral
configuration.connectionProxyDictionary = [AnyHashable: Any]()
configuration.connectionProxyDictionary?[kCFStreamPropertySOCKSProxyPort as String] = SOCKSPort
configuration.connectionProxyDictionary?[kCFStreamPropertySOCKSProxyHost as String] = SOCKSHost
self.urlSession = URLSession(configuration: configuration, delegate: self as? URLSessionDelegate, delegateQueue: OperationQueue.main)
}
/*func loadWebPage (url: String) -> String
{
let needUrl = URL(string: url)
let dataTask: URLSessionDataTask? = urlSession.dataTask(with: needUrl!, completionHandler: { (data, response, error) in
if let error = error {
print(error.localizedDescription)
}
let backToString = String(data: data!, encoding: String.Encoding.utf8) as String!
return backToString
})
dataTask?.resume()
}*/
}
|
mit
|
7ff11d752c1b757e8eb834eeaad856f5
| 44.215686 | 141 | 0.69948 | 4.764463 | false | true | false | false |
ccrama/Slide-iOS
|
Slide for Apple Watch Extension/Votable.swift
|
1
|
1849
|
//
// Votable.swift
// Slide for Apple Watch Extension
//
// Created by Carlos Crane on 3/5/20.
// Copyright © 2020 Haptic Apps. All rights reserved.
//
import Foundation
import WatchConnectivity
import WatchKit
class Votable: WKInterfaceController {
weak var sharedUp: WKInterfaceButton?
weak var sharedDown: WKInterfaceButton?
weak var sharedReadLater: WKInterfaceButton?
func doVote(id: String, upvote: Bool, downvote: Bool) {
print("Doing vote")
WCSession.default.sendMessage(["vote": id, "upvote": upvote, "downvote": downvote], replyHandler: { (result) in
if result["failed"] == nil {
WKInterfaceDevice.current().play(.success)
self.sharedUp?.setBackgroundColor((result["upvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#FF5700") : UIColor.gray)
self.sharedDown?.setBackgroundColor((result["downvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#9494FF") : UIColor.gray)
} else {
WKInterfaceDevice.current().play(.failure)
}
self.sharedUp = nil
self.sharedDown = nil
}, errorHandler: { (error) in
print(error)
})
}
func doReadLater(id: String, sub: String) {
WCSession.default.sendMessage(["readlater": id, "sub": sub], replyHandler: { (result) in
if result["failed"] == nil {
WKInterfaceDevice.current().play(.success)
self.sharedReadLater?.setBackgroundColor((result["isReadLater"] ?? false) as! Bool ? UIColor.init(hexString: "#4CAF50") : UIColor.gray)
} else {
WKInterfaceDevice.current().play(.failure)
}
self.sharedReadLater = nil
}, errorHandler: { (error) in
print(error)
})
}
}
|
apache-2.0
|
6714a7887e3714087e470dd47780c3fb
| 37.5 | 151 | 0.600108 | 4.431655 | false | false | false | false |
melling/ios_topics
|
GameClock/GameClock/GameClock.swift
|
1
|
1471
|
//
// GameClock.swift
// GameClock
//
// Created by Michael Mellinger on 11/24/17.
// Copyright © 2017 h4labs. All rights reserved.
//
import UIKit
class GameClock {
// MARK: - private
var gameTime = 0 // Want to allow pausing?
private var startTimeInterval = Date()
var timeLabel:UILabel!
private var timer:Timer!
private let dateFormatter = DateFormatter()
public func setLabel(label:UILabel) {
self.timeLabel = label
}
public func startClock() {
timer = Timer()
startTimeInterval = Date()
dateFormatter.dateFormat = "h:mm:ss a"
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
gameTime += 1
let timeInterval = Date().timeIntervalSince(startTimeInterval)
if timeLabel != nil {
let s = timeString(time: timeInterval)
timeLabel.text = "\(s)"
}
}
public func pauseClock() {
timer.invalidate()
}
public func resetClock() {
gameTime = 0
startTimeInterval = Date()
timer.invalidate()
}
private func timeString(time:TimeInterval) -> String {
let minutes = Int(time) / 60
let seconds = time - Double(minutes) * 60
let s = String(format:"%02i:%02i",minutes,Int(seconds))
return s
}
}
|
cc0-1.0
|
9f8e26fc1c2ca201375b210b2cc1f866
| 23.5 | 131 | 0.587755 | 4.38806 | false | false | false | false |
leizh007/HiPDA
|
HiPDA/HiPDATests/PostInfoTests.swift
|
1
|
1833
|
//
// PostInfoTests.swift
// HiPDA
//
// Created by leizh007 on 2017/5/15.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import XCTest
@testable import HiPDA
class PostInfoTests: XCTestCase {
func testInitialization1() {
let urlString = "https://www.hi-pda.com/forum/viewthread.php?tid=2094735&extra=page%3D1&page=1"
guard let postInfo = PostInfo(urlString: urlString) else {
XCTFail()
return
}
XCTAssert(postInfo == PostInfo(tid: 2094735, page: 1, pid: nil))
}
func testInitialization2() {
let urlString = "https://www.hi-pda.com/forum/viewthread.php?tid=2094735&rpid=41821617&ordertype=0&page=1#pid41821617"
guard let postInfo = PostInfo(urlString: urlString) else {
XCTFail()
return
}
XCTAssert(postInfo == PostInfo(tid: 2094735, page: 1, pid: 41821617))
}
func testInitialization3() {
let urlString = "https://www.hi-pda.com/forum/viewthread.php?tid=2094735&extra=page%3D1&page=1"
guard let postInfo = PostInfo(urlString: urlString) else {
XCTFail()
return
}
XCTAssert(postInfo == PostInfo(tid: 2094735, page: 1, pid: nil))
}
func testInitialization4() {
let urlString = "https://www.hi-pda.com/forum/post.php?action=newthread&fid=2&special=1"
if let _ = PostInfo(urlString: urlString) {
XCTFail()
}
}
func testInitialization5() {
let urlString = "https://www.hi-pda.com/forum/viewthread.php?tid=1272557&page=3&authorid=644982"
guard let postInfo = PostInfo(urlString: urlString) else {
XCTFail()
return
}
XCTAssert(postInfo == PostInfo(tid: 1272557, page: 3, pid: nil, authorid: 644982))
}
}
|
mit
|
908cc68740000234b2d8c6f1f46d3750
| 32.272727 | 126 | 0.610929 | 3.526012 | false | true | false | false |
airbnb/lottie-ios
|
Sources/Public/DotLottie/Cache/DotLottieCache.swift
|
2
|
1152
|
//
// LRUDotLottieCache.swift
// Lottie
//
// Created by Evandro Hoffmann on 20/10/22.
//
import Foundation
/// A DotLottie Cache that will store lottie files up to `cacheSize`.
///
/// Once `cacheSize` is reached, the least recently used lottie will be ejected.
/// The default size of the cache is 100.
public class DotLottieCache: DotLottieCacheProvider {
// MARK: Lifecycle
public init() {
cache.countLimit = Self.defaultCacheCountLimit
}
// MARK: Public
/// The global shared Cache.
public static let sharedCache = DotLottieCache()
/// The size of the cache.
public var cacheSize = defaultCacheCountLimit {
didSet {
cache.countLimit = cacheSize
}
}
/// Clears the Cache.
public func clearCache() {
cache.removeAllObjects()
}
public func file(forKey key: String) -> DotLottieFile? {
cache.object(forKey: key as NSString)
}
public func setFile(_ lottie: DotLottieFile, forKey key: String) {
cache.setObject(lottie, forKey: key as NSString)
}
// MARK: Private
private static let defaultCacheCountLimit = 100
private var cache = NSCache<NSString, DotLottieFile>()
}
|
apache-2.0
|
ea603add49a783e0a2d4367c47842478
| 20.735849 | 80 | 0.692708 | 4.099644 | false | false | false | false |
zhou9734/Warm
|
Warm/Classes/Experience/Model/WTags.swift
|
1
|
1449
|
//
// WTag.swift
// Warm
//
// Created by zhoucj on 16/9/14.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
class WTags: NSObject {
//tagid
var tagid: Int64 = -1
//排序
var sort: Int64 = -1
//图片地址
var avatar: String?
//创建时间
var created_at: Int64 = -1
//更新时间
var updated_at: Int64 = -1
var tag: WTag?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forKey key: String) {
if key == "tag"{
guard let _data = value else{
return
}
tag = WTag(dict: _data as! [String: AnyObject])
return
}
super.setValue(value, forKey: key)
}
//防治没有匹配到的key报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
class WTag: NSObject {
//id
var id: Int64 = -1
//标签名称
var name: String?
//图标
var icon: String?
//类型
var type: Int64 = -1
//创建时间
var created_at: Int64 = -1
//更新时间
var updated_at: Int64 = -1
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
//防治没有匹配到的key报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
|
mit
|
4e76c274075730e84b3fce040cae3092
| 20.365079 | 76 | 0.558692 | 3.551451 | false | false | false | false |
takebayashi/SwiftGumbo
|
Sources/Attribute.swift
|
1
|
1643
|
import CGumbo
public struct Attribute: Node {
public typealias RawType = GumboAttribute
public let children: [OpaqueNode] = []
public let name: String
public let value: String
public init(name: String, value: String) {
self.name = name
self.value = value
}
public init(rawNode: GumboAttribute) {
self.name = String(cString: rawNode.name)
self.value = String(cString: rawNode.value)
}
}
extension Attribute {
public var valuesSeparatedByWhiteSpaces: [String] {
get {
// https://www.w3.org/TR/html5/infrastructure.html#space-character
// The space characters, for the purposes of this specification,
// are U+0020 SPACE, "tab" (U+0009), "LF" (U+000A), "FF" (U+000C),
// and "CR" (U+000D).
let chunks = self.value.characters.split { c in
switch c {
case Character(UnicodeScalar(0x20)):
return true
case Character(UnicodeScalar(0x09)):
return true
case Character(UnicodeScalar(0x0a)):
return true
case Character(UnicodeScalar(0x0c)):
return true
case Character(UnicodeScalar(0x0d)):
return true
default:
return false
}
}
return chunks.map(String.init)
}
}
}
extension Collection where Iterator.Element == Attribute {
public subscript(key: String) -> Attribute? {
return self.first { $0.name == key }
}
}
|
mit
|
5acf192ce8503fdbfcba79107d6756d0
| 29.425926 | 78 | 0.544735 | 4.440541 | false | false | false | false |
xixi197/XXColorTheme
|
Classes/UIKit/TCButton+XXColorStyle.swift
|
1
|
1951
|
//
// TCButton+XXColorStyle.swift
// XXColorTheme
//
// Created by xixi197 on 16/1/21.
// Copyright © 2016年 xixi197. All rights reserved.
//
import UIKit
import RxSwift
import NSObject_Rx
extension TCButton {
private struct AssociatedKeys {
static var NormalTintColorStyle = "xx_normalTintColorStyle"
static var HighlightedTintColorStyle = "xx_highlightedTintColorStyle"
static var SelectedTintColorStyle = "xx_selectedTintColorStyle"
}
var xx_normalTintColorStyle: XXColorStyle? {
get {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.NormalTintColorStyle) as? String ?? ""
return XXColorStyle(rawValue: lookup)
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.NormalTintColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
xx_addColorStyle(newValue, forSelector: "setXx_normalTintColor:")
}
}
var xx_highlightedTintColorStyle: XXColorStyle? {
get {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.HighlightedTintColorStyle) as? String ?? ""
return XXColorStyle(rawValue: lookup)
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.HighlightedTintColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
xx_addColorStyle(newValue, forSelector: "setXx_highlightedTintColor:")
}
}
var xx_selectedTintColorStyle: XXColorStyle? {
get {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.SelectedTintColorStyle) as? String ?? ""
return XXColorStyle(rawValue: lookup)
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.SelectedTintColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
xx_addColorStyle(newValue, forSelector: "setXx_selectedTintColor:")
}
}
}
|
mit
|
6031352a026e5059414cd39fc0753658
| 34.418182 | 141 | 0.677105 | 4.649165 | false | false | false | false |
Off-Piste/Trolley.io
|
Trolley/Database/TRLDatabase-Objc/TRLBasket-Objc.swift
|
2
|
2014
|
//
// TRLBasket-Objc.swift
// Pods
//
// Created by Harry Wright on 03.07.17.
//
//
import Foundation
@objc public class TRLBasket : NSObject {
internal typealias Core = _Basket<Product>
fileprivate var core: Core
public var products: [Product] {
return core._products
}
public override init() {
self.core = []
super.init()
}
public init(withProducts products: Array<Product>) {
self.core = Core(indexes: products)
super.init()
}
public init(withProduct product: Product) {
self.core = Core(index: product)
super.init()
}
init(_ core: Core) {
self.core = core
super.init()
}
}
public extension TRLBasket {
@objc(productForIndex:)
func product(for index: Int) -> Product {
assert(index > self.core.endIndex, "\(index) should not be larger than \(self.core.count)")
return self.core[index]
}
@objc(productForID:)
func product(for id: String) -> Product? {
return self.core.getProduct(for: id)
}
@objc(appendProduct:)
func append(_ product: Product) {
self.core.append(product)
}
@objc(appendingProduct:)
func appending(_ product: Product) -> TRLBasket {
return TRLBasket(self.core.appending(product))
}
}
public extension TRLBasket {
@objc(addProduct:withQuantity:block:)
func add(
_ product: Product,
withQuantity q: NSNumber,
block: @escaping (TRLBasket, Error?) -> Void
)
{
let quantity = Int(q)
self.core.add(product, withQuantity: quantity) {
block(TRLBasket($0.0), $0.1)
}
}
@objc(addProduct:withBlock:)
func append(
_ product: Product,
block: @escaping (TRLBasket, Error?) -> Void
)
{
self.core.add(product, withQuantity: 1) {
block(TRLBasket($0.0), $0.1)
}
}
}
|
mit
|
6180547ea522fd4175cb157e11dbb252
| 20.425532 | 99 | 0.558093 | 3.895551 | false | false | false | false |
ZhengShouDong/CloudPacker
|
Sources/CloudPacker/Handlers/SimulatorAppsHandler.swift
|
1
|
3382
|
//
// SimulatorAppsHandler.swift
// CloudPacker
//
// Created by ZHENGSHOUDONG on 2018/3/8.
//
import Foundation
import PerfectLib
import PerfectHTTP
extension Handlers {
/// 获取已经编译好的模拟器包列表
public static func getSimulatorAppsHandler(data: [String: Any]) throws -> RequestHandler {
return {
request, response in
response.setHeader(.server, value: "CloudPacker/\(cloudPackerVersion)")
if filterIP(request: request) {
response.setHeader(.contentType, value: "application/json")
response.setBody(string: JSONManager.makeAPIJsonString(type: .authorizedError, msg: "serverError"))
response.completed(status: .notFound)
return
}
/// 获得符合通配符的请求路径
request.path = request.urlVariables[routeTrailingWildcardKey] ?? emptyString
if (request.path.isEmpty) {
response.setHeader(.contentType, value: "text/html; charset=UTF-8")
response.setBody(string: "not found").completed(status: .notFound)
return
}
StaticFileHandler(documentRoot: simulatorAppsDir, allowResponseFilters: false).handleRequest(request: request, response: response)
}
}
/// 获取已经打包好的模拟器包列表(json返回)
public static func appsListHandler(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
response.setHeader(.contentType, value: "application/json")
response.setHeader(.server, value: "CloudPacker/\(cloudPackerVersion)")
if filterIP(request: request) {
response.setBody(string: JSONManager.makeAPIJsonString(type: .authorizedError, msg: "serverError"))
response.completed(status: .notFound)
return
}
if !Dir(simulatorAppsDir).exists {
CloudPackerUtils.createFolderIfNeeded(path: simulatorAppsDir)
}
let dirNames = try? FileManager.default.contentsOfDirectory(atPath: simulatorAppsDir)
if !dirNames!.isEmpty {
var array = Array<Dictionary<String, String>>()
for fileName in dirNames! {
if fileName == "index.html" || fileName.hasPrefix(".") { continue }
var dict = Dictionary<String, String>()
let modificationTime = File(String(format:"%@/%@", simulatorAppsDir, fileName)).modificationTime
/// 时间戳转换为时间
let date = Date(timeIntervalSince1970: TimeInterval(modificationTime))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
dict["path"] = String(format: "/v1/app/%@",fileName)
dict["time"] = dateFormatter.string(from: date)
array.append(dict)
}
response.setBody(string: array.jsonEncoded())
}else {
response.setBody(string: emptyString)
}
response.completed(status: .ok)
}
}
}
|
apache-2.0
|
a370fdfc3fb97d5e7adbafbbe6ec9b83
| 39.518519 | 142 | 0.565509 | 5.104199 | false | false | false | false |
chris-wood/reveiller
|
reveiller/Pods/SwiftCharts/SwiftCharts/Layers/ChartGuideLinesLayer.swift
|
7
|
8166
|
//
// ChartGuideLinesLayer.swift
// SwiftCharts
//
// Created by ischuetz on 26/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartGuideLinesLayerSettings {
let linesColor: UIColor
let linesWidth: CGFloat
public init(linesColor: UIColor = UIColor.grayColor(), linesWidth: CGFloat = 0.3) {
self.linesColor = linesColor
self.linesWidth = linesWidth
}
}
public class ChartGuideLinesDottedLayerSettings: ChartGuideLinesLayerSettings {
let dotWidth: CGFloat
let dotSpacing: CGFloat
public init(linesColor: UIColor, linesWidth: CGFloat, dotWidth: CGFloat = 2, dotSpacing: CGFloat = 2) {
self.dotWidth = dotWidth
self.dotSpacing = dotSpacing
super.init(linesColor: linesColor, linesWidth: linesWidth)
}
}
public enum ChartGuideLinesLayerAxis {
case X, Y, XAndY
}
public class ChartGuideLinesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer {
private let settings: T
private let onlyVisibleX: Bool
private let onlyVisibleY: Bool
private let axis: ChartGuideLinesLayerAxis
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: T, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
self.settings = settings
self.onlyVisibleX = onlyVisibleX
self.onlyVisibleY = onlyVisibleY
self.axis = axis
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
fatalError("override")
}
override public func chartViewDrawing(context context: CGContextRef, chart: Chart) {
let originScreenLoc = self.innerFrame.origin
let xScreenLocs = onlyVisibleX ? self.xAxis.visibleAxisValuesScreenLocs : self.xAxis.axisValuesScreenLocs
let yScreenLocs = onlyVisibleY ? self.yAxis.visibleAxisValuesScreenLocs : self.yAxis.axisValuesScreenLocs
if self.axis == .X || self.axis == .XAndY {
for xScreenLoc in xScreenLocs {
let x1 = xScreenLoc
let y1 = originScreenLoc.y
let x2 = x1
let y2 = originScreenLoc.y + self.innerFrame.height
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
if self.axis == .Y || self.axis == .XAndY {
for yScreenLoc in yScreenLocs {
let x1 = originScreenLoc.x
let y1 = yScreenLoc
let x2 = originScreenLoc.x + self.innerFrame.width
let y2 = y1
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
}
}
public typealias ChartGuideLinesLayer = ChartGuideLinesLayer_<Any>
public class ChartGuideLinesLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesLayerSettings> {
override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: ChartGuideLinesLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor)
}
}
public typealias ChartGuideLinesDottedLayer = ChartGuideLinesDottedLayer_<Any>
public class ChartGuideLinesDottedLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesDottedLayerSettings> {
override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: ChartGuideLinesDottedLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing)
}
}
public class ChartGuideLinesForValuesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer {
private let settings: T
private let axisValuesX: [ChartAxisValue]
private let axisValuesY: [ChartAxisValue]
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: T, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
self.settings = settings
self.axisValuesX = axisValuesX
self.axisValuesY = axisValuesY
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
private func drawGuideline(context: CGContextRef, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint, dotWidth: CGFloat, dotSpacing: CGFloat) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: width, color: color, dotWidth: dotWidth, dotSpacing: dotSpacing)
}
private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
fatalError("override")
}
override public func chartViewDrawing(context context: CGContextRef, chart: Chart) {
let originScreenLoc = self.innerFrame.origin
for axisValue in self.axisValuesX {
let screenLoc = self.xAxis.screenLocForScalar(axisValue.scalar)
let x1 = screenLoc
let y1 = originScreenLoc.y
let x2 = x1
let y2 = originScreenLoc.y + self.innerFrame.height
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
for axisValue in self.axisValuesY {
let screenLoc = self.yAxis.screenLocForScalar(axisValue.scalar)
let x1 = originScreenLoc.x
let y1 = screenLoc
let x2 = originScreenLoc.x + self.innerFrame.width
let y2 = y1
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
}
public typealias ChartGuideLinesForValuesLayer = ChartGuideLinesForValuesLayer_<Any>
public class ChartGuideLinesForValuesLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesLayerSettings> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor)
}
}
public typealias ChartGuideLinesForValuesDottedLayer = ChartGuideLinesForValuesDottedLayer_<Any>
public class ChartGuideLinesForValuesDottedLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesDottedLayerSettings> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesDottedLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing)
}
}
|
mit
|
72308a4a2839ed8352bb82bf99aefc82
| 45.135593 | 235 | 0.706098 | 4.357524 | false | false | false | false |
insidegui/WWDC
|
WWDC/SessionSummaryViewController.swift
|
1
|
7901
|
//
// SessionSummaryViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 22/04/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RxSwift
import RxCocoa
import ConfCore
class SessionSummaryViewController: NSViewController {
private var disposeBag = DisposeBag()
var viewModel: SessionViewModel? = nil {
didSet {
updateBindings()
}
}
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
enum Metrics {
static let summaryHeight: CGFloat = 100
}
private lazy var titleLabel: WWDCTextField = {
let l = WWDCTextField(labelWithString: "")
l.cell?.backgroundStyle = .dark
l.lineBreakMode = .byWordWrapping
l.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
l.allowsDefaultTighteningForTruncation = true
l.maximumNumberOfLines = 2
l.translatesAutoresizingMaskIntoConstraints = false
l.isSelectable = true
l.allowsEditingTextAttributes = true
return l
}()
lazy var actionsViewController: SessionActionsViewController = {
let v = SessionActionsViewController()
v.view.isHidden = true
v.view.translatesAutoresizingMaskIntoConstraints = false
return v
}()
lazy var relatedSessionsViewController: RelatedSessionsViewController = {
let c = RelatedSessionsViewController()
c.title = "Related Sessions"
return c
}()
private func attributedSummaryString(from string: String) -> NSAttributedString {
.create(with: string, font: .systemFont(ofSize: 15), color: .secondaryText, lineHeightMultiple: 1.2)
}
private lazy var summaryTextView: NSTextView = {
let v = NSTextView()
v.drawsBackground = false
v.backgroundColor = .clear
v.autoresizingMask = [.width]
v.textContainer?.widthTracksTextView = true
v.textContainer?.heightTracksTextView = false
v.isEditable = false
v.isVerticallyResizable = true
v.isHorizontallyResizable = false
v.textContainer?.containerSize = NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude)
return v
}()
private lazy var summaryScrollView: NSScrollView = {
let v = NSScrollView()
v.contentView = FlippedClipView()
v.drawsBackground = false
v.backgroundColor = .clear
v.borderType = .noBorder
v.documentView = self.summaryTextView
v.autohidesScrollers = true
v.hasVerticalScroller = true
v.hasHorizontalScroller = false
v.verticalScrollElasticity = .none
return v
}()
private lazy var contextLabel: NSTextField = {
let l = NSTextField(labelWithString: "")
l.font = .systemFont(ofSize: 16)
l.textColor = .tertiaryText
l.cell?.backgroundStyle = .dark
l.lineBreakMode = .byTruncatingTail
l.allowsDefaultTighteningForTruncation = true
return l
}()
private lazy var actionLinkLabel: ActionLabel = {
let l = ActionLabel(labelWithString: "")
l.font = .systemFont(ofSize: 16)
l.textColor = .primary
l.target = self
l.action = #selector(clickedActionLabel)
return l
}()
private lazy var contextStackView: NSStackView = {
let v = NSStackView(views: [self.contextLabel, self.actionLinkLabel])
v.orientation = .horizontal
v.alignment = .top
v.distribution = .fillProportionally
v.spacing = 16
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
private lazy var stackView: NSStackView = {
let v = NSStackView(views: [self.summaryScrollView, self.contextStackView])
v.orientation = .vertical
v.alignment = .leading
v.distribution = .fill
v.spacing = 24
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func loadView() {
view = NSView(frame: NSRect(x: 0, y: 0, width: MainWindowController.defaultRect.width - 300, height: MainWindowController.defaultRect.height / 2))
view.wantsLayer = true
view.addSubview(titleLabel)
view.addSubview(actionsViewController.view)
view.addSubview(stackView)
titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
actionsViewController.view.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor).isActive = true
actionsViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: actionsViewController.view.leadingAnchor, constant: -24).isActive = true
titleLabel.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 24).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
summaryScrollView.heightAnchor.constraint(equalToConstant: Metrics.summaryHeight).isActive = true
addChild(relatedSessionsViewController)
relatedSessionsViewController.view.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(relatedSessionsViewController.view)
relatedSessionsViewController.view.heightAnchor.constraint(equalToConstant: RelatedSessionsViewController.Metrics.height).isActive = true
relatedSessionsViewController.view.leadingAnchor.constraint(equalTo: stackView.leadingAnchor).isActive = true
relatedSessionsViewController.view.trailingAnchor.constraint(equalTo: stackView.trailingAnchor).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
updateBindings()
}
private func updateBindings() {
actionsViewController.view.isHidden = (viewModel == nil)
actionsViewController.viewModel = viewModel
self.summaryScrollView.scroll(.zero)
guard let viewModel = viewModel else { return }
disposeBag = DisposeBag()
viewModel.rxTitle.map(NSAttributedString.attributedBoldTitle(with:)).subscribe(onNext: { [weak self] title in
self?.titleLabel.attributedStringValue = title
}).disposed(by: disposeBag)
viewModel.rxFooter.bind(to: contextLabel.rx.text).disposed(by: disposeBag)
viewModel.rxSummary.subscribe(onNext: { [weak self] summary in
guard let self = self else { return }
guard let textStorage = self.summaryTextView.textStorage else { return }
let range = NSRange(location: 0, length: textStorage.length)
textStorage.replaceCharacters(in: range, with: self.attributedSummaryString(from: summary))
}).disposed(by: disposeBag)
viewModel.rxRelatedSessions.subscribe(onNext: { [weak self] relatedResources in
let relatedSessions = relatedResources.compactMap({ $0.session })
self?.relatedSessionsViewController.sessions = relatedSessions.compactMap(SessionViewModel.init)
}).disposed(by: disposeBag)
relatedSessionsViewController.scrollToBeginningOfDocument(nil)
viewModel.rxActionPrompt.bind(to: actionLinkLabel.rx.text).disposed(by: disposeBag)
}
@objc private func clickedActionLabel() {
guard let url = viewModel?.actionLinkURL else { return }
NSWorkspace.shared.open(url)
}
}
|
bsd-2-clause
|
fc87ed6ff497fbb71fe7d9118fbf79dc
| 34.267857 | 154 | 0.688101 | 5.166776 | false | false | false | false |
insidegui/WWDC
|
WWDC/DeepLink.swift
|
1
|
2596
|
//
// DeepLink.swift
// WWDC
//
// Created by Guilherme Rambo on 19/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
struct DeepLink {
struct Constants {
static let appleHost = "developer.apple.com"
static let nativeHost = "wwdc.io"
static let hosts = [Self.appleHost, Self.nativeHost]
}
let year: Int
let eventIdentifier: String
let sessionNumber: Int
let isForCurrentYear: Bool
var sessionIdentifier: String {
return "\(year)-\(sessionNumber)"
}
init?(url: URL) {
guard let host = url.host else { return nil }
guard Constants.hosts.contains(host) else { return nil }
let components = url.pathComponents
guard components.count >= 3 else { return nil }
let yearParameter = components[components.count - 2]
let sessionIdentifierParameter = components[components.count - 1]
guard let sessionNumber = Int(sessionIdentifierParameter) else { return nil }
let year: String
let fullYear: String
if yearParameter.count > 6 {
year = String(yearParameter.suffix(4))
fullYear = year
} else {
year = String(yearParameter.suffix(2))
// this will only work for the next 983 years ¯\_(ツ)_/¯
fullYear = "20\(year)"
}
guard let yearNumber = Int(fullYear) else { return nil }
let currentYear = "\(Calendar.current.component(.year, from: today()))"
let currentYearDigits = String(currentYear[currentYear.index(currentYear.startIndex, offsetBy: 2)...])
self.year = yearNumber
eventIdentifier = "wwdc\(year)"
self.sessionNumber = sessionNumber
isForCurrentYear = (year == currentYearDigits || year == currentYear)
}
init?(from command: WWDCAppCommand) {
guard case .revealVideo(let id) = command else { return nil }
let components = id.components(separatedBy: "-")
guard components.count == 2 else { return nil }
guard let url = URL(string: "https://wwdc.io/share/\(components[0])/\(components[1])") else { return nil }
self.init(url: url)
}
}
extension URL {
var replacingAppleDeveloperHostWithNativeHost: URL {
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return self }
components.host = DeepLink.Constants.nativeHost
components.path = "/share" + components.path
return components.url ?? self
}
}
|
bsd-2-clause
|
32991d1fda1023cefeae045cc0a40105
| 29.482353 | 114 | 0.62254 | 4.42906 | false | false | false | false |
qoncept/TensorSwift
|
Sources/TensorSwift/Utils.swift
|
1
|
862
|
extension Int {
internal func ceilDiv(_ rhs: Int) -> Int {
return (self + rhs - 1) / rhs
}
}
internal func hasSuffix<Element: Equatable>(array: [Element], suffix: [Element]) -> Bool {
guard array.count >= suffix.count else { return false }
return zip(array[(array.count - suffix.count)..<array.count], suffix).reduce(true) { $0 && $1.0 == $1.1 }
}
internal func zipMap(_ a: [Float], _ b: [Float], operation: (Float, Float) -> Float) -> [Float] {
var result: [Float] = []
for i in a.indices {
result.append(operation(a[i], b[i]))
}
return result
}
internal func zipMapRepeat(_ a: [Float], _ infiniteB: [Float], operation: (Float, Float) -> Float) -> [Float] {
var result: [Float] = []
for i in a.indices {
result.append(operation(a[i], infiniteB[i % infiniteB.count]))
}
return result
}
|
mit
|
a7df677f672f4ee4fb62434789427e5a
| 30.925926 | 111 | 0.596288 | 3.302682 | false | false | false | false |
danielmartin/swift
|
test/Constraints/closures.swift
|
1
|
29863
|
// RUN: %target-typecheck-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
_ = myMap(intArray, { String($0) })
_ = myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
foo({ [intArray] in $0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
_ = mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
_ = f0(X2(), {$0.g()})
// Closures with inout arguments and '__shared' conversions.
func inoutToSharedConversions() {
func fooOW<T, U>(_ f : (__owned T) -> U) {}
fooOW({ (x : Int) in return Int(5) }) // defaut-to-'__owned' allowed
fooOW({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__owned' allowed
fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed
fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__owned _) -> _'}}
func fooIO<T, U>(_ f : (inout T) -> U) {}
fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed
fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(inout _) -> _'}}
fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout _) -> _'}}
fooIO({ (x : __owned Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__owned Int) -> Int' to expected argument type '(inout _) -> _'}}
func fooSH<T, U>(_ f : (__shared T) -> U) {}
fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed
fooSH({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__shared' allowed
fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared _) -> _'}}
fooSH({ (x : Int) in return Int(5) }) // default-to-'__shared' allowed
}
// Autoclosure
func f1(f: @autoclosure () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
// <https://bugs.swift.org/browse/SR-3671>
func r21544303() {
var inSubcall = true
{
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true {
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
var v2 : Bool = false
v2 = inSubcall
{ // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
}
}
// <https://bugs.swift.org/browse/SR-3671>
func SR3671() {
let n = 42
func consume(_ x: Int) {}
{ consume($0) }(42)
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
// This is technically a valid call, so nothing goes wrong until (42)
{ $0(3) }
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
{ $0(3) }
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
// Equivalent but more obviously unintended.
{ $0(3) } // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
({ $0(3) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// Also a valid call (!!)
{ $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}}
consume(111)
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{cannot invoke 'reduce' with an argument list of type '((_, _) -> _)'}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
func callCC<U>(_ f: (CC) -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: ((String) -> String)?,
bar: @escaping (String) -> String) {
let _: (String) -> String = foo != nil ? foo! : bar
let _: (String) -> String = foo ?? bar
}
func verify_NotAC_to_AC_failure(_ arg: () -> ()) {
func takesAC(_ arg: @autoclosure () -> ()) {}
takesAC(arg) // expected-error {{function produces expected type '()'; did you mean to call it with '()'?}}
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable {
let wrappedMethod = { (object: AnyObject, value: T) in }
// expected-error @+3 {{value of optional type 'Object?' must be unwrapped to a value of type 'Object'}}
// expected-note @+2{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note @+1{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
}
}
// Similar to SR1069 but with multiple generic arguments
func simplified1069() {
class C {}
struct S {
func genericallyNonOptional<T: AnyObject>(_ a: T, _ b: T, _ c: T) { }
func f(_ a: C?, _ b: C?, _ c: C) {
genericallyNonOptional(a, b, c) // expected-error 2{{value of optional type 'C?' must be unwrapped to a value of type 'C'}}
// expected-note @-1 2{{coalesce}}
// expected-note @-2 2{{force-unwrap}}
}
}
}
// Make sure we cannot infer an () argument from an empty parameter list.
func acceptNothingToInt (_: () -> Int) {}
func testAcceptNothingToInt(ac1: @autoclosure () -> Int) {
acceptNothingToInt({ac1($0)})
// expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}}
}
// <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
struct Thing {
init?() {}
}
// This throws a compiler error
let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> Thing }}
// Commenting out this makes it compile
_ = thing
return thing
}
// <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches
func r21675896(file : String) {
let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }}
if true {
return "foo"
}
else {
return file
}
}().pathExtension
}
// <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
func ident<T>(_ t: T) -> T {}
var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}}
// <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block
var afterMessageCount : Int?
func uintFunc() -> UInt {}
func takeVoidVoidFn(_ a : () -> ()) {}
takeVoidVoidFn { () -> Void in
afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}}
}
// <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure
func f19997471(_ x: String) {}
func f19997471(_ x: Int) {}
func someGeneric19997471<T>(_ x: T) {
takeVoidVoidFn {
f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}}
// expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (Int), (String)}}
}
}
// <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r }
[0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }}
_ in
let r = (1,2).0
return r
}
// <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type
func rdar21078316() {
var foo : [String : String]?
var bar : [(String, String)]?
bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) throws -> [(String, String)]' expects 1 argument, but 2 were used in closure body}}
}
// <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure
var numbers = [1, 2, 3]
zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}}
// <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type'
func foo20868864(_ callback: ([String]) -> ()) { }
func rdar20868864(_ s: String) {
var s = s
foo20868864 { (strings: [String]) in
s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}}
}
}
// <rdar://problem/22058555> crash in cs diags in withCString
func r22058555() {
var firstChar: UInt8 = 0
"abc".withCString { chars in
firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}}
}
}
// <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type
func r20789423() {
class C {
func f(_ value: Int) { }
}
let p: C
print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}}
let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }}
print("a")
return "hi"
}
}
// Make sure that behavior related to allowing trailing closures to match functions
// with Any as a final parameter is the same after the changes made by SR-2505, namely:
// that we continue to select function that does _not_ have Any as a final parameter in
// presence of other possibilities.
protocol SR_2505_Initable { init() }
struct SR_2505_II : SR_2505_Initable {}
protocol P_SR_2505 {
associatedtype T: SR_2505_Initable
}
extension P_SR_2505 {
func test(it o: (T) -> Bool) -> Bool {
return o(T.self())
}
}
class C_SR_2505 : P_SR_2505 {
typealias T = SR_2505_II
func test(_ o: Any) -> Bool {
return false
}
func call(_ c: C_SR_2505) -> Bool {
// Note: no diagnostic about capturing 'self', because this is a
// non-escaping closure -- that's how we know we have selected
// test(it:) and not test(_)
return c.test { o in test(o) }
}
}
let _ = C_SR_2505().call(C_SR_2505())
// <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic
extension Collection {
func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index {
return startIndex
}
}
func fn_r28909024(n: Int) {
return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}}
_ in true
}
}
// SR-2994: Unexpected ambiguous expression in closure with generics
struct S_2994 {
var dataOffset: Int
}
class C_2994<R> {
init(arg: (R) -> Void) {}
}
func f_2994(arg: String) {}
func g_2994(arg: Int) -> Double {
return 2
}
C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}}
let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}}
let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}}
let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}}
// https://bugs.swift.org/browse/SR-403
// The () -> T => () -> () implicit conversion was kicking in anywhere
// inside a closure result, not just at the top-level.
let mismatchInClosureResultType : (String) -> ((Int) -> Void) = {
(String) -> ((Int) -> Void) in
return { }
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}}
}
// SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS
func sr3520_1<T>(_ g: (inout T) -> Int) {}
sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
// This test makes sure that having closure with inout argument doesn't crash with member lookup
struct S_3520 {
var number1: Int
}
func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} // expected-note {{in call to function 'sr3520_set_via_closure'}}
sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{generic parameter 'S' could not be inferred}}
// SR-3073: UnresolvedDotExpr in single expression closure
struct SR3073Lense<Whole, Part> {
let set: (inout Whole, Part) -> ()
}
struct SR3073 {
var number1: Int
func lenses() {
let _: SR3073Lense<SR3073, Int> = SR3073Lense(
set: { $0.number1 = $1 } // ok
)
}
}
// SR-3479: Segmentation fault and other error for closure with inout parameter
func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {}
func sr3497() {
let _ = sr3497_unfold((0, 0)) { s in 0 } // ok
}
// SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs
let _: ((Any?) -> Void) = { (arg: Any!) in }
// This example was rejected in 3.0 as well, but accepting it is correct.
let _: ((Int?) -> Void) = { (arg: Int!) in }
// rdar://30429709 - We should not attempt an implicit conversion from
// () -> T to () -> Optional<()>.
func returnsArray() -> [Int] { return [] }
returnsArray().compactMap { $0 }.compactMap { }
// expected-warning@-1 {{expression of type 'Int' is unused}}
// expected-warning@-2 {{result of call to 'compactMap' is unused}}
// rdar://problem/30271695
_ = ["hi"].compactMap { $0.isEmpty ? nil : $0 }
// rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
func r32432145(_ a: () -> ()) {}
r32432145 { _ in let _ = 42 }
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
r32432145 { _ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
print("answer is 42")
}
r32432145 { _,_ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}}
print("answer is 42")
}
// rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller
[1, 2].first { $0.foo = 3 }
// expected-error@-1 {{value of type 'Int' has no member 'foo'}}
// rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem
protocol A_SR_5030 {
associatedtype Value
func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U>
}
struct B_SR_5030<T> : A_SR_5030 {
typealias Value = T
func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() }
}
func sr5030_exFalso<T>() -> T {
fatalError()
}
extension A_SR_5030 {
func foo() -> B_SR_5030<Int> {
let tt : B_SR_5030<Int> = sr5030_exFalso()
return tt.map { x in (idx: x) }
// expected-error@-1 {{cannot convert value of type '(idx: Int)' to closure result type 'Int'}}
}
}
// rdar://problem/33296619
let u = rdar33296619().element //expected-error {{use of unresolved identifier 'rdar33296619'}}
[1].forEach { _ in
_ = "\(u)"
_ = 1 + "hi" // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists}}
}
class SR5666 {
var property: String?
}
func testSR5666(cs: [SR5666?]) -> [String?] {
return cs.map({ c in
let a = c.propertyWithTypo ?? "default"
// expected-error@-1 {{value of type 'SR5666?' has no member 'propertyWithTypo'}}
let b = "\(a)"
return b
})
}
// Ensure that we still do the appropriate pointer conversion here.
_ = "".withCString { UnsafeMutableRawPointer(mutating: $0) }
// rdar://problem/34077439 - Crash when pre-checking bails out and
// leaves us with unfolded SequenceExprs inside closure body.
_ = { (offset) -> T in // expected-error {{use of undeclared type 'T'}}
return offset ? 0 : 0
}
struct SR5202<T> {
func map<R>(fn: (T) -> R) {}
}
SR5202<()>().map{ return 0 }
SR5202<()>().map{ _ in return 0 }
SR5202<Void>().map{ return 0 }
SR5202<Void>().map{ _ in return 0 }
func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) {
var x = item
update(&x)
}
var sr3250_arg = 42
sr3520_2(sr3250_arg) { $0 += 3 } // ok
// SR-1976/SR-3073: Inference of inout
func sr1976<T>(_ closure: (inout T) -> Void) {}
sr1976({ $0 += 2 }) // ok
// rdar://problem/33429010
struct I_33429010 : IteratorProtocol {
func next() -> Int? {
fatalError()
}
}
extension Sequence {
public func rdar33429010<Result>(into initialResult: Result,
_ nextPartialResult: (_ partialResult: inout Result, Iterator.Element) throws -> ()
) rethrows -> Result {
return initialResult
}
}
extension Int {
public mutating func rdar33429010_incr(_ inc: Int) {
self += inc
}
}
func rdar33429010_2() {
let iter = I_33429010()
var acc: Int = 0 // expected-warning {{}}
let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0 + $1 })
// expected-warning@-1 {{result of operator '+' is unused}}
let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0.rdar33429010_incr($1) })
}
class P_33429010 {
var name: String = "foo"
}
class C_33429010 : P_33429010 {
}
func rdar33429010_3() {
let arr = [C_33429010()]
let _ = arr.map({ ($0.name, $0 as P_33429010) }) // Ok
}
func rdar36054961() {
func bar(dict: [String: (inout String, Range<String.Index>, String) -> Void]) {}
bar(dict: ["abc": { str, range, _ in
str.replaceSubrange(range, with: str[range].reversed())
}])
}
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 }
_ = S({ foo() }, { bar() }) // expected-warning {{result of call to 'foo()' is unused}}
_ = S({ baz() }, { bar() }) // expected-warning {{result of call to 'baz()' is unused}}
_ = S({ bzz(("question", 42)) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(String.self) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(((), (()))) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(C1()) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ faz(C2()) }, { bar() }) // expected-warning {{result of call to 'faz' is unused}}
}
// <rdar://problem/39489003>
typealias KeyedItem<K, T> = (key: K, value: T)
protocol Node {
associatedtype T
associatedtype E
associatedtype K
var item: E {get set}
var children: [(key: K, value: T)] {get set}
}
extension Node {
func getChild(for key:K)->(key: K, value: T) {
return children.first(where: { (item:KeyedItem) -> Bool in
return item.key == key
// expected-error@-1 {{binary operator '==' cannot be applied to operands of type '_' and 'Self.K'}}
// expected-note@-2 {{overloads for '==' exist with these partially matching parameter lists:}}
})!
}
}
// Make sure we don't allow this anymore
func takesTwo(_: (Int, Int) -> ()) {}
func takesTwoInOut(_: (Int, inout Int) -> ()) {}
takesTwo { _ in } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
takesTwoInOut { _ in } // expected-error {{contextual closure type '(Int, inout Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
_ = x.filter { ($0 + y) > 42 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt, UInt)}}
}
// rdar://problem/42337247
func overloaded(_ handler: () -> Int) {} // expected-note {{found this candidate}}
func overloaded(_ handler: () -> Void) {} // expected-note {{found this candidate}}
overloaded { } // empty body => inferred as returning ()
overloaded { print("hi") } // single-expression closure => typechecked with body
overloaded { print("hi"); print("bye") } // multiple expression closure without explicit returns; can default to any return type
// expected-error@-1 {{ambiguous use of 'overloaded'}}
func not_overloaded(_ handler: () -> Int) {}
not_overloaded { } // empty body
// expected-error@-1 {{cannot convert value of type '() -> ()' to expected argument type '() -> Int'}}
not_overloaded { print("hi") } // single-expression closure
// expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}}
// no error in -typecheck, but dataflow diagnostics will complain about missing return
not_overloaded { print("hi"); print("bye") } // multiple expression closure
func apply(_ fn: (Int) throws -> Int) rethrows -> Int {
return try fn(0)
}
enum E : Error {
case E
}
func test() -> Int? {
return try? apply({ _ in throw E.E })
}
var fn: () -> [Int] = {}
// expected-error@-1 {{cannot convert value of type '() -> ()' to specified type '() -> [Int]'}}
fn = {}
// expected-error@-1 {{cannot assign value of type '() -> ()' to type '() -> [Int]'}}
func test<Instances : Collection>(
_ instances: Instances,
_ fn: (Instances.Index, Instances.Index) -> Bool
) { fatalError() }
test([1]) { _, _ in fatalError(); () }
// rdar://problem/40537960 - Misleading diagnostic when using closure with wrong type
protocol P_40537960 {}
func rdar_40537960() {
struct S {
var v: String
}
struct L : P_40537960 {
init(_: String) {}
}
struct R<T : P_40537960> {
init(_: P_40537960) {}
}
struct A<T: Collection, P: P_40537960> {
typealias Data = T.Element
init(_: T, fn: (Data) -> R<P>) {}
}
var arr: [S] = []
_ = A(arr, fn: { L($0.v) }) // expected-error {{cannot convert value of type 'L' to closure result type 'R<T>'}}
}
// rdar://problem/45659733
func rdar_45659733() {
func foo<T : BinaryInteger>(_: AnyHashable, _: T) {}
func bar(_ a: Int, _ b: Int) {
_ = (a ..< b).map { i in foo(i, i) } // Ok
}
struct S<V> {
func map<T>(
get: @escaping (V) -> T,
set: @escaping (inout V, T) -> Void
) -> S<T> {
fatalError()
}
subscript<T>(
keyPath: WritableKeyPath<V, T?>,
default defaultValue: T
) -> S<T> {
return map(
get: { $0[keyPath: keyPath] ?? defaultValue },
set: { $0[keyPath: keyPath] = $1 }
) // Ok, make sure that we deduce result to be S<T>
}
}
}
func rdar45771997() {
struct S {
mutating func foo() {}
}
let _: Int = { (s: inout S) in s.foo() }
// expected-error@-1 {{cannot convert value of type '(inout S) -> ()' to specified type 'Int'}}
}
|
apache-2.0
|
6c3c901ebd333c4b8dad1a5f7cea8745
| 33.724419 | 254 | 0.625088 | 3.354639 | false | false | false | false |
USAssignmentWarehouse/EnglishNow
|
EnglishNow/View/Cell/AverageRatingCell.swift
|
1
|
1371
|
//
// AverageRatingCell.swift
// EnglishNow
//
// Created by GeniusDoan on 7/3/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import Foundation
class AverageRatingCell: UITableViewCell {
@IBOutlet weak var totalRatingsLabel: UILabel!
@IBOutlet weak var pointsLabel: UILabel!
@IBOutlet weak var circlePoint: UIView!
@IBOutlet weak var circlePoint1: UIView!
var review:Review?{
didSet{
let point = ((review?.ratings?.listening)! + (review?.ratings?.listening)! + (review?.ratings?.fluency)! + (review?.ratings?.vocabulary)!)/4
var roundedPoint = round(point * 10) / 10
if roundedPoint == 0 {
roundedPoint = Double(arc4random_uniform(5) + 1)
}
pointsLabel.text = "\(roundedPoint)"
//totalRatingsLabel.text = review
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
circlePoint.clipsToBounds = true
circlePoint.layer.cornerRadius = 12
circlePoint1.clipsToBounds = true
circlePoint1.layer.cornerRadius = 9
// Configure the view for the selected state
}
}
|
apache-2.0
|
4cfbab1cdf8465458f761f6b3d81131f
| 28.782609 | 152 | 0.610949 | 4.675768 | false | false | false | false |
edwellbrook/gosquared-swift
|
Sources/URLRequest.swift
|
1
|
961
|
//
// URLRequest.swift
// GoSquaredAPI
//
// Created by Edward Wellbrook on 19/06/2016.
// Copyright © 2016 Edward Wellbrook. All rights reserved.
//
import Foundation
extension URLRequest {
enum HTTPMethod: String {
case GET
case POST
case DELETE
}
init(url: URL, bearer: String?) {
self.init(url: url)
if let token = bearer {
self.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
}
init(method: HTTPMethod, url: URL, body: Any? = nil, bearer: String? = nil) {
self.init(url: url, bearer: bearer)
self.httpMethod = method.rawValue
guard let json = body else {
return
}
do {
self.httpBody = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
self.setValue("application/json", forHTTPHeaderField: "Content-Type")
} catch _ {
}
}
}
|
mit
|
4c3d26b9fa62f61283b464399e1fc968
| 21.857143 | 101 | 0.583333 | 4.210526 | false | false | false | false |
tectijuana/patrones
|
Bloque1SwiftArchivado/PracticasSwift/CarlosGastelum/programa.swift
|
1
|
919
|
/*
Nombre del programa: ................... Introducir un entero N positivo. Encontrar la suma de los N enteros. Imprimir cada uno de los enteros y la suma.
Creado por: Carlos Gastelum Nieves ..........
No Control: .................................................14210456
Fecha ......................................................17-02-2017
Practicas Swift del libro..........................................
*/
// librerías
import Foundation
//declaramos nuestras constantes
let n = 30
//contador
var I = 2
//variable donde guardamos nuestra suma de los enteros ( N)
var sum = 0
// Aqui iremos guardando la cadena de la suma
var txt = ""
print("Suma de N valores")
print("N = \(n)")
//suma de los N valores
while I<=n
{
sum = sum + I
//Concatenacion de la suma
if I!= n
{txt += "\(I)+"}
else
{txt += "\(I)"}
//incremento
I = I+2
}
print("\(txt)=\(sum)")
|
gpl-3.0
|
828d7248d30cf5b22421821f9ee52e2d
| 19.372093 | 153 | 0.512514 | 3.179931 | false | false | false | false |
touchopia/Codementor-Swift-201
|
SourceCode/Background-Final/BackgroundChooser/HomeViewController.swift
|
1
|
1300
|
//
// HomeViewController.swift
// BackgroundChooser
//
// Created by Phil Wright on 10/1/15.
// Copyright © 2015 Touchopia LLC. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
var backgroundImageString : String = ""
var backgroundImageView : UIImageView! = UIImageView(frame: CGRectZero)
override func viewDidLoad() {
super.viewDidLoad()
updateBackgroundImage()
}
@IBAction func unwindToVC(segue:UIStoryboardSegue) {
if segue.identifier == "unwindIdentifier" {
if let controller = segue.sourceViewController as? BackgroundViewController {
backgroundImageString = controller.backgroundImageString
updateBackgroundImage()
}
}
}
func updateBackgroundImage() {
backgroundImageView.removeFromSuperview()
if backgroundImageString == "" {
backgroundImageString = "blueBackground"
}
backgroundImageView = UIImageView(image: UIImage(named: backgroundImageString))
backgroundImageView?.frame = view.frame
backgroundImageView?.contentMode = .ScaleAspectFill
view.insertSubview(backgroundImageView!, atIndex: 0)
}
}
|
mit
|
e0efc1e8ca281998ad177b17a2036a7d
| 26.638298 | 89 | 0.642032 | 5.904545 | false | false | false | false |
pawan007/SmartZip
|
SmartZip/Views/Cells/FeedCell.swift
|
1
|
2014
|
//
// FeedCell.swift
// SmartZip
//
// Created by Pawan Kumar on 07/06/16.
// Copyright © 2016 Modi. All rights reserved.
//
import UIKit
import Kingfisher
protocol FeedCellDelegate1: class {
func heartClick(index: NSInteger)
}
class FeedCell: UITableViewCell {
weak var delegate: FeedCellDelegate?
@IBOutlet weak var name: UILabel!
var index: NSInteger! = 0
@IBOutlet weak var feedImage: UIImageView!
@IBOutlet weak var imageHighConst: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let screenRatio = (UIScreen.mainScreen().bounds.size.width / CGFloat(Constants.DEFAULT_SCREEN_RATIO))
let imgHight = 200 * screenRatio
self.imageHighConst.constant=imgHight
/*
let url:NSURL? = NSURL(string: "http://www.blueevents-agency.com/wp-content/uploads/2013/11/explore-events-food-and-wine-events.jpg")
//
let progressiveImageView = CCBufferedImageView(frame: feedImage.bounds)
if let urlP = NSURL(string: "http://www.pooyak.com/p/progjpeg/jpegload.cgi?o=1") {
progressiveImageView.load(url!)
feedImage.addSubview(progressiveImageView)
}
*/
let url:NSURL? = NSURL(string: "http://www.blueevents-agency.com/wp-content/uploads/2013/11/explore-events-food-and-wine-events.jpg")
imageView!.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "img_shadow"))
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: Control Actions
@IBAction private func heartClick(sender: UIButton) {
sender.selected = !sender.selected;
if (self.delegate != nil) {
self.delegate?.heartClick(index)
}
}
}
|
mit
|
9d13256961fb0e75cc45e8190aec40f3
| 27.771429 | 142 | 0.627919 | 4.237895 | false | false | false | false |
vimeo/VimeoNetworking
|
Tests/Shared/VIMVideoTests.swift
|
1
|
10457
|
//
// VIMVideoTests.swift
// VimeoNetworkingExample-iOS
//
// Copyright © 2017 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import VimeoNetworking
class VIMVideoTests: XCTestCase {
private var liveDictionary: [String: Any] = ["link": "vimeo.com", "key": "abcdefg", "activeTime": Date(), "endedTime": Date(), "archivedTime": Date()]
func test_isLive_returnsTrue_whenLiveObjectExists() {
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.isLive())
}
func test_isLive_returnsFalse_whenLiveObjectDoesNotExist() {
let videoDictionary: [String: Any] = ["link": "vimeo.com"]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testVideoObject)
XCTAssertFalse(testVideoObject.isLive())
}
func test_isLiveEventInProgress_returnsTrue_whenEventIsInUnavailablePreBroadcastState() {
liveDictionary["status"] = "unavailable"
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.isLiveEventInProgress())
}
func test_isLiveEventInProgress_returnsTrue_whenEventIsInPendingPreBroadcastState() {
liveDictionary["status"] = "pending"
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.isLiveEventInProgress())
}
func test_isLiveEventInProgress_returnsTrue_whenEventIsInReadyPreBroadcastState() {
liveDictionary["status"] = "ready"
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.isLiveEventInProgress())
}
func test_isLiveEventInProgress_returnsTrue_whenEventIsInMidBroadcastState() {
liveDictionary["status"] = "streaming"
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.isLiveEventInProgress())
}
func test_isLiveEventInProgress_returnsTrue_whenEventIsInArchivingState() {
liveDictionary["status"] = "archiving"
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.isLiveEventInProgress())
}
func test_isLiveEventInProgress_returnsFalse_whenEventIsInPostBroadcastState() {
liveDictionary["status"] = "done"
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertFalse(testVideoObject.isLiveEventInProgress())
}
func test_isPostBroadcast_returnsTrue_whenEventIsInDoneState() {
liveDictionary["status"] = "done"
let testLiveObject = VIMLive(keyValueDictionary: liveDictionary)!
let videoDictionary: [String: Any] = ["live": testLiveObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(testLiveObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.isPostBroadcast())
}
// MARK: - Review Page
func test_video_has_review_page() {
let reviewPageDictionary: [String: Any] = ["active": true, "link": "test/linkNotEmpty"]
let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))!
let videoDictionary: [String: Any] = ["reviewPage": reviewObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertNotNil(reviewObject)
XCTAssertNotNil(testVideoObject)
XCTAssertTrue(testVideoObject.hasReviewPage())
}
func test_video_hasnt_review_page() {
let reviewPageDictionary: [String: Any] = ["active": true, "link": ""]
let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))!
let videoDictionary: [String: Any] = ["reviewPage": reviewObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertFalse(testVideoObject.hasReviewPage())
}
func test_video_hasnt_review_page_because_is_inactive() {
let reviewPageDictionary: [String: Any] = ["active": false, "link": "test/LinkExistButIsNotActive"]
let reviewObject = (VIMReviewPage(keyValueDictionary: reviewPageDictionary))!
let videoDictionary: [String: Any] = ["reviewPage": reviewObject]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertEqual(testVideoObject.hasReviewPage(), false)
}
// MARK: - Privacy
// Note: Invalid values of `canDownload` will trigger an assertion failure.
func test_canDownloadFromDesktop_returnsTrue_whenCanDownloadIsOne() {
let privacyDictionary: [String: Any] = ["canDownload": 1]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let videoDictionary: [String: Any] = ["privacy": privacy as Any]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
let canDownload = testVideoObject.canDownloadFromDesktop()
XCTAssertTrue(canDownload, "canDownloadFromDesktop unexpectedly returns false")
}
func test_canDownloadFromDesktop_returnsFalse_whenCanDownloadIsZero() {
let privacyDictionary: [String: Any] = ["canDownload": 0]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let videoDictionary: [String: Any] = ["privacy": privacy as Any]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
let canDownload = testVideoObject.canDownloadFromDesktop()
XCTAssertFalse(canDownload, "canDownloadFromDesktop unexpectedly returns true")
}
func test_isStock_returnsTrue_whenPrivacyViewIsStock() {
let privacyDictionary: [String: Any] = ["view": "stock"]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let videoDictionary: [String: Any] = ["privacy": privacy as Any]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertTrue(testVideoObject.isStock(), "Test video object was stock but unexpectedly returned false.")
}
func test_isStock_returnsFalse_whenPrivacyViewIsNotStock() {
let privacyDictionary: [String: Any] = ["view": "unlisted"]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let videoDictionary: [String: Any] = ["privacy": privacy as Any]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertFalse(testVideoObject.isStock(), "Test video object was not stock but unexpectedly returned true.")
}
func test_isPrivate_returnsFalse_whenPrivacyViewIsStock() {
let privacyDictionary: [String: Any] = ["view": "stock"]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let videoDictionary: [String: Any] = ["privacy": privacy as Any]
let testVideoObject = VIMVideo(keyValueDictionary: videoDictionary)!
XCTAssertFalse(testVideoObject.isPrivate(), "Test video object is stock and should not return as private.")
}
func test_videoAppProperty_isParsedAsExpected() throws {
let json: [String: Any] = [
"name": "Test Video",
"uri": "/videos/12345",
"status": "available",
"resource_key": "a1b2c3d4",
"app": ["name": "Cameo", "uri": "apps/123"] as Any
]
let video = try VIMObjectMapper.mapObject(responseDictionary: json) as VIMVideo
XCTAssertNotNil(video.sourceClientApp)
XCTAssertEqual(try XCTUnwrap(video.sourceClientApp).name, "Cameo")
XCTAssertEqual(try XCTUnwrap(video.sourceClientApp).uri, "apps/123")
}
}
|
mit
|
66b0da46aa93faaa11d1f03e58cab988
| 47.407407 | 154 | 0.703806 | 4.642984 | false | true | false | false |
malt03/PictureInPicture
|
Example/PictureInPicture/ViewController.swift
|
1
|
4072
|
//
// ViewController.swift
// PictureInPicture
//
// Created by Koji Murata on 07/17/2017.
// Copyright (c) 2017 Koji Murata. All rights reserved.
//
import UIKit
import PictureInPicture
final class ViewController: UIViewController {
private static var instanceNumber = 0
@IBOutlet weak var instanceNumberLabel: UILabel! {
didSet {
instanceNumberLabel.text = "\(ViewController.instanceNumber)"
ViewController.instanceNumber += 1
}
}
@IBAction func present() {
PictureInPicture.shared.present(with: UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: "PiP"))
}
@IBAction func presentWithoutMakingLarger() {
PictureInPicture.shared.present(with: UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: "PiP"), makeLargerIfNeeded: false)
}
@IBAction func dismiss() {
PictureInPicture.shared.dismiss(animation: true)
}
@IBAction func changeWindow() {
NewWindowViewController.present()
}
@IBAction func changeRootViewController() {
UIApplication.shared.keyWindow?.rootViewController = UIStoryboard(name: "Main", bundle: .main).instantiateInitialViewController()
}
@IBAction func printPresented() {
guard let vc = PictureInPicture.shared.presentedViewController else {
print("nil")
return
}
print(vc)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observeNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
}
// Notifications
extension ViewController {
fileprivate func observeNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(pictureInPictureMadeSmaller), name: .PictureInPictureMadeSmaller, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(pictureInPictureMadeLarger), name: .PictureInPictureMadeLarger, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(pictureInPictureMoved(_:)), name: .PictureInPictureMoved, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(pictureInPictureDismissed), name: .PictureInPictureDismissed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(pictureInPictureDidBeginMakingSmaller), name: .PictureInPictureDidBeginMakingSmaller, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(pictureInPictureDidBeginMakingLarger), name: .PictureInPictureDidBeginMakingLarger, object: nil)
}
@objc private func pictureInPictureMadeSmaller() {
print("pictureInPictureMadeSmaller")
}
@objc private func pictureInPictureMadeLarger() {
print("pictureInPictureMadeLarger")
}
@objc private func pictureInPictureMoved(_ notification: Notification) {
let userInfo = notification.userInfo!
let oldCorner = userInfo[PictureInPictureOldCornerUserInfoKey] as! PictureInPicture.Corner
let newCorner = userInfo[PictureInPictureNewCornerUserInfoKey] as! PictureInPicture.Corner
print("pictureInPictureMoved(old: \(oldCorner), new: \(newCorner))")
}
@objc private func pictureInPictureDismissed() {
print("pictureInPictureDismissed")
}
@objc private func pictureInPictureDidBeginMakingSmaller() {
print("pictureInPictureDidBeginMakingSmaller")
}
@objc private func pictureInPictureDidBeginMakingLarger() {
print("pictureInPictureDidBeginMakingLarger")
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "default", for: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
}
|
mit
|
bc1b690f825af68fcb9d89f1d57576f6
| 35.035398 | 167 | 0.758595 | 4.888355 | false | false | false | false |
VicFrolov/Markit
|
iOS/Markit/Markit/ProfileViewController.swift
|
1
|
7402
|
//
// ProfileViewController.swift
// Markit
//
// Created by Bryan Ku on 10/13/16.
// Copyright © 2016 Victor Frolov. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
class ProfileViewController: UIViewController {
@IBOutlet var collectionOfStars: Array<UIImageView>?
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var logOutButton: UIButton!
@IBOutlet weak var notificationsButton: UIButton!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var profileBackGround: UIImageView!
@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var firstLastNameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var hubLabel: UILabel!
@IBOutlet weak var noRatingLabel: UILabel!
@IBOutlet weak var otherPaymentLabel: UILabel!
@IBOutlet weak var venmoPaymentLabel: UILabel!
@IBOutlet weak var cashPaymentLabel: UILabel!
var ref: FIRDatabaseReference!
var firstName = "", lastName = "", paymentPreference : NSArray = []
var profilePic = UIImage(named: "profilepicture")
override func viewDidLoad() {
super.viewDidLoad()
drawButtonWhiteBorder(button: editButton)
drawButtonWhiteBorder(button: logOutButton)
for star in collectionOfStars! {
star.isHidden = true
}
self.pageControl.currentPageIndicatorTintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
definesPresentationContext = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueToEditProfile" {
if let destination = segue.destination as? EditProfileViewController {
destination.firstName = self.firstName
destination.lastName = self.lastName
destination.email = self.emailLabel.text!
destination.username = self.usernameLabel.text!
destination.hub = self.hubLabel.text!
destination.paymentPreference = self.paymentPreference
destination.profilePic = self.profilePic!
}
}
if let profilePageViewController = segue.destination as? ProfilePageViewController {
profilePageViewController.profileDelegate = self
}
}
@IBAction func unwindEditProfile(segue: UIStoryboardSegue) { }
@IBAction func unwindNotifications(segue: UIStoryboardSegue) { }
@IBAction func logOut(sender: UIButton) {
try! FIRAuth.auth()!.signOut()
self.dismiss(animated: false, completion: {
self.performSegue(withIdentifier: "segueBackToLogin", sender: self)
})
}
override func viewDidLayoutSubviews() {
makeProfilePicCircular()
updateProfilePic()
}
override func viewDidAppear(_ animated: Bool) {
updateProfile()
updateProfilePic()
}
func updateProfilePic() {
let user = FIRAuth.auth()?.currentUser
let storage = FIRStorage.storage()
let storageRef = storage.reference(forURL: "gs://markit-80192.appspot.com")
let profilePicRef = storageRef.child("images/profileImages/\(user!.uid)/imageOne")
profilePicRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
print("NO PICTURE????")
self.profilePicture.image = self.profilePic
} else {
// Data for "images/island.jpg" is returned
// ... let islandImage: UIImage! = UIImage(data: data!)
self.profilePic = UIImage(data: data!)
self.profilePicture.contentMode = .scaleAspectFill
//self.makeProfilePicCircular()
self.profilePicture.image = self.profilePic
}
}
}
func makeProfilePicCircular() {
profilePicture.layer.borderWidth = 3
profilePicture.layer.masksToBounds = false
profilePicture.layer.borderColor = UIColor.clear.cgColor
profilePicture.layer.cornerRadius = profilePicture.frame.height/2
profilePicture.clipsToBounds = true
}
func drawButtonWhiteBorder(button: UIButton) {
button.backgroundColor = .clear
button.layer.cornerRadius = 3
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.white.cgColor
}
func updateProfile() {
ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
self.firstName = value?["firstName"] as? String ?? ""
self.lastName = value?["lastName"] as? String ?? ""
let name = "\(self.firstName) \(self.lastName)"
let email = value?["email"] as? String ?? ""
let hub = value?["userHub"] as? String ?? ""
let rating = value?["rating"] as? String ?? "-1"
let stars = Int(rating)! - 1
self.paymentPreference = value?["paymentPreference"] as! NSArray
self.paymentContains(array: self.paymentPreference, paymentOptions: ["cash", "venmo", "other"])
self.firstLastNameLabel.text = name
self.usernameLabel.text = username
self.emailLabel.text = email
self.hubLabel.text = hub
if (rating != "-1" && stars <= 4) {
for i in 0...stars {
self.collectionOfStars![i].isHidden = false
}
self.noRatingLabel.isHidden = true
} else {
self.noRatingLabel.isHidden = false
}
}) { (error) in
print(error.localizedDescription)
}
}
private func paymentContains(array: NSArray, paymentOptions: [String]) {
cashPaymentLabel.textColor = UIColorFromRGB(rgbValue: 0xCACACA)
venmoPaymentLabel.textColor = UIColorFromRGB(rgbValue: 0xCACACA)
otherPaymentLabel.textColor = UIColorFromRGB(rgbValue: 0xCACACA)
print("ADFA \(array)")
for option in paymentOptions {
if array.contains(option) {
if (option == "cash") {
cashPaymentLabel.textColor = UIColor.gray
} else if (option == "venmo") {
venmoPaymentLabel.textColor = UIColor.gray
} else if (option == "other") {
otherPaymentLabel.textColor = UIColor.gray
}
}
}
}
private func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
|
apache-2.0
|
871959d91235a87378587f31de9978cf
| 37.546875 | 107 | 0.598838 | 5.062244 | false | false | false | false |
randallli/material-components-ios
|
components/BottomAppBar/examples/BottomAppBarTypicalUseExample.swift
|
1
|
4528
|
/*
Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialBottomAppBar
import MaterialComponents.MaterialButtons_ColorThemer
class BottomAppBarTypicalUseSwiftExample: UIViewController {
let appBar = MDCAppBar()
let bottomBarView = MDCBottomAppBarView()
init() {
super.init(nibName: nil, bundle: nil)
self.title = "Bottom App Bar (Swift)"
self.addChildViewController(appBar.headerViewController)
let color = UIColor(white: 0.2, alpha:1)
appBar.headerViewController.headerView.backgroundColor = color
appBar.navigationBar.tintColor = .white
appBar.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
commonInitBottomAppBarTypicalUseSwiftExample()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInitBottomAppBarTypicalUseSwiftExample()
}
override func viewDidLoad() {
super.viewDidLoad()
appBar.addSubviewsToParent()
}
func commonInitBottomAppBarTypicalUseSwiftExample() {
bottomBarView.autoresizingMask = [ .flexibleWidth, .flexibleTopMargin ]
view.addSubview(bottomBarView)
// Add touch handler to the floating button.
bottomBarView.floatingButton.addTarget(self,
action: #selector(didTapFloatingButton(_:)),
for: .touchUpInside)
// Set the image on the floating button.
let addImage = UIImage(named:"Add")
bottomBarView.floatingButton.setImage(addImage, for: .normal)
// Set the position of the floating button.
bottomBarView.floatingButtonPosition = .center
// Theme the floating button.
let colorScheme = MDCBasicColorScheme(primaryColor: .white)
MDCButtonColorThemer.apply(colorScheme, to: bottomBarView.floatingButton)
// Configure the navigation buttons to be shown on the bottom app bar.
let barButtonLeadingItem = UIBarButtonItem()
let menuImage = UIImage(named:"Menu")
barButtonLeadingItem.image = menuImage
let barButtonTrailingItem = UIBarButtonItem()
let searchImage = UIImage(named:"Search")
barButtonTrailingItem.image = searchImage
bottomBarView.leadingBarButtonItems = [ barButtonLeadingItem ]
bottomBarView.trailingBarButtonItems = [ barButtonTrailingItem ]
}
@objc func didTapFloatingButton(_ sender : MDCFloatingButton) {
// Example of how to animate position of the floating button.
if (bottomBarView.floatingButtonPosition == .center) {
bottomBarView.setFloatingButtonPosition(.trailing, animated: true)
} else {
bottomBarView.setFloatingButtonPosition(.center, animated: true)
}
}
func layoutBottomAppBar() {
let size = bottomBarView.sizeThatFits(view.bounds.size)
let bottomBarViewFrame = CGRect(x: 0,
y: view.bounds.size.height - size.height,
width: size.width,
height: size.height)
bottomBarView.frame = bottomBarViewFrame
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.backgroundColor = .white
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layoutBottomAppBar()
}
#if swift(>=3.2)
@available(iOS 11, *)
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
layoutBottomAppBar()
}
#endif
}
// MARK: Catalog by convention
extension BottomAppBarTypicalUseSwiftExample {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Bottom App Bar", "Bottom App Bar (Swift)"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
func catalogShouldHideNavigation() -> Bool {
return true
}
}
|
apache-2.0
|
acf1c6527b92b782d02a643ea6236938
| 31.342857 | 95 | 0.719302 | 5.047938 | false | false | false | false |
tjw/swift
|
test/SILOptimizer/access_enforcement_noescape.swift
|
1
|
31323
|
// RUN: %target-swift-frontend -module-name access_enforcement_noescape -enable-sil-ownership -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s
// RUN: %target-swift-frontend -module-name access_enforcement_noescape -enable-sil-ownership -enforce-exclusivity=checked -Onone -emit-sil -swift-version 3 -parse-as-library %s | %FileCheck %s
// REQUIRES: asserts
// This tests SILGen and AccessEnforcementSelection as a single set of tests.
// (Some static/dynamic enforcement selection is done in SILGen, and some is
// deferred. That may change over time but we want the outcome to be the same).
//
// These tests attempt to fully cover the possibilities of reads and
// modifications to captures along with `inout` arguments on both the caller and
// callee side.
// Helper
func doOne(_ f: () -> ()) {
f()
}
// Helper
func doTwo(_: ()->(), _: ()->()) {}
// Helper
func doOneInout(_: ()->(), _: inout Int) {}
// Error: Cannot capture nonescaping closure.
// This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift.
// func reentrantCapturedNoescape(fn: (() -> ()) -> ()) {
// let c = { fn {} }
// fn(c)
// }
// Helper
struct Frob {
mutating func outerMut() { doOne { innerMut() } }
mutating func innerMut() {}
}
// Allow nested mutable access via closures.
func nestedNoEscape(f: inout Frob) {
doOne { f.outerMut() }
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF : $@convention(thin) (@inout Frob) -> () {
// CHECK-NOT: begin_access
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF'
// closure #1 in nestedNoEscape(f:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Frob) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Frob
// CHECK: %{{.*}} = apply %{{.*}}([[ACCESS]]) : $@convention(method) (@inout Frob) -> ()
// CHECK: end_access [[ACCESS]] : $*Frob
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_'
// Allow aliased noescape reads.
func readRead() {
var x = 3
// Inside each closure: [read] [static]
doTwo({ _ = x }, { _ = x })
x = 42
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape8readReadyyF : $@convention(thin) () -> () {
// CHECK: [[ALLOC:%.*]] = alloc_stack $Int, var, name "x"
// CHECK-NOT: begin_access
// CHECK: apply
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape8readReadyyF'
// closure #1 in readRead()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape8readReadyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape8readReadyyFyyXEfU_'
// closure #2 in readRead()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape8readReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape8readReadyyFyyXEfU0_'
// Allow aliased noescape reads of an `inout` arg.
func inoutReadRead(x: inout Int) {
// Inside each closure: [read] [static]
doTwo({ _ = x }, { _ = x })
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape09inoutReadE01xySiz_tF : $@convention(thin) (@inout Int) -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape09inoutReadE01xySiz_tF'
// closure #1 in inoutReadRead(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_'
// closure #2 in inoutReadRead(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_'
// Allow aliased noescape read + boxed read.
func readBoxRead() {
var x = 3
let c = { _ = x }
// Inside may-escape closure `c`: [read] [dynamic]
// Inside never-escape closure: [read] [dynamic]
doTwo(c, { _ = x })
x = 42
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape11readBoxReadyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape11readBoxReadyyF'
// closure #1 in readBoxRead()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape11readBoxReadyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape11readBoxReadyyFyycfU_'
// closure #2 in readBoxRead()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape11readBoxReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape11readBoxReadyyFyyXEfU0_'
// Error: cannout capture inout.
//
// func inoutReadReadBox(x: inout Int) {
// let c = { _ = x }
// doTwo({ _ = x }, c)
// }
// Allow aliased noescape read + write.
func readWrite() {
var x = 3
// Inside closure 1: [read] [static]
// Inside closure 2: [modify] [static]
doTwo({ _ = x }, { x = 42 })
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape9readWriteyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape9readWriteyyF'
// closure #1 in readWrite()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape9readWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape9readWriteyyFyyXEfU_'
// closure #2 in readWrite()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape9readWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape9readWriteyyFyyXEfU0_'
// Allow aliased noescape read + write of an `inout` arg.
func inoutReadWrite(x: inout Int) {
// Inside closure 1: [read] [static]
// Inside closure 2: [modify] [static]
doTwo({ _ = x }, { x = 3 })
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape14inoutReadWrite1xySiz_tF : $@convention(thin) (@inout Int) -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape14inoutReadWrite1xySiz_tF'
// closure #1 in inoutReadWrite(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape14inoutReadWrite1xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape14inoutReadWrite1xySiz_tFyyXEfU_'
// closure #2 in inoutReadWrite(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape14inoutReadWrite1xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape14inoutReadWrite1xySiz_tFyyXEfU0_'
func readBoxWrite() {
var x = 3
let c = { _ = x }
// Inside may-escape closure `c`: [read] [dynamic]
// Inside never-escape closure: [modify] [dynamic]
doTwo(c, { x = 42 })
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape12readBoxWriteyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape12readBoxWriteyyF'
// closure #1 in readBoxWrite()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape12readBoxWriteyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape12readBoxWriteyyFyycfU_'
// closure #2 in readBoxWrite()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_'
// Error: cannout capture inout.
// func inoutReadBoxWrite(x: inout Int) {
// let c = { _ = x }
// doTwo({ x = 42 }, c)
// }
func readWriteBox() {
var x = 3
let c = { x = 42 }
// Inside may-escape closure `c`: [modify] [dynamic]
// Inside never-escape closure: [read] [dynamic]
doTwo({ _ = x }, c)
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape12readWriteBoxyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT2]], [[CVT1]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape12readWriteBoxyyF'
// closure #1 in readWriteBox()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape12readWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape12readWriteBoxyyFyycfU_'
// closure #2 in readWriteBox()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_'
// Error: cannout capture inout.
// func inoutReadWriteBox(x: inout Int) {
// let c = { x = 42 }
// doTwo({ _ = x }, c)
// }
// Error: noescape read + write inout.
func readWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ _ = x }, &x)
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape14readWriteInoutyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS2]])
// CHECK: end_access [[ACCESS2]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape14readWriteInoutyyF'
// closure #1 in readWriteInout()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape14readWriteInoutyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape14readWriteInoutyyFyyXEfU_'
// Error: noescape read + write inout of an inout.
func inoutReadWriteInout(x: inout Int) {
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ _ = x }, &x)
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape19inoutReadWriteInout1xySiz_tF : $@convention(thin) (@inout Int) -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS2]])
// CHECK: end_access [[ACCESS2]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape19inoutReadWriteInout1xySiz_tF'
// closure #1 in inoutReadWriteInout(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape19inoutReadWriteInout1xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape19inoutReadWriteInout1xySiz_tFyyXEfU_'
// Traps on boxed read + write inout.
// Covered by Interpreter/enforce_exclusive_access.swift.
func readBoxWriteInout() {
var x = 3
let c = { _ = x }
// Around the call: [modify] [dynamic]
// Inside closure: [read] [dynamic]
doOneInout(c, &x)
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape17readBoxWriteInoutyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS]])
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape17readBoxWriteInoutyyF'
// closure #1 in readBoxWriteInout()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_'
// Error: inout cannot be captured.
// This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift.
// func inoutReadBoxWriteInout(x: inout Int) {
// let c = { _ = x }
// doOneInout(c, &x)
// }
// Allow aliased noescape write + write.
func writeWrite() {
var x = 3
// Inside closure 1: [modify] [static]
// Inside closure 2: [modify] [static]
doTwo({ x = 42 }, { x = 87 })
_ = x
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape10writeWriteyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape10writeWriteyyF'
// closure #1 in writeWrite()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape10writeWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape10writeWriteyyFyyXEfU_'
// closure #2 in writeWrite()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape10writeWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape10writeWriteyyFyyXEfU0_'
// Allow aliased noescape write + write of an `inout` arg.
func inoutWriteWrite(x: inout Int) {
// Inside closure 1: [modify] [static]
// Inside closure 2: [modify] [static]
doTwo({ x = 42}, { x = 87 })
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape010inoutWriteE01xySiz_tF : $@convention(thin) (@inout Int) -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape010inoutWriteE01xySiz_tF'
// closure #1 in inoutWriteWrite(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_'
// closure #2 in inoutWriteWrite(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_'
// Traps on aliased boxed write + noescape write.
// Covered by Interpreter/enforce_exclusive_access.swift.
func writeWriteBox() {
var x = 3
let c = { x = 87 }
// Inside may-escape closure `c`: [modify] [dynamic]
// Inside never-escape closure: [modify] [dynamic]
doTwo({ x = 42 }, c)
_ = x
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape13writeWriteBoxyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT2]], [[CVT1]])
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape13writeWriteBoxyyF'
// closure #1 in writeWriteBox()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape13writeWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape13writeWriteBoxyyFyycfU_'
// closure #2 in writeWriteBox()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_'
// Error: inout cannot be captured.
// func inoutWriteWriteBox(x: inout Int) {
// let c = { x = 87 }
// doTwo({ x = 42 }, c)
// }
// Error: on noescape write + write inout.
func writeWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ x = 42 }, &x)
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape15writeWriteInoutyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS2]])
// CHECK: end_access [[ACCESS2]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape15writeWriteInoutyyF'
// closure #1 in writeWriteInout()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape15writeWriteInoutyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape15writeWriteInoutyyFyyXEfU_'
// Error: on noescape write + write inout.
func inoutWriteWriteInout(x: inout Int) {
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doOneInout({ x = 42 }, &x)
}
// inoutWriteWriteInout(x:)
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape010inoutWriteE5Inout1xySiz_tF : $@convention(thin) (@inout Int) -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS2]])
// CHECK: end_access [[ACCESS2]]
// CHECK-LABEL: // end sil function '$S27access_enforcement_noescape010inoutWriteE5Inout1xySiz_tF'
// closure #1 in inoutWriteWriteInout(x:)
// CHECK-LABEL: sil private @$S27access_enforcement_noescape010inoutWriteE5Inout1xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape010inoutWriteE5Inout1xySiz_tFyyXEfU_'
// Traps on boxed write + write inout.
// Covered by Interpreter/enforce_exclusive_access.swift.
func writeBoxWriteInout() {
var x = 3
let c = { x = 42 }
// Around the call: [modify] [dynamic]
// Inside closure: [modify] [dynamic]
doOneInout(c, &x)
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape18writeBoxWriteInoutyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS]])
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape18writeBoxWriteInoutyyF'
// closure #1 in writeBoxWriteInout()
// CHECK-LABEL: sil private @$S27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_'
// Error: Cannot capture inout
// This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift.
// func inoutWriteBoxWriteInout(x: inout Int) {
// let c = { x = 42 }
// doOneInout(c, &x)
// }
// Helper
func doBlockInout(_: @convention(block) ()->(), _: inout Int) {}
func readBlockWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [read] [static]
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doBlockInout({ _ = x }, &x)
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape19readBlockWriteInoutyyF : $@convention(thin) () -> () {
// CHECK: [[F1:%.*]] = function_ref @$S27access_enforcement_noescape19readBlockWriteInoutyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[F1]](%0) : $@convention(thin) (@inout_aliasable Int) -> ()
// CHECK-NOT: begin_access
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: apply
// CHECK: end_access [[WRITE]] : $*Int
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape19readBlockWriteInoutyyF'
// CHECK-LABEL: sil private @$S27access_enforcement_noescape19readBlockWriteInoutyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: begin_access [read] [static] %0 : $*Int
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape19readBlockWriteInoutyyFyyXEfU_'
// Test AccessSummaryAnalysis.
//
// The captured @inout_aliasable argument to `doOne` is re-partially applied,
// then stored is a box before passing it to doBlockInout.
func noEscapeBlock() {
var x = 3
doOne {
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
doBlockInout({ _ = x }, &x)
}
}
// CHECK-LABEL: sil hidden @$S27access_enforcement_noescape13noEscapeBlockyyF : $@convention(thin) () -> () {
// CHECK: partial_apply [callee_guaranteed]
// CHECK-NOT: begin_access
// CHECK: apply
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape13noEscapeBlockyyF'
// CHECK-LABEL: sil private @$S27access_enforcement_noescape13noEscapeBlockyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[F1:%.*]] = function_ref @$S27access_enforcement_noescape13noEscapeBlockyyFyyXEfU_yyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[F1]](%0) : $@convention(thin) (@inout_aliasable Int) -> ()
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[STORAGE:%.*]] = alloc_stack $@block_storage @noescape @callee_guaranteed () -> ()
// CHECK: [[ADDR:%.*]] = project_block_storage [[STORAGE]] : $*@block_storage @noescape @callee_guaranteed () -> ()
// CHECK: store [[CVT]] to [[ADDR]] : $*@noescape @callee_guaranteed () -> ()
// CHECK: [[F2:%.*]] = function_ref @$SIg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> ()
// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[STORAGE]] : $*@block_storage @noescape @callee_guaranteed () -> (), invoke [[F2]] : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> ()
// CHECK: [[ARG:%.*]] = copy_block [[BLOCK]] : $@convention(block) @noescape () -> ()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: apply %{{.*}}([[ARG]], [[WRITE]]) : $@convention(thin) (@guaranteed @convention(block) @noescape () -> (), @inout Int) -> ()
// CHECK: end_access [[WRITE]] : $*Int
// CHECK: dealloc_stack [[STORAGE]] : $*@block_storage @noescape @callee_guaranteed () -> ()
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape13noEscapeBlockyyFyyXEfU_'
// CHECK-LABEL: sil private @$S27access_enforcement_noescape13noEscapeBlockyyFyyXEfU_yyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: begin_access [read] [static] %0 : $*Int
// CHECK-LABEL: } // end sil function '$S27access_enforcement_noescape13noEscapeBlockyyFyyXEfU_yyXEfU_'
|
apache-2.0
|
576b536263eb38ac9528367218e23f09
| 51.821248 | 276 | 0.65993 | 3.366255 | false | false | false | false |
egosapien/SSASideMenu
|
SSASideMenu/SSASideMenu.swift
|
1
|
44827
|
//
// SSASideMenu.swift
// SSASideMenuExample
//
// Created by Sebastian Andersen on 06/10/14.
// Copyright (c) 2015 Sebastian Andersen. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
var sideMenuViewController: SSASideMenu? {
get {
return getSideViewController(self)
}
}
private func getSideViewController(viewController: UIViewController) -> SSASideMenu? {
if let parent = viewController.parentViewController {
if parent is SSASideMenu {
return parent as? SSASideMenu
}else {
return getSideViewController(parent)
}
}
return nil
}
@IBAction func presentLeftMenuViewController() {
sideMenuViewController?._presentLeftMenuViewController()
}
@IBAction func presentRightMenuViewController() {
sideMenuViewController?._presentRightMenuViewController()
}
}
@objc protocol SSASideMenuDelegate {
optional func sideMenuDidRecognizePanGesture(sideMenu: SSASideMenu, recongnizer: UIPanGestureRecognizer)
optional func sideMenuWillShowMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
optional func sideMenuDidShowMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
optional func sideMenuWillHideMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
optional func sideMenuDidHideMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
}
class SSASideMenu: UIViewController, UIGestureRecognizerDelegate {
enum SSASideMenuPanDirection {
case Edge
case EveryWhere
case Rect(CGRect)
case EdgeAndRect(CGRect)
}
enum SSASideMenuType: Int {
case Scale = 0
case Slip = 1
}
enum SSAStatusBarStyle: Int {
case Hidden = 0
case Black = 1
case Light = 2
}
private enum SSASideMenuSide: Int {
case Left = 0
case Right = 1
}
struct ContentViewShadow {
var enabled: Bool = true
var color: UIColor = UIColor.blackColor()
var offset: CGSize = CGSizeZero
var opacity: Float = 0.4
var radius: Float = 8.0
init(enabled: Bool = true, color: UIColor = UIColor.blackColor(), offset: CGSize = CGSizeZero, opacity: Float = 0.4, radius: Float = 8.0) {
self.enabled = false
self.color = color
self.offset = offset
self.opacity = opacity
self.radius = radius
}
}
struct MenuViewEffect {
var fade: Bool = true
var scale: Bool = true
var scaleBackground: Bool = true
var parallaxEnabled: Bool = true
var bouncesHorizontally: Bool = true
var statusBarStyle: SSAStatusBarStyle = .Black
init(fade: Bool = true, scale: Bool = true, scaleBackground: Bool = true, parallaxEnabled: Bool = true, bouncesHorizontally: Bool = true, statusBarStyle: SSAStatusBarStyle = .Black) {
self.fade = fade
self.scale = scale
self.scaleBackground = scaleBackground
self.parallaxEnabled = parallaxEnabled
self.bouncesHorizontally = bouncesHorizontally
self.statusBarStyle = statusBarStyle
}
}
struct ContentViewEffect {
var alpha: Float = 1.0
var scale: Float = 0.7
var landscapeOffsetX: Float = 30
var portraitOffsetX: Float = 30
var minParallaxContentRelativeValue: Float = -25.0
var maxParallaxContentRelativeValue: Float = 25.0
var interactivePopGestureRecognizerEnabled: Bool = true
init(alpha: Float = 1.0, scale: Float = 0.7, landscapeOffsetX: Float = 30, portraitOffsetX: Float = 30, minParallaxContentRelativeValue: Float = -25.0, maxParallaxContentRelativeValue: Float = 25.0, interactivePopGestureRecognizerEnabled: Bool = true) {
self.alpha = alpha
self.scale = scale
self.landscapeOffsetX = landscapeOffsetX
self.portraitOffsetX = portraitOffsetX
self.minParallaxContentRelativeValue = minParallaxContentRelativeValue
self.maxParallaxContentRelativeValue = maxParallaxContentRelativeValue
self.interactivePopGestureRecognizerEnabled = interactivePopGestureRecognizerEnabled
}
}
struct SideMenuOptions {
var animationDuration: Float = 0.35
var panGestureEnabled: Bool = true
var panDirection: SSASideMenuPanDirection = .Edge
var type: SSASideMenuType = .Scale
var panMinimumOpenThreshold: UInt = 60
var menuViewControllerTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.5, 1.5)
var backgroundTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.7, 1.7)
var endAllEditing: Bool = false
init(animationDuration: Float = 0.35, panGestureEnabled: Bool = true, panDirection: SSASideMenuPanDirection = .Edge, type: SSASideMenuType = .Scale, panMinimumOpenThreshold: UInt = 60, menuViewControllerTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.5, 1.5), backgroundTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.7, 1.7), endAllEditing: Bool = false) {
self.animationDuration = animationDuration
self.panGestureEnabled = panGestureEnabled
self.panDirection = panDirection
self.type = type
self.panMinimumOpenThreshold = panMinimumOpenThreshold
self.menuViewControllerTransformation = menuViewControllerTransformation
self.backgroundTransformation = backgroundTransformation
self.endAllEditing = endAllEditing
}
}
func configure(configuration: MenuViewEffect) {
fadeMenuView = configuration.fade
scaleMenuView = configuration.scale
scaleBackgroundImageView = configuration.scaleBackground
parallaxEnabled = configuration.parallaxEnabled
bouncesHorizontally = configuration.bouncesHorizontally
}
func configure(configuration: ContentViewShadow) {
contentViewShadowEnabled = configuration.enabled
contentViewShadowColor = configuration.color
contentViewShadowOffset = configuration.offset
contentViewShadowOpacity = configuration.opacity
contentViewShadowRadius = configuration.radius
}
func configure(configuration: ContentViewEffect) {
contentViewScaleValue = configuration.scale
contentViewFadeOutAlpha = configuration.alpha
contentViewInPortraitOffsetCenterX = configuration.portraitOffsetX
parallaxContentMinimumRelativeValue = configuration.minParallaxContentRelativeValue
parallaxContentMaximumRelativeValue = configuration.maxParallaxContentRelativeValue
}
func configure(configuration: SideMenuOptions) {
animationDuration = configuration.animationDuration
panGestureEnabled = configuration.panGestureEnabled
panDirection = configuration.panDirection
type = configuration.type
panMinimumOpenThreshold = configuration.panMinimumOpenThreshold
menuViewControllerTransformation = configuration.menuViewControllerTransformation
backgroundTransformation = configuration.backgroundTransformation
endAllEditing = configuration.endAllEditing
}
// MARK: Storyboard Support
@IBInspectable var contentViewStoryboardID: String?
@IBInspectable var leftMenuViewStoryboardID: String?
@IBInspectable var rightMenuViewStoryboardID: String?
// MARK: Private Properties: MenuView & BackgroundImageView
@IBInspectable var fadeMenuView: Bool = true
@IBInspectable var startMenuAlpha: Float = 0.2
@IBInspectable var scaleMenuView: Bool = true
@IBInspectable var scaleBackgroundImageView: Bool = true
@IBInspectable var parallaxEnabled: Bool = true
@IBInspectable var bouncesHorizontally: Bool = true
// MARK: Public Properties: MenuView
@IBInspectable var statusBarStyle: SSAStatusBarStyle = .Black
// MARK: Private Properties: ContentView
@IBInspectable var contentViewScaleValue: Float = 1.1
@IBInspectable var contentViewFadeOutAlpha: Float = 1.0
@IBInspectable var contentViewInPortraitOffsetCenterX: Float = 30.0
@IBInspectable var contentViewInPortraitOffsetCenterY: Float = 60.0
@IBInspectable var parallaxContentMinimumRelativeValue: Float = -25.0
@IBInspectable var parallaxContentMaximumRelativeValue: Float = 25.0
// MARK: Public Properties: ContentView
@IBInspectable var interactivePopGestureRecognizerEnabled: Bool = true
@IBInspectable var endAllEditing: Bool = false
// MARK: Private Properties: Shadow for ContentView
@IBInspectable var contentViewShadowEnabled: Bool = true
@IBInspectable var contentViewShadowColor: UIColor = UIColor.blackColor()
@IBInspectable var contentViewShadowOffset: CGSize = CGSizeZero
@IBInspectable var contentViewShadowOpacity: Float = 0.4
@IBInspectable var contentViewShadowRadius: Float = 8.0
// MARK: Public Properties: SideMenu
@IBInspectable var animationDuration: Float = 0.35
@IBInspectable var panGestureEnabled: Bool = true
@IBInspectable var panDirection: SSASideMenuPanDirection = .Edge
@IBInspectable var type: SSASideMenuType = .Scale
@IBInspectable var panMinimumOpenThreshold: UInt = 60
@IBInspectable var menuViewControllerTransformation: CGAffineTransform = CGAffineTransformMakeScale(0.8, 0.8)
@IBInspectable var backgroundTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.7, 1.7)
// MARK: Internal Private Properties
weak var delegate: SSASideMenuDelegate?
private var visible: Bool = false
private var leftMenuVisible: Bool = false
private var rightMenuVisible: Bool = false
private var originalPoint: CGPoint = CGPoint()
private var didNotifyDelegate: Bool = false
private let iOS8: Bool = kCFCoreFoundationVersionNumber > kCFCoreFoundationVersionNumber_iOS_7_1
private let menuViewContainer: UIView = UIView()
private let contentViewContainer: UIView = UIView()
private let contentButton: UIButton = UIButton()
private let backgroundImageView: UIImageView = UIImageView()
// MARK: Public Properties
@IBInspectable var backgroundImage: UIImage? {
willSet {
if let bckImage = newValue {
backgroundImageView.image = bckImage
}
}
}
var contentViewController: UIViewController? {
willSet {
setupViewController(contentViewContainer, targetViewController: newValue)
}
didSet {
if let controller = oldValue {
hideViewController(controller)
}
setupContentViewShadow()
if visible {
setupContentViewControllerMotionEffects()
}
}
}
var leftMenuViewController: UIViewController? {
willSet {
setupViewController(menuViewContainer, targetViewController: newValue)
}
didSet {
if let controller = oldValue {
hideViewController(controller)
}
setupMenuViewControllerMotionEffects()
view.bringSubviewToFront(contentViewContainer)
}
}
var rightMenuViewController: UIViewController? {
willSet {
setupViewController(menuViewContainer, targetViewController: newValue)
}
didSet {
if let controller = oldValue {
hideViewController(controller)
}
setupMenuViewControllerMotionEffects()
view.bringSubviewToFront(contentViewContainer)
}
}
// MARK: Initializers
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience init(contentViewController: UIViewController, leftMenuViewController: UIViewController) {
self.init()
self.contentViewController = contentViewController
self.leftMenuViewController = leftMenuViewController
}
convenience init(contentViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.contentViewController = contentViewController
self.rightMenuViewController = rightMenuViewController
}
convenience init(contentViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.contentViewController = contentViewController
self.leftMenuViewController = leftMenuViewController
self.rightMenuViewController = rightMenuViewController
}
// MARK: Present / Hide Menu ViewControllers
func _presentLeftMenuViewController() {
presentMenuViewContainerWithMenuViewController(leftMenuViewController)
showLeftMenuViewController()
}
func _presentRightMenuViewController() {
presentMenuViewContainerWithMenuViewController(rightMenuViewController)
showRightMenuViewController()
}
func hideMenuViewController() {
hideMenuViewController(true)
}
private func showRightMenuViewController() {
if let viewController = rightMenuViewController {
showMenuViewController(.Right, menuViewController: viewController)
UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: {[unowned self] () -> Void in
self.animateMenuViewController(.Right)
self.menuViewContainer.alpha = 1
self.contentViewContainer.alpha = CGFloat(self.contentViewFadeOutAlpha)
}, completion: {[unowned self] (Bool) -> Void in
self.animateMenuViewControllerCompletion(.Right, menuViewController: viewController)
})
statusBarNeedsAppearanceUpdate()
}
}
private func showLeftMenuViewController() {
if let viewController = leftMenuViewController {
showMenuViewController(.Left, menuViewController: viewController)
UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: {[unowned self] () -> Void in
self.animateMenuViewController(.Left)
self.menuViewContainer.alpha = 1
self.contentViewContainer.alpha = CGFloat(self.contentViewFadeOutAlpha)
}, completion: {[unowned self] (Bool) -> Void in
self.animateMenuViewControllerCompletion(.Left, menuViewController: viewController)
})
statusBarNeedsAppearanceUpdate()
}
}
private func showMenuViewController(side: SSASideMenuSide, menuViewController: UIViewController) {
menuViewController.view.hidden = false
switch side {
case .Left:
leftMenuViewController?.beginAppearanceTransition(true, animated: true)
rightMenuViewController?.view.hidden = true
case .Right:
rightMenuViewController?.beginAppearanceTransition(true, animated: true)
leftMenuViewController?.view.hidden = true
}
if endAllEditing {
view.window?.endEditing(true)
}else {
setupUserInteractionForContentButtonAndTargetViewControllerView(true, targetViewControllerViewInteractive: false)
}
setupContentButton()
setupContentViewShadow()
resetContentViewScale()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
private func animateMenuViewController(side: SSASideMenuSide) {
if type == .Scale {
contentViewContainer.transform = CGAffineTransformMakeScale(CGFloat(contentViewScaleValue), CGFloat(contentViewScaleValue))
} else {
contentViewContainer.transform = CGAffineTransformIdentity
}
if side == .Left {
let contentWidth = CGFloat(CGRectGetWidth(view.frame)) / 2
let centerX = CGFloat(CGRectGetWidth(view.frame)) + contentWidth - CGFloat(contentViewInPortraitOffsetCenterX)
let centerY = CGRectGetHeight(contentViewContainer.frame) / 2 + CGFloat(contentViewInPortraitOffsetCenterX)
contentViewContainer.center = CGPointMake(centerX, centerY)
} else {
let centerX = CGFloat(-self.contentViewInPortraitOffsetCenterX)
contentViewContainer.center = CGPointMake(centerX, contentViewContainer.center.y)
}
menuViewContainer.transform = CGAffineTransformIdentity
if scaleBackgroundImageView {
if let _ = backgroundImage {
backgroundImageView.transform = CGAffineTransformIdentity
}
}
}
private func animateMenuViewControllerCompletion(side: SSASideMenuSide, menuViewController: UIViewController) {
if !visible {
self.delegate?.sideMenuDidShowMenuViewController?(self, menuViewController: menuViewController)
}
visible = true
switch side {
case .Left:
leftMenuViewController?.endAppearanceTransition()
leftMenuVisible = true
case .Right:
if contentViewContainer.frame.size.width == view.bounds.size.width &&
contentViewContainer.frame.size.height == view.bounds.size.height &&
contentViewContainer.frame.origin.x == 0 &&
contentViewContainer.frame.origin.y == 0 {
visible = false
}
rightMenuVisible = visible
rightMenuViewController?.endAppearanceTransition()
}
UIApplication.sharedApplication().endIgnoringInteractionEvents()
setupContentViewControllerMotionEffects()
}
private func presentMenuViewContainerWithMenuViewController(menuViewController: UIViewController?) {
menuViewContainer.transform = CGAffineTransformIdentity
menuViewContainer.frame = view.bounds
if scaleBackgroundImageView {
if backgroundImage != nil {
backgroundImageView.transform = CGAffineTransformIdentity
backgroundImageView.frame = view.bounds
backgroundImageView.transform = backgroundTransformation
}
}
if scaleMenuView {
menuViewContainer.transform = menuViewControllerTransformation
}
menuViewContainer.alpha = fadeMenuView ? CGFloat(startMenuAlpha) : 1
if let viewController = menuViewController {
delegate?.sideMenuWillShowMenuViewController?(self, menuViewController: viewController)
}
}
private func hideMenuViewController(animated: Bool) {
let isRightMenuVisible: Bool = rightMenuVisible
let visibleMenuViewController: UIViewController? = isRightMenuVisible ? rightMenuViewController : leftMenuViewController
visibleMenuViewController?.beginAppearanceTransition(true, animated: true)
if isRightMenuVisible, let viewController = rightMenuViewController {
delegate?.sideMenuWillHideMenuViewController?(self, menuViewController: viewController)
}
if !isRightMenuVisible, let viewController = leftMenuViewController {
delegate?.sideMenuWillHideMenuViewController?(self, menuViewController: viewController)
}
if !endAllEditing {
setupUserInteractionForContentButtonAndTargetViewControllerView(false, targetViewControllerViewInteractive: true)
}
visible = false
leftMenuVisible = false
rightMenuVisible = false
contentButton.removeFromSuperview()
let animationsClosure: () -> () = {[unowned self] () -> () in
self.contentViewContainer.transform = CGAffineTransformIdentity
self.contentViewContainer.frame = self.view.bounds
if self.scaleMenuView {
self.menuViewContainer.transform = self.menuViewControllerTransformation
}
self.menuViewContainer.alpha = self.fadeMenuView ? CGFloat(self.startMenuAlpha) : 1
self.contentViewContainer.alpha = CGFloat(self.contentViewFadeOutAlpha)
if self.scaleBackgroundImageView {
if self.backgroundImage != nil {
self.backgroundImageView.transform = self.backgroundTransformation
}
}
if self.parallaxEnabled {
self.removeMotionEffects(self.contentViewContainer)
}
}
let completionClosure: () -> () = {[weak self] () -> () in
visibleMenuViewController?.endAppearanceTransition()
if isRightMenuVisible, let viewController = self?.rightMenuViewController {
self?.delegate?.sideMenuDidHideMenuViewController?(self!, menuViewController: viewController)
}
if !isRightMenuVisible, let viewController = self?.leftMenuViewController {
self?.delegate?.sideMenuDidHideMenuViewController?(self!, menuViewController: viewController)
}
}
if animated {
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: { () -> Void in
animationsClosure()
}, completion: { (Bool) -> Void in
completionClosure()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
})
}else {
animationsClosure()
completionClosure()
}
statusBarNeedsAppearanceUpdate()
}
// MARK: ViewController life cycle
override func awakeFromNib() {
super.awakeFromNib()
if iOS8 {
if let cntentViewStoryboardID = contentViewStoryboardID {
contentViewController = storyboard?.instantiateViewControllerWithIdentifier(cntentViewStoryboardID)
}
if let lftViewStoryboardID = leftMenuViewStoryboardID {
leftMenuViewController = storyboard?.instantiateViewControllerWithIdentifier(lftViewStoryboardID)
}
if let rghtViewStoryboardID = rightMenuViewStoryboardID {
rightMenuViewController = storyboard?.instantiateViewControllerWithIdentifier(rghtViewStoryboardID)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .blackColor()
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
menuViewContainer.frame = view.bounds;
menuViewContainer.autoresizingMask = [.FlexibleWidth, .FlexibleHeight];
menuViewContainer.alpha = fadeMenuView ? CGFloat(startMenuAlpha) : 1
contentViewContainer.frame = view.bounds
contentViewContainer.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
setupViewController(contentViewContainer, targetViewController: contentViewController)
setupViewController(menuViewContainer, targetViewController: leftMenuViewController)
setupViewController(menuViewContainer, targetViewController: rightMenuViewController)
if panGestureEnabled {
view.multipleTouchEnabled = false
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(SSASideMenu.panGestureRecognized(_:)))
panGestureRecognizer.delegate = self
view.addGestureRecognizer(panGestureRecognizer)
}
if let _ = backgroundImage {
if scaleBackgroundImageView {
backgroundImageView.transform = backgroundTransformation
}
backgroundImageView.frame = view.bounds
backgroundImageView.contentMode = .ScaleAspectFill;
backgroundImageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight];
view.addSubview(backgroundImageView)
}
view.addSubview(menuViewContainer)
view.addSubview(contentViewContainer)
setupMenuViewControllerMotionEffects()
setupContentViewShadow()
}
// MARK: Setup
private func setupViewController(targetView: UIView, targetViewController: UIViewController?) {
if let viewController = targetViewController {
addChildViewController(viewController)
viewController.view.frame = view.bounds
viewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
targetView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
}
}
private func hideViewController(targetViewController: UIViewController) {
targetViewController.willMoveToParentViewController(nil)
targetViewController.view.removeFromSuperview()
targetViewController.removeFromParentViewController()
}
// MARK: Layout
private func setupContentButton() {
if let _ = contentButton.superview {
return
} else {
contentButton.addTarget(self, action: #selector(SSASideMenu.hideMenuViewController as (SSASideMenu) -> () -> ()), forControlEvents:.TouchUpInside)
contentButton.autoresizingMask = .None
contentButton.frame = contentViewContainer.bounds
contentButton.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
contentButton.tag = 101
contentViewContainer.addSubview(contentButton)
}
}
private func statusBarNeedsAppearanceUpdate() {
if self.respondsToSelector(#selector(UIViewController.setNeedsStatusBarAppearanceUpdate)) {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.setNeedsStatusBarAppearanceUpdate()
})
}
}
private func setupContentViewShadow() {
if contentViewShadowEnabled {
let layer: CALayer = contentViewContainer.layer
let path: UIBezierPath = UIBezierPath(rect: layer.bounds)
layer.shadowPath = path.CGPath
layer.shadowColor = contentViewShadowColor.CGColor
layer.shadowOffset = contentViewShadowOffset
layer.shadowOpacity = contentViewShadowOpacity
layer.shadowRadius = CGFloat(contentViewShadowRadius)
}
}
// MARK: Helper Functions
private func resetContentViewScale() {
let t: CGAffineTransform = contentViewContainer.transform
let scale: CGFloat = sqrt(t.a * t.a + t.c * t.c)
let frame: CGRect = contentViewContainer.frame
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.transform = CGAffineTransformMakeScale(scale, scale)
contentViewContainer.frame = frame
}
private func setupUserInteractionForContentButtonAndTargetViewControllerView(contentButtonInteractive: Bool, targetViewControllerViewInteractive: Bool) {
if let viewController = contentViewController {
for view in viewController.view.subviews {
if view.tag == 101 {
view.userInteractionEnabled = contentButtonInteractive
}else {
view.userInteractionEnabled = targetViewControllerViewInteractive
}
}
}
}
// MARK: Motion Effects (Private)
private func removeMotionEffects(targetView: UIView) {
let targetViewMotionEffects = targetView.motionEffects
for effect in targetViewMotionEffects {
targetView.removeMotionEffect(effect)
}
}
private func setupMenuViewControllerMotionEffects() {
if parallaxEnabled {
removeMotionEffects(menuViewContainer)
// We need to refer to self in closures!
UIView.animateWithDuration(0.2, animations: { [unowned self] () -> Void in
let interpolationHorizontal: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
let interpolationVertical: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
self.menuViewContainer.addMotionEffect(interpolationHorizontal)
self.menuViewContainer.addMotionEffect(interpolationVertical)
})
}
}
private func setupContentViewControllerMotionEffects() {
if parallaxEnabled {
removeMotionEffects(contentViewContainer)
// We need to refer to self in closures!
UIView.animateWithDuration(0.2, animations: { [unowned self] () -> Void in
let interpolationHorizontal: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
let interpolationVertical: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
self.contentViewContainer.addMotionEffect(interpolationHorizontal)
self.contentViewContainer.addMotionEffect(interpolationVertical)
})
}
}
// MARK: View Controller Rotation handler
override func shouldAutorotate() -> Bool {
if let cntViewController = contentViewController {
return cntViewController.shouldAutorotate()
}
return false
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
if visible {
menuViewContainer.bounds = view.bounds
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.frame = view.bounds
if type == .Scale {
contentViewContainer.transform = CGAffineTransformMakeScale(CGFloat(contentViewScaleValue), CGFloat(contentViewScaleValue))
} else {
contentViewContainer.transform = CGAffineTransformIdentity
}
var center: CGPoint
if leftMenuVisible {
let centerX = CGFloat(contentViewInPortraitOffsetCenterX) + CGFloat(CGRectGetWidth(view.frame))
center = CGPointMake(centerX, contentViewContainer.center.y)
} else {
let centerX = CGFloat(-self.contentViewInPortraitOffsetCenterX)
center = CGPointMake(centerX, contentViewContainer.center.y)
}
contentViewContainer.center = center
}
setupContentViewShadow()
}
// MARK: Status Bar Appearance Management
override func preferredStatusBarStyle() -> UIStatusBarStyle {
var style: UIStatusBarStyle
switch statusBarStyle {
case .Hidden:
style = .Default
case .Black:
style = .Default
case .Light:
style = .LightContent
}
if visible || contentViewContainer.frame.origin.y <= 0, let cntViewController = contentViewController {
style = cntViewController.preferredStatusBarStyle()
}
return style
}
override func prefersStatusBarHidden() -> Bool {
var statusBarHidden: Bool
switch statusBarStyle {
case .Hidden:
statusBarHidden = true
default:
statusBarHidden = false
}
if visible || contentViewContainer.frame.origin.y <= 0, let cntViewController = contentViewController {
statusBarHidden = cntViewController.prefersStatusBarHidden()
}
return statusBarHidden
}
override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
var statusBarAnimation: UIStatusBarAnimation = .None
if let cntViewController = contentViewController, leftMenuViewController = leftMenuViewController {
statusBarAnimation = visible ? leftMenuViewController.preferredStatusBarUpdateAnimation() : cntViewController.preferredStatusBarUpdateAnimation()
if contentViewContainer.frame.origin.y > 10 {
statusBarAnimation = leftMenuViewController.preferredStatusBarUpdateAnimation()
} else {
statusBarAnimation = cntViewController.preferredStatusBarUpdateAnimation()
}
}
if let cntViewController = contentViewController, rghtMenuViewController = rightMenuViewController {
statusBarAnimation = visible ? rghtMenuViewController.preferredStatusBarUpdateAnimation() : cntViewController.preferredStatusBarUpdateAnimation()
if contentViewContainer.frame.origin.y > 10 {
statusBarAnimation = rghtMenuViewController.preferredStatusBarUpdateAnimation()
} else {
statusBarAnimation = cntViewController.preferredStatusBarUpdateAnimation()
}
}
return statusBarAnimation
}
// MARK: UIGestureRecognizer Delegate (Private)
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if interactivePopGestureRecognizerEnabled,
let viewController = contentViewController as? UINavigationController
where viewController.viewControllers.count > 1 && viewController.interactivePopGestureRecognizer!.enabled {
return false
}
if gestureRecognizer is UIPanGestureRecognizer && !visible {
switch panDirection {
case .EveryWhere:
return true
case .Edge:
let point = touch.locationInView(gestureRecognizer.view)
return point.x < 20.0 || point.x > view.frame.size.width - 20.0
case .Rect(let rect):
let point = touch.locationInView(gestureRecognizer.view)
return point.x > rect.origin.x
&& point.y > rect.origin.y
&& point.x < rect.origin.x + rect.size.width
&& point.y < rect.origin.y + rect.size.height
case .EdgeAndRect(let rect):
let point = touch.locationInView(gestureRecognizer.view)
return point.x < 20.0 || point.x > view.frame.size.width - 20.0
|| point.x > rect.origin.x
&& point.y > rect.origin.y
&& point.x < rect.origin.x + rect.size.width
&& point.y < rect.origin.y + rect.size.height
}
}
return true
}
func panGestureRecognized(recognizer: UIPanGestureRecognizer) {
delegate?.sideMenuDidRecognizePanGesture?(self, recongnizer: recognizer)
if !panGestureEnabled {
return
}
var point: CGPoint = recognizer.translationInView(view)
if recognizer.state == .Began {
setupContentViewShadow()
originalPoint = CGPointMake(contentViewContainer.center.x - CGRectGetWidth(contentViewContainer.bounds) / 2.0,
contentViewContainer.center.y - CGRectGetHeight(contentViewContainer.bounds) / 2.0)
menuViewContainer.transform = CGAffineTransformIdentity
if (scaleBackgroundImageView) {
backgroundImageView.transform = CGAffineTransformIdentity
backgroundImageView.frame = view.bounds
}
menuViewContainer.frame = view.bounds
setupContentButton()
if endAllEditing {
view.window?.endEditing(true)
}else {
setupUserInteractionForContentButtonAndTargetViewControllerView(true, targetViewControllerViewInteractive: false)
}
didNotifyDelegate = false
}
if recognizer.state == .Changed {
var delta: CGFloat = 0.0
if visible {
delta = originalPoint.x != 0 ? (point.x + originalPoint.x) / originalPoint.x : 0
} else {
delta = point.x / view.frame.size.width
}
delta = min(fabs(delta), 1.6)
var contentViewScale: CGFloat = type == .Scale ? 1 + ((CGFloat(contentViewScaleValue) - 1) * delta) : 1
var contentOffsetY = CGFloat(contentViewInPortraitOffsetCenterY)
contentOffsetY = visible ? -((1-delta)*contentOffsetY) : delta*contentOffsetY
var backgroundViewScale: CGFloat = backgroundTransformation.a - ((backgroundTransformation.a - 1) * delta)
var menuViewScale: CGFloat = menuViewControllerTransformation.a - ((menuViewControllerTransformation.a - 1) * delta)
if !bouncesHorizontally {
contentViewScale = min(contentViewScale, CGFloat(contentViewScaleValue))
backgroundViewScale = min(backgroundViewScale, 1.0)
menuViewScale = min(menuViewScale, 1.0)
}
let menuAlphaDelta = (delta * CGFloat(1.0 - startMenuAlpha)) + CGFloat(startMenuAlpha)
menuViewContainer.alpha = fadeMenuView ? menuAlphaDelta : 1
contentViewContainer.alpha = 1 - (1 - CGFloat(contentViewFadeOutAlpha)) * delta
if scaleBackgroundImageView {
backgroundImageView.transform = CGAffineTransformMakeScale(backgroundViewScale, backgroundViewScale)
}
if scaleMenuView {
menuViewContainer.transform = CGAffineTransformMakeScale(menuViewScale, menuViewScale)
}
if scaleBackgroundImageView && backgroundViewScale < 1 {
backgroundImageView.transform = CGAffineTransformIdentity
}
if bouncesHorizontally && visible {
if contentViewContainer.frame.origin.x > contentViewContainer.frame.size.width / 2.0 {
point.x = min(0.0, point.x)
}
if contentViewContainer.frame.origin.x < -(contentViewContainer.frame.size.width / 2.0) {
point.x = max(0.0, point.x)
}
}
// Limit size
if point.x < 0 {
point.x = max(point.x, -UIScreen.mainScreen().bounds.size.height)
} else {
point.x = min(point.x, UIScreen.mainScreen().bounds.size.height)
}
recognizer.setTranslation(point, inView: view)
if !didNotifyDelegate {
if point.x > 0 && !visible, let viewController = leftMenuViewController {
delegate?.sideMenuWillShowMenuViewController?(self, menuViewController: viewController)
}
if point.x < 0 && !visible, let viewController = rightMenuViewController {
delegate?.sideMenuWillShowMenuViewController?(self, menuViewController: viewController)
}
didNotifyDelegate = true
}
contentViewContainer.transform = CGAffineTransformMakeScale(contentViewScale, contentViewScale)
contentViewContainer.transform = CGAffineTransformTranslate(contentViewContainer.transform, point.x, contentOffsetY)
leftMenuViewController?.view.hidden = contentViewContainer.frame.origin.x < 0
rightMenuViewController?.view.hidden = contentViewContainer.frame.origin.x > 0
if leftMenuViewController == nil && contentViewContainer.frame.origin.x > 0 {
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.frame = view.bounds
visible = false
leftMenuVisible = false
} else if self.rightMenuViewController == nil && contentViewContainer.frame.origin.x < 0 {
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.frame = view.bounds
visible = false
rightMenuVisible = false
}
statusBarNeedsAppearanceUpdate()
}
if recognizer.state == .Ended {
didNotifyDelegate = false
if panMinimumOpenThreshold > 0 &&
contentViewContainer.frame.origin.x < 0 &&
contentViewContainer.frame.origin.x > -CGFloat(panMinimumOpenThreshold) ||
contentViewContainer.frame.origin.x > 0 &&
contentViewContainer.frame.origin.x < CGFloat(panMinimumOpenThreshold) {
hideMenuViewController()
}
else if contentViewContainer.frame.origin.x == 0 {
hideMenuViewController(false)
}
else if recognizer.velocityInView(view).x > 0 {
if contentViewContainer.frame.origin.x < 0 {
hideMenuViewController()
} else if leftMenuViewController != nil {
showLeftMenuViewController()
}
}
else {
if contentViewContainer.frame.origin.x < 20 && rightMenuViewController != nil{
showRightMenuViewController()
} else {
hideMenuViewController()
}
}
}
}
}
|
mit
|
83fa17064e308a9be06b10e608d41057
| 38.740248 | 399 | 0.630201 | 6.486326 | false | false | false | false |
cemolcay/BlockTableView-Swift
|
BlockTableView-Swift/ViewController.swift
|
1
|
4166
|
//
// ViewController.swift
// BlockTableView-Swift
//
// Created by Cem Olcay on 12/11/14.
// Copyright (c) 2014 Cem Olcay. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
createSingleSectionTableView()
//createMultiSectionTableView()
}
func createSingleSectionTableView () {
// Setup data source
var dataSource : [String] = []
for i in 1...20 {
dataSource.append("cell \(i)")
}
// Create BlockTableView
let table = BlockTableView (frame: self.view.frame,
registeredCells: ["asd": UITableViewCell.self],
numberOfRowsInSection: { (section) -> Int in
return dataSource.count
},
cellForRowAtIndexPath: { (tableView, indexPath) -> UITableViewCell in
var cell = tableView.dequeueReusableCellWithIdentifier("asd", forIndexPath: indexPath) as UITableViewCell
let current = dataSource[indexPath.row]
cell.textLabel?.text = current
cell.textLabel?.numberOfLines = 0
return cell
},
didSelectRowAtIndexPath: { (tableView, indexPath) -> () in
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let selected = dataSource[indexPath.row]
println("\(selected) selected")
}
)
// add a search bar
var filtered: [String]! // search result dataSource
table.addSearchBar(searchResultTableView:
BlockTableView (frame: self.view.frame,
numberOfRowsInSection: { (section) -> Int in
return filtered.count
},
cellForRowAtIndexPath: { (tableView, indexPath) -> UITableViewCell in
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = filtered[indexPath.row]
return cell
},
didSelectRowAtIndexPath: { (tableView, indexPath) -> () in
return
}
), didSearch: { searchText in
filtered = filter (dataSource) { $0.rangeOfString(searchText) != nil }
}
)
// Add table to view
self.view.addSubview(table)
}
func createMultiSectionTableView () {
// Setup data source
var dataSource : [String:[String]] = [
"Section 1":["Cell 1", "Cell 2", "Cell 3", "Cell 4"],
"Section 2":["Cell 1", "Cell 2", "Cell 3", "Cell 4", "Cell 5"],
"Section 3":["Cell 1", "Cell 2", "Cell 3"]
]
// Create BlockTableView
let table = BlockTableView (frame: self.view.frame,
numberOfSections: dataSource.count,
titleForHeaderInSection: { (section) -> String in
return dataSource.keys.array[section]
},
numberOfRowsInSection: { (section) -> Int in
dataSource.values.array[section].count
},
cellForRowAtIndexPath: { (tableView, indexPath) -> UITableViewCell in
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let current = dataSource.values.array[indexPath.section][indexPath.row]
cell.textLabel?.text = current
return cell
},
didSelectRowAtIndexPath: { (tableView, indexPath) -> () in
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let selected = dataSource.values.array[indexPath.section][indexPath.row]
println("\(selected) selected")
}
)
// Add table to view
self.view.addSubview(table)
}
}
|
mit
|
8cf491b2aac1b872e97dc8870a6f04b6
| 34.913793 | 126 | 0.538166 | 5.754144 | false | false | false | false |
krzysztofzablocki/Sourcery
|
Templates/Tests/TemplatesTests.swift
|
1
|
5464
|
import Foundation
import Quick
import Nimble
#if SWIFT_PACKAGE
import PathKit
#endif
class TemplatesTests: QuickSpec {
#if SWIFT_PACKAGE
override class func setUp() {
super.setUp()
print("Generating sources...", terminator: " ")
let buildDir: Path
// Xcode + SPM
if let xcTestBundlePath = ProcessInfo.processInfo.environment["XCTestBundlePath"] {
buildDir = Path(xcTestBundlePath).parent()
} else {
// SPM only
buildDir = Path(Bundle.module.bundlePath).parent()
}
let sourcery = buildDir + "sourcery"
let resources = Bundle.module.resourcePath!
let outputDirectory = Path(resources) + "Generated"
if outputDirectory.exists {
do {
try outputDirectory.delete()
} catch {
print(error)
}
}
var output: String?
buildDir.chdir {
output = launch(
sourceryPath: sourcery,
args: [
"--sources",
"\(resources)/Context",
"--templates",
"\(resources)/Templates",
"--output",
"\(resources)/Generated",
"--disableCache",
"--verbose"
]
)
}
if let output = output {
print(output)
} else {
print("Done!")
}
}
#endif
override func spec() {
func check(template name: String) {
guard let generatedFilePath = path(forResource: "\(name).generated", ofType: "swift", in: "Generated") else {
fatalError("Template \(name) can not be checked as the generated file is not presented in the bundle")
}
guard let expectedFilePath = path(forResource: name, ofType: "expected", in: "Expected") else {
fatalError("Template \(name) can not be checked as the expected file is not presented in the bundle")
}
guard let generatedFileString = try? String(contentsOfFile: generatedFilePath) else {
fatalError("Template \(name) can not be checked as the generated file can not be read")
}
guard let expectedFileString = try? String(contentsOfFile: expectedFilePath) else {
fatalError("Template \(name) can not be checked as the expected file can not be read")
}
let emptyLinesFilter: (String) -> Bool = { line in return !line.isEmpty }
let commentLinesFilter: (String) -> Bool = { line in return !line.hasPrefix("//") }
let generatedFileLines = generatedFileString.components(separatedBy: .newlines).filter(emptyLinesFilter)
let generatedFileFilteredLines = generatedFileLines.filter(emptyLinesFilter).filter(commentLinesFilter)
let expectedFileLines = expectedFileString.components(separatedBy: .newlines)
let expectedFileFilteredLines = expectedFileLines.filter(emptyLinesFilter).filter(commentLinesFilter)
expect(generatedFileFilteredLines).to(equal(expectedFileFilteredLines))
}
describe("AutoCases template") {
it("generates expected code") {
check(template: "AutoCases")
}
}
describe("AutoEquatable template") {
it("generates expected code") {
check(template: "AutoEquatable")
}
}
describe("AutoHashable template") {
it("generates expected code") {
check(template: "AutoHashable")
}
}
describe("AutoLenses template") {
it("generates expected code") {
check(template: "AutoLenses")
}
}
describe("AutoMockable template") {
it("generates expected code") {
check(template: "AutoMockable")
}
}
describe("LinuxMain template") {
it("generates expected code") {
check(template: "LinuxMain")
}
}
describe("AutoCodable template") {
it("generates expected code") {
check(template: "AutoCodable")
}
}
}
private func path(forResource name: String, ofType ext: String, in dirName: String) -> String? {
#if SWIFT_PACKAGE
if let resources = Bundle.module.resourcePath {
return resources + "/\(dirName)/\(name).\(ext)"
}
return nil
#else
let bundle = Bundle.init(for: type(of: self))
return bundle.path(forResource: name, ofType: ext)
#endif
}
#if SWIFT_PACKAGE
private static func launch(sourceryPath: Path, args: [String]) -> String? {
let process = Process()
let output = Pipe()
process.launchPath = sourceryPath.string
process.arguments = args
process.standardOutput = output
do {
try process.run()
process.waitUntilExit()
if process.terminationStatus == 0 {
return nil
}
return String(data: output.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)
} catch {
return "error: can't run Sourcery from the \(sourceryPath.parent().string)"
}
}
#endif
}
|
mit
|
affde39d071f2e5fc492b22214ad2988
| 32.728395 | 121 | 0.551794 | 5.174242 | false | false | false | false |
BrantSteven/SinaProject
|
BSweibo/BSweibo/class/main/QRCodeViewController.swift
|
1
|
7921
|
//
// QRCodeViewController.swift
// BSweibo
//
// Created by 驴徒 on 16/8/2.
// Copyright © 2016年 白霜. All rights reserved.
//
import UIKit
import AVFoundation
class QRCodeViewController: UIViewController,UITabBarDelegate{
@IBOutlet weak var waveImageView: UIImageView!//冲击波视图
@IBOutlet weak var scanHeightCons: NSLayoutConstraint!//容器的高约束
@IBOutlet weak var waveTopCons: NSLayoutConstraint!//波的高约束
@IBOutlet weak var successLabel: UILabel!
@IBOutlet weak var customTabBar: UITabBar!
@IBAction func dismiss(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
//监听名片按钮点击
@IBAction func MyCardClick(_ sender: AnyObject) {
let QRView = QRViewController()
self.navigationController?.pushViewController(QRView, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
customTabBar.selectedItem = customTabBar.items![0]
customTabBar.delegate = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//1.开始冲击波动画
startAnimation()
//2.开始扫描
startScan()
}
//开始扫描二维码
func startScan(){
//1.判断我们是否能够将输入添加到会话中
if !session.canAddInput(deviceInput) {
return
}
//2.判断我们是否能够将输出添加到会话中
if !session.canAddOutput(output) {
return
}
//3.将输入和输出都添加到会话中
session.addInput(deviceInput)
session.addOutput(output)
//4.设置输出能够解析的数据类型
//注意:设置能够解析的数据类型 一定要在输出对象添加到会话之后设置 否则会报错
output.metadataObjectTypes = output.availableMetadataObjectTypes
//5.设置输出对象的代理方法 只要解析成功就会通知代理
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
//系统自带的二维码不允许只扫描一个 如果你想扫描一个 下面操作
//output.rectOfInterest = CGRectMake(0.5, 0.5, 0.5, 0.5) 扫描的区间不能保证只扫描一个 可以设置感兴趣的区域
//6.添加预览图层
view.layer.insertSublayer(previewLayer,at: 0)
//将绘制的图层添加到预览的图层上(绘制图层后添加的)
previewLayer.addSublayer(drawLayer)
//7.告诉session开始扫描
session.startRunning()
}
fileprivate func startAnimation()//开始动画
{
// 让约束从顶部开始
self.waveTopCons.constant = -self.scanHeightCons.constant
self.waveImageView.layoutIfNeeded()
// 执行冲击波动画
UIView.animate(withDuration: 2.0, animations: { () -> Void in
// 1.修改约束
self.waveTopCons.constant = self.scanHeightCons.constant
// 设置动画指定的次数
UIView.setAnimationRepeatCount(MAXFLOAT)
// 2.强制更新界面
self.waveImageView.layoutIfNeeded()
})
}
// MARK: - UITabBarDelegate
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
// 1.修改容器的高度
if item.tag == 1{
//print("二维码")
self.scanHeightCons.constant = 300
}else{
print("条形码")
self.scanHeightCons.constant = 150
}
// 2.停止动画
self.waveImageView.layer.removeAllAnimations()
// 3.重新开始动画
startAnimation()
}
//MARK:-懒加载
//会话
fileprivate lazy var session: AVCaptureSession = AVCaptureSession()//(懒加载只创建对象的简便方法)
//拿到输入设备
fileprivate lazy var deviceInput:AVCaptureDeviceInput? = {
//获取摄像头
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
/// 创建输入对象(成功)
let input = try AVCaptureDeviceInput.init(device: device)
return input
}catch{
print(error)//打印错误信息
return nil //可选值才能输出nil
}
}()
//拿到输出对象
fileprivate lazy var output:AVCaptureMetadataOutput = AVCaptureMetadataOutput()
//创建预览图层
fileprivate lazy var previewLayer:AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer.init(session: self.session)
layer?.frame = UIScreen.main.bounds
return layer!
}()
//创建用于绘制边线的图层
fileprivate lazy var drawLayer:CALayer = {
let layer = CALayer()
layer.frame = UIScreen.main.bounds
return layer
}()
}
extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate
{
//只要解析到数据就会掉用
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
//0.清空图层
clearConers()
//1.获取扫描的数据
successLabel.text = (metadataObjects.last as AnyObject).stringValue
successLabel.sizeToFit()
//2 获取扫描的位置
//2.1 转化坐标
// print(metadataObjects.last)
for object in metadataObjects
{
print(object)
//2.1.1判断当前获取的数据 是否时机器可识别的类型
if object is AVMetadataMachineReadableCodeObject {
//2.1.2将坐标转化为界面可识别的坐标
let codeObject = previewLayer.transformedMetadataObject(for: object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
//2.3.1绘制图形
drawCorner(codeObject)
}
}
}
fileprivate func drawCorner(_ codeObject:AVMetadataMachineReadableCodeObject){//绘制图形 (codeObject 中保存了坐标对象)
if codeObject.corners.isEmpty {
return
}
//1.创建一个图层
let layer = CAShapeLayer()
layer.lineWidth = 4
layer.strokeColor = UIColor.red.cgColor
layer.fillColor = UIColor.clear.cgColor
//2.创建路径
let path = UIBezierPath()
var point = CGPoint.zero
var index:Int = 0
//2.1移动到第一个点
// print(codeObject.corners.last)
//从corners数组中取出第0个元素 将这个字典中的x/y赋值给Point
/*
CGPoint.init(CGPointMakeWithDictionaryRepresentation((codeObject.corners[var inde=index+1] as! CFDictionary),&point))
path.move(to: point)
//2.2移动到其他的点
while index < codeObject.corners.count {
dictionaryRepresentation:CGPoint.init(CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionary),&point));
path.addLine(to: point)
}
*/
//2.3关闭路径
path.close()
//2.4 绘制路径
layer.path = path.cgPath
//3.将配置好的图层添加到drawLayer上
drawLayer.addSublayer(layer)
}
//清空边线
fileprivate func clearConers(){
//1.判断drawLayer上是否有其他图层
if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0 {
return
}
//2.移除所有子视图
for subLayer in drawLayer.sublayers! {
subLayer.removeFromSuperlayer()
}
}
}
|
mit
|
ebcad0da1b761c05a8d562e21c72038b
| 32.352941 | 148 | 0.605232 | 4.476316 | false | false | false | false |
mutualmobile/VIPER-SWIFT
|
VIPER-SWIFT/Classes/Modules/List/Application Logic/Interactor/ListInteractor.swift
|
1
|
1440
|
//
// ListInteractor.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/5/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
class ListInteractor : NSObject, ListInteractorInput {
var output : ListInteractorOutput?
let clock : Clock
let dataManager : ListDataManager
init(dataManager: ListDataManager, clock: Clock) {
self.dataManager = dataManager
self.clock = clock
}
// MARK: ListInteractorInput
func findUpcomingItems() {
let today = clock.today()
let endOfNextWeek = Calendar.current.dateForEndOfFollowingWeekWithDate(today)
dataManager.todoItemsBetweenStartDate(today,
endDate: endOfNextWeek,
completion: { todoItems in
let upcomingItems = self.upcomingItemsFromToDoItems(todoItems)
self.output?.foundUpcomingItems(upcomingItems)
})
}
func upcomingItemsFromToDoItems(_ todoItems: [TodoItem]) -> [UpcomingItem] {
let calendar = Calendar.autoupdatingCurrent
let upcomingItems: [UpcomingItem] = todoItems.map() { todoItem in
let dateRelation = calendar.nearTermRelationForDate(todoItem.dueDate, relativeToToday: clock.today())
return UpcomingItem(title: todoItem.name, dueDate: todoItem.dueDate, dateRelation: dateRelation)
}
return upcomingItems
}
}
|
mit
|
4e70c6a533bf83ea18675302cbea60eb
| 31 | 113 | 0.661806 | 4.8 | false | false | false | false |
GraphQLSwift/Graphiti
|
Sources/Graphiti/Subscription/SubscribeField.swift
|
1
|
28412
|
import GraphQL
import NIO
// Subscription resolver MUST return an Observer<Any>, not a specific type, due to lack of support for covariance generics in Swift
public class SubscriptionField<
SourceEventType,
ObjectType,
Context,
FieldType,
Arguments: Decodable
>: FieldComponent<ObjectType, Context> {
let name: String
let arguments: [ArgumentComponent<Arguments>]
let resolve: AsyncResolve<SourceEventType, Context, Arguments, Any?>
let subscribe: AsyncResolve<ObjectType, Context, Arguments, EventStream<SourceEventType>>
override func field(
typeProvider: TypeProvider,
coders: Coders
) throws -> (String, GraphQLField) {
let field = GraphQLField(
type: try typeProvider.getOutputType(from: FieldType.self, field: name),
description: description,
deprecationReason: deprecationReason,
args: try arguments(typeProvider: typeProvider, coders: coders),
resolve: { source, arguments, context, eventLoopGroup, _ in
guard let _source = source as? SourceEventType else {
throw GraphQLError(
message: "Expected source type \(SourceEventType.self) but got \(type(of: source))"
)
}
guard let _context = context as? Context else {
throw GraphQLError(
message: "Expected context type \(Context.self) but got \(type(of: context))"
)
}
let args = try coders.decoder.decode(Arguments.self, from: arguments)
return try self.resolve(_source)(_context, args, eventLoopGroup)
},
subscribe: { source, arguments, context, eventLoopGroup, _ in
guard let _source = source as? ObjectType else {
throw GraphQLError(
message: "Expected source type \(ObjectType.self) but got \(type(of: source))"
)
}
guard let _context = context as? Context else {
throw GraphQLError(
message: "Expected context type \(Context.self) but got \(type(of: context))"
)
}
let args = try coders.decoder.decode(Arguments.self, from: arguments)
return try self.subscribe(_source)(_context, args, eventLoopGroup)
.map { $0.map { $0 as Any } }
}
)
return (name, field)
}
func arguments(typeProvider: TypeProvider, coders: Coders) throws -> GraphQLArgumentConfigMap {
var map: GraphQLArgumentConfigMap = [:]
for argument in arguments {
let (name, argument) = try argument.argument(typeProvider: typeProvider, coders: coders)
map[name] = argument
}
return map
}
init(
name: String,
arguments: [ArgumentComponent<Arguments>],
resolve: @escaping AsyncResolve<SourceEventType, Context, Arguments, Any?>,
subscribe: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
self.name = name
self.arguments = arguments
self.resolve = resolve
self.subscribe = subscribe
}
convenience init<ResolveType>(
name: String,
arguments: [ArgumentComponent<Arguments>],
asyncResolve: @escaping AsyncResolve<SourceEventType, Context, Arguments, ResolveType>,
asyncSubscribe: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let resolve: AsyncResolve<SourceEventType, Context, Arguments, Any?> = { type in
{ context, arguments, eventLoopGroup in
try asyncResolve(type)(context, arguments, eventLoopGroup).map { $0 }
}
}
self.init(name: name, arguments: arguments, resolve: resolve, subscribe: asyncSubscribe)
}
convenience init(
name: String,
arguments: [ArgumentComponent<Arguments>],
as _: FieldType.Type,
asyncSubscribe: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let resolve: AsyncResolve<SourceEventType, Context, Arguments, Any?> = { source in
{ _, _, eventLoopGroup in
eventLoopGroup.next().makeSucceededFuture(source)
}
}
self.init(name: name, arguments: arguments, resolve: resolve, subscribe: asyncSubscribe)
}
convenience init<ResolveType>(
name: String,
arguments: [ArgumentComponent<Arguments>],
simpleAsyncResolve: @escaping SimpleAsyncResolve<
SourceEventType,
Context,
Arguments,
ResolveType
>,
simpleAsyncSubscribe: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let asyncResolve: AsyncResolve<SourceEventType, Context, Arguments, ResolveType> = { type in
{ context, arguments, group in
// We hop to guarantee that the future will
// return in the same event loop group of the execution.
try simpleAsyncResolve(type)(context, arguments).hop(to: group.next())
}
}
let asyncSubscribe: AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
> = { type in
{ context, arguments, group in
// We hop to guarantee that the future will
// return in the same event loop group of the execution.
try simpleAsyncSubscribe(type)(context, arguments).hop(to: group.next())
}
}
self.init(
name: name,
arguments: arguments,
asyncResolve: asyncResolve,
asyncSubscribe: asyncSubscribe
)
}
convenience init(
name: String,
arguments: [ArgumentComponent<Arguments>],
as: FieldType.Type,
simpleAsyncSubscribe: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let asyncSubscribe: AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
> = { type in
{ context, arguments, group in
// We hop to guarantee that the future will
// return in the same event loop group of the execution.
try simpleAsyncSubscribe(type)(context, arguments).hop(to: group.next())
}
}
self.init(name: name, arguments: arguments, as: `as`, asyncSubscribe: asyncSubscribe)
}
convenience init<ResolveType>(
name: String,
arguments: [ArgumentComponent<Arguments>],
syncResolve: @escaping SyncResolve<SourceEventType, Context, Arguments, ResolveType>,
syncSubscribe: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let asyncResolve: AsyncResolve<SourceEventType, Context, Arguments, ResolveType> = { type in
{ context, arguments, group in
let result = try syncResolve(type)(context, arguments)
return group.next().makeSucceededFuture(result)
}
}
let asyncSubscribe: AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
> = { type in
{ context, arguments, group in
let result = try syncSubscribe(type)(context, arguments)
return group.next().makeSucceededFuture(result)
}
}
self.init(
name: name,
arguments: arguments,
asyncResolve: asyncResolve,
asyncSubscribe: asyncSubscribe
)
}
convenience init(
name: String,
arguments: [ArgumentComponent<Arguments>],
as: FieldType.Type,
syncSubscribe: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let asyncSubscribe: AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
> = { type in
{ context, arguments, group in
let result = try syncSubscribe(type)(context, arguments)
return group.next().makeSucceededFuture(result)
}
}
self.init(name: name, arguments: arguments, as: `as`, asyncSubscribe: asyncSubscribe)
}
}
// MARK: AsyncResolve Initializers
public extension SubscriptionField where FieldType: Encodable {
convenience init(
_ name: String,
at function: @escaping AsyncResolve<SourceEventType, Context, Arguments, FieldType>,
atSub subFunc: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
asyncResolve: function,
asyncSubscribe: subFunc
)
}
convenience init(
_ name: String,
at function: @escaping AsyncResolve<SourceEventType, Context, Arguments, FieldType>,
atSub subFunc: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(
name: name,
arguments: arguments(),
asyncResolve: function,
asyncSubscribe: subFunc
)
}
}
public extension SubscriptionField {
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], as: `as`, asyncSubscribe: subFunc)
}
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(name: name, arguments: arguments(), as: `as`, asyncSubscribe: subFunc)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping AsyncResolve<SourceEventType, Context, Arguments, ResolveType>,
atSub subFunc: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
asyncResolve: function,
asyncSubscribe: subFunc
)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping AsyncResolve<SourceEventType, Context, Arguments, ResolveType>,
atSub subFunc: @escaping AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(
name: name,
arguments: arguments(),
asyncResolve: function,
asyncSubscribe: subFunc
)
}
}
// MARK: SimpleAsyncResolve Initializers
public extension SubscriptionField where FieldType: Encodable {
convenience init(
_ name: String,
at function: @escaping SimpleAsyncResolve<SourceEventType, Context, Arguments, FieldType>,
atSub subFunc: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
simpleAsyncResolve: function,
simpleAsyncSubscribe: subFunc
)
}
convenience init(
_ name: String,
at function: @escaping SimpleAsyncResolve<SourceEventType, Context, Arguments, FieldType>,
atSub subFunc: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(
name: name,
arguments: arguments(),
simpleAsyncResolve: function,
simpleAsyncSubscribe: subFunc
)
}
}
public extension SubscriptionField {
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], as: `as`, simpleAsyncSubscribe: subFunc)
}
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(name: name, arguments: arguments(), as: `as`, simpleAsyncSubscribe: subFunc)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping SimpleAsyncResolve<SourceEventType, Context, Arguments, ResolveType>,
as: FieldType.Type,
atSub subFunc: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
simpleAsyncResolve: function,
simpleAsyncSubscribe: subFunc
)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping SimpleAsyncResolve<SourceEventType, Context, Arguments, ResolveType>,
as: FieldType.Type,
atSub subFunc: @escaping SimpleAsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(
name: name,
arguments: arguments(),
simpleAsyncResolve: function,
simpleAsyncSubscribe: subFunc
)
}
}
// MARK: SyncResolve Initializers
public extension SubscriptionField where FieldType: Encodable {
convenience init(
_ name: String,
at function: @escaping SyncResolve<SourceEventType, Context, Arguments, FieldType>,
atSub subFunc: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
syncResolve: function,
syncSubscribe: subFunc
)
}
convenience init(
_ name: String,
at function: @escaping SyncResolve<SourceEventType, Context, Arguments, FieldType>,
atSub subFunc: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(name: name, arguments: arguments(), syncResolve: function, syncSubscribe: subFunc)
}
}
public extension SubscriptionField {
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], as: `as`, syncSubscribe: subFunc)
}
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(name: name, arguments: arguments(), as: `as`, syncSubscribe: subFunc)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping SyncResolve<SourceEventType, Context, Arguments, ResolveType>,
as: FieldType.Type,
atSub subFunc: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
syncResolve: function,
syncSubscribe: subFunc
)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping SyncResolve<SourceEventType, Context, Arguments, ResolveType>,
as: FieldType.Type,
atSub subFunc: @escaping SyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(name: name, arguments: arguments(), syncResolve: function, syncSubscribe: subFunc)
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
public extension SubscriptionField {
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init<ResolveType>(
name: String,
arguments: [ArgumentComponent<Arguments>],
concurrentResolve: @escaping ConcurrentResolve<
SourceEventType,
Context,
Arguments,
ResolveType
>,
concurrentSubscribe: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let asyncResolve: AsyncResolve<SourceEventType, Context, Arguments, ResolveType> =
{ type in
{ context, arguments, eventLoopGroup in
let promise = eventLoopGroup.next().makePromise(of: ResolveType.self)
promise.completeWithTask {
try await concurrentResolve(type)(context, arguments)
}
return promise.futureResult
}
}
let asyncSubscribe: AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
> = { type in
{ context, arguments, eventLoopGroup in
let promise = eventLoopGroup.next()
.makePromise(of: EventStream<SourceEventType>.self)
promise.completeWithTask {
try await concurrentSubscribe(type)(context, arguments)
}
return promise.futureResult
}
}
self.init(
name: name,
arguments: arguments,
asyncResolve: asyncResolve,
asyncSubscribe: asyncSubscribe
)
}
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init(
name: String,
arguments: [ArgumentComponent<Arguments>],
as: FieldType.Type,
concurrentSubscribe: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>
) {
let asyncSubscribe: AsyncResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
> = { type in
{ context, arguments, eventLoopGroup in
let promise = eventLoopGroup.next()
.makePromise(of: EventStream<SourceEventType>.self)
promise.completeWithTask {
try await concurrentSubscribe(type)(context, arguments)
}
return promise.futureResult
}
}
self.init(name: name, arguments: arguments, as: `as`, asyncSubscribe: asyncSubscribe)
}
}
// MARK: ConcurrentResolve Initializers
public extension SubscriptionField where FieldType: Encodable {
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init(
_ name: String,
at function: @escaping ConcurrentResolve<
SourceEventType,
Context,
Arguments,
FieldType
>,
atSub subFunc: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
concurrentResolve: function,
concurrentSubscribe: subFunc
)
}
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init(
_ name: String,
at function: @escaping ConcurrentResolve<
SourceEventType,
Context,
Arguments,
FieldType
>,
atSub subFunc: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(
name: name,
arguments: arguments(),
concurrentResolve: function,
concurrentSubscribe: subFunc
)
}
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [arguments()], as: `as`, concurrentSubscribe: subFunc)
}
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init(
_ name: String,
as: FieldType.Type,
atSub subFunc: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(name: name, arguments: arguments(), as: `as`, concurrentSubscribe: subFunc)
}
}
public extension SubscriptionField {
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init<ResolveType>(
_ name: String,
at function: @escaping ConcurrentResolve<
SourceEventType,
Context,
Arguments,
ResolveType
>,
as: FieldType.Type,
atSub subFunc: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(
name: name,
arguments: [argument()],
concurrentResolve: function,
concurrentSubscribe: subFunc
)
}
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
convenience init<ResolveType>(
_ name: String,
at function: @escaping ConcurrentResolve<
SourceEventType,
Context,
Arguments,
ResolveType
>,
as: FieldType.Type,
atSub subFunc: @escaping ConcurrentResolve<
ObjectType,
Context,
Arguments,
EventStream<SourceEventType>
>,
@ArgumentComponentBuilder<Arguments> _ arguments: ()
-> [ArgumentComponent<Arguments>] = { [] }
) {
self.init(
name: name,
arguments: arguments(),
concurrentResolve: function,
concurrentSubscribe: subFunc
)
}
}
#endif
// TODO: Determine if we can use keypaths to initialize
// MARK: Keypath Initializers
// public extension SubscriptionField where Arguments == NoArguments {
// convenience init(
// _ name: String,
// at keyPath: KeyPath<ObjectType, FieldType>
// ) {
// let syncResolve: SyncResolve<Any, Context, Arguments, ResolveType> = { type in
// { context, _ in
// type[keyPath: keyPath]
// }
// }
//
// self.init(name: name, arguments: [], syncResolve: syncResolve)
// }
// }
//
// public extension SubscriptionField where Arguments == NoArguments {
// convenience init<ResolveType>(
// _ name: String,
// at keyPath: KeyPath<ObjectType, ResolveType>,
// as: FieldType.Type
// ) {
// let syncResolve: SyncResolve<ObjectType, Context, NoArguments, ResolveType> = { type in
// return { context, _ in
// return type[keyPath: keyPath]
// }
// }
//
// self.init(name: name, arguments: [], syncResolve: syncResolve)
// }
// }
|
mit
|
dc503d4062cd8e09b7dfdfba932e52cb
| 32.152859 | 131 | 0.546917 | 5.274179 | false | false | false | false |
nmdias/FeedParser
|
Sources/Model/RSS/RSSPath.swift
|
2
|
7344
|
//
// RSSPath.swift
//
// Copyright (c) 2016 Nuno Manuel Dias
//
// 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
/**
Describes the individual path for each XML DOM element of an RSS feed
See http://web.resource.org/rss/1.0/modules/content/
*/
enum RSSPath: String {
case RSS = "/rss"
case RSSChannel = "/rss/channel"
case RSSChannelTitle = "/rss/channel/title"
case RSSChannelLink = "/rss/channel/link"
case RSSChannelDescription = "/rss/channel/description"
case RSSChannelLanguage = "/rss/channel/language"
case RSSChannelCopyright = "/rss/channel/copyright"
case RSSChannelManagingEditor = "/rss/channel/managingEditor"
case RSSChannelWebMaster = "/rss/channel/webMaster"
case RSSChannelPubDate = "/rss/channel/pubDate"
case RSSChannelLastBuildDate = "/rss/channel/lastBuildDate"
case RSSChannelCategory = "/rss/channel/category"
case RSSChannelGenerator = "/rss/channel/generator"
case RSSChannelDocs = "/rss/channel/docs"
case RSSChannelCloud = "/rss/channel/cloud"
case RSSChannelRating = "/rss/channel/rating"
case RSSChannelTTL = "/rss/channel/ttl"
case RSSChannelImage = "/rss/channel/image"
case RSSChannelImageURL = "/rss/channel/image/url"
case RSSChannelImageTitle = "/rss/channel/image/title"
case RSSChannelImageLink = "/rss/channel/image/link"
case RSSChannelImageWidth = "/rss/channel/image/width"
case RSSChannelImageHeight = "/rss/channel/image/height"
case RSSChannelImageDescription = "/rss/channel/image/description"
case RSSChannelTextInput = "/rss/channel/textInput"
case RSSChannelTextInputTitle = "/rss/channel/textInput/title"
case RSSChannelTextInputDescription = "/rss/channel/textInput/description"
case RSSChannelTextInputName = "/rss/channel/textInput/name"
case RSSChannelTextInputLink = "/rss/channel/textInput/link"
case RSSChannelSkipHours = "/rss/channel/skipHours"
case RSSChannelSkipHoursHour = "/rss/channel/skipHours/hour"
case RSSChannelSkipDays = "/rss/channel/skipDays"
case RSSChannelSkipDaysDay = "/rss/channel/skipDays/day"
case RSSChannelItem = "/rss/channel/item"
case RSSChannelItemTitle = "/rss/channel/item/title"
case RSSChannelItemLink = "/rss/channel/item/link"
case RSSChannelItemDescription = "/rss/channel/item/description"
case RSSChannelItemAuthor = "/rss/channel/item/author"
case RSSChannelItemCategory = "/rss/channel/item/category"
case RSSChannelItemComments = "/rss/channel/item/comments"
case RSSChannelItemEnclosure = "/rss/channel/item/enclosure"
case RSSChannelItemGUID = "/rss/channel/item/guid"
case RSSChannelItemPubDate = "/rss/channel/item/pubDate"
case RSSChannelItemSource = "/rss/channel/item/source"
// Content
case RSSChannelItemContentEncoded = "/rss/channel/item/content:encoded"
// Syndication
case RSSChannelSyndicationUpdatePeriod = "/rss/channel/sy:updatePeriod"
case RSSChannelSyndicationUpdateFrequency = "/rss/channel/sy:updateFrequency"
case RSSChannelSyndicationUpdateBase = "/rss/channel/sy:updateBase"
// Dublin Core
case RSSChannelDublinCoreTitle = "/rss/channel/dc:title"
case RSSChannelDublinCoreCreator = "/rss/channel/dc:creator"
case RSSChannelDublinCoreSubject = "/rss/channel/dc:subject"
case RSSChannelDublinCoreDescription = "/rss/channel/dc:description"
case RSSChannelDublinCorePublisher = "/rss/channel/dc:publisher"
case RSSChannelDublinCoreContributor = "/rss/channel/dc:contributor"
case RSSChannelDublinCoreDate = "/rss/channel/dc:date"
case RSSChannelDublinCoreType = "/rss/channel/dc:type"
case RSSChannelDublinCoreFormat = "/rss/channel/dc:format"
case RSSChannelDublinCoreIdentifier = "/rss/channel/dc:identifier"
case RSSChannelDublinCoreSource = "/rss/channel/dc:source"
case RSSChannelDublinCoreLanguage = "/rss/channel/dc:language"
case RSSChannelDublinCoreRelation = "/rss/channel/dc:relation"
case RSSChannelDublinCoreCoverage = "/rss/channel/dc:coverage"
case RSSChannelDublinCoreRights = "/rss/channel/dc:rights"
case RSSChannelItemDublinCoreTitle = "/rss/channel/item/dc:title"
case RSSChannelItemDublinCoreCreator = "/rss/channel/item/dc:creator"
case RSSChannelItemDublinCoreSubject = "/rss/channel/item/dc:subject"
case RSSChannelItemDublinCoreDescription = "/rss/channel/item/dc:description"
case RSSChannelItemDublinCorePublisher = "/rss/channel/item/dc:publisher"
case RSSChannelItemDublinCoreContributor = "/rss/channel/item/dc:contributor"
case RSSChannelItemDublinCoreDate = "/rss/channel/item/dc:date"
case RSSChannelItemDublinCoreType = "/rss/channel/item/dc:type"
case RSSChannelItemDublinCoreFormat = "/rss/channel/item/dc:format"
case RSSChannelItemDublinCoreIdentifier = "/rss/channel/item/dc:identifier"
case RSSChannelItemDublinCoreSource = "/rss/channel/item/dc:source"
case RSSChannelItemDublinCoreLanguage = "/rss/channel/item/dc:language"
case RSSChannelItemDublinCoreRelation = "/rss/channel/item/dc:relation"
case RSSChannelItemDublinCoreCoverage = "/rss/channel/item/dc:coverage"
case RSSChannelItemDublinCoreRights = "/rss/channel/item/dc:rights"
}
|
mit
|
e22bd5983566e06700151e92f123e151
| 58.225806 | 89 | 0.648557 | 4.294737 | false | false | false | false |
alonecuzzo/Places
|
Places/PlacesViewController.swift
|
1
|
3954
|
//
// ViewController.swift
// Places
//
// Created by Jabari Bell on 11/2/15.
// Copyright © 2015 Code Mitten. All rights reserved.
//
import UIKit
import GoogleMaps
import CoreLocation
import SnapKit
struct PlacesViewModel {
//list of places -> just bind to this
//maybe we convert to our own place model object
var places = [GMSAutocompletePrediction]() //Model should be hidden
//binding for search
//internally updates places array
func placesForLocation(location: CLLocation, searchString string: String) {
}
//configureCellForRowAtindexPath
}
class PlacesViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource {
//MARK: Property
private let tableView = UITableView()
private let searchBar = UISearchBar()
private var places = [GMSAutocompletePrediction]()
private let CellIdentifier = "CellIdentifier"
private var placesClient: GMSPlacesClient?
//Testing @40.708882,-74.0136213
private let paperlessPostLocation = CLLocation(latitude: 40.708882, longitude: -74.0136213)
//MARK: Method
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup() -> Void {
view.addSubview(tableView)
tableView.tableHeaderView = searchBar
tableView.dataSource = self
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)
tableView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(view)
}
searchBar.snp_makeConstraints { (make) -> Void in
make.left.right.equalTo(view)
make.top.equalTo(0)
make.height.equalTo(55)
}
searchBar.delegate = self
//places stuff -> viewmodel / services
placesClient = GMSPlacesClient()
}
//MARK: TableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return places.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier)
cell!.textLabel?.attributedText = places[indexPath.row].attributedFullText
return cell!
}
//MARK: SearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) -> Void {
let northEast = CLLocationCoordinate2DMake(paperlessPostLocation.coordinate.latitude + 1, paperlessPostLocation.coordinate.longitude + 1)
let southWest = CLLocationCoordinate2DMake(paperlessPostLocation.coordinate.latitude - 1, paperlessPostLocation.coordinate.longitude - 1)
let bounds = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let filter = GMSAutocompleteFilter()
filter.type = GMSPlacesAutocompleteTypeFilter.Establishment
if searchText.characters.count > 0 {
print("Searching for '\(searchText)'")
placesClient?.autocompleteQuery(searchText, bounds: bounds, filter: filter, callback: { (results, error) -> Void in
if error != nil {
print("Autocomplete error \(error) for query '\(searchText)'")
return
}
print("Populating results for query '\(searchText)'")
self.places = [GMSAutocompletePrediction]()
for result in results! {
if let result = result as? GMSAutocompletePrediction {
self.places.append(result)
}
}
self.tableView.reloadData()
})
} else {
self.places = [GMSAutocompletePrediction]()
self.tableView.reloadData()
}
}
}
|
mit
|
d5893869b762fd889eb13c9a83d0dc2d
| 33.982301 | 145 | 0.63572 | 5.392906 | false | false | false | false |
payjp/payjp-ios
|
Sources/Networking/Core/APIError.swift
|
1
|
3324
|
//
// APIError.swift
// PAYJP
//
// Created by [email protected] on 10/4/16.
// Copyright © 2016 PAY, Inc. All rights reserved.
//
import Foundation
#if canImport(PassKit)
import PassKit
protocol NSErrorSerializable: Error {
var errorCode: Int { get }
var errorDescription: String? { get }
var userInfo: [String: Any] { get }
}
extension NSErrorSerializable {
var userInfo: [String: Any] {
return [String: Any]()
}
}
/// API error types.
public enum APIError: LocalizedError, NSErrorSerializable {
/// The Apple Pay token is invalid.
case invalidApplePayToken(PKPaymentToken)
/// The system error.
case systemError(Error)
/// No body data or no response error.
case invalidResponse(HTTPURLResponse?)
/// The error response object that is coming back from the server side.
case serviceError(PAYErrorResponseType)
/// Invalid JSON object.
case invalidJSON(Data, Error?)
/// Too many requests in a short period of time.
case rateLimitExceeded
// MARK: - LocalizedError
public var errorDescription: String? {
switch self {
case .invalidApplePayToken:
return "Invalid Apple Pay Token"
case .systemError(let error):
return error.localizedDescription
case .invalidResponse:
return "The response is not a HTTPURLResponse instance."
case .serviceError(let errorResponse):
return errorResponse.message
case .invalidJSON:
return "Unable parse JSON object into expected classes."
case .rateLimitExceeded:
return "Request throttled due to excessive requests."
}
}
public var errorCode: Int {
switch self {
case .invalidApplePayToken:
return PAYErrorInvalidApplePayToken
case .systemError:
return PAYErrorSystemError
case .invalidResponse:
return PAYErrorInvalidResponse
case .serviceError:
return PAYErrorServiceError
case .invalidJSON:
return PAYErrorInvalidJSON
case .rateLimitExceeded:
return PAYErrorRateLimitExceeded
}
}
public var userInfo: [String: Any] {
var userInfo = [String: Any]()
switch self {
case .invalidApplePayToken(let token):
userInfo[PAYErrorInvalidApplePayTokenObject] = token
case .systemError(let error):
userInfo[PAYErrorSystemErrorObject] = error
case .invalidResponse(let response):
userInfo[PAYErrorInvalidResponseObject] = response
case .serviceError(let errorResponse):
userInfo[PAYErrorServiceErrorObject] = errorResponse
case .invalidJSON(let json, let error):
userInfo[PAYErrorInvalidJSONObject] = json
if error != nil {
userInfo[PAYErrorInvalidJSONErrorObject] = error
}
case .rateLimitExceeded: break
}
return userInfo
}
// MARK: - NSError helper
/// Returns error response object if the type is `.serviceError`.
public var payError: PAYErrorResponseType? {
switch self {
case .serviceError(let errorResponse):
return errorResponse
default:
return nil
}
}
}
#endif
|
mit
|
22c4a3f5e967ce3d9a82c7cd101f2db2
| 29.209091 | 75 | 0.636774 | 5.042489 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.