repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
IAskWind/IAWExtensionTool
|
IAWExtensionTool/IAWExtensionTool/Classes/Tool/IAW_WebViewTool.swift
|
1
|
1768
|
//
// IAW_WebViewTool.swift
// IAWExtensionTool
//
// Created by winston on 17/1/6.
// Copyright © 2017年 winston. All rights reserved.
//
import Foundation
import ObjectMapper
open class IAW_WebViewTool{
open class func webViewLoadUrl(webView:UIWebView,urlStr:String) {
let accessToken = UserDefaults.standard.string(forKey:IAW_AccessToken) != nil ? UserDefaults.standard.string(forKey: IAW_AccessToken)! : "";
webView.iawLoadUrlByHeader(url: urlStr, headers: [accessToken : IAW_AccessToken])
}
open class func webViewDealValidateToken(webView:UIWebView){
webView.isHidden = true
let str = webView.iawGetContentStr()
if let msgModel = Mapper<IAW_ResponseMsgModel>().map(JSONString: str!){
//
if IAW_TokenTool.tokenDeal(tokenInvalid: msgModel.tokenInvalid){
IAW_ProgressHUDTool.showErrorInfo(msg: msgModel.msg)
return
}
// if WBNetworkTool.shareNetworkTool.vipDeal(vipInvalid: msgModel.vipInvalid,msg: msgModel.msg){
// return
// }
}
webView.isHidden = false
}
open class func webViewNoTokenLoadUrl(webView:UIWebView,urlStr:String) {
//处理中文参数,报错的问题,进行url编码
let urlS = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(urlS as Any)
let request = URLRequest(url: URL(string: urlS!)!)
// request.addValue(UserDefaults.standard.string(forKey: accessToken) != nil ? UserDefaults.standard.string(forKey: accessToken)! : "", forHTTPHeaderField: "accesstoken")
webView.loadRequest(request)
}
}
|
mit
|
f5baa3809f20909ff2bcc95e71f7292b
| 36.630435 | 185 | 0.639515 | 4.360202 | false | false | false | false |
anpavlov/swiftperl
|
Sources/Perl/Object.swift
|
1
|
6581
|
import CPerl
/// Provides a safe wrapper for Perl objects (blessed references).
/// Performs reference counting on initialization and deinitialization.
///
/// Any Perl object of unregistered type will be imported to Swift
/// as an instance of this class. To provide clean API to your
/// Perl object implement class derived from `PerlObject`, make it
/// conforming to `PerlNamedClass` and supply it with methods and
/// calculated attributes providing access to Perl methods of your
/// object. Use `register` method on startup to enable automatical
/// conversion of Perl objects of class `perlClassName` to instances
/// of your Swift class.
///
/// For example:
///
/// ```swift
/// final class URI : PerlObject, PerlNamedClass {
/// static let perlClassName = "URI"
///
/// convenience init(_ str: String) throws {
/// try self.init(method: "new", args: [str])
/// }
///
/// convenience init(_ str: String, scheme: String) throws {
/// try self.init(method: "new", args: [str, scheme])
/// }
///
/// convenience init(copyOf uri: URI) {
/// try! self.init(uri.call(method: "clone") as PerlScalar)
/// }
///
/// var scheme: String? { return try! call(method: "scheme") }
/// func scheme(_ scheme: String) throws -> String? { return try call(method: "scheme", scheme) }
///
/// var path: String {
/// get { return try! call(method: "path") }
/// set { try! call(method: "path", newValue) as Void }
/// }
///
/// var asString: String { return try! call(method: "as_string") }
///
/// func abs(base: String) -> String { return try! call(method: "abs", base) }
/// func rel(base: String) -> String { return try! call(method: "rel", base) }
///
/// var secure: Bool { return try! call(method: "secure") }
/// }
/// ```
open class PerlObject : PerlValue, PerlDerived {
public typealias UnsafeValue = UnsafeSV
convenience init(noinc sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
guard sv.pointee.isObject(perl: perl) else {
throw PerlError.notObject(fromUnsafeSvPointer(noinc: sv, perl: perl))
}
if let named = type(of: self) as? PerlNamedClass.Type {
guard sv.pointee.isDerived(from: named.perlClassName, perl: perl) else {
throw PerlError.unexpectedObjectType(fromUnsafeSvPointer(noinc: sv, perl: perl), want: type(of: self))
}
}
self.init(noincUnchecked: sv, perl: perl)
}
public convenience init(_ sv: PerlScalar) throws {
defer { _fixLifetime(sv) }
let (usv, perl) = sv.withUnsafeSvPointer { $0 }
try self.init(inc: usv, perl: perl)
}
var perlClassName: String {
return withUnsafeSvPointer { sv, perl in sv.pointee.classname(perl: perl)! }
}
var referent: AnyPerl {
return withUnsafeSvPointer { sv, perl in fromUnsafeSvPointer(inc: sv.pointee.referent!, perl: perl) }
}
/// A textual representation of the SV, suitable for debugging.
public override var debugDescription: String {
var rvDesc = ""
debugPrint(referent, terminator: "", to: &rvDesc)
return "\(type(of: self))(\(perlClassName), rv=\(rvDesc))"
}
static func derivedClass(for classname: String) -> PerlObject.Type {
return classMapping[classname] ?? PerlObject.self
}
static var classMapping = [String: PerlObject.Type ]()
/// Registers class `swiftClass` as a counterpart of Perl's class with name `classname`.
public static func register<T>(_ swiftClass: T.Type, as classname: String) where T : PerlObject, T : PerlNamedClass {
classMapping[classname] = swiftClass
}
}
/// A Swift class which instances can be passed to Perl as a blessed SV.
///
/// Implementing an object that conforms to `PerlBridgedObject` is simple.
/// Declare a `static var perlClassName` that contains a name of the Perl class
/// your Swift class should be bridged to. Use `addPerlMethod` method on
/// startup to provide ability to access your methods and attributes from Perl.
public protocol PerlBridgedObject : AnyPerl, PerlNamedClass, PerlSvConvertible {}
/// A class having Perl representation.
public protocol PerlNamedClass : class {
/// A name of the class in Perl.
static var perlClassName: String { get }
}
extension PerlNamedClass {
/// Loads the module which name is in `perlClassName` attribute.
public static func loadModule(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) {
perl.pointee.loadModule(perlClassName)
}
}
extension PerlNamedClass where Self : PerlObject {
/// Creates a new object by calling its Perl constructor.
///
/// The recomended way is to wrap this constructor
/// invocations by implementing more concrete initializers
/// which hide Perl method calling magic behind.
///
/// Let's imagine a class:
///
/// ```swift
/// final class URI : PerlObject, PerlNamedClass {
/// static let perlClassName = "URI"
///
/// convenience init(_ str: String) throws {
/// try self.init(method: "new", args: [str])
/// }
/// }
/// ```
///
/// Then Swift expression:
///
/// ```swift
/// let uri = URI("https://my.mail.ru/music")
/// ```
///
/// will be equal to Perl:
///
/// ```perl
/// my $uri = URI->new("https://my.mail.ru/music")
/// ```
///
/// - Parameter method: A name of the constuctor. Usually it is *new*.
/// - Parameter args: Arguments to pass to constructor.
public init(method: String, args: [PerlSvConvertible?], perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
perl.pointee.enterScope()
defer { perl.pointee.leaveScope() }
let classname = (type(of: self) as PerlNamedClass.Type).perlClassName
let args = [classname as PerlSvConvertible?] + args
let svArgs: [UnsafeSvPointer] = args.map { $0?.toUnsafeSvPointer(perl: perl) ?? perl.pointee.newSV() }
let sv = try perl.pointee.unsafeCall(sv: perl.pointee.newSV(method, mortal: true), args: svArgs, flags: G_METHOD|G_SCALAR)[0]
guard sv.pointee.isObject(perl: perl) else {
throw PerlError.notObject(fromUnsafeSvPointer(inc: sv, perl: perl))
}
guard sv.pointee.isDerived(from: classname, perl: perl) else {
throw PerlError.unexpectedObjectType(fromUnsafeSvPointer(inc: sv, perl: perl), want: Self.self)
}
self.init(incUnchecked: sv, perl: perl)
}
/// Registers this class as a counterpart of Perl class which name is provided in `perlClassName`.
public static func register() {
PerlObject.register(self, as: (self as PerlNamedClass.Type).perlClassName)
}
/// Assuming that the Perl class is in the module with the same name, loads it and registers.
public static func loadAndRegister(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) {
loadModule(perl: perl)
register()
}
}
|
mit
|
5f618c04f50a8ed7d6c7a6678666d985
| 36.180791 | 127 | 0.696703 | 3.253089 | false | false | false | false |
payjp/payjp-ios
|
Sources/Networking/Core/ParametersSerialization.swift
|
1
|
1423
|
//
// ParametersSerialization.swift
// PAYJP
//
// Created by Li-Hsuan Chen on 2019/07/24.
// Copyright © 2019 PAY, Inc. All rights reserved.
//
import Foundation
struct ParametersSerialization {
static func string(from parameters: [String: Any]) -> String {
let pairs = parameters.map { key, value -> String in
if value is NSNull {
return key
}
let valueString = (value as? String) ?? "\(value)"
return "\(escape(key))=\(escape(valueString))"
}
return pairs.joined(separator: "&")
}
private static func escape(_ string: String) -> String {
return string.addingPercentEncoding(withAllowedCharacters: .payUrlQueryAllowed) ?? string
}
}
extension CharacterSet {
/// RFC 3986 Section 2.2, Section 3.4
/// reserved = gen-delims / sub-delims
/// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
/// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
static let payUrlQueryAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // Remove "?" and "/" due to RFC3986, Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
}()
}
|
mit
|
37b136daa605f7c96d52527afaf6dcd2
| 33.682927 | 116 | 0.580169 | 4.429907 | false | false | false | false |
DataBreweryIncubator/StructuredQuery
|
Sources/Compiler/ResultString.swift
|
1
|
4121
|
import Basic
/// Type that wraps a string or a list of failures. `ResultString` is used for
/// constructing a result that is composed by concatenation of multiple
/// strings. Multiple errors might occur during the concatenation and they
/// gathered in the failure case of the object.
///
public enum ResultString<ErrorType> where ErrorType: Error {
case value(String)
case failure([ErrorType])
public init(error: ErrorType) {
self = .failure([error])
}
/// Is `true` if the receiver is a failure.
public var isFailure: Bool {
switch self {
case .value: return false
case .failure: return true
}
}
/// Get list of errors if the receiver is a failure, otherwise `nil`.
public var errors: [ErrorType] {
switch self {
case .value: return []
case .failure(let errors): return errors
}
}
/// Get strnig value of the receiver or `nil` if the receivers is a
/// failure.
public var string: String? {
switch self {
case let .value(str): return str
case .failure: return nil
}
}
/// Prefix the value with `left` and suffix with `right` when condition is
/// `true`.
public func wrap(left: String, right: String, when: Bool=false) -> ResultString {
switch self {
case let .value(str) where when == true: return .value(left + str + right)
default: return self
}
}
/// Pad the value with spaces on both sides.
public func pad() -> ResultString {
switch self {
case let .value(str): return .value(" \(str) ")
default: return self
}
}
}
extension ResultString: Concatenable {
/// Concatenate two results and produce another result string. If both
/// objects are string values, the result is a value of concatenated
/// strings. If one of the results is a failure, then result is concatenation
/// of the failures.
///
public func concatenate(_ other: ResultString<ErrorType>)
-> ResultString<ErrorType>
{
switch (self, other) {
case let (.value(lvalue), .value(rvalue)): return .value(lvalue + rvalue)
case let (.failure(error), .value(_)): return .failure(error)
case let (.value(_), .failure(error)): return .failure(error)
case let (.failure(lerror), .failure(rerror)): return .failure(lerror + rerror)
}
}
}
public func +<E: Error>(lhs: ResultString<E>, rhs: ResultString<E>) -> ResultString<E> {
return lhs.concatenate(rhs)
}
public func +<E: Error>(lhs: ResultString<E>, error: E) -> ResultString<E> {
switch lhs {
case .value: return .failure([error])
case .failure(let errors): return .failure(errors + [error])
}
}
public func +<E: Error>(lhs: ResultString<E>, string: String) -> ResultString<E> {
switch lhs {
case .value(let value): return .value(value + string)
case .failure: return lhs
}
}
public func +<E: Error>(string: String, rhs: ResultString<E>) -> ResultString<E> {
switch rhs {
case .value(let value): return .value(string + value)
case .failure: return rhs
}
}
public func +=<E: Error>(lhs: inout ResultString<E>, error: E) {
lhs = lhs + error
}
public func +=<E: Error>(lhs: inout ResultString<E>, string: String) {
lhs = lhs + string
}
public func +=<E: Error>(lhs: inout ResultString<E>, rhs: ResultString<E>) {
lhs = lhs + rhs
}
// Comparison
// TODO: Add error comparison
public func ==<E: Error>(lhs: ResultString<E>, string: String) -> Bool {
switch lhs {
case .value(let value) where value == string: return true
default: return false
}
}
extension ResultString: ExpressibleByStringLiteral {
public init(stringLiteral value: String.StringLiteralType) {
self = .value(value)
}
public init(extendedGraphemeClusterLiteral value:
String.ExtendedGraphemeClusterLiteralType){
self = .value(value)
}
public init(unicodeScalarLiteral value: String.UnicodeScalarLiteralType) {
self = .value(value)
}
}
|
mit
|
ac451f54a071a2e0bb2d65d4f6f5a14b
| 29.525926 | 88 | 0.629459 | 4.064103 | false | false | false | false |
Mikelulu/BaiSiBuDeQiJie
|
LKBS/LKBS/Classes/Other/AppDelegate.swift
|
1
|
2566
|
//
// AppDelegate.swift
// LKBS
//
// Created by admin on 2017/6/16.
// Copyright © 2017年 LK. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 11.0, *) {
UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
}
/// 两秒后启动app
// Thread.sleep(until: 2)
window = UIWindow()
window?.backgroundColor = UIColor.white
window?.frame = UIScreen.main.bounds
window?.rootViewController = LKTabbarController()
window?.makeKeyAndVisible()
UIApplication.shared.statusBarStyle = .lightContent
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
11d5fbfcff1dd63f96712365934fd791
| 40.177419 | 285 | 0.725813 | 5.55 | false | false | false | false |
yannickl/Splitflap
|
Sources/TokenGenerator.swift
|
1
|
2456
|
/*
* Splitflap
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.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
/**
A TokenGenerator helps the flap view by choosing the right token rescpecting the
initial order.
*/
final class TokenGenerator: IteratorProtocol {
typealias Element = String
let tokens: [String]
required init(tokens: [String]) {
self.tokens = tokens
}
// MARK: - Implementing GeneratorType
/// Current element index
fileprivate var currentIndex = 0
/// Returns the current element of the generator, nil otherwise.
var currentElement: Element? {
get {
if currentIndex < tokens.count {
return tokens[currentIndex]
}
return nil
}
set(newValue) {
if let value = newValue {
currentIndex = tokens.firstIndex(of: value) ?? currentIndex
}
else {
currentIndex = 0
}
}
}
/// Advance to the next element and return it, or `nil` if no next.
/// element exists.
@discardableResult
func next() -> Element? {
let tokenCount = tokens.count
guard tokenCount > 0 else {
return nil
}
currentIndex = (currentIndex + 1) % tokens.count
return tokens[currentIndex]
}
// MARK: - Convenience Methods
/// Returns the first token, or `nil` if no token.
var firstToken: String? {
get {
return tokens.first
}
}
}
|
mit
|
4ebab949752d92f8a9656d97d72a6d24
| 26.595506 | 81 | 0.693811 | 4.473588 | false | false | false | false |
jakubholik/mi-ios
|
mi-ios/GuideViewModel.swift
|
1
|
5367
|
//
// GuideViewModel.swift
//
//
// Created by Jakub Holík on 11.04.17.
// Copyright © 2017 Symphony No. 9 s.r.o. All rights reserved.
//
import Foundation
import RealmSwift
class GuideViewModel: NSObject {
var notificationToken: NotificationToken? = nil
var delegate: GuideViewController?
var realm: Realm?
var places: Results<Place>?
var placesMonitoringTimer = Timer()
@objc func loadPlacesToMapView(){
guard let delegate = delegate,
let places = places
else {
return
}
delegate.mapView.clear()
for i in 0..<places.count {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: places[i].latitude, longitude: places[i].longitude)
marker.title = places[i].title
marker.snippet = places[i].placeDescription
marker.userData = places[i]
switch(places[i].type){
case PlaceType.historic.rawValue:
marker.icon = UIImage(named: "map_pin")
marker.map = delegate.mapView
break
case PlaceType.sightseeing.rawValue:
marker.icon = UIImage(named: "map_marker")
marker.map = delegate.mapView
break
default:
break
}
}
}
@objc func loadDetailView(for place: Place){
guard let guideDetailViewController:GuideDetailViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "guideDetailView") as? GuideDetailViewController,
let delegate = delegate,
let navigationController = delegate.navigationController
else {
return
}
guideDetailViewController.title = place.title
guideDetailViewController.viewModel.delegate = guideDetailViewController
guideDetailViewController.viewModel.placeTitle = place.title
guideDetailViewController.viewModel.placeDescription = place.placeDescription
guideDetailViewController.viewModel.posts = place.posts
let backItem = UIBarButtonItem()
backItem.title = "MAP".localized()
guideDetailViewController.navigationItem.backBarButtonItem = backItem
navigationController.pushViewController(guideDetailViewController, animated: true)
}
@objc func loadPanoramaView(for place: Place){
guard let panoramaViewController:PanoramaViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "panoramaView") as? PanoramaViewController,
let delegate = delegate,
let navigationController = delegate.navigationController
else {
return
}
panoramaViewController.viewModel.place = place
panoramaViewController.viewModel.delegate = panoramaViewController
panoramaViewController.title = place.title
navigationController.pushViewController(panoramaViewController, animated: true)
}
func viewDidLoad(){
realm = try! Realm()
places = realm?.objects(Place.self)
notificationToken = places?.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
self?.loadPlacesToMapView()
break
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the UITableView
self?.loadPlacesToMapView()
break
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
break
}
}
if let delegate = delegate {
delegate.title = "MAP".localized()
guard let navController = delegate.navigationController,
let topItem = navController.navigationBar.topItem else {
return
}
navController.title = "MAP".localized()
topItem.title = "MAP".localized()
}
}
deinit {
notificationToken?.stop()
}
func monitorPointsDistance(){
//placesMonitoringTimer.invalidate()
placesMonitoringTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkPlacesDistance), userInfo: nil, repeats: true)
}
@objc private func checkPlacesDistance(){
guard let delegate = delegate,
let placesArray = places,
let userLocation = delegate.locationManager.location
else {
return
}
var alertPresented = false
var i: Int = 0
while !alertPresented && i < placesArray.count {
switch(placesArray[i].type){
case PlaceType.historic.rawValue:
if userLocation.distance(from: CLLocation(latitude: placesArray[i].latitude, longitude: placesArray[i].longitude)) < 50{
let alertController = UIAlertController(title: "POINT_NEARBY_HISTORIC".localized(), message: "POINT_NEARBY_HISTORIC_MESSAGE".localized(), preferredStyle: .alert)
let acceptAction = UIAlertAction(title: "YES".localized(), style: .default){
(result : UIAlertAction) -> Void in
self.loadDetailView(for: placesArray[i])
}
let declineAction = UIAlertAction(title: "NO".localized(), style: .destructive){
(result : UIAlertAction) -> Void in
}
alertController.addAction(acceptAction)
alertController.addAction(declineAction)
delegate.present(alertController, animated: true, completion: nil)
alertPresented = true
placesMonitoringTimer.invalidate()
} else {
i += 1
}
break
default:
i += 1
break
}
}
}
}
|
mit
|
8b4b13d94b2443cacd06fa1d3e6ef63f
| 25.170732 | 197 | 0.705499 | 4.181606 | false | false | false | false |
rmuhamedgaliev/IsoWorld
|
IsoWorld/IsoWorld/Scenes/Game/Game.swift
|
1
|
15712
|
//
// Game.swift
// IsoWorld
//
// Created by Rinat Muhamedgaliev on 5/22/16.
// Copyright © 2016 Rinat Muhamedgaliev. All rights reserved.
//
import UIKit
import SpriteKit
import AVFoundation
class GameScene: SKScene, SKPhysicsContactDelegate {
private var musicPlayer: AVAudioPlayer!
private var backButton: SKSpriteNode!
private let stopWatch = Stopwatch()
private let userService = UserService()
// MARK: Hero
private var heroObj = Hero()
// MARK: Island
private var islandObj = Island()
private var leftIsland: SKSpriteNode?
private var rightIsland: SKSpriteNode?
private let gravity: CGFloat = -100.0
private let HeroSpeed: CGFloat = 760
private var isBegin = false
private var isEnd = false
private var nextLeftStartX: CGFloat = 0
private var bridgeHeight: CGFloat = 0
private lazy var playAbleRect: CGRect = {
let maxAspectRatio: CGFloat = 16.0/9.0
let maxAspectRatioWidth = self.size.height / maxAspectRatio
let playableMargin = (self.size.width - maxAspectRatioWidth) / 2.0
return CGRectMake(playableMargin, 0, maxAspectRatioWidth, self.size.height)
}()
private var gameOver = false {
willSet {
if newValue {
let gameOverLayer = childNodeWithName(GameSceneChildName.GameOverLayerName.rawValue) as SKNode?
gameOverLayer?.runAction(SKAction.moveDistance(CGVectorMake(0, 100), fadeInWithDuration: 0.2))
}
}
}
private var score: Int = 0 {
willSet {
let scoreBand = childNodeWithName(GameSceneChildName.ScoreName.rawValue) as? SKLabelNode
scoreBand?.text = "\(newValue)"
scoreBand?.runAction(SKAction.sequence([SKAction.scaleTo(1.5, duration: 0.1), SKAction.scaleTo(1, duration: 0.1)]))
if newValue == 1 {
let tip = childNodeWithName(GameSceneChildName.TipName.rawValue) as? SKLabelNode
tip?.runAction(SKAction.fadeAlphaTo(0, duration: 0.4))
}
}
}
// MARK: - override
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPointMake(0.5, 0.5)
physicsWorld.contactDelegate = self
musicPlayer = setupAudioPlayerWithFile("bg_country", type: "mp3")
musicPlayer.numberOfLoops = -1
musicPlayer.play()
}
override func didMoveToView(view: SKView) {
start()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = (touch as UITouch).locationInNode(self)
if let touchNode = self.nodeAtPoint(location) as? SKSpriteNode {
if touchNode.name == "back" {
let scene = MenuScene()
let skView = self.view
scene.size = skView!.bounds.size
scene.scaleMode = .AspectFill
skView!.presentScene(scene)
} else {
guard !gameOver else {
let gameOverLayer = childNodeWithName(GameSceneChildName.GameOverLayerName.rawValue) as SKNode?
let location = touches.first?.locationInNode(gameOverLayer!)
let retry = gameOverLayer!.nodeAtPoint(location!)
if retry.name == GameSceneChildName.RetryButtonName.rawValue {
retry.runAction(SKAction.sequence([SKAction.setTexture(SKTexture(imageNamed: "button_retry_down"), resize: false), SKAction.waitForDuration(0.3)]), completion: {[unowned self] () -> Void in
self.restart()
})
}
return
}
if !isBegin && !isEnd {
isBegin = true
let bridge = loadBridge()
let action = SKAction.resizeToHeight(
CGFloat(
DefinedScreenHeight - IslandConstants.height
),
duration: 1.5
)
bridge.runAction(action, withKey: GameSceneActionKey.BridgeGrowAction.rawValue)
let loopAction = SKAction.group(
[SKAction.playSoundFileNamed(
GameSceneEffectAudioName.BridgeGrowAudioName.rawValue,
waitForCompletion: true)]
)
bridge.runAction(
SKAction.repeatActionForever(loopAction),
withKey: GameSceneActionKey.BridgeGrowAudioAction.rawValue
)
return
}
}
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if isBegin && !isEnd {
isEnd = true
let hero = heroObj.getHeroNodeFromParent()
hero.removeActionForKey(GameSceneActionKey.HeroScaleAction.rawValue)
hero.runAction(SKAction.scaleYTo(1, duration: 0.04))
let bridge = childNodeWithName(GameSceneChildName.BridgeName.rawValue) as? SKSpriteNode
bridge!.removeActionForKey(GameSceneActionKey.BridgeGrowAction.rawValue)
bridge!.removeActionForKey(GameSceneActionKey.BridgeGrowAudioAction.rawValue)
bridge!.runAction(
SKAction.playSoundFileNamed(
GameSceneEffectAudioName.BridgeGrowOverAudioName.rawValue, waitForCompletion: false
)
)
bridgeHeight = bridge!.size.height
let action = SKAction.rotateToAngle(
CGFloat(-M_PI / 2),
duration: 0.4,
shortestUnitArc: true
)
let playFall = SKAction.playSoundFileNamed(
GameSceneEffectAudioName.BridgeFallAudioName.rawValue,
waitForCompletion: false
)
bridge!.runAction(
SKAction.sequence(
[SKAction.waitForDuration(0.2), action, playFall]),
completion: {[unowned self] () -> Void in
self.heroGo(self.checkPass())
})
}
}
// MARK: Audio player
func setupAudioPlayerWithFile(file: NSString, type: NSString) -> AVAudioPlayer {
let url = NSBundle.mainBundle().URLForResource(file as String, withExtension: type as String)
var audioPlayer: AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url!)
} catch {
print("NO AUDIO PLAYER")
}
return audioPlayer!
}
private func start() {
loadBackground()
loadScoreBackground()
loadScore()
loadTip()
loadBackButton()
loadGameOverLayer()
addleftIsland(false)
loadHero()
let rightIslandStartPosition = islandObj.calculateGap(
self.playAbleRect.width,
leftIslandWidth: self.leftIsland!.size.width,
nextLeftStartX: self.nextLeftStartX
)
addRightIsland(false, rightIslandStartPosition: rightIslandStartPosition)
gameOver = false
stopWatch.start()
}
private func addleftIsland(animated: Bool) {
let leftIslandData = islandObj.loadIslands(
animated,
startLeftPoint: playAbleRect.origin.x,
completition: {[unowned self] () -> Void in
self.isBegin = false
self.isEnd = false
}
)
self.leftIsland = leftIslandData.islandNode
addChild(self.leftIsland!)
self.nextLeftStartX = leftIslandData.leftStartX
}
private func addRightIsland(
animated: Bool,
rightIslandStartPosition: CGFloat) {
let rightIslandData = islandObj.loadIslands(
animated,
startLeftPoint: rightIslandStartPosition,
completition: {[unowned self] () -> Void in
self.isBegin = false
self.isEnd = false
}
)
self.rightIsland = rightIslandData.islandNode
self.addChild(self.rightIsland!)
self.nextLeftStartX = rightIslandData.leftStartX
}
private func restart() {
let userScore = UserScore(
name: userService.getCurrentUserName(),
score: self.score,
time: lround(stopWatch.elapsedTime),
me: false
)
self.userService.saveCurrentUserScore(userScore)
self.stopWatch.stop()
isBegin = false
isEnd = false
score = 0
nextLeftStartX = 0
removeAllChildren()
start()
}
private func checkPass() -> Bool {
let bridge = childNodeWithName(GameSceneChildName.BridgeName.rawValue) as? SKSpriteNode
let rightPoint = DefinedScreenWidth / 2 + bridge!.position.x + self.bridgeHeight
guard rightPoint < self.nextLeftStartX else {
return false
}
guard CGRectIntersectsRect((leftIsland?.frame)!, bridge!.frame)
&& CGRectIntersectsRect((rightIsland?.frame)!, bridge!.frame) else {
return false
}
return true
}
private func heroGo(pass: Bool) {
let hero = heroObj.getHeroNodeFromParent()
guard pass else {
let bridge = childNodeWithName(
GameSceneChildName.BridgeName.rawValue) as? SKSpriteNode
let dis: CGFloat = bridge!.position.x + self.bridgeHeight
let disGap = nextLeftStartX
- (DefinedScreenWidth / 2
- abs(hero.position.x))
- (rightIsland?.frame.size.width)! / 2
let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed)))
hero.runAction(heroObj.walkAction, withKey: GameSceneActionKey.WalkAction.rawValue)
hero.runAction(move, completion: {[unowned self] () -> Void in
bridge!.runAction(SKAction.rotateToAngle(CGFloat(-M_PI), duration: 0.4))
hero.physicsBody!.affectedByGravity = true
hero.runAction(
SKAction.playSoundFileNamed(
GameSceneEffectAudioName.DeadAudioName.rawValue, waitForCompletion: false
)
)
hero.removeActionForKey(GameSceneActionKey.WalkAction.rawValue)
self.runAction(SKAction.waitForDuration(0.5), completion: {[unowned self] () -> Void in
self.gameOver = true
})
})
return
}
let dis: CGFloat = -DefinedScreenWidth / 2 + nextLeftStartX - hero.size.width / 2 - 20
let disGap = nextLeftStartX
- (DefinedScreenWidth / 2
- abs(hero.position.x))
- (rightIsland?.frame.size.width)! / 2
let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed)))
hero.runAction(heroObj.walkAction, withKey: GameSceneActionKey.WalkAction.rawValue)
hero.runAction(move) { [unowned self] () -> Void in
hero.runAction(
SKAction.playSoundFileNamed(
GameSceneEffectAudioName.VictoryAudioName.rawValue, waitForCompletion: false
)
)
hero.removeActionForKey(GameSceneActionKey.WalkAction.rawValue)
self.moveIslandAndCreateNew()
}
self.score += 1
}
private func moveIslandAndCreateNew() {
let action = SKAction.moveBy(
CGVectorMake(
-nextLeftStartX
+ (rightIsland?.frame.size.width)!
+ playAbleRect.origin.x - 2,
0
),
duration: 0.3
)
rightIsland?.runAction(action)
let hero = heroObj.getHeroNodeFromParent()
let bridge = childNodeWithName(GameSceneChildName.BridgeName.rawValue) as? SKSpriteNode
hero.runAction(action)
bridge!.runAction(
SKAction.group(
[SKAction.moveBy(
CGVectorMake(-DefinedScreenWidth, 0),
duration: 0.5
),
SKAction.fadeAlphaTo(0, duration: 0.3)
])) { () -> Void in
bridge!.removeFromParent()
}
leftIsland?.runAction(SKAction.moveBy(
CGVectorMake(-DefinedScreenWidth, 0), duration: 0.5),
completion: {[unowned self] () -> Void in
self.leftIsland?.removeFromParent()
let maxGap = Int(self.playAbleRect.width
- (self.rightIsland?.frame.size.width)!
- IslandConstants.maxWidth)
let gap = CGFloat(randomInRange(IslandConstants.gapMinWidth...maxGap))
self.leftIsland = self.rightIsland
let rightIslandStartPosition =
self.playAbleRect.origin.x + (self.rightIsland?.frame.size.width)! + gap
self.addRightIsland(true, rightIslandStartPosition: rightIslandStartPosition)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - load node
private extension GameScene {
private func loadBackground() {
guard let _ = childNodeWithName("background") as? SKSpriteNode else {
let texture = SKTexture(image: UIImage(named: "background.png")!)
let node = SKSpriteNode(texture: texture)
node.size = texture.size()
node.zPosition = GameSceneZposition.BackgroundZposition.rawValue
self.physicsWorld.gravity = CGVectorMake(0, gravity)
addChild(node)
return
}
}
private func loadHero() {
let hero = heroObj.getHeroNode(
nextLeftStartX: self.nextLeftStartX,
islandHeight: self.leftIsland!.size.height
)
addChild(hero)
}
private func loadBridge() -> SKSpriteNode {
let hero = heroObj.getHeroNodeFromParent()
let texture = SKTexture(imageNamed: "bridge")
let bridge = SKSpriteNode(texture: texture, size: CGSizeMake(12, 1))
bridge.zPosition = GameSceneZposition.BridgeZposition.rawValue
bridge.name = GameSceneChildName.BridgeName.rawValue
bridge.anchorPoint = CGPointMake(0.5, 0)
bridge.position = CGPointMake(hero.position.x + hero.size.width / 2 + 18, hero.position.y - hero.size.height / 2)
addChild(bridge)
print(bridge.size.height)
return bridge
}
private func loadGameOverLayer() {
let node = SKNode()
node.alpha = 0
node.name = GameSceneChildName.GameOverLayerName.rawValue
node.zPosition = GameSceneZposition.GameOverZposition.rawValue
addChild(node)
let label = SKLabelNode(fontNamed: "HelveticaNeue-Bold")
label.text = "Game Over"
label.fontColor = SKColor.redColor()
label.fontSize = 150
label.position = CGPointMake(0, 100)
label.horizontalAlignmentMode = .Center
node.addChild(label)
let retry = SKSpriteNode(imageNamed: "button_retry_up")
retry.name = GameSceneChildName.RetryButtonName.rawValue
retry.position = CGPointMake(0, -200)
node.addChild(retry)
}
private func loadScore() {
let scoreBand = SKLabelNode(fontNamed: "Arial")
scoreBand.name = GameSceneChildName.ScoreName.rawValue
scoreBand.text = "0"
scoreBand.position = CGPointMake(0, DefinedScreenHeight / 2 - 200)
scoreBand.fontColor = SKColor.whiteColor()
scoreBand.fontSize = 100
scoreBand.zPosition = GameSceneZposition.ScoreZposition.rawValue
scoreBand.horizontalAlignmentMode = .Center
addChild(scoreBand)
}
private func loadBackButton() {
let backButton = SKSpriteNode()
backButton.position = CGPointMake(-470, DefinedScreenHeight / 2 - 150)
backButton.texture = SKTexture(imageNamed: "left_arrow")
backButton.zPosition = 300
backButton.colorBlendFactor = 1.0
backButton.alpha = 1.0
backButton.color = UIColor.whiteColor()
backButton.size.height = 99
backButton.size.width = 99
addChild(backButton)
let backButtonPlace = SKSpriteNode()
backButtonPlace.position = CGPointMake(-470, DefinedScreenHeight / 2 - 150)
backButtonPlace.zPosition = 10000
backButtonPlace.colorBlendFactor = 1.0
backButtonPlace.alpha = 1.0
backButtonPlace.color = UIColor.clearColor()
backButtonPlace.size.height = 200
backButtonPlace.size.width = 200
backButtonPlace.name = "back"
addChild(backButtonPlace)
}
private func loadScoreBackground() {
let back = SKShapeNode(rect: CGRectMake(0-120, 1024-200-30, 240, 140), cornerRadius: 20)
back.zPosition = GameSceneZposition.ScoreBackgroundZposition.rawValue
back.fillColor = SKColor.blackColor().colorWithAlphaComponent(0.3)
back.strokeColor = SKColor.blackColor().colorWithAlphaComponent(0.3)
addChild(back)
}
private func loadTip() {
let tip = SKLabelNode(fontNamed: "HelveticaNeue-Bold")
tip.name = GameSceneChildName.TipName.rawValue
tip.text = ""
tip.position = CGPointMake(0, DefinedScreenHeight / 2 - 350)
tip.fontColor = SKColor.blackColor()
tip.fontSize = 52
tip.zPosition = GameSceneZposition.TipZposition.rawValue
tip.horizontalAlignmentMode = .Center
addChild(tip)
}
}
|
mit
|
64ded5320c16a4ea7ac40d3987b4cab3
| 32.498934 | 203 | 0.67596 | 4.508178 | false | false | false | false |
64characters/Telephone
|
UseCasesTests/UserAgentSoundIOSelectionUseCaseTests.swift
|
1
|
1732
|
//
// UserAgentSoundIOSelectionUseCaseTests.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
import Domain
import DomainTestDoubles
@testable import UseCases
import UseCasesTestDoubles
import XCTest
final class UserAgentSoundIOSelectionUseCaseTests: XCTestCase {
func testSelectsDeviceIdentifiersOfSoundIO() throws {
let input = SystemAudioDeviceTestFactory().someInput
let output = SystemAudioDeviceTestFactory().someOutput
let agent = UserAgentSpy()
agent.audioDevicesResult = [
SimpleUserAgentAudioDevice(device: output), SimpleUserAgentAudioDevice(device: input)
]
let sut = UserAgentSoundIOSelectionUseCase(
devicesFactory: SystemAudioDevicesTestFactory(factory: SystemAudioDeviceTestFactory()),
soundIOFactory: SoundIOFactoryStub(
soundIO: SimpleSoundIO(input: input, output: output, ringtoneOutput: NullSystemAudioDevice())
),
agent: agent
)
try sut.execute()
XCTAssertEqual(agent.invokedInputDeviceID, input.identifier)
XCTAssertEqual(agent.invokedOutputDeviceID, output.identifier)
}
}
|
gpl-3.0
|
75413655a09316c1a30ec58d6e4191ec
| 36.608696 | 109 | 0.72659 | 4.985591 | false | true | false | false |
laurentVeliscek/AudioKit
|
AudioKit/Common/Playgrounds/Filters.playground/Pages/Low Pass Butterworth Filter.xcplaygroundpage/Contents.swift
|
1
|
1375
|
//: ## Low Pass Butterworth Filter
//: ### A low-pass filter takes an audio signal as an input, and cuts out the
//: ### high-frequency components of the audio signal, allowing for the
//: ### lower frequency components to "pass through" the filter.
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var filter = AKLowPassButterworthFilter(player)
filter.cutoffFrequency = 500 // Hz
AudioKit.output = filter
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Low Pass Butterworth Filter")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: filtersPlaygroundFiles))
addSubview(AKBypassButton(node: filter))
addSubview(AKPropertySlider(
property: "Cutoff Frequency",
format: "%0.1f Hz",
value: filter.cutoffFrequency, minimum: 20, maximum: 22050,
color: AKColor.greenColor()
) { sliderValue in
filter.cutoffFrequency = sliderValue
})
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
|
mit
|
6f4c31b5fd9a15885b9210db95a0d224
| 28.255319 | 77 | 0.682182 | 4.963899 | false | false | false | false |
malaonline/iOS
|
mala-ios/Tool/ThemeTool/PageControl.swift
|
1
|
11572
|
import UIKit
/// The `PageControl` displays a horizontal arrangement of circle outlines, each representing a page or section in your app. The currently viewed page is indicated by a filled circle.
///
/// When `setCurrentPage()` method is called with the animated parameter set to `true` the current page indicator will move to the new page with an animation.
/// This method can be used together with a `UIScrollViewDelegate`'s `scrollViewDidScroll` method to update the current page indicator continuously as the user swipes through your app's pages.
///
/// - SeeAlso: `UIPageControl`
@IBDesignable
public class PageControl: UIControl {
// MARK: - Interface
/// The current page, diplayed as a filled circle.
///
/// The default value is 0.
@IBInspectable
public var currentPage: Int {
get {
return Int(_currentPage)
}
set {
setCurrentPage(CGFloat(newValue), animated: true)
}
}
/// The current page, diplayed as a filled or partially filled circle.
///
/// - Parameter currentPage: The current page indicator is filled if the value is .0, and about half filled if ±.25.
/// - Parameter animated: `true` to animate the transition to the new page, `false` to make the transition immediate.
public func setCurrentPage(_ currentPage: CGFloat, animated: Bool = false) {
let newPage = max(0, min(currentPage, CGFloat(numberOfPages - 1)))
_currentPage = newPage
updateCurrentPageDisplayWithAnimation(animated)
updateAccessibility()
}
/// The number of page indicators to display.
///
/// The default value is 0.
@IBInspectable
public var numberOfPages: Int = 0 {
didSet {
isHidden = hidesForSinglePage && numberOfPages <= 1
if numberOfPages != oldValue {
clearPageIndicators()
generatePageIndicators()
updateMaskSubviews()
invalidateIntrinsicContentSize()
}
if numberOfPages > oldValue {
updateCornerRadius()
updateColors()
}
setCurrentPage(_currentPage, animated: false)
updateAccessibility()
}
}
/// Hides the page control when there is only one page.
///
/// The default is `false`.
@IBInspectable
public var hidesForSinglePage: Bool = false {
didSet {
isHidden = hidesForSinglePage && numberOfPages <= 1
}
}
/// Controls when the current page will update.
///
/// The default is `false`.
@IBInspectable
public var defersCurrentPageDisplay: Bool = false
/// Updates the current page indicator to the current page.
///
public func updateCurrentPageDisplay() {
updateCurrentPageDisplayWithAnimation()
}
/// Use to size the control to fit a certain number of pages.
/// - Parameter pageCount: A number of pages to calculate size from.
/// - Returns: Minimum size required to display all page indicators.
public func size(forNumberOfPages pageCount: Int) -> CGSize {
let width = pageIndicatorSize * CGFloat(pageCount) + pageIndicatorSpacing * CGFloat(max(0, pageCount - 1))
return CGSize(width: max(7, width), height: defaultControlHeight)
}
// MARK: - Tint Color Overrides
/// When set this property overrides the page indicator border color.
///
/// The default is the control's `tintColor`.
@IBInspectable
public var pageIndicatorTintColor: UIColor?
/// When set this property overrides the current page indicator's fill color.
///
/// The default is the control's `tintColor`.
@IBInspectable
public var currentPageIndicatorTintColor: UIColor?
// MARK: - Private
fileprivate var _currentPage: CGFloat = -1
fileprivate var currentPageChangeAnimationDuration: TimeInterval = 0.3
fileprivate var currentPageIndicatorContainerView = UIView()
fileprivate var currentPageIndicatorView = UIView()
fileprivate var pageIndicatorMaskingView = UIView()
fileprivate var pageIndicatorContainerView = UIView()
fileprivate let pageIndicatorSize: CGFloat = 7
fileprivate let pageIndicatorSpacing: CGFloat = 9
fileprivate let defaultControlHeight: CGFloat = 37
fileprivate let accessibilityPageControl = UIPageControl()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: UILayoutConstraintAxis.vertical)
setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: UILayoutConstraintAxis.horizontal)
autoresizingMask = [UIViewAutoresizing.flexibleWidth]
didInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didInit()
}
fileprivate func didInit() {
currentPageIndicatorContainerView.addSubview(currentPageIndicatorView)
currentPageIndicatorContainerView.layer.mask = pageIndicatorMaskingView.layer
addSubview(currentPageIndicatorContainerView)
addSubview(pageIndicatorContainerView)
generatePageIndicators()
updateMaskSubviews()
updateCornerRadius()
updateColors()
updateCurrentPageDisplayWithAnimation(false)
updateAccessibility()
}
}
// MARK: - Current Page Display
private extension PageControl {
func updateCurrentPageDisplayWithAnimation(_ animated: Bool = true) {
let pageFrame = frame(forPage: _currentPage, in: numberOfPages)
if animated && currentPageChangeAnimationDuration > 0.0 {
UIView.animate(withDuration: currentPageChangeAnimationDuration) {
self.currentPageIndicatorView.frame = pageFrame
}
} else {
currentPageIndicatorView.frame = pageFrame
}
}
}
// MARK: - Tint Color
extension PageControl {
public override func tintColorDidChange() {
super.tintColorDidChange()
updateColors()
}
}
// MARK: - Subview Layout
extension PageControl {
public override func layoutSubviews() {
super.layoutSubviews()
pageIndicatorContainerView.frame = bounds
pageIndicatorMaskingView.frame = bounds
currentPageIndicatorContainerView.frame = bounds
updateCurrentPageDisplayWithAnimation(false)
for (index, view) in pageIndicatorContainerView.subviews.enumerated() {
view.frame = frame(forPage: CGFloat(index), in: numberOfPages)
}
for (index, view) in pageIndicatorMaskingView.subviews.enumerated() {
view.frame = frame(forPage: CGFloat(index), in: numberOfPages)
}
}
}
// MARK: - Auto Layout
extension PageControl {
public override func sizeThatFits(_ size: CGSize) -> CGSize {
if numberOfPages == 0 || hidesForSinglePage && numberOfPages == 1 {
return .zero
} else if let superview = superview {
return CGSize(width: superview.bounds.width, height: defaultControlHeight)
} else {
return self.size(forNumberOfPages: numberOfPages)
}
}
public override var intrinsicContentSize: CGSize {
if numberOfPages == 0 || hidesForSinglePage && numberOfPages == 1 {
return .zero
} else {
return size(forNumberOfPages: numberOfPages)
}
}
}
// MARK: - Interface Builder
extension PageControl {
public override func prepareForInterfaceBuilder() {
}
}
// MARK: - Control
extension PageControl {
override public var isEnabled: Bool {
didSet {
tintAdjustmentMode = isEnabled ? UIViewTintAdjustmentMode.normal : UIViewTintAdjustmentMode.dimmed
}
}
}
// MARK: - Page Indicators
private extension PageControl {
func clearPageIndicators() {
for pageIndicatorView in pageIndicatorContainerView.subviews {
pageIndicatorView.removeFromSuperview()
}
}
func generatePageIndicators() {
for _ in 0..<numberOfPages {
let view = UIView()
pageIndicatorContainerView.addSubview(view)
}
}
func frame(forPage page: CGFloat, in numberOfPages: Int) -> CGRect {
let clampedHorizontalIndex = max(0, min(page, CGFloat(numberOfPages) - 1))
let totalSize = size(forNumberOfPages: numberOfPages)
let horizontalCenter = bounds.width / 2.0
let verticalCenter = bounds.height / 2.0 - pageIndicatorSize / 2.0
let horizontalOffset = (pageIndicatorSize + pageIndicatorSpacing) * clampedHorizontalIndex
return CGRect(x: horizontalOffset - totalSize.width / 2.0 + horizontalCenter, y: verticalCenter, width: pageIndicatorSize, height: pageIndicatorSize)
}
}
// MARK: - Appearance
private extension PageControl {
func updateColors() {
currentPageIndicatorView.backgroundColor = currentPageIndicatorTintColor ?? tintColor
for view in pageIndicatorContainerView.subviews {
view.layer.borderColor = pageIndicatorTintColor?.cgColor ?? tintColor.cgColor
view.layer.borderWidth = 0.5
}
}
func updateCornerRadius() {
currentPageIndicatorView.layer.cornerRadius = pageIndicatorSize / 2.0
for view in pageIndicatorContainerView.subviews {
view.layer.cornerRadius = pageIndicatorSize / 2.0
}
for view in pageIndicatorMaskingView.subviews {
view.layer.cornerRadius = pageIndicatorSize / 2.0
}
}
func updateMaskSubviews() {
for dotView in pageIndicatorMaskingView.subviews {
dotView.removeFromSuperview()
}
for _ in 0..<numberOfPages {
let view = UIView(UIColor.black)
view.clipsToBounds = true
pageIndicatorMaskingView.addSubview(view)
}
}
}
// MARK: - Touch
extension PageControl {
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, isEnabled == true {
if touch.location(in: self).x < bounds.size.width / 2 {
if _currentPage - floor(_currentPage) > 0.01 {
_currentPage = floor(_currentPage)
} else {
_currentPage = max(0, floor(_currentPage) - 1)
}
}
else {
_currentPage = min(round(_currentPage + 1), CGFloat(numberOfPages - 1))
}
if !defersCurrentPageDisplay {
updateCurrentPageDisplayWithAnimation(true)
updateAccessibility()
}
sendActions(for: UIControlEvents.valueChanged)
}
}
}
// MARK: - Accessibility
private extension PageControl {
func updateAccessibility() {
accessibilityPageControl.currentPage = currentPage
accessibilityPageControl.numberOfPages = numberOfPages
isAccessibilityElement = accessibilityPageControl.isAccessibilityElement
accessibilityLabel = accessibilityPageControl.accessibilityLabel
accessibilityHint = accessibilityPageControl.accessibilityHint
accessibilityTraits = accessibilityPageControl.accessibilityTraits
accessibilityValue = accessibilityPageControl.accessibilityValue
}
}
|
mit
|
0526288eccca5d4c99d2b4f74ce1369b
| 32.833333 | 192 | 0.650851 | 5.504757 | false | false | false | false |
groovelab/SwiftBBS
|
SwiftBBS/SwiftBBS/Extension.swift
|
1
|
1135
|
//
// Extension.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/01/17.
// Copyright GrooveLab
//
import UIKit
extension NSObject {
static var className: String {
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
}
extension UITableViewCell {
static var identifierForReuse: String {
return className
}
}
extension NSMutableURLRequest {
func addTokenToCookie() {
guard let url = URL, let sessionToken = User.sessionToken else {
return
}
var cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(url)
if cookies == nil {
return
}
let properties = [
NSHTTPCookieDomain: Config.END_POINT_HOST,
NSHTTPCookiePath: "/",
NSHTTPCookieName: Config.SESSION_KEY,
NSHTTPCookieValue: sessionToken
]
if let cookieForSession = NSHTTPCookie(properties: properties) {
cookies?.append(cookieForSession)
allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
}
}
}
|
mit
|
ec963d9cabd3013b6d42951be61ff573
| 24.222222 | 87 | 0.630837 | 5.182648 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
|
AwesomeAdsDemo/SettingRow.swift
|
1
|
961
|
//
// SettingsRow.swift
// AwesomeAdsDemo
//
// Created by Gabriel Coman on 28/11/2016.
// Copyright © 2016 Gabriel Coman. All rights reserved.
//
import UIKit
class SettingRow: UITableViewCell {
static let Identifier = "SettingRowID"
@IBOutlet weak var settingsItem: UILabel!
@IBOutlet weak var settingsDescription: UILabel!
@IBOutlet weak var settingsSwitch: UISwitch!
var viewModel: SettingViewModel! {
didSet {
backgroundColor = viewModel.getIndex() % 2 == 0 ? UIColor.white : UIColor(rgb: 0xf7f7f7)
settingsItem.text = viewModel.getItemTitle()
settingsDescription.text = viewModel.getItemDetails()
settingsSwitch.isOn = viewModel.getItemValue()
settingsSwitch.addTarget(self, action: #selector(toggle), for: UIControl.Event.valueChanged)
}
}
@objc private func toggle () {
viewModel.setValue(settingsSwitch.isOn)
}
}
|
apache-2.0
|
d6b59e60e8ca244a2930eec73156bf3c
| 29 | 104 | 0.665625 | 4.444444 | false | false | false | false |
chicio/Exploring-SceneKit
|
ExploringSceneKit/Model/Scenes/BlinnPhong/BlinnPhongMaterial.swift
|
1
|
604
|
//
// BlinnPhongMaterial.swift
// ExploringSceneKit
//
// Created by Fabrizio Duroni on 26.08.17.
//
import SceneKit
class BlinnPhongMaterial {
let material: SCNMaterial
init(ambient: Any, diffuse: BlinnPhongDiffuseMaterialComponent, specular: Any) {
material = SCNMaterial()
material.lightingModel = .blinn
material.ambient.contents = ambient
material.diffuse.contents = diffuse.value
material.diffuse.wrapS = diffuse.textureWrapMode
material.diffuse.wrapT = diffuse.textureWrapMode
material.specular.contents = specular
}
}
|
mit
|
3bc1762b99c1fb9d2b39c8291279ebf1
| 26.454545 | 84 | 0.698675 | 4.108844 | false | false | false | false |
kNeerajPro/EcommerceApp
|
ECommerceApp/Entities/Category.swift
|
1
|
1492
|
//
// Category.swift
// ECommerceApp
//
// Created by Neeraj Kumar on 18/12/14.
// Copyright (c) 2014 Neeraj Kumar. All rights reserved.
//
import UIKit
class Category: NSObject {
private(set) var detail:Detail
private(set) var products:ProductCollection?
private(set) var subCategories:CategoryCollection?// Breaking rule of having not more than two instances in a class.
init(name:String) {
self.detail = Detail(id:NSUUID().UUIDString ,name:name)
super.init()
}
var name:String {
return self.detail.name
}
}
extension Category:Printable {
override var description: String {
return "detail:\(self.detail), products:\(self.products)"
}
}
//MARK: Subcategory support.
extension Category {
func insertSubcategory(category:Category) {
self.subCategories?.insertCategory(category)
}
func insertSubCategoryAtIndex(category:Category, index:Int) {
self.subCategories?.insertCategoryAtIndex(category, index: index)
}
func removeSubCategoryAtIndex(index:Int) {
self.subCategories?.removeCategoryAtIndex(index)
}
func removeCategory(category:Category) {
self.subCategories?.removeCategory(category)
}
}
extension Category:Equatable {
}
func ==(lhs: Category, rhs: Category) -> Bool {
// Instead of taking decision here ask producDetail to do it for you.
if (lhs.detail == rhs.detail) {
return true
}
return false
}
|
mit
|
2a1d9c85af49f803cd81bf3cde0f1425
| 23.47541 | 120 | 0.673592 | 4.032432 | false | false | false | false |
Glucosio/glucosio-ios
|
Glucosio Watch Extension/ComplicationController.swift
|
2
|
5460
|
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
handler([.backward])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
let min = DayTimeline.init().elements
.min {a, b in a.timestamp.compare(b.timestamp) == ComparisonResult.orderedAscending}
handler(min?.timestamp)
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
let max = DayTimeline.init().elements
.max {a, b in a.timestamp.compare(b.timestamp) == ComparisonResult.orderedAscending}
handler(max?.timestamp)
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
handler(.showOnLockScreen)
}
// MARK: - Timeline Population
func template(family: CLKComplicationFamily, withReading reading: String, withUnit unit: String, desc: String) -> CLKComplicationTemplate? {
switch(family) {
case .modularLarge:
let template = CLKComplicationTemplateModularLargeStandardBody()
template.headerTextProvider = CLKSimpleTextProvider(text: reading + " " + unit)
template.body1TextProvider = CLKSimpleTextProvider(text: desc)
return template
case .modularSmall:
let template = CLKComplicationTemplateModularSmallStackText()
template.line1TextProvider = CLKSimpleTextProvider(text: reading)
template.line2TextProvider = CLKSimpleTextProvider(text: unit)
return template
case .utilitarianLarge:
let template = CLKComplicationTemplateUtilitarianLargeFlat()
template.textProvider = CLKSimpleTextProvider(text: reading)
return template;
case .utilitarianSmall:
let template = CLKComplicationTemplateUtilitarianSmallFlat()
template.textProvider = CLKSimpleTextProvider(text: reading)
return template;
case .utilitarianSmallFlat:
let template = CLKComplicationTemplateUtilitarianSmallFlat()
template.textProvider = CLKSimpleTextProvider(text: reading)
return template
case .circularSmall:
let template = CLKComplicationTemplateCircularSmallSimpleText()
template.textProvider = CLKSimpleTextProvider(text: reading)
return template
default:
return Optional.none
}
}
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
// Call the handler with the current timeline entry
let item = DayTimeline.init().elements.last
let reading = item?.value ?? "N/A"
let unit = item?.unit ?? ""
let desc = item?.desc ?? ""
if let template = template(family: complication.family, withReading: reading, withUnit: unit, desc: desc) {
template.tintColor = UIColor.glucosio_pink()
let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template)
handler(entry)
}else {
handler(nil)
}
}
func filterTimelineEntries(for complication: CLKComplication, with filter: (TimelineItem) -> Bool) -> [CLKComplicationTimelineEntry]{
let entries = DayTimeline.init().elements
.filter(filter)
.map({item -> CLKComplicationTimelineEntry? in
if let template = template(family: complication.family, withReading: item.value, withUnit: item.unit, desc: item.desc) {
return CLKComplicationTimelineEntry(date: item.timestamp, complicationTemplate: template)
} else {
return nil
}
})
.compactMap {$0}
return entries
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
//TODO: EMI: respect limit
let entries = filterTimelineEntries(for: complication, with: {date.compare($0.timestamp) == ComparisonResult.orderedDescending })
// Call the handler with the timeline entries prior to the given date
handler(entries)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
//TODO: EMI: respect limit
let entries = filterTimelineEntries(for: complication, with: {date.compare($0.timestamp) == ComparisonResult.orderedAscending })
// Call the handler with the timeline entries after to the given date
handler(entries)
}
// MARK: - Placeholder Templates
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
handler(nil)
}
}
|
gpl-3.0
|
a78998594354469eb957b63d42c33600
| 39.147059 | 169 | 0.667949 | 5.699374 | false | false | false | false |
googlecreativelab/justaline-ios
|
ViewControllers/AboutViewController.swift
|
1
|
5146
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class AboutViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var learnMoreTextView: UITextView!
@IBOutlet weak var privacyButton: UIButton!
@IBOutlet weak var thirdPartyButton: UIButton!
@IBOutlet weak var termsButton: UIButton!
@IBOutlet weak var buildLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let closeButton = UIBarButtonItem(image: UIImage(named: "ic_close"), style: .plain, target: self, action: #selector(closeTapped))
closeButton.accessibilityLabel = NSLocalizedString("menu_close", comment: "Close")
self.navigationItem.leftBarButtonItem = closeButton
formatButton(termsButton, stringKey: "terms_of_service")
formatButton(privacyButton, stringKey: "privacy_policy")
formatButton(thirdPartyButton, stringKey: "third_party_licenses")
formatLearnMore()
let versionString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
let buildString = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as! String
buildLabel.text = "\(versionString)(\(buildString))"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonTapped(_ sender: UIButton) {
var urlString: String?
if sender == termsButton {
urlString = "terms_url"
} else if sender == privacyButton {
urlString = "privacy_policy_url"
}
if let urlKey = urlString {
UIApplication.shared.open(URL(string:NSLocalizedString(urlKey, comment: ""))!, options: [:], completionHandler: nil)
}
}
@objc func closeTapped(_ sender: UIButton) {
performSegue(withIdentifier: "unwindAboutSegue", sender: self)
}
func formatButton(_ button: UIButton, stringKey: String) {
let attributedString = NSAttributedString(string: NSLocalizedString(stringKey, comment: ""),
attributes: [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
// .font: UIFont(name: "CoolSans-Medium", size: 11)!,
.font: UIFont.systemFont(ofSize: 11),
.foregroundColor: UIColor.white,
.underlineColor: UIColor.white])
button.setAttributedTitle(attributedString, for: .normal)
}
func formatLearnMore() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineSpacing = 6
let learnMoreString = NSMutableAttributedString(string: NSLocalizedString("about_text", comment: "Just a Line is an AR Experiment..."), attributes: [.paragraphStyle: paragraphStyle, .foregroundColor: UIColor.white])
learnMoreTextView.linkTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
let linkRange = (learnMoreString.string as NSString).range(of:NSLocalizedString("about_text_link", comment: "g.co/justaline"))
learnMoreString.addAttribute(.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: linkRange)
learnMoreString.addAttribute(.link,
value: URL(string: NSLocalizedString("jal_url", comment: "https://g.co/justaline"))!,
range: linkRange)
learnMoreTextView.attributedText = learnMoreString
learnMoreTextView.font = UIFont.systemFont(ofSize: 14)
// learnMoreTextView.font = UIFont(name: "CoolSans-Medium", size: 14)
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
bab95d5307961f809b494d4e92ff6dec
| 44.946429 | 223 | 0.634085 | 5.486141 | false | false | false | false |
ninjaprawn/iFW
|
iOS/iFW/NewsDetailTableViewController.swift
|
1
|
2394
|
//
// NewsDetailTableViewController.swift
// iFW
//
// Created by George Dan on 8/04/2016.
// Copyright © 2016 George Dan. All rights reserved.
//
import UIKit
class NewsDetailTableViewController: UITableViewController {
var post: RSSItem!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath)
let titleLabel = cell.viewWithTag(1000) as! UILabel
let dateLabel = cell.viewWithTag(1001) as! UILabel
titleLabel.text = post.title
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.timeZone = NSTimeZone.defaultTimeZone()
if let date = post.pubDate {
dateLabel.text = dateFormatter.stringFromDate(date).fixDate()
} else {
dateLabel.text = "Date not found"
}
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath)
let contentView = cell.viewWithTag(1000) as! UILabel
contentView.text = post.itemDescription
return cell
}
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 80
}
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
@IBAction func shareButtonPressed(sender: UIBarButtonItem) {
let activityItems = ["\(post.title!) (\(post.links[0].absoluteString)) via iFW"]
let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypeAirDrop, UIActivityTypePostToFlickr]
self.presentViewController(activityController, animated: true, completion: nil)
}
}
|
mit
|
7d08de801c08c6fc8354e19dbe7811ad
| 29.679487 | 118 | 0.742583 | 4.834343 | false | false | false | false |
madoffox/Stretching
|
Stretching/Stretching/TrainingView.swift
|
1
|
10019
|
//
// ViewController.swift
// Stretching
//
// Created by Admin on 16.12.16.
// Copyright © 2016 Admin. All rights reserved.
//
import UIKit
class TrainingController: UIViewController {
@IBOutlet weak var numberOfCicle: UILabel!
@IBOutlet weak var numberOfExercise: UILabel!
@IBOutlet weak var restLabel: UILabel!
@IBOutlet weak var exerciseName: UILabel!
@IBOutlet weak var exerciseSeconds: UILabel!
@IBOutlet weak var exercisePercents: UILabel!
@IBOutlet weak var exerciseProgress: UIProgressView!
@IBOutlet weak var exercisePicture: UIImageView!
var trainingTitle = ""
var startDate:NSDate = NSDate()
override func viewDidLoad() {
super.viewDidLoad()
if(isMonday){
ifItIsMonday()
print("it is monday")
trainingTitle = "Today was Monday Training"
}
if(isWednesday){
ifItIsWednesday()
print("it is wednesday")
trainingTitle = "Today was Wednesday Training"
}
if(isFriday){
ifItIsFriday()
print("it is friday")
trainingTitle = "Today was Friday Training"
}
startDate = NSDate()
if(isRandomOrder_constants){
dayTraining.shuffle()
}
numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)"
exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)"
exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture
numberOfCicle.text = "\(cicleNumber_constants)"+"/"+"\(numberOfCicle_constants)"
rest()
}
@IBAction func endTraining(_ sender: UIButton) {
timerTrain.invalidate()
addEvent(title: trainingTitle,startDate: startDate,endDate: NSDate())
returnValuesToDefault()
print("end training")
}
@IBAction func previousExercise() {
if(exerciseNumber_constants > 0){
timerTrain.invalidate()
stopClockTikTak()
exerciseNumber_constants -= 1
cicleNumber_constants = 1
print("previous exercise")
numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)"
exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)"
exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture
numberOfCicle.text = "1"+"/"+"\(numberOfCicle_constants)"
}
else
{
print("no previous exercise")
}
}
@IBAction func nextExericse() {
if(exerciseNumber_constants + 1 < UInt8(dayTraining.count)){
if(isRest)
{
stopClockTikTak()
train()
return
}
if(isTraining){
timerTrain.invalidate()
stopClockTikTak()
exerciseNumber_constants += 1
cicleNumber_constants = 1
print("next exercise")
numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)"
exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)"
exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture
numberOfCicle.text = "1"+"/"+"\(numberOfCicle_constants)"
}
}
else
{
print("no next exercise")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if(isTraining || isRest){
print("pause")
if(timerTrain.isValid){
timerTrain.invalidate()
self.view.alpha = 0.5
restLabel.text = "ПАУЗА!"
}
else{
timerTrain = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
self.view.alpha = 1
if(isRest){
restLabel.text = "ОТДЫХ!"
}
if(isTraining){
restLabel.text = "РАБОТАЙ!"
}
}
}
}
func rest(){
if(exerciseNumber_constants < UInt8(dayTraining.count))
{
isRest = true
isTraining = false
restLabel.text = "ОТДЫХ!"
numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)"
exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)"
exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture
numberOfCicle.text = "\(cicleNumber_constants)"+"/"+"\(numberOfCicle_constants)"
timerTrain.invalidate()
timerTrain = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
}
func train()
{
if(exerciseNumber_constants < UInt8(dayTraining.count))
{
isRest = false
isTraining = true
restLabel.text = "РАБОТАЙ!"
timerTrain.invalidate()
timerTrain = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
}
func timerAction()
{
if(isRest){
if(UInt8(seconds.minutes * 60 + seconds.seconds) < restDuration ){
clockTikTak()
}
else{
stopClockTikTak()
print("train")
train()
}
}
if(isTraining)
{
if(UInt8(seconds.minutes * 60 + seconds.seconds) < trainingDuration ){
clockTikTak()
}
else{
stopClockTikTak()
print("rest")
cicleNumber_constants += 1
if(cicleNumber_constants % (numberOfCicle_constants+1) == 0){
cicleNumber_constants = 1
exerciseNumber_constants += 1
}
rest()
}
}
}
func clockTikTak()
{
seconds.miliseconds += 1
//print(seconds.miliseconds)
if(seconds.miliseconds % 100 == 0){
seconds.seconds += 1
seconds.miliseconds = 0
b = true
exerciseSeconds.text = "0"+"\(seconds.minutes)"+":"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds)"
exercisePercents.text = "\(Int((Double(seconds.seconds) / Double(restDuration))*100))"+"%"
exerciseProgress.setProgress(Float(Double(seconds.seconds) / Double(restDuration)), animated: true)
}
if(seconds.seconds % 60 == 0 && b){
seconds.seconds = 0
seconds.minutes += 1
}
if(seconds.seconds < 10){
if(seconds.miliseconds < 10){
exerciseSeconds.text = "0"+"\(seconds.minutes)"+":0"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds)"
}
else
{
exerciseSeconds.text = "0"+"\(seconds.minutes)"+":0"+"\(seconds.seconds)"+":"+"\(seconds.miliseconds)"
}
}
else{
if(seconds.miliseconds < 10){
exerciseSeconds.text = "0"+"\(seconds.minutes)"+":"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds)"
}
else
{
exerciseSeconds.text = "0"+"\(seconds.minutes)"+":"+"\(seconds.seconds)"+":"+"\(seconds.miliseconds)"
}
}
}
func stopClockTikTak()
{
timerTrain.invalidate()
b = false
seconds.miliseconds = 1
seconds.seconds = 0
seconds.minutes = 0
isRest = false
restLabel.text = "РАБОТАЙ!"
//sleep(1)
exercisePercents.text = "\(Int((Double(seconds.seconds) / Double(restDuration))*100))"+"%"
exerciseProgress.setProgress(Float(Double(seconds.seconds) / Double(restDuration)), animated: true)
exerciseSeconds.text = "0"+"\(seconds.minutes)"+":0"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds - 1)"
if(exerciseNumber_constants+1 == UInt8(dayTraining.count) && cicleNumber_constants % (numberOfCicle_constants) == 0)
{
print("end of training")
addEvent(title: trainingTitle,startDate: startDate,endDate: NSDate())
returnValuesToDefault()
self.show(CongratulationsController(), sender: nil)
}
}
func returnValuesToDefault(){
isMonday = false
isWednesday = false
isFriday = false
numberOfCicle_constants = 5
isRandomOrder_constants = false
restDuration = 120
trainingDuration = 120
exerciseNumber_constants = 0
cicleNumber_constants = 1
b = false
seconds = (minutes: 0, seconds: 0, miliseconds: 1)
isRest = false
isTraining = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
6f9433622408f1ec340d4c8dfa8be0cd
| 28.102041 | 147 | 0.504508 | 4.885952 | false | false | false | false |
TotemTraining/PracticaliOSAppSecurity
|
V6/Keymaster/Keymaster/DataManager.swift
|
1
|
2760
|
//
// DataManager.swift
// Keymaster
//
// Created by Chris Forant on 4/25/15.
// Copyright (c) 2015 Totem. All rights reserved.
//
import Foundation
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL
let entriesPath = documentsDirectory.URLByAppendingPathComponent("Entries", isDirectory: true)
let sharedContainerPath = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.keymaster_shared")!
let sharedEntriesPath = sharedContainerPath.URLByAppendingPathComponent("Entries", isDirectory: true)
// Singleton
class DataManager: NSObject {
static let sharedManager = DataManager()
var entries = [[String: AnyObject]]()
override init() {
super.init()
loadAllEntries()
}
}
// MARK: - Subscript
extension DataManager {
subscript(#category: String, #ascending: Bool) -> [[String: AnyObject]] {
// Filter
let filteredEntries = entries.filter({ (entry) -> Bool in
return (entry["category"] as! String == category) ? true : false
})
// Sort
let sortedEntries: [[String: AnyObject]]
switch ascending {
case true:
sortedEntries = filteredEntries.sorted({ (entryA, entryB) -> Bool in
if (entryA["desc"] as! String).localizedCaseInsensitiveCompare(entryB["desc"] as! String) == NSComparisonResult.OrderedAscending {
return true
}else{
return false
}
})
case false:
sortedEntries = filteredEntries.sorted({ (entryA, entryB) -> Bool in
if (entryA["desc"] as! String).localizedCaseInsensitiveCompare(entryB["desc"] as! String) == NSComparisonResult.OrderedDescending {
return true
}else{
return false
}
})
default: return filteredEntries
}
return sortedEntries
}
}
// MARK: - Helpers
extension DataManager {
func loadEntryFromFile(url: NSURL) -> [String: AnyObject]? {
return NSDictionary(contentsOfURL: url) as? [String: AnyObject]
}
func loadAllEntries() {
// Reset entries
entries = [[String: AnyObject]]()
// Load entries from file
if let urls = NSFileManager.defaultManager().contentsOfDirectoryAtURL(sharedEntriesPath, includingPropertiesForKeys: nil, options: nil, error: nil) as? [NSURL] {
for url in urls {
if let entry = loadEntryFromFile(url) {
entries.append(entry)
}
}
}
}
}
|
mit
|
8d35b1fb3e564b8409546a5f53122437
| 31.482353 | 169 | 0.605435 | 5.18797 | false | false | false | false |
CodeEagle/XMan
|
Sources/XMan/main.swift
|
1
|
1034
|
//
// main.swift
// Carthelper
//
// Created by lincolnlaw on 2017/7/5.
//
import Foundation
func main() {
if CommandLine.argc < 2 {
getXMan()?.processTarget()
} else {
let path = CommandLine.arguments[1]
switch path {
case "version": print("Carthelper version \(XMan.version)")
case "help": Log.usage()
case "init": XMan.initFile()
case "restore": getXMan()?.restore()
case "backup": getXMan()?.backup()
default: break
}
}
}
func getXMan() -> XMan? {
let target = "xman.yaml"
guard let currnetFolder = ProcessInfo.processInfo.environment["PWD"] else { return nil }
let contents = try? FileManager.default.contentsOfDirectory(atPath: currnetFolder)
if contents?.contains(target) == true {
let filePath = currnetFolder.appending("/\(target)")
let xman = XMan(configFile: filePath)
return xman
} else {
Log.error("Not Found \(target) in \(currnetFolder)")
exit(0)
}
}
main()
|
mit
|
ce27fdd7014e7a14e6a0f410443805a8
| 26.210526 | 92 | 0.597679 | 3.82963 | false | false | false | false |
edmoks/RecordBin
|
RecordBin/Class/Constants/KDatabaseStore.swift
|
1
|
1001
|
//
// KDatabaseStore.swift
// RecordBin
//
// Created by Eduardo Rangel on 24/03/2018.
// Copyright © 2018 Eduardo Rangel. All rights reserved.
//
import Foundation
struct KDatabaseStore {
struct Model {
static let About = "about"
static let Address = "address"
static let BusinessHours = "businessHours"
static let City = "city"
static let Country = "country"
static let Email = "email"
static let Latitude = "latitude"
static let Longitude = "longitude"
static let MobilePhone = "mobilePhone"
static let Name = "name"
static let Neighborhood = "neighborhood"
static let State = "state"
static let Telephone = "telephone"
static let URL = "url"
static let ZipCode = "zipCode"
}
struct Firestore {
static let Document = "stores/store"
}
}
|
mit
|
5a37ba8331d50d644057591d56afcd11
| 26.027027 | 57 | 0.546 | 4.444444 | false | false | false | false |
hilen/TimedSilver
|
Sources/UIKit/UIWindow+TSHierarchy.swift
|
3
|
767
|
//
// UIWindow+TSHierarchy.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/4/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
public extension UIWindow {
/**
The top ViewController
- returns: UIViewController
*/
func ts_topViewController() -> UIViewController? {
var topController = self.rootViewController
while let pVC = topController?.presentedViewController {
topController = pVC
}
if topController == nil {
assert(false, "Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
}
return topController
}
}
|
mit
|
dcdae36f7f3b2c3d4e55e03f260df876
| 24.566667 | 132 | 0.638381 | 4.670732 | false | false | false | false |
hirooka/chukasa-ios
|
chukasa-ios/src/model/enum/TranscodingSettings.swift
|
1
|
442
|
import UIKit
enum TranscodingSettings: String {
case CELLULAR_LOW = "CELLULAR_LOW"
case CELLULAR_MID = "CELLULAR_MID"
case CELLULAR_HIGH = "CELLULAR_HIGH"
case WIFI_LOW = "WIFI_LOW"
case WIFI_MID = "WIFI_MID"
case WIFI_HIGH = "WIFI_HIGH"
case HD_LOW = "HD_LOW"
case HD_HIGH = "HD_HIGH"
case FULL_HD_LOW = "FULL_HD_LOW"
case FULL_HD_HIGH = "FULL_HD_HIGH"
case FULL_HD_EXTREME = "FULL_HD_EXTREME"
}
|
mit
|
08b78f443900f78dba7f86fad2a84247
| 28.466667 | 44 | 0.638009 | 2.711656 | false | false | false | false |
chrislzm/TimeAnalytics
|
Time Analytics/TASettingsViewController.swift
|
1
|
6278
|
//
// TASettingsViewController.swift
// Time Analytics
//
// Settings panel for the app. Displays the last time we checked for udpates. Allows user to manually refresh data or logout.
//
// Created by Chris Leung on 5/15/17.
// Copyright © 2017 Chris Leung. All rights reserved.
//
import UIKit
class TASettingsViewController:TADataUpdateViewController {
// MARK: Outlets
@IBOutlet weak var lastUpdatedLabel: UILabel!
@IBOutlet weak var autoUpdateLabel: UILabel!
@IBOutlet weak var refreshActivityView: UIActivityIndicatorView!
@IBOutlet weak var refreshDataButton: BorderedButton!
// MARK: Actions
@IBAction func refreshDataButtonPressed() {
startActivityView()
// After this begins, AppDelegate will handle the rest of the data processing flow, including importing HealthKit data
TAModel.sharedInstance.downloadAndProcessNewMovesData()
}
@IBAction func rescueTimeButtonPressed() {
editRescueTimeApiKey()
}
@IBAction func logOutButtonPressed() {
// Confirmation dialog for logout
let alert = UIAlertController(title: "Confirm Log Out", message: "All Time Analytics data will cleared. You can analyze your data again by logging back in.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Log Out", style: UIAlertActionStyle.default, handler: logoutConfirmed))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
present(alert, animated: true, completion: nil)
}
// MARK: Action Helper Methods
// RescueTime API Key
func editRescueTimeApiKey() {
let dialog = UIAlertController(title: "RescueTime API Key", message: "Entering a RescueTime API Key here will allow us to display your computer usage along with your other activities. Please note this feature is currently under development.", preferredStyle: UIAlertControllerStyle.alert)
dialog.addTextField() { (textField) in
textField.text = TAModel.sharedInstance.getRescueTimeApiKey()
}
dialog.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: {
alert -> Void in
let textField = dialog.textFields![0] as UITextField
self.confirmRescueTimeApiKey(textField.text!)
}))
dialog.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
DispatchQueue.main.async {
self.present(dialog, animated: true, completion: nil)
}
}
func confirmRescueTimeApiKey(_ apiKey:String) {
let confirmDialog = UIAlertController(title: "Confirm", message: "RescueTime API Key:\n\(apiKey)", preferredStyle: UIAlertControllerStyle.alert)
confirmDialog.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.default, handler: {
alert -> Void in
self.saveRescueTimeApiKey(apiKey)
}))
confirmDialog.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
DispatchQueue.main.async {
self.present(confirmDialog, animated: true, completion: nil)
}
}
func saveRescueTimeApiKey(_ apiKey:String) {
TAModel.sharedInstance.setRescueTimeApiKey(apiKey)
let updatedDialog = UIAlertController(title: "Updated", message: "We will use this API key to request updates from RescueTime", preferredStyle: UIAlertControllerStyle.alert)
updatedDialog.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
DispatchQueue.main.async {
self.present(updatedDialog, animated: true, completion: nil)
}
}
// Logout
func logoutConfirmed(alert:UIAlertAction!) {
DispatchQueue.main.async {
// Clear context and persistent data
self.clearAllData()
// Clear session variables
TAModel.sharedInstance.deleteAllSessionData()
// Unwind and display login screen
self.performSegue(withIdentifier: "LogOut", sender: self)
}
}
// MARK: Lifecycle
override func viewDidLoad() {
super .viewDidLoad()
setLastUpdatedText()
setAutoUpdateLabelText()
// Hide button title when disabled so we can show the activity indicator on top of it
refreshDataButton.setTitle("", for: .disabled)
// Stop the activity view if we have an error
errorCompletionHandler = { () in
DispatchQueue.main.async {
self.stopActivityView()
}
}
}
override func didCompleteAllUpdates(_ notification: Notification) {
super.didCompleteAllUpdates(notification)
self.stopActivityView()
self.setLastUpdatedText()
}
// MARK: View Update Methods
func startActivityView() {
refreshActivityView.startAnimating()
refreshDataButton.isEnabled = false
}
func stopActivityView() {
DispatchQueue.main.async {
self.refreshActivityView.stopAnimating()
self.refreshDataButton.isEnabled = true
}
}
// Tells the user the last time we updated our data
func setLastUpdatedText() {
DispatchQueue.main.async {
let lastChecked = TANetClient.sharedInstance.lastCheckedForNewData!
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.doesRelativeDateFormatting = true
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "h:mm a"
let lastUpdatedString = "Last Updated - \(timeFormatter.string(from: lastChecked)) \(dateFormatter.string(from: lastChecked))"
self.lastUpdatedLabel.text = lastUpdatedString
}
}
// Tells the user how often we automatically update
func setAutoUpdateLabelText() {
autoUpdateLabel.text = "Automatically Updates Every \(TAModel.AutoUpdateInterval) Minutes"
}
}
|
mit
|
3b4e3f0ca58f2f5217628c6ad011dc1c
| 37.509202 | 296 | 0.658436 | 5.29258 | false | false | false | false |
PorridgeBear/imvs
|
IMVS/Octree.swift
|
1
|
7497
|
//
// Octree.swift
// IMVS
//
// Created by Allistair Crossley on 29/08/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
class OctreeNode {
// All OctNodes will be leaf nodes at first, ten subdivided later as more objects get added
var isLeaf: Bool = true
// Possible 8 branches
var branches: [OctreeNode?] = [nil, nil, nil, nil, nil, nil, nil, nil]
var ldb: [Float]
var ruf: [Float]
// OctreeNode cubes have a position and size
// position is related to, but not the same as the objects the node contains.
var position: [Float]
var size: Float = 0.0
// Data to store
var objects: [AnyObject?]?
init(position: [Float], size: Float, objects: [AnyObject?]) {
self.position = position
self.size = size
self.objects = objects
var half: Float = (size / 2.0)
// The cube's bounding coordinates -- Not currently used
self.ldb = [position[0] - half, position[1] - half, position[2] - half]
self.ruf = [position[0] + half, position[1] + half, position[2] + half]
}
}
/**
* A Swift Octree implementation based on
* http://code.activestate.com/recipes/498121-python-octree-implementation/
* Not tested and not currently used. Class AtomCloud is used instead.
* No nearest neighbour routines exist in this implementation.
*/
class Octree {
var MAX_OBJECTS_PER_NODE = 10
var DIR_LOOKUP = ["3": 0, "2": 1, "-2": 2, "-1": 3, "1": 4, "0": 5, "-4":6, "-3": 7]
var worldSize: Float = 0.0
var root: OctreeNode?
/**
* Init the world bounding root cube all world geometry is inside this
* it will first be created as a leaf node (i.e., without branches)
* this is because it has no objects, which is less than MAX_OBJECTS_PER_CUBE
* if we insert more objects into it than MAX_OBJECTS_PER_CUBE, then it will subdivide itself.
*/
init(worldSize: Float) {
self.worldSize = worldSize
var position = [Float(0.0), Float(0.0), Float(0.0)]
self.root = addNode(position, size: worldSize, objects: [])
}
func addNode(position: [Float], size: Float, objects: [AnyObject?]) -> OctreeNode {
return OctreeNode(position: position, size: size, objects: objects)
}
func insertNode(root: OctreeNode?, size: Float, parent: OctreeNode, object: Atom)
-> OctreeNode {
let objectPosition = [object.position.x, object.position.y, object.position.z]
if root == nil {
var pos = parent.position
var offset = size / 2
var branch = findBranch(parent, position: objectPosition)
var newCenter: [Float]?
if branch == 0 {
// left down back
newCenter = [pos[0] - offset, pos[1] - offset, pos[2] - offset]
} else if branch == 1 {
// left down forwards
newCenter = [pos[0] - offset, pos[1] - offset, pos[2] + offset]
} else if branch == 2 {
// right down forwards
newCenter = [pos[0] + offset, pos[1] - offset, pos[2] + offset]
} else if branch == 3 {
// right down back
newCenter = [pos[0] + offset, pos[1] - offset, pos[2] - offset]
} else if branch == 4 {
// left up back
newCenter = [pos[0] - offset, pos[1] + offset, pos[2] - offset]
} else if branch == 5 {
// left up forward
newCenter = [pos[0] - offset, pos[1] + offset, pos[2] + offset]
} else if branch == 6 {
// right up forward
newCenter = [pos[0] + offset, pos[1] - offset, pos[2] + offset]
} else if branch == 7 {
// right up back
newCenter = [pos[0] + offset, pos[1] + offset, pos[2] - offset]
}
return addNode(newCenter!, size: size, objects: [object])
} else if root!.position != objectPosition && !root!.isLeaf {
// we're in an octNode still, we need to traverse further
var branch: Int = findBranch(root!, position: objectPosition)
// Find the new scale we working with
let newSize: Float = Float(root!.size / 2)
// Perform the same operation on the appropriate branch recursively
root!.branches[branch] = insertNode(root!.branches[branch], size: newSize, parent: root!, object: object)
} else if root!.isLeaf {
if root!.objects!.count < MAX_OBJECTS_PER_NODE {
root!.objects!.append(object)
} else if root!.objects!.count == MAX_OBJECTS_PER_NODE {
root!.objects!.append(object)
var objects = root!.objects!
root!.objects = nil
root!.isLeaf = false
let newSize: Float = Float(root!.size / 2)
for obj in objects {
let atom = obj as! Atom
let objPosition = [atom.position.x, atom.position.y, atom.position.z]
let branch: Int = findBranch(root!, position: objPosition)
root!.branches[branch] = insertNode(root!.branches[branch], size: newSize, parent: root!, object: atom)
}
}
}
return root!
}
/**
* Basic collision lookup that finds the leaf node containing the specified position
* Returns the child objects of the leaf, or None if the leaf is empty or none
*
func findPosition(root: OctreeNode?, position: [Float]) -> OctreeNode? {
if root == nil {
return nil
} else if root!.isLeaf {
return root!.objects
} else {
branch = findBranch(root, position)
return findPosition(root.branches[branch], position)
}
}
*/
/**
* helper function
* returns an index corresponding to a branch
* pointing in the direction we want to go
*/
func findBranch(root: OctreeNode, position: [Float]) -> Int {
let vec1: [Float] = root.position
let vec2: [Float] = position
var result: Int = 0
// Equation created by adding nodes with known branch directions
// into the tree, and comparing results.
// See DIR_LOOKUP above for the corresponding return values and branch indices
for i in 0...2 {
if vec1[i] <= vec2[i] {
result += (-4 / (i + 1) / 2)
} else {
result += (4 / (i + 1) / 2)
}
}
result = DIR_LOOKUP[String(result)]!
return result
}
func display() {
displayNode(root!, depth: 1)
}
func displayNode(node: OctreeNode?, depth: Int) {
if node != nil {
for branch in node!.branches {
let indent = String(count: depth, repeatedValue: Character("-"))
println("\(indent)>\(branch) has \(branch?.objects!.count)")
displayNode(branch, depth: depth + 1)
}
}
}
}
|
mit
|
23940ee297068b5f566084128d10e0bd
| 34.535545 | 123 | 0.528211 | 4.240385 | false | false | false | false |
olejnjak/KartingCoach
|
KartingCoach/AppDelegate.swift
|
1
|
1192
|
//
// AppDelegate.swift
// KartingCoach
//
// Created by Jakub Olejník on 06/08/2017.
//
import UIKit
import FirebaseCore
import IQKeyboardManagerSwift
final class AppDelegate: UIResponder, UIApplicationDelegate {
private lazy var appFlow: AppFlowController = AppFlowController(window: window!)
var window: UIWindow?
// MARK: UIApplication delegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
setupAppearance()
IQKeyboardManager.shared.enable = true
appFlow.start()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let store = dependencies.circuitStore
return store.import(from: url)
}
// MARK: Private helpers
private func setupAppearance() {
let tableView = UITableView.appearance()
tableView.tableFooterView = UIView()
}
}
|
gpl-3.0
|
690f00c4dc4fc26f01ab04d5be43d976
| 26.068182 | 145 | 0.665827 | 5.269912 | false | false | false | false |
bettkd/KenyaNews
|
KenyaNews/HolderView.swift
|
1
|
3314
|
//
// HolderView.swift
// SBLoader
//
// Created by Satraj Bambra on 2015-03-17.
// Copyright (c) 2015 Satraj Bambra. All rights reserved.
//
import UIKit
protocol HolderViewDelegate:class {
func animateLabel()
}
class HolderView: UIView {
let ovalLayer = OvalLayer()
let triangleLayer = TriangleLayer()
let redRectangleLayer = RectangleLayer()
let blueRectangleLayer = RectangleLayer()
let arcLayer = ArcLayer()
var parentFrame :CGRect = CGRectZero
weak var delegate:HolderViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = Colors.clear
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func addOval() {
layer.addSublayer(ovalLayer)
ovalLayer.expand()
NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "wobbleOval",
userInfo: nil, repeats: false)
}
func wobbleOval() {
ovalLayer.wobble()
// 1
layer.addSublayer(triangleLayer) // Add this line
ovalLayer.wobble()
// 2
// Add the code below
NSTimer.scheduledTimerWithTimeInterval(0.9, target: self,
selector: "drawAnimatedTriangle", userInfo: nil,
repeats: false)
}
func drawAnimatedTriangle() {
triangleLayer.animate()
NSTimer.scheduledTimerWithTimeInterval(0.9, target: self, selector: "spinAndTransform",
userInfo: nil, repeats: false)
}
func spinAndTransform() {
// 1
layer.anchorPoint = CGPointMake(0.5, 0.6)
// 2
let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = CGFloat(M_PI * 2.0)
rotationAnimation.duration = 0.45
rotationAnimation.removedOnCompletion = true
layer.addAnimation(rotationAnimation, forKey: nil)
// 3
ovalLayer.contract()
NSTimer.scheduledTimerWithTimeInterval(0.45, target: self,
selector: "drawRedAnimatedRectangle",
userInfo: nil, repeats: false)
NSTimer.scheduledTimerWithTimeInterval(0.65, target: self,
selector: "drawBlueAnimatedRectangle",
userInfo: nil, repeats: false)
}
func drawRedAnimatedRectangle() {
layer.addSublayer(redRectangleLayer)
redRectangleLayer.animateStrokeWithColor(Colors.red)
}
func drawBlueAnimatedRectangle() {
layer.addSublayer(blueRectangleLayer)
blueRectangleLayer.animateStrokeWithColor(Colors.blue)
NSTimer.scheduledTimerWithTimeInterval(0.40, target: self, selector: "drawArc",
userInfo: nil, repeats: false)
}
func drawArc() {
layer.addSublayer(arcLayer)
arcLayer.animate()
NSTimer.scheduledTimerWithTimeInterval(0.90, target: self, selector: "expandView",
userInfo: nil, repeats: false)
}
func expandView() {
backgroundColor = Colors.blue
frame = CGRectMake(frame.origin.x - blueRectangleLayer.lineWidth,
frame.origin.y - blueRectangleLayer.lineWidth,
frame.size.width + blueRectangleLayer.lineWidth * 2,
frame.size.height + blueRectangleLayer.lineWidth * 2)
layer.sublayers = nil
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.frame = self.parentFrame
}, completion: { finished in
self.addLabel()
})
}
func addLabel() {
delegate?.animateLabel()
}
}
|
apache-2.0
|
17ee17918d5946ab684753ee344d1ab0
| 26.38843 | 109 | 0.704888 | 4.179067 | false | false | false | false |
colemancda/StyleKitView
|
StyleKitSwiftExtractor/StyleKitSwiftExtractor/StyleKitView.swift
|
1
|
2701
|
//
// StyleKitView.swift
// StyleKitSwiftExtractor
//
// Created by Alsey Coleman Miller on 6/9/15.
// Copyright (c) 2015 ColemanCDA. All rights reserved.
//
import Foundation
/** Extracts the canvas names from StyleKit source code (that conform to 'class func drawCanvasName(frame frame: CGRect, tintColor: UIColor)' pattern. */
public func ExtractCanvasNames(inputText: String) -> [String] {
let pattern = "class func draw(\\w+)\\(frame frame: CGRect"
let regularExpression = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions())
let inputTextRange = NSRange(location: 0, length: (inputText as NSString).length)
let matches = regularExpression.matchesInString(inputText, options: NSMatchingOptions(), range: inputTextRange)
var names = [String]()
for result in matches {
let canvasNameRange = result.rangeAtIndex(1)
let canvasName = (inputText as NSString).substringWithRange(canvasNameRange)
names.append(canvasName)
}
return names
}
/** Generates Swift source code from Canvas Names. */
public func GenerateStyleKitViewSourceCode(canvasNames: [String]) -> String {
// No Style Kit Found
if canvasNames.count == 0 {
return "// Compatible canvas names could not be extracted, StyleKitCanvas and StyleKitView and will not be generated."
}
// generate source code...
var sourceCode = ""
// for less code
func sourcePrint(string: String) {
sourceCode.appendLine(string)
}
// add enum
sourcePrint(GenerateStyleKitCanvasSourceCode(canvasNames))
sourcePrint("/** View for displaying PaintCode canvasses. */")
sourcePrint("@IBDesignable public class StyleKitView: UIView {")
sourcePrint("")
sourcePrint("/** Name of the PaintCode canvas to be rendered. Raw value of StyleKitCanvas. */")
sourcePrint("@IBInspectable public var canvasName: String = \"\" { didSet { self.setNeedsDisplay() }}")
sourcePrint("")
sourcePrint("public override func drawRect(rect: CGRect) {")
sourcePrint("if let canvas = StyleKitCanvas(rawValue: self.canvasName) {")
sourcePrint("switch canvas {")
for canvas in canvasNames {
sourcePrint("case .\(canvas): StyleKit.draw\(canvas)(frame: self.bounds, tintColor: self.tintColor)")
}
sourcePrint("}}}")
sourcePrint("public override func prepareForInterfaceBuilder() {")
sourcePrint("if StyleKitCanvas(rawValue: self.canvasName) == nil {\nself.backgroundColor = UIColor.grayColor()\n }")
sourcePrint("}}")
return sourceCode
}
|
mit
|
c1dd5ed1c02b05b09d300b47907be667
| 32.7625 | 153 | 0.670492 | 4.789007 | false | false | false | false |
NUKisZ/TestKitchen_1606
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRedPacketCell.swift
|
1
|
3500
|
//
// CBRedPacketCell.swift
// TestKitchen
//
// Created by NUK on 16/8/18.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
class CBRedPacketCell: UITableViewCell {
@IBOutlet weak var scrollView: UIScrollView!
//显示数据
var model:CBRecommendWidgetListModel?{
didSet{
showData()
}
}
//显示图片
func showData(){
for sub in scrollView.subviews{
sub.removeFromSuperview()
}
scrollView.showsHorizontalScrollIndicator = false
//1.容器视图
let container = UIView.createView()
scrollView.addSubview(container)
container.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView)
make.height.equalTo(self!.scrollView.snp_height)
}
//循环添加图片
var lastView:UIView? = nil
let cnt = model?.widget_data?.count
if cnt > 0 {
for i in 0..<cnt!{
let imageModel = model?.widget_data![i]
if imageModel?.type == "image"{
let imageView = UIImageView.createImageView(nil)
let url = NSURL(string: (imageModel?.content)!)
imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
container.addSubview(imageView)
imageView.snp_makeConstraints(closure: {
(make) in
make.top.bottom.equalTo(container)
make.width.equalTo(180)
if i == 0{
make.left.equalTo(0)
}else{
make.left.equalTo((lastView?.snp_right)!)
}
})
imageView.userInteractionEnabled = true
let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
imageView.tag = 400+i
imageView.addGestureRecognizer(g)
lastView = imageView
}
}
//修改容器的大小
container.snp_makeConstraints(closure: { (make) in
make.right.equalTo((lastView?.snp_right)!)
})
}
}
func tapAction(g:UIGestureRecognizer){
let index = (g.view?.tag)! - 400
print("红包入口\(index)")
}
class func createRedPackageCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendWidgetListModel)->CBRedPacketCell{
let cellId = "redPacketCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId)as? CBRedPacketCell
if cell == nil{
cell = NSBundle.mainBundle().loadNibNamed("CBRedPacketCell", owner: nil, options: nil).last as? CBRedPacketCell
}
cell?.model = listModel
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
5f0b1b01dd80e68a1c6a24676347affb
| 29.166667 | 166 | 0.533585 | 5.340062 | false | false | false | false |
Draveness/RbSwift
|
RbSwift/IO/Dir.swift
|
1
|
9979
|
//
// Dir.swift
// RbSwift
//
// Created by draveness on 10/04/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
public class Dir: CustomStringConvertible {
private var _dir: UnsafeMutablePointer<DIR>?
/// Returns the path parameter passed to dir’s constructor.
public let path: String
/// Returns the file descriptor used in dir.
/// This method uses `dirfd()` function defined by POSIX 2008.
public var fileno: Int {
return dirfd(_dir).to_i
}
/// Returns the current position in dir. See also `Dir#seek(pos:)`.
public var pos: Int {
get {
return telldir(_dir)
}
set {
seek(newValue)
}
}
/// Returns the current position in dir.
public var tell: Int {
return pos
}
/// Returns the path parameter passed to dir’s constructor.
public var to_path: String {
return path
}
/// Return a string describing this Dir object.
public var inspect: String {
return path
}
/// Return a string describing this Dir object.
public var description: String {
return path
}
/// Returns a new directory object for the named directory.
public init?(_ path: String) {
self.path = path
guard let dir = opendir(path) else { return nil }
self._dir = dir
}
/// Returns a new directory object for the named directory.
///
/// - Parameter path: A directory path.
/// - Returns: A new `Dir` object or nil.
public static func new(_ path: String) -> Dir? {
return Dir(path)
}
/// Returns a new directory object for the named directory.
///
/// - Parameter path: A directory path.
/// - Returns: A new `Dir` object or nil.
public static func open(_ path: String) -> Dir? {
return Dir(path)
}
/// Returns the path to the current working directory of this process as a string.
public static var getwd: String {
return FileManager.default.currentDirectoryPath
}
/// Returns the path to the current working directory of this process as a string.
/// An alias to `Dir#getwd` var.
public static var pwd: String {
return getwd
}
// public static func glob(_ pattern: String) -> [String] {
// return []
// }
/// Returns the home directory of the current user or the named user if given.
///
/// Dir.home #=> "/Users/username"
///
public static var home: String {
return NSHomeDirectory()
}
/// Error throws when user doesn't exists.
///
/// - notExists: User doesn't exists
public enum HomeDirectory: Error {
case notExists
}
/// Returns the home directory of the current user or the named user if given.
///
/// Dir.home() #=> "/Users/username"
/// Dir.home("user") #=> "/Users/user"
///
/// - Parameter path: The name of user.
/// - Returns: Home directory.
/// - Throws: HomeDirectory.notExists if user doesn't exist.
public static func home(_ user: String? = nil) throws -> String {
if let home = NSHomeDirectoryForUser(user) { return home }
throw HomeDirectory.notExists
}
/// Changes the current working directory of the process to the given string.
///
/// Dir.chdir("/var/spool/mail")
/// Dir.pwd #=> "/var/spool/mail"
///
/// - Parameter path: A new current working directory.
/// - Returns: A bool indicates the result of `Dir#chdir(path:)`
@discardableResult
public static func chdir(_ path: String = "~") -> Bool {
return FileManager.default.changeCurrentDirectoryPath(path)
}
/// Changes this process’s idea of the file system root.
///
/// - Parameter path: A directory path.
/// - Returns: A bool value indicates the result of `Darwin.chroot`
/// - SeeAlso: `Darwin.chroot`.
@discardableResult
public static func chroot(_ path: String) -> Bool {
return Darwin.chroot(path) == 0
}
/// Changes the current working directory of the process to the given string.
/// Block is passed the name of the new current directory, and the block
/// is executed with that as the current directory. The original working directory
/// is restored when the block exits. The return value of chdir is the value of the block.
///
/// Dir.pwd #=> "/work"
/// let value = Dir.chdir("/var") {
/// Dir.pwd #=> "/var"
/// return 1
/// }
/// Dir.pwd #=> "/work"
/// value #=> 1
///
/// - Parameters:
/// - path: A new current working directory.
/// - closure: A block executed in target directory.
/// - Returns: The value of the closure.
@discardableResult
public static func chdir<T>(_ path: String = "~", closure: (() -> T)) -> T {
let pwd = Dir.pwd
Dir.chdir(path)
let result = closure()
Dir.chdir(pwd)
return result
}
/// Makes a new directory named by string, with permissions specified by the optional parameter anInteger.
///
/// try Dir.mkdir("draveness")
/// try! Dir.mkdir("draveness/spool/mail", recursive: true)
///
/// - Parameters:
/// - path: A new directory path.
/// - recursive: Whether creats intermeidate directories.
/// - permissions: An integer represents the posix permission.
/// - Throws: When `FileManager#createDirectory(atPath:withIntermediateDirectories:attributes:)` throws.
public static func mkdir(_ path: String, recursive: Bool = false, _ permissions: Int? = nil) throws {
var attributes: [FileAttributeKey: Any] = [:]
if let permissions = permissions {
attributes[FileAttributeKey.posixPermissions] = permissions
}
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: recursive, attributes: attributes)
}
/// Error throws when called `Dir#rmdir(path:)` method.
///
/// - notEmpty: Directory is not empty.
/// - notExists: Directory is not exists.
public enum RemoveDirectoryError: Error {
case notEmpty
case cocoa(String)
}
/// Deletes the named directory.
///
/// try Dir.rmdir("/a/folder/path")
///
/// - Parameter path: A directory path
/// - Throws: `RemoveDirectoryError` if the directory isn’t empty.
public static func rmdir(_ path: String) throws {
if !Dir.isEmpty(path) {
throw RemoveDirectoryError.notEmpty
}
do {
try FileManager.default.removeItem(atPath: path)
} catch {
throw RemoveDirectoryError.cocoa(error.localizedDescription)
}
}
/// Deletes the named directory. An alias to `Dir.rmdir(path:)`.
///
/// try Dir.unlink("/a/folder/path")
///
/// - Parameter path: A directory path
/// - Throws: `RemoveDirectoryError` if the directory isn’t empty.
public static func unlink(_ path: String) throws {
try rmdir(path)
}
/// Returns true if the named file is a directory, false otherwise.
///
/// Dir.isExist("/a/folder/path/not/exists") #=> false
/// Dir.isExist("/a/folder/path/exists") #=> true
///
/// - Parameter path: A file path.
/// - Returns: A bool value indicates whether there is a directory in given path.
public static func isExist(_ path: String) -> Bool {
var isDirectory = false as ObjCBool
let exist = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
return exist && isDirectory.boolValue
}
/// Returns true if the named file is an empty directory, false if it is
/// not a directory or non-empty.
///
/// Dir.isEmpty("/a/empty/folder") #=> true
/// Dir.isEmpty("/a/folder/not/exists") #=> true
/// Dir.isEmpty("/a/folder/with/files") #=> false
///
/// - Parameter path: A directory path.
/// - Returns: A bool value indicates the directory is not exists or is empty.
public static func isEmpty(_ path: String) -> Bool {
if let result = try? FileManager.default.contentsOfDirectory(atPath: path) {
return result.isEmpty
}
return true
}
/// Returns an array containing all of the filenames in the given directory. Will return an empty array
/// if the named directory doesn’t exist.
///
/// - Parameter path: A directory path.
/// - Returns: An array of all filenames in the given directory.
public static func entries(_ path: String) -> [String] {
do {
let filenames = try FileManager.default.contentsOfDirectory(atPath: path)
return [".", ".."] + filenames
} catch {
return []
}
}
/// Calls the block once for each entry in the named directory, passing the filename of each
/// entry as a parameter to the block.
///
/// - Parameters:
/// - path: A directory path.
/// - closure: A closure accepts all the entries in current directory.
public static func foreach(_ path: String, closure: (String) -> ()) {
entries(path).each(closure)
}
/// Deletes the named directory.
///
/// - Parameter path: A directory path.
/// - Returns: A bool value indicates the result of `Dir.delete(path:)`
@discardableResult
public static func delete(_ path: String) -> Bool {
return Darwin.rmdir(path) == 0
}
/// Seeks to a particular location in dir.
///
/// - Parameter pos: A particular location.
public func seek(_ pos: Int) {
seekdir(_dir, pos)
}
/// Repositions dir to the first entry.
public func rewind() {
rewinddir(_dir)
}
}
|
mit
|
6c1e37e317153ea89794047e02ad5a17
| 32.897959 | 125 | 0.595324 | 4.4254 | false | false | false | false |
Finb/V2ex-Swift
|
Common/UIImage+Extension.swift
|
2
|
1204
|
//
// UIImage+Extension.swift
// V2ex-Swift
//
// Created by huangfeng on 2/3/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
extension UIImage {
func roundedCornerImageWithCornerRadius(_ cornerRadius:CGFloat) -> UIImage {
let w = self.size.width
let h = self.size.height
var targetCornerRadius = cornerRadius
if cornerRadius < 0 {
targetCornerRadius = 0
}
if cornerRadius > min(w, h) {
targetCornerRadius = min(w,h)
}
let imageFrame = CGRect(x: 0, y: 0, width: w, height: h)
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
UIBezierPath(roundedRect: imageFrame, cornerRadius: targetCornerRadius).addClip()
self.draw(in: imageFrame)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
class func imageUsedTemplateMode(_ named:String) -> UIImage? {
let image = UIImage(named: named)
if image == nil {
return nil
}
return image!.withRenderingMode(.alwaysTemplate)
}
}
|
mit
|
848233e9ff8662b40df2af74dabbbc16
| 25.733333 | 89 | 0.610973 | 4.754941 | false | false | false | false |
JiongXing/PhotoBrowser
|
Sources/JXPhotoBrowser/JXPhotoBrowserLog.swift
|
1
|
1055
|
//
// JXPhotoBrowserLog.swift
// JXPhotoBrowser
//
// Created by JiongXing on 2019/11/12.
// Copyright © 2019 JiongXing. All rights reserved.
//
import Foundation
public struct JXPhotoBrowserLog {
/// 日志重要程度等级
public enum Level: Int {
case low = 0
case middle
case high
case forbidden
}
/// 允许输出日志的最低等级。`forbidden`为禁止所有日志
public static var level: Level = .forbidden
public static func low(_ item: @autoclosure () -> Any) {
if level.rawValue <= Level.low.rawValue {
print("[JXPhotoBrowser] [low]", item())
}
}
public static func middle(_ item: @autoclosure () -> Any) {
if level.rawValue <= Level.middle.rawValue {
print("[JXPhotoBrowser] [middle]", item())
}
}
public static func high(_ item: @autoclosure () -> Any) {
if level.rawValue <= Level.high.rawValue {
print("[JXPhotoBrowser] [high]", item())
}
}
}
|
mit
|
bc14fae710c459b6c4ff10c78418f900
| 23.390244 | 63 | 0.568 | 4.166667 | false | false | false | false |
byvapps/ByvManager-iOS
|
ByvManager/Classes/SocialWebViewController.swift
|
1
|
6107
|
//
// SocialWebViewController.swift
// Pods
//
// Created by Adrian Apodaca on 28/10/16.
//
//
import UIKit
import SVProgressHUD
public enum SocialType {
case facebook
case twitter
case linkedin
case google
func title() -> String {
switch self {
case .facebook: return "Facebook"
case .twitter: return "Twitter"
case .linkedin: return "Linkedin"
case .google: return "Google"
}
}
func path() -> String {
switch self {
case .facebook: return url_facebook_login()
case .twitter: return url_twitter_login()
case .linkedin: return url_linkedin_login()
case .google: return url_google_login()
}
}
func codeKey() -> String {
switch self {
case .facebook: return "code"
case .twitter: return "oauth_token"
case .linkedin: return "code"
case .google: return "code"
}
}
}
public class SocialWebViewController: UIViewController, UIWebViewDelegate {
private let html = "<!DOCTYPE html><html><head><style>body {text-align: center;font-family: sans-serif;color: #555;}.loader {border: 5px solid #f3f3f3;border-radius: 50%;border-top: 5px solid #888;width: 50px;height: 50px;margin: auto;margin-top: 20%;-webkit-animation: spin 2s linear infinite;animation: spin 1.4s linear infinite;}@-webkit-keyframes spin {0% { -webkit-transform: rotate(0deg); }100% { -webkit-transform: rotate(360deg); }}@keyframes spin {0% { transform: rotate(0deg); }100% { transform: rotate(360deg); }}</style></head><body><div class=\"loader\"></div></body></html>"
private var _type: SocialType = .facebook
public var type: SocialType {
get {
return _type
}
set (newType) {
_type = newType
self.navigationItem.title = _type.title()
}
}
private var webView: UIWebView = UIWebView()
private var _code: String? = nil
public func loadPreWeb() {
webView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
webView.loadHTMLString(html, baseURL: nil)
}
override public func viewDidLoad() {
super.viewDidLoad()
webView.translatesAutoresizingMaskIntoConstraints = false
self.view.backgroundColor = UIColor.white
self.view.addSubview(webView)
let v: UIView = webView
let views = ["view": v]
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options:[], metrics: nil, views: views)
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: views)
view.addConstraints(horizontalConstraints)
view.addConstraints(verticalConstraints)
if self.navigationController?.viewControllers[0] == self {
let bi = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.close(sender:)))
self.navigationItem.rightBarButtonItem = bi
}
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
_code = nil
webView.alpha = 1.0
let url = "\(Environment.baseUrl())/\(type.path())"
self.webView.delegate = self
self.webView.loadRequest(URLRequest(url: URL(string: url)!))
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if ByvManager.debugMode {
print("URL: \(String(describing: request.url?.absoluteURL))")
print("PATH: \(String(describing: request.url?.path))")
}
let callbackPath = "/\(type.path())/\(url_social_callback())"
if ByvManager.debugMode {
print("callbackPath: \(callbackPath)")
}
if request.url?.path == callbackPath {
let urlComponents = NSURLComponents(string: request.url!.absoluteString)
let queryItems = urlComponents?.queryItems
var params: [String: Any] = [:]
for item in queryItems! {
params[item.name] = item.value
}
if let code = params[self.type.codeKey()] as! String? {
_code = code
webView.alpha = 0.0
}
return true
}
return true
}
public func webViewDidStartLoad(_ webView: UIWebView) {
// print("webViewDidStartLoad")
}
public func webViewDidFinishLoad(_ webView: UIWebView) {
if let code = _code {
ByvAuth.socialLogin(code: code, background: false, success: { (data) in
self.close(sender: nil)
})
_code = nil
}
// print("webViewDidFinishLoad")
//
// print("RESPUESTA: \(webView.stringByEvaluatingJavaScript(from: "getCredentials()")!)")
//
//
// let jsonData: String = webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")!
// if let json = try? JSONSerialization.jsonObject(with: jsonData.data(using: .utf8)!) {
// print("JSON: \(json)")
// self.close(sender: nil)
// }
}
public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
SVProgressHUD.showError(withStatus: NSLocalizedString("Error", comment: "Spinner"))
}
@objc func close(sender: UIBarButtonItem?) {
webView.loadHTMLString(html, baseURL: nil)
if self.navigationController?.viewControllers[0] == self {
self.dismiss(animated: true, completion: nil)
} else {
_ = self.navigationController?.popViewController(animated: true)
}
}
}
|
mit
|
4de96a8f08f4f9cbb1606cc7f8bb01d8
| 34.097701 | 592 | 0.595546 | 4.651181 | false | false | false | false |
narner/AudioKit
|
AudioKit/Common/Nodes/Effects/Filters/High Pass Butterworth Filter/AKHighPassButterworthFilter.swift
|
1
|
3460
|
//
// AKHighPassButterworthFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// These filters are Butterworth second-order IIR filters. They offer an almost
/// flat passband and very good precision and stopband attenuation.
///
open class AKHighPassButterworthFilter: AKNode, AKToggleable, AKComponent, AKInput {
public typealias AKAudioUnitType = AKHighPassButterworthFilterAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(effect: "bthp")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var cutoffFrequencyParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// Cutoff frequency. (in Hertz)
@objc open dynamic var cutoffFrequency: Double = 500.0 {
willSet {
if cutoffFrequency != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
cutoffFrequencyParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.cutoffFrequency = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - Parameters:
/// - input: Input node to process
/// - cutoffFrequency: Cutoff frequency. (in Hertz)
///
@objc public init(
_ input: AKNode? = nil,
cutoffFrequency: Double = 500.0) {
self.cutoffFrequency = cutoffFrequency
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
input?.connect(to: self!)
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
cutoffFrequencyParameter = tree["cutoffFrequency"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.cutoffFrequency = Float(cutoffFrequency)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
|
mit
|
f54c57604e6d1a6c8c651b12e6aeec86
| 30.733945 | 102 | 0.613472 | 5.280916 | false | false | false | false |
rherndon47/TIYAssignments
|
Swift playground folder/5-TableViewTest.playground/section-1.swift
|
1
|
2489
|
class TipCalculatorModel
{
var total: Double
var taxPercent: Double
var subTotal: Double
{
get
{
return total / (taxPercent + 1)
}
}
init(total: Double, taxPercent: Double)
{
self.total = total
self.taxPercent = taxPercent
}
func calcTipWithTipPercent(tipPercent: Double) -> (tipAmount:Double, total:Double)
{
let tipAmount = subTotal * tipPercent
let finalTotal = total + tipAmount
return (tipAmount, finalTotal)
}
func printPossibleTips()
{
println("15%: \(calcTipWithTipPercent(0.15))")
println("18%: \(calcTipWithTipPercent(0.18))")
println("20%: \(calcTipWithTipPercent(0.20))")
}
func returnPossibleTips() -> [Int: (tipAmount:Double, total:Double)]
{
let possibleTips = [0.15, 0.18, 0.20]
var rValue = Dictionary<Int, (tipAmount:Double, total:Double)>()
for possibleTip in possibleTips
{
let integerPercent = Int(possibleTip*100)
rValue[integerPercent] = calcTipWithTipPercent(possibleTip)
}
return rValue
}
}
import UIKit
class TestDataSource : NSObject, UITableViewDataSource
{
let tipCalc = TipCalculatorModel(total: 42.75, taxPercent: 0.06)
var possibleTips = Dictionary<Int, (tipAmount:Double, total:Double)>()
var sortedKeys:[Int] = []
override init()
{
possibleTips = tipCalc.returnPossibleTips()
sortedKeys = sorted(Array(possibleTips.keys))
super.init()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return sortedKeys.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: nil)
let tipPercent = sortedKeys[indexPath.row]
let tipAmount = possibleTips[tipPercent]!.tipAmount
let total = possibleTips[tipPercent]!.total
cell.textLabel?.text = "\(tipPercent)%:"
cell.detailTextLabel?.text = String(format: "Tip: $%0.2f, Total: $%0.2f", tipAmount, total)
return cell
}
}
let testDataSource = TestDataSource()
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 320, height: 320), style: .Plain)
tableView.dataSource = testDataSource
tableView.reloadData()
|
cc0-1.0
|
1c704a75714c57fa57356b257a9b750e
| 29 | 107 | 0.629972 | 4.500904 | false | false | false | false |
ji3g4m6zo6/bookmark
|
Pods/BarcodeScanner/Sources/HeaderView.swift
|
1
|
1852
|
import UIKit
protocol HeaderViewDelegate: class {
func headerViewDidPressClose(_ headerView: HeaderView)
}
/**
Header view that simulates a navigation bar.
*/
class HeaderView: UIView {
/// Title label.
lazy var label: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor.white
label.text = Title.text
label.font = Title.font
label.textColor = Title.color
label.numberOfLines = 1
label.textAlignment = .center
return label
}()
/// Close button.
lazy var button: UIButton = {
let button = UIButton(type: .system)
button.setTitle(CloseButton.text, for: UIControlState())
button.titleLabel?.font = CloseButton.font
button.tintColor = CloseButton.color
button.addTarget(self, action: #selector(buttonDidPress), for: .touchUpInside)
return button
}()
/// Header view delegate.
weak var delegate: HeaderViewDelegate?
// MARK: - Initialization
/**
Creates a new instance of `HeaderView`.
- Parameter frame: View frame.
*/
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
[label, button].forEach {
addSubview($0)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
let padding: CGFloat = 8
let labelHeight: CGFloat = 40
button.sizeToFit()
button.frame.origin = CGPoint(x: 15,
y: ((frame.height - button.frame.height) / 2) + padding)
label.frame = CGRect(
x: 0, y: ((frame.height - labelHeight) / 2) + padding,
width: frame.width, height: labelHeight)
}
// MARK: - Actions
/**
Close button action handler.
*/
func buttonDidPress() {
delegate?.headerViewDidPressClose(self)
}
}
|
mit
|
5444228e1d92887c71b4d1477069ba1a
| 20.534884 | 82 | 0.658747 | 4.209091 | false | false | false | false |
IvanGao0217/AHRouter
|
Demo/AHRouterDemo/extensions.swift
|
1
|
696
|
//
// extensions.swift
// AHRouter
//
// Created by IvanGao on 10/17/17.
// Copyright © 2017 IvanGao. All rights reserved.
//
import Foundation
import UIKit
func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
|
mit
|
3589c9abcb324cdde9fdefcdd7f6db45
| 25.730769 | 125 | 0.692086 | 4.760274 | false | false | false | false |
younata/RSSClient
|
TethysKitSpecs/WebPageParserSpec.swift
|
1
|
1886
|
import Quick
import Nimble
import TethysKit
class WebPageParserSpec: QuickSpec {
override func spec() {
var subject: WebPageParser!
let bundle = Bundle(for: self.classForCoder)
let url = bundle.url(forResource: "webpage", withExtension: "html")!
let webPage = try! String(contentsOf: url)
var receivedUrls: [URL]? = nil
beforeEach {
receivedUrls = nil
subject = WebPageParser(string: webPage) {
receivedUrls = $0
}
}
describe("specifying a search for feeds") {
it("returns the found feeds when it completes") {
subject.searchType = .feeds
subject.start()
expect(receivedUrls) == [URL(string: "/feed.xml")!, URL(string: "/feed2.xml")!]
}
}
describe("Specifying links") {
it("returns all links of type <a href=...") {
subject.searchType = .links
subject.start()
let urls = [
"/",
"#",
"/about/",
"/libraries/",
"/2015/12/23/iot-homemade-thermostat/",
"/2015/08/21/osx-programming-set-up-core-animation/",
"/2015/08/14/osx-programming-programmatic-menu-buttons/",
"/2015/08/08/osx-programming-programmatic-scrolling-tableview/",
"/2015/07/21/muon-rss-parsing-swift/",
"/2015/01/28/setting-up-travis-for-objc/",
"/2014/07/31/homekit-basics/",
"/feed.xml",
"https://github.com/younata",
"https://twitter.com/younata"
].compactMap(URL.init)
expect(receivedUrls) == urls
}
}
}
}
|
mit
|
32f3f0b1534671eb032f1b95d8cbf840
| 31.517241 | 95 | 0.483033 | 4.588808 | false | false | false | false |
borchero/WebParsing
|
WebParsing/WPElement.swift
|
1
|
15250
|
// MIT License
//
// Copyright (c) 2017 Oliver Borchert (borchero@in.tum.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreUtility
public protocol WPElement: CustomStringConvertible {
/// Initializes a `WPElement` with type `Any`. In fact, this is not really
/// type `Any` but just used for internal simplicity and generic
/// programming. **It should not be used outside of this module.**
///
/// - parameter any: The value to initialize the element with.
///
/// - returns: A newly initialized instance.
init(_ any: Any)
init(reading: Data)
/// Initializes a `WPElement` with a specified value. **This initializer
/// should not be used outside of this module.** Use the convenience
/// initializers for simple Swift types instead.
///
/// - parameter value: The value to initialize the element with.
///
/// - returns: A newly initialized instacne.
init(value: WPValue<Self>)
/// The value the current element is wrapping.
var value: WPValue<Self> { get set }
/// Returns a description for the element.
///
/// - parameter offset: Shouldn't be used publicly, just for
/// printing objects and arrays prettily.
/// - parameter prettyPrinted: `true` if the description should be read
/// by a human, `false` if it should just be
/// as small as possible.
///
/// - returns: The description as `String`.
func description(forOffset offset: String, prettyPrinted: Bool) -> String
}
extension WPElement {
public static var array: Self {
return Self(value: .array([]))
}
public static var dictionary: Self {
return Self(value: .object([:]))
}
public static var null: Self {
return Self(value: .null)
}
public static var undefined: Self {
return Self(value: .undefined)
}
internal func simpleDescription() -> String {
switch value {
case .string(let string):
return string
case .null:
return "nil"
case .number(let number):
return "\(number)"
case .boolean(let bool):
return "\(bool)"
case .array(let array):
return "[\(array.map { "\($0.simpleDescription())" }.joined(separator: ",\n"))]"
case .object(let dictionary):
return "[\(dictionary.map { "\($0.0): \($0.1.simpleDescription())" }.joined(separator: ",\n"))]"
case .undefined:
return "<undefined>"
}
}
// MARK: Computed properties
public func anyValue() throws -> Any {
switch value {
case .string(let string):
return string
case .number(let number):
return number
case .boolean(let bool):
return bool
case .array(let array):
return array.map { $0.anyValue }
case .object(let dictionary):
return dictionary.mapValues { $0.anyValue }
case .null, .undefined:
throw WPError.anyIncompatibleValue
}
}
public func anyDictionary() throws -> [String: Any] {
return try (anyValue() as? [String: Any]).unwrap()
}
/// The keys of all subelements in case `self` wraps an object.
public var propertyKeys: Set<String>? {
switch value {
case .object(let object): return Set(object.keys)
default: return nil
}
}
/// Returns the number of subelements in case `self` is either
/// an array or an object (equals dictionary in this case).
public var count: Int {
switch value {
case .array(let array): return array.count
case .object(let dictionary): return dictionary.count
default: return 0
}
}
// MARK: Check access
/// Returns if `self` wraps a string.
public var isString: Bool {
if case .string = value {
return true
}
return false
}
/// Returns if `self` wraps a boolean.
public var isBoolean: Bool {
if case .boolean = value {
return true
}
return false
}
/// Returns if `self` wraps a number.
public var isNumber: Bool {
if case .number = value {
return true
}
return false
}
/// Returns if `self` wraps an object (dictionary).
public var isDictionary: Bool {
if case .object = value {
return true
}
return false
}
/// Returns if `self` wraps an array.
public var isArray: Bool {
if case .array = value {
return true
}
return false
}
public var isCollection: Bool {
switch value {
case .array, .object: return true
default: return false
}
}
/// Returns if `self` is neither `nil` nor `undefined`.
public var isValue: Bool {
switch value {
case .null, .undefined: return false
default: return true
}
}
/// Returns if `self` wraps `nil`.
public var isNull: Bool {
if case .null = value {
return true
}
return false
}
/// Returns if `self` is not equal to the `undefined` value which
/// indicates an error when reading the document.
public var isDefined: Bool {
if case .undefined = value {
return false
}
return true
}
// MARK: Access and manipulation
/// The string in case `self` wraps a string, `nil` otherwise.
public var stringValue: String? {
switch value {
case .string(let string): return string
default: return nil
}
}
/// The boolean in case `self` wraps a boolean, `nil` otherwise.
public var boolValue: Bool? {
switch value {
case .boolean(let bool): return bool
default: return nil
}
}
/// The double in case `self` wraps a double, `nil` otherwise.
public var doubleValue: Double? {
switch value {
case .number(let number): return number.doubleValue
default: return nil
}
}
/// The string in case `self` wraps a string, `nil` otherwise.
public var intValue: Int? {
switch value {
case .number(let number): return number.intValue
default: return nil
}
}
public var int64Value: Int64? {
switch value {
case .number(let number): return number.int64Value
default: return nil
}
}
public var int32Value: Int32? {
switch value {
case .number(let number): return number.int32Value
default: return nil
}
}
public var int16Value: Int16? {
switch value {
case .number(let number): return number.int16Value
default: return nil
}
}
public var int8Value: Int8? {
switch value {
case .number(let number): return number.int8Value
default: return nil
}
}
public var uintValue: UInt? {
switch value {
case .number(let number): return number.uintValue
default: return nil
}
}
public var uint64Value: UInt64? {
switch value {
case .number(let number): return number.uint64Value
default: return nil
}
}
public var uint32Value: UInt32? {
switch value {
case .number(let number): return number.uint32Value
default: return nil
}
}
public var uint16Value: UInt16? {
switch value {
case .number(let number): return number.uint16Value
default: return nil
}
}
public var uint8Value: UInt8? {
switch value {
case .number(let number): return number.uint8Value
default: return nil
}
}
public var decimalValue: Decimal? {
switch value {
case .number(let number): return number.decimalValue
default: return nil
}
}
public var arrayValue: [Self]? {
switch value {
case .array(let array): return array
default: return nil
}
}
public var dictionaryValue: [String: Self]? {
switch value {
case .object(let object): return object
default: return nil
}
}
/// The subscript may be used on objects to access properties by name.
/// Both accessing and setting a property of an element that is no
/// object won't quit the application. When accessing, an `unvailable`
/// value is returned, when setting, the function simply does nothing
/// except for printing an error message to the console.
///
/// - parameter key: The key is the name of the property. When there
/// is no property that is named like that, an
/// `unavailable` value with a helpful error message
/// is returned. When setting the value, all prior
/// values are silently overridden or a new property
/// is created.
///
/// - returns: The subscript returns the element that was accessed by
/// the property.
public subscript(key: String) -> Self {
get {
switch value {
case .object(let object):
return object[key] ?? Self.undefined
default:
return Self.undefined
}
} set {
switch value {
case .object(var object):
object[key] = newValue
value = .object(object)
default:
print("Setting a property is only allowed on objects.")
}
}
}
/// If `self` wraps an array, this subscript returns the value at
/// the specified index. If the index is out of bounds, an `undefined`
/// value is returned. If `self` is anything else (except for `undefined`)
/// and `index` is zero, the element itself is returned. The reason for
/// this is: when using XML, there can't be distinguished between an
/// array and a simple value when there only exists a single value. Yet,
/// the code should still work, if it's supposed to be an array but only
/// holds one value making it being stored as simple value internally.
///
/// When setting an index, a simple error message is printed to the
/// in case `self` wraps an array, the program is not terminated. When
/// having values apart from `undefined`, they can be set using index 0
/// as well (same reason as above). When the index is not equal to 0,
/// an error message is printed and the program continues to run.
///
/// - parameter index: The index to subscript for.
///
/// - returns: The element that was accessed by the specified index.
public subscript(index: Int) -> Self {
get {
switch value {
case .array(let array):
return array.get(at: index) ?? Self.undefined
case .string, .boolean, .number, .null, .object:
if index == 0 {
return self
}
fallthrough
default:
return Self.undefined
}
} set {
switch value {
case .array(var array):
guard array.indices.contains(index) ||
array.count == index else {
print("Index is out of range.")
return
}
array[index] = newValue
self.value = .array(array)
case .string, .boolean, .number, .null, .object:
if index == 0 {
self = newValue
} else {
fallthrough
}
default:
print("Setting an index is not allowed on type undefined and" +
"indices not equal 0 may only be used on arrays.")
}
}
}
/// Appends a value to `self` in case it wraps an array.
/// In case `self` is not an array, `self` is made an
/// array and the element is appended to this array. The
/// original `self` value is the first element of the
/// newly created array. If `self` is `undefined`, it
/// is the first element of the array as well.
///
/// - parameter element: The element to append.
public mutating func append(_ element: Self) {
switch value {
case .array(var array):
array.append(element)
value = .array(array)
default:
let value = self
self.value = .array([value, element])
}
}
/// Removes a value from `self` in case it wraps an array.
/// Index 0 can always be removed. If `self` is not an array,
/// `self` deletes itself and replaces itself by an empty
/// array. The reason for doing this is, XML single values
/// should be treated as arrays as well. In all other cases
/// (including `self` is `undefined`), nothing is done and
/// `nil` is returned.
///
/// - parameter index: The index to remove the element at.
///
/// - returns: The element that has been removed or `nil`
/// if there was no element removed.
public mutating func remove(at index: Int) -> Self? {
switch value {
case .array(var array):
let removed = array.remove(at: index)
value = .array(array)
return removed
default:
if index == 0 {
let removed = self
self.value = .array([])
return removed
}
return nil
}
}
/// A human readable description of `self`.
public var description: String {
return description(forOffset: "", prettyPrinted: true)
}
}
|
mit
|
0eb82b17cdd7b538fa518ef7fe627b46
| 31.446809 | 108 | 0.56577 | 4.738968 | false | false | false | false |
SusanDoggie/Doggie
|
Sources/DoggieGraphics/ImageCodec/AnimatedEncoder/PNGAnimatedEncoder.swift
|
1
|
10583
|
//
// PNGAnimatedEncoder.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
extension PNGEncoder: AnimatedImageEncoder {
struct Frame<Pixel: ColorPixel> {
var image: Image<Pixel>
var duration: Double
}
static func encodeAnimationControlChunk(frames_count: Int, repeats: Int) -> PNGChunk {
var data = Data(capacity: 8)
data.encode(BEUInt32(frames_count))
data.encode(BEUInt32(repeats))
return PNGChunk(signature: "acTL", data: data)
}
static func encodeFrameControlChunk(sequence_number: Int, region: PNGRegion, duration: Int, dispose_op: UInt8, blend_op: UInt8) -> PNGChunk {
var data = Data(capacity: 26)
data.encode(BEUInt32(sequence_number))
data.encode(BEUInt32(region.width))
data.encode(BEUInt32(region.height))
data.encode(BEUInt32(region.x))
data.encode(BEUInt32(region.y))
data.encode(BEUInt16(duration))
data.encode(1000 as BEUInt16)
data.encode(dispose_op)
data.encode(blend_op)
return PNGChunk(signature: "fcTL", data: data)
}
static func encodeFrameDataChunk<Pixel>(image: Image<Pixel>, region: PNGRegion, sequence_number: Int, deflate_level: Deflate.Level, predictor: PNGPrediction, interlaced: Bool, opaque: Bool) -> PNGChunk? where Pixel: TIFFEncodablePixel {
guard let encoded_data = encodeIDAT(image: image, region: region, deflate_level: deflate_level, predictor: predictor, interlaced: interlaced, opaque: opaque)?.data else { return nil }
var data = Data(capacity: encoded_data.count + 4)
data.encode(BEUInt32(sequence_number))
data.append(encoded_data)
return PNGChunk(signature: "fdAT", data: data)
}
static func trim_to_minimize<Pixel>(prev_image: Image<Pixel>, image: Image<Pixel>) -> PNGRegion {
var region = PNGRegion(x: 0, y: 0, width: image.width, height: image.height)
let width = image.width
let height = image.height
prev_image.withUnsafeBufferPointer {
guard let prev_image = $0.baseAddress else { return }
image.withUnsafeBufferPointer {
guard let image = $0.baseAddress else { return }
var top = 0
var left = 0
var bottom = 0
var right = 0
loop: for y in (0..<height).reversed() {
let prev_image = prev_image + width * y
let image = image + width * y
for x in 0..<width where prev_image[x] != image[x] {
break loop
}
bottom += 1
}
let max_y = height - bottom
loop: for y in 0..<max_y {
let prev_image = prev_image + width * y
let image = image + width * y
for x in 0..<width where prev_image[x] != image[x] {
break loop
}
top += 1
}
loop: for x in (0..<width).reversed() {
for y in top..<max_y where prev_image[x + width * y] != image[x + width * y] {
break loop
}
right += 1
}
let max_x = width - right
loop: for x in 0..<max_x {
for y in top..<max_y where prev_image[x + width * y] != image[x + width * y] {
break loop
}
left += 1
}
region = PNGRegion(x: left, y: top, width: max_x - left, height: max_y - top)
}
}
return region
}
static func encodeFrames<Pixel>(frames: [Frame<Pixel>], deflate_level: Deflate.Level, predictor: PNGPrediction, interlaced: Bool, opaque: Bool) -> [PNGChunk]? where Pixel: TIFFEncodablePixel {
var chunks: [PNGChunk] = []
chunks.reserveCapacity(frames.count << 1)
var prev_image: Image<Pixel>?
var last_duration = 0
var last_sequence_number = 0
var sequence_number = 0
for (i, frame) in frames.enumerated() {
var region = PNGRegion(x: 0, y: 0, width: frame.image.width, height: frame.image.height)
if let prev_image = prev_image {
region = trim_to_minimize(prev_image: prev_image, image: frame.image)
}
if region.width == 0 && region.height == 0 {
last_duration += Int(Double(frame.duration * 1000).rounded())
let fctl = encodeFrameControlChunk(sequence_number: last_sequence_number, region: region, duration: last_duration, dispose_op: 0, blend_op: 0)
chunks[chunks.count - 2] = fctl
continue
} else {
last_duration = Int(Double(frame.duration * 1000).rounded())
let fctl = encodeFrameControlChunk(sequence_number: sequence_number, region: region, duration: last_duration, dispose_op: 0, blend_op: 0)
chunks.append(fctl)
last_sequence_number = sequence_number
sequence_number += 1
}
if i == 0 {
guard let idat = encodeIDAT(image: frame.image, region: region, deflate_level: deflate_level, predictor: predictor, interlaced: interlaced, opaque: opaque) else { return nil }
chunks.append(idat)
} else {
guard let fdat = encodeFrameDataChunk(image: frame.image, region: region, sequence_number: sequence_number, deflate_level: deflate_level, predictor: predictor, interlaced: interlaced, opaque: opaque) else { return nil }
chunks.append(fdat)
sequence_number += 1
}
prev_image = frame.image
}
return chunks
}
static func encode(image: AnimatedImage, properties: [ImageRep.PropertyKey: Any]) -> Data? {
let deflate_level = properties[.deflateLevel] as? Deflate.Level ?? .default
let predictor = properties[.predictor] as? PNGPrediction ?? .all
let interlaced = properties[.interlaced] as? Bool == true
let opaque = image.frames.allSatisfy { $0.image.isOpaque }
guard let first = image.frames.first else { return nil }
guard image.frames.allSatisfy({ $0.image.width == first.image.width && $0.image.height == first.image.height }) else { return nil }
let phys = pHYs(first.image.resolution)
let actl = encodeAnimationControlChunk(frames_count: image.frames.count, repeats: image.repeats)
let ihdr: PNGChunk
let iccp: PNGChunk
let frame_chunks: [PNGChunk]
if var colorSpace = first.image.colorSpace.base as? ColorSpace<GrayColorModel> {
if let _iccp = iCCP(colorSpace, deflate_level: deflate_level) {
iccp = _iccp
} else {
colorSpace = .genericGamma22Gray
iccp = iCCP(colorSpace, deflate_level: deflate_level)!
}
ihdr = IHDR(width: first.image.width, height: first.image.height, bitDepth: 8, colour: opaque ? 0 : 4, interlaced: interlaced)
let frames = image.frames.map { Frame(image: $0.image.convert(to: colorSpace) as Image<Gray16ColorPixel>, duration: $0.duration) }
guard let _frame_chunks = encodeFrames(frames: frames, deflate_level: deflate_level, predictor: predictor, interlaced: interlaced, opaque: opaque) else { return nil }
frame_chunks = _frame_chunks
} else {
var colorSpace = first.image.colorSpace.base as? ColorSpace<RGBColorModel> ?? .sRGB
if let _iccp = iCCP(colorSpace, deflate_level: deflate_level) {
iccp = _iccp
} else {
colorSpace = .sRGB
iccp = iCCP(colorSpace, deflate_level: deflate_level)!
}
ihdr = IHDR(width: first.image.width, height: first.image.height, bitDepth: 8, colour: opaque ? 2 : 6, interlaced: interlaced)
let frames = image.frames.map { Frame(image: $0.image.convert(to: colorSpace) as Image<RGBA32ColorPixel>, duration: $0.duration) }
guard let _frame_chunks = encodeFrames(frames: frames, deflate_level: deflate_level, predictor: predictor, interlaced: interlaced, opaque: opaque) else { return nil }
frame_chunks = _frame_chunks
}
return encode([ihdr, phys, iccp, actl] + frame_chunks).data
}
}
|
mit
|
ecc19ca3e6073f4515ece40a7f8d71a7
| 40.339844 | 240 | 0.547387 | 4.567544 | false | false | false | false |
TheNounProject/CollectionView
|
Example/Example/MyPlayground.playground/Contents.swift
|
1
|
1939
|
/*:
# Collection View
This playground includes some of the utilities in the CollectionView library
*/
import Cocoa
import CollectionView
//: ## Sort Descriptors
struct Person {
let name: String
let age: Int
}
let jim = Person(name: "Jim", age: 30)
let bob = Person(name: "Bob", age: 35)
let alex = Person(name: "Alex", age: 30)
let steve = Person(name: "Steve", age: 35)
func theAgeGame(with a: Person, and b: Person) -> String {
switch SortDescriptor(\Person.age).compare(a, to: b) {
case .same:
return ("\(a.name) and \(b.name) are both \(a.age)")
case .ascending:
return ("\(b.name)(\(b.age)) is \(b.age - a.age) years older than \(a.name)(\(a.age))")
case .descending:
return ("\(a.name)(\(a.age)) is \(a.age - b.age) years older than \(b.name)(\(b.age))")
}
}
theAgeGame(with: jim, and: alex) // "Jim and Alex are both 30"
theAgeGame(with: jim, and: bob) // "Bob(35) is 5 years older than Jim(30)"
var dudes = [steve, jim, bob, alex]
let ageThenName = [SortDescriptor(\Person.age), SortDescriptor(\Person.name)]
let ordered = dudes.sorted(using: ageThenName)
//: ## CollectionView editing
class Section {
enum State {
case updated(index: Int, count: Int)
case inserted(index: Int)
case deleted(index: Int)
}
var target: Int?
var state: State
var expected: Int {
if case let .updated(_, count) = self.state {
return count + inserted.count - removed.count
}
return 0
}
var inserted = Set<IndexPath>()
var removed = Set<IndexPath>()
init(index: Int, count: Int) {
self.state = .updated(index: index, count: count)
}
}
var data = [5, 5, 5, 5]
//var insert : [IndexPath] = [[0,2], [2,0]]
//var remove : [IndexPath] = [[0,2], [2,0]]
//var sections = [Section]()
//for s in data.enumerated() {
// sections.append(Section(index: s.offset, count: s.element))
//}
|
mit
|
e7b54e6bb20042f2ab37c68a4d0816c6
| 25.930556 | 95 | 0.60753 | 3.231667 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples
|
GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/PolygonsViewController.swift
|
1
|
7963
|
// Copyright 2020 Google LLC. 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 GoogleMaps
import UIKit
final class PolygonsViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let cameraPosition = GMSCameraPosition(latitude: 39.13006, longitude: -77.508545, zoom: 4)
return GMSMapView(frame: .zero, camera: cameraPosition)
}()
override func loadView() {
mapView.delegate = self
view = mapView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Create renderer related objects after view appears, so a renderer will be available;
let polygon = GMSPolygon()
polygon.path = GMSPath.newYorkState()
polygon.holes = [GMSPath.newYorkStateHole()]
polygon.title = "New York"
polygon.fillColor = UIColor(red: 0.25, green: 0, blue: 0, alpha: 0.2)
polygon.strokeColor = .black
polygon.strokeWidth = 2
polygon.isTappable = true
polygon.map = mapView
// Copy the existing polygon and its settings and use it as a base for the
// second polygon.
let carolina = polygon.copy() as! GMSPolygon
carolina.title = "North Carolina"
carolina.path = GMSPath.northCarolina()
carolina.fillColor = UIColor(red: 0, green: 0.25, blue: 0, alpha: 0.5)
carolina.map = mapView
}
}
extension GMSPath {
static func newYorkState() -> GMSPath {
let data: [[CLLocationDegrees]] = [
[42.5142, -79.7624],
[42.7783, -79.0672],
[42.8508, -78.9313],
[42.9061, -78.9024],
[42.9554, -78.9313],
[42.9584, -78.9656],
[42.9886, -79.0219],
[43.0568, -79.0027],
[43.0769, -79.0727],
[43.1220, -79.0713],
[43.1441, -79.0302],
[43.1801, -79.0576],
[43.2482, -79.0604],
[43.2812, -79.0837],
[43.4509, -79.2004],
[43.6311, -78.6909],
[43.6321, -76.7958],
[43.9987, -76.4978],
[44.0965, -76.4388],
[44.1349, -76.3536],
[44.1989, -76.3124],
[44.2049, -76.2437],
[44.2413, -76.1655],
[44.2973, -76.1353],
[44.3327, -76.0474],
[44.3553, -75.9856],
[44.3749, -75.9196],
[44.3994, -75.8730],
[44.4308, -75.8221],
[44.4740, -75.8098],
[44.5425, -75.7288],
[44.6647, -75.5585],
[44.7672, -75.4088],
[44.8101, -75.3442],
[44.8383, -75.3058],
[44.8676, -75.2399],
[44.9211, -75.1204],
[44.9609, -74.9995],
[44.9803, -74.9899],
[44.9852, -74.9103],
[45.0017, -74.8856],
[45.0153, -74.8306],
[45.0046, -74.7633],
[45.0027, -74.7070],
[45.0007, -74.5642],
[44.9920, -74.1467],
[45.0037, -73.7306],
[45.0085, -73.4203],
[45.0109, -73.3430],
[44.9874, -73.3547],
[44.9648, -73.3379],
[44.9160, -73.3396],
[44.8354, -73.3739],
[44.8013, -73.3324],
[44.7419, -73.3667],
[44.6139, -73.3873],
[44.5787, -73.3736],
[44.4916, -73.3049],
[44.4289, -73.2953],
[44.3513, -73.3365],
[44.2757, -73.3118],
[44.1980, -73.3818],
[44.1142, -73.4079],
[44.0511, -73.4367],
[44.0165, -73.4065],
[43.9375, -73.4079],
[43.8771, -73.3749],
[43.8167, -73.3914],
[43.7790, -73.3557],
[43.6460, -73.4244],
[43.5893, -73.4340],
[43.5655, -73.3969],
[43.6112, -73.3818],
[43.6271, -73.3049],
[43.5764, -73.3063],
[43.5675, -73.2582],
[43.5227, -73.2445],
[43.2582, -73.2582],
[42.9715, -73.2733],
[42.8004, -73.2898],
[42.7460, -73.2664],
[42.4630, -73.3708],
[42.0840, -73.5095],
[42.0218, -73.4903],
[41.8808, -73.4999],
[41.2953, -73.5535],
[41.2128, -73.4834],
[41.1011, -73.7275],
[41.0237, -73.6644],
[40.9851, -73.6578],
[40.9509, -73.6132],
[41.1869, -72.4823],
[41.2551, -72.0950],
[41.3005, -71.9714],
[41.3108, -71.9193],
[41.1838, -71.7915],
[41.1249, -71.7929],
[41.0462, -71.7517],
[40.6306, -72.9465],
[40.5368, -73.4628],
[40.4887, -73.8885],
[40.5232, -73.9490],
[40.4772, -74.2271],
[40.4861, -74.2532],
[40.6468, -74.1866],
[40.6556, -74.0547],
[40.7618, -74.0156],
[40.8699, -73.9421],
[40.9980, -73.8934],
[41.0343, -73.9854],
[41.3268, -74.6274],
[41.3583, -74.7084],
[41.3811, -74.7101],
[41.4386, -74.8265],
[41.5075, -74.9913],
[41.6000, -75.0668],
[41.6719, -75.0366],
[41.7672, -75.0545],
[41.8808, -75.1945],
[42.0013, -75.3552],
[42.0003, -75.4266],
[42.0013, -77.0306],
[41.9993, -79.7250],
[42.0003, -79.7621],
[42.1827, -79.7621],
[42.5146, -79.7621],
]
let path = GMSMutablePath()
for degrees in data {
path.addLatitude(degrees[0], longitude: degrees[1])
}
return path
}
static func newYorkStateHole() -> GMSPath {
let path = GMSMutablePath()
path.addLatitude(43.5000, longitude: -76.3651)
path.addLatitude(43.5000, longitude: -74.3651)
path.addLatitude(42.0000, longitude: -74.3651)
return path
}
static func northCarolina() -> GMSPath {
let path = GMSMutablePath()
let data = [
[33.7963, -78.4850],
[34.8037, -79.6742],
[34.8206, -80.8003],
[34.9377, -80.7880],
[35.1019, -80.9377],
[35.0356, -81.0379],
[35.1457, -81.0324],
[35.1660, -81.3867],
[35.1985, -82.2739],
[35.2041, -82.3933],
[35.0637, -82.7765],
[35.0817, -82.7861],
[34.9996, -83.1075],
[34.9918, -83.6183],
[34.9918, -84.3201],
[35.2131, -84.2885],
[35.2680, -84.2226],
[35.2310, -84.1113],
[35.2815, -84.0454],
[35.4058, -84.0248],
[35.4719, -83.9424],
[35.5166, -83.8559],
[35.5512, -83.6938],
[35.5680, -83.5181],
[35.6327, -83.3849],
[35.7142, -83.2475],
[35.7799, -82.9962],
[35.8445, -82.9276],
[35.9224, -82.8191],
[35.9958, -82.7710],
[36.0613, -82.6419],
[35.9702, -82.6103],
[35.9547, -82.5677],
[36.0236, -82.4730],
[36.0669, -82.4194],
[36.1168, -82.3535],
[36.1345, -82.2862],
[36.1467, -82.1461],
[36.1035, -82.1228],
[36.1268, -82.0267],
[36.2797, -81.9360],
[36.3527, -81.7987],
[36.3361, -81.7081],
[36.5880, -81.6724],
[36.5659, -80.7234],
[36.5438, -80.2977],
[36.5449, -79.6729],
[36.5449, -77.2559],
[36.5505, -75.7562],
[36.3129, -75.7068],
[35.7131, -75.4129],
[35.2041, -75.4720],
[34.9794, -76.0748],
[34.5258, -76.4951],
[34.5880, -76.8109],
[34.5314, -77.1378],
[34.3910, -77.4481],
[34.0481, -77.7983],
[33.7666, -77.9260],
[33.7963, -78.4863],
]
for degrees in data {
path.addLatitude(degrees[0], longitude: degrees[1])
}
return path
}
}
extension PolygonsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {
// When a polygon is tapped, randomly change its fill color to a new hue.
guard let polygon = overlay as? GMSPolygon else { return }
polygon.fillColor = UIColor(
hue: CGFloat.random(in: 0..<1), saturation: 1, brightness: 1, alpha: 0.5)
}
}
|
apache-2.0
|
00dff27af190584ba6e476d8920e6a8a
| 27.956364 | 94 | 0.536732 | 2.573691 | false | false | false | false |
xedin/swift
|
test/IRGen/conformance_resilience.swift
|
8
|
2438
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution %s | %FileCheck %s -DINT=i%target-ptrsize
// RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution -O %s
import resilient_protocol
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22conformance_resilience14useConformanceyyx18resilient_protocol22OtherResilientProtocolRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.OtherResilientProtocol)
public func useConformance<T : OtherResilientProtocol>(_: T) {}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22conformance_resilience14getConformanceyy18resilient_protocol7WrapperVyxGlF"(%swift.opaque* noalias nocapture, %swift.type* %T)
public func getConformance<T>(_ w: Wrapper<T>) {
// CHECK: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s18resilient_protocol7WrapperVMa"([[INT]] 0, %swift.type* %T)
// CHECK: [[META:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK: [[WTABLE:%.*]] = call i8** @swift_getWitnessTable(%swift.protocol_conformance_descriptor* @"$s18resilient_protocol7WrapperVyxGAA22OtherResilientProtocolAAMc", %swift.type* [[META]], i8*** undef)
// CHECK: call swiftcc void @"$s22conformance_resilience14useConformanceyyx18resilient_protocol22OtherResilientProtocolRzlF"(%swift.opaque* noalias nocapture %0, %swift.type* [[META]], i8** [[WTABLE]])
// CHECK: ret void
useConformance(w)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22conformance_resilience14getConformanceyy18resilient_protocol15ConcreteWrapperVF"(%swift.opaque* noalias nocapture)
public func getConformance(_ w: ConcreteWrapper) {
// CHECK: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s18resilient_protocol15ConcreteWrapperVMa"([[INT]] 0)
// CHECK: [[META:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK: call swiftcc void @"$s22conformance_resilience14useConformanceyyx18resilient_protocol22OtherResilientProtocolRzlF"(%swift.opaque* noalias nocapture %0, %swift.type* [[META]], i8** @"$s18resilient_protocol15ConcreteWrapperVAA22OtherResilientProtocolAAWP")
// CHECK: ret void
useConformance(w)
}
|
apache-2.0
|
b08b02798127ad793b7fbbfdda2f0009
| 86.071429 | 266 | 0.748564 | 3.951378 | false | false | false | false |
CaiMiao/CGSSGuide
|
DereGuide/LiveSimulator/LiveFormulator.swift
|
1
|
4476
|
//
// LiveFormulator.swift
// DereGuide
//
// Created by zzk on 2017/5/18.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import SwiftyJSON
fileprivate extension Int {
func addGreatPercent(_ percent: Double) -> Int {
return Int(round(Double(self) * (1 - 0.3 * percent / 100)))
}
}
extension LSNote {
func expectation(in distribution: LFDistribution) -> Double {
//先对离散分布的每种情况进行分别取整 再做单个note的得分期望计算
let expectation = distribution.samples.reduce(0.0) { $0 + round(baseScore * comboFactor * Double($1.value.bonusValue) / 10000) * $1.probability }
return expectation
}
}
/// Formulator is only used in optimistic score 2 and average score calculation
class LiveFormulator {
var notes: [LSNote]
var bonuses: [LSSkill]
lazy var distributions: [LFDistribution] = {
return self.generateScoreDistributions()
}()
init(notes: [LSNote], bonuses: [LSSkill]) {
self.bonuses = bonuses
self.notes = notes
}
var averageScore: Int {
// var scores = [Int]()
var sum = 0.0
for i in 0..<notes.count {
let note = notes[i]
let distribution = distributions[i]
sum += note.expectation(in: distribution)
// scores.append(Int(round(note.baseScore * note.comboFactor * distribution.average / 10000)))
}
// (scores as NSArray).write(to: URL.init(fileURLWithPath: NSHomeDirectory() + "/new.txt"), atomically: true)
return Int(round(sum)).addGreatPercent(LiveSimulationAdvanceOptionsManager.default.greatPercent)
}
var maxScore: Int {
var sum = 0
for i in 0..<notes.count {
let note = notes[i]
let distribution = distributions[i]
sum += Int(round(note.baseScore * note.comboFactor * Double(distribution.maxValue) / 10000))
}
return sum.addGreatPercent(LiveSimulationAdvanceOptionsManager.default.greatPercent)
}
var minScore: Int {
var sum = 0
for i in 0..<notes.count {
let note = notes[i]
let distribution = distributions[i]
sum += Int(round(note.baseScore * note.comboFactor * Double(distribution.minValue) / 10000))
}
return sum.addGreatPercent(LiveSimulationAdvanceOptionsManager.default.greatPercent)
}
private func generateScoreDistributions() -> [LFDistribution] {
var distributions = [LFDistribution]()
for i in 0..<notes.count {
let note = notes[i]
let validBonuses = bonuses.filter { $0.range.contains(note.sec) }
var samples = [LFSamplePoint<LSScoreBonusGroup>]()
for mask in 0..<(1 << validBonuses.count) {
var bonusGroup = LSScoreBonusGroup.basic
var p = 1.0
for j in 0..<validBonuses.count {
let bonus = validBonuses[j]
if mask & (1 << j) != 0 {
p *= bonus.probability
switch bonus.type {
case .comboBonus, .allRound:
bonusGroup.baseComboBonus = max(bonusGroup.baseComboBonus, bonus.value)
case .perfectBonus, .overload, .concentration:
bonusGroup.basePerfectBonus = max(bonusGroup.basePerfectBonus, bonus.value)
case .skillBoost:
bonusGroup.skillBoost = max(bonusGroup.skillBoost, bonus.value)
case .deep, .synergy:
bonusGroup.basePerfectBonus = max(bonusGroup.basePerfectBonus, bonus.value)
bonusGroup.baseComboBonus = max(bonusGroup.baseComboBonus, bonus.value2)
default:
break
}
} else {
p *= 1 - bonus.probability
}
}
let sample = LFSamplePoint<LSScoreBonusGroup>.init(probability: p, value: bonusGroup)
samples.append(sample)
}
let distribution = LFDistribution(samples: samples)
distributions.append(distribution)
}
return distributions
}
}
|
mit
|
edd9173cd3ea34bb486da5b52bc03f26
| 35.504132 | 153 | 0.556034 | 4.425852 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Loader/Pulse/PulseViewPresenter.swift
|
1
|
4453
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import PlatformKit
import RxSwift
import ToolKit
/// Presenter in charge of displaying a `PulseAnimationView`.
/// Note that though this API is very similar to that of the Loader, this
/// `PulseAnimationView` isn't necessarily meant for loading, but rather an on-boarding
/// tutorial. It servers as a CTA when the user creats a wallet for the first time.
@objc public final class PulseViewPresenter: NSObject, PulseViewPresenting {
// MARK: - Types
/// Describes the state of the `PulseAnimationView`
enum State {
case animating
case hidden
/// Returns `true` if the `PulseAnimationView` is currently animating
var isAnimating: Bool {
switch self {
case .animating:
return true
case .hidden:
return false
}
}
}
// MARK: - Properties
/// The shared instance of the pulse view
public static let shared = PulseViewPresenter()
/// sharedInstance function declared so that the LoadingViewPresenter singleton can be accessed
/// from Obj-C. Should deprecate this once all Obj-c references have been removed.
@objc public class func sharedInstance() -> PulseViewPresenter { shared }
// Returns `.visible` if the `PulseAnimationView` is currently visible and animating
public var visibility: Visibility {
state.isAnimating ? .visible : .hidden
}
/// Returns `true` if the `PulseAnimationView` is currently visible and animating
@objc public var isVisible: Bool {
state.isAnimating
}
/// Controls the availability of the `PulseAnimationView` from outside.
/// In case `isEnabled` is `false`, the loader does not show.
/// `isEnabled` is thread-safe.
@objc public var isEnabled: Bool {
get {
lock.lock()
defer { lock.unlock() }
return _isEnabled
}
set {
lock.lock()
defer { lock.unlock() }
_isEnabled = newValue
}
}
private let bag = DisposeBag()
// Privately used by exposed `isEnabled` only.
private var _isEnabled = true
// The container of the `PulseAnimationView`. Allocated on demand, when done spinning it should be deallocated.
private var view: PulseContainerViewProtocol!
// Recursive lock for shared resources held by that class
private let lock = NSRecursiveLock()
/// The state of the `PulseAnimationView`
private var state = State.hidden {
didSet {
switch (oldValue, state) {
case (.hidden, .animating):
view.animate()
case (.animating, .hidden):
view.fadeOut()
case (.hidden, .hidden), (.animating, .animating):
break
}
}
}
// MARK: - API
/// Hides the `PulseAnimationView`
public func hide() {
Execution.MainQueue.dispatch { [weak self] in
guard let self = self else { return }
guard self.view != nil else { return }
self.state = .hidden
self.view = nil
}
}
/// Shows the `PulseAnimationView` in a provided view
public func show(viewModel: PulseViewModel) {
guard viewModel.container.subviews.contains(where: { $0 is PulseContainerView }) == false else { return }
Execution.MainQueue.dispatch { [weak self] in
guard let self = self, self.isEnabled else { return }
self.setupView(in: viewModel.container)
self.view.selection.emit(onNext: { [weak self] _ in
guard let self = self else { return }
viewModel.onSelection()
// We should hide the pulse when the user taps it.
self.hide()
})
.disposed(by: self.bag)
self.state = .animating
}
}
// MARK: - Accessors
private func setupView(in superview: UIView) {
view = PulseContainerView()
attach(to: superview)
}
/// Add the view to a superview
private func attach(to superview: UIView) {
superview.addSubview(view.viewRepresentation)
view.viewRepresentation.layoutToSuperview(axis: .horizontal)
view.viewRepresentation.layoutToSuperview(axis: .vertical)
superview.layoutIfNeeded()
}
}
|
lgpl-3.0
|
87e8855ccb884c9baca36630c1927043
| 31.977778 | 115 | 0.612758 | 4.913907 | false | false | false | false |
Erulezz/Ultimate-AdBlock
|
Ultimate AdBlock/Controllers/FiltersSocialTVC.swift
|
1
|
3921
|
//
// FiltersSocialTVC.swift
// Ultimate AdBlock
//
// Created by Eric Horstmanshof on 15-12-15.
// Copyright © 2015 Arrow Webprojects. All rights reserved.
//
import UIKit
class FiltersSocialTVC: UITableViewController, UISearchResultsUpdating {
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.searchBarStyle = .minimal
searchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = searchController.searchBar
self.navigationItem.title = NSLocalizedString("NAVBAR_FILTERS_SOCIAL", comment: "")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func updateSearchResults(for searchController: UISearchController) {
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
da997f37e46373a07c1b0c16c9452eaf
| 34.315315 | 157 | 0.693622 | 5.756241 | false | false | false | false |
Azurelus/Swift-Useful-Files
|
Sources/Extensions/UIApplication+Extension.swift
|
1
|
917
|
//
// UIApplication+Extension.swift
// Swift-Useful-Files
//
// Created by Husar Maksym on 2/14/17.
// Copyright © 2017 Husar Maksym. All rights reserved.
//
import UIKit
extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
|
mit
|
19fefbcbeb482d07b5f1427f9d99bd02
| 34.230769 | 139 | 0.691048 | 5.452381 | false | false | false | false |
Jnosh/swift
|
test/IDE/complete_overridden_decls.swift
|
27
|
4489
|
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift
// RUN: %target-swift-frontend -typecheck -verify %t_no_errors.swift
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVER_BASE_1 > %t.over.txt
// RUN: %FileCheck %s -check-prefix=OVER_BASE_1 < %t.over.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVER_DERIVED_1 > %t.over.txt
// RUN: %FileCheck %s -check-prefix=OVER_DERIVED_1 < %t.over.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OVER_MORE_DERIVED_1 > %t.over.txt
// RUN: %FileCheck %s -check-prefix=OVER_MORE_DERIVED_1 < %t.over.txt
//===---
//===--- Check that we don't show overridden decls (only show the overriding decl).
//===---
class FooBase {}
class FooDerived : FooBase {}
class FooMoreDerived : FooDerived {}
class TestABase {
var baseInstanceVar: FooBase { return FooBase() }
var baseOverInstanceVar: FooBase { return FooBase() }
func baseOverFunc() {}
func baseOverContravariant(_ a: FooMoreDerived) {}
func baseOverCovariant() -> FooBase {}
}
class TestADerived : TestABase {
var derivedInstanceVar: FooBase { return FooBase() }
override var baseOverInstanceVar: FooDerived { return FooDerived() }
var derivedOverInstanceVar: FooBase { return FooBase() }
override func baseOverFunc() {}
override func baseOverContravariant(_ a: FooDerived) {}
override func baseOverCovariant() -> FooDerived {}
}
class TestAMoreDerived : TestADerived {
var moreDerivedInstanceVar: FooBase { return FooBase() }
override var baseOverInstanceVar: FooMoreDerived { return FooMoreDerived() }
override var derivedOverInstanceVar: FooDerived { return FooDerived() }
override func baseOverFunc() {}
override func baseOverContravariant(_ a: FooBase) {}
override func baseOverCovariant() -> FooMoreDerived {}
}
// NO_ERRORS_UP_TO_HERE
func test1(_ b: TestABase) {
b.#^OVER_BASE_1^#
}
// OVER_BASE_1: Begin completions
// OVER_BASE_1-NEXT: Decl[InstanceVar]/CurrNominal: baseInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_BASE_1-NEXT: Decl[InstanceVar]/CurrNominal: baseOverInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_BASE_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverFunc()[#Void#]{{; name=.+$}}
// OVER_BASE_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverContravariant({#(a): FooMoreDerived#})[#Void#]{{; name=.+$}}
// OVER_BASE_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverCovariant()[#FooBase#]{{; name=.+$}}
// OVER_BASE_1-NEXT: End completions
func test2(_ d: TestADerived) {
d.#^OVER_DERIVED_1^#
}
// OVER_DERIVED_1: Begin completions
// OVER_DERIVED_1-NEXT: Decl[InstanceVar]/CurrNominal: derivedInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_DERIVED_1-NEXT: Decl[InstanceVar]/CurrNominal: baseOverInstanceVar[#FooDerived#]{{; name=.+$}}
// OVER_DERIVED_1-NEXT: Decl[InstanceVar]/CurrNominal: derivedOverInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_DERIVED_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverFunc()[#Void#]{{; name=.+$}}
// OVER_DERIVED_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverContravariant({#(a): FooDerived#})[#Void#]{{; name=.+$}}
// OVER_DERIVED_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverCovariant()[#FooDerived#]{{; name=.+$}}
// OVER_DERIVED_1-NEXT: Decl[InstanceVar]/Super: baseInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_DERIVED_1-NEXT: End completions
func test3(_ md: TestAMoreDerived) {
md.#^OVER_MORE_DERIVED_1^#
}
// OVER_MORE_DERIVED_1: Begin completions
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceVar]/CurrNominal: moreDerivedInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceVar]/CurrNominal: baseOverInstanceVar[#FooMoreDerived#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceVar]/CurrNominal: derivedOverInstanceVar[#FooDerived#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverFunc()[#Void#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverContravariant({#(a): FooBase#})[#Void#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceMethod]/CurrNominal: baseOverCovariant()[#FooMoreDerived#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceVar]/Super: derivedInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: Decl[InstanceVar]/Super: baseInstanceVar[#FooBase#]{{; name=.+$}}
// OVER_MORE_DERIVED_1-NEXT: End completions
|
apache-2.0
|
50f31f8b4dfc4e5800d518a79f1f991a
| 49.438202 | 124 | 0.703275 | 3.551424 | false | true | false | false |
rporzuc/FindFriends
|
FindFriends/FindFriends/HTTPStatusCodes.swift
|
1
|
2108
|
//
// HTTPStatusCodes.swift
// FindFriends
//
// Created by MacOSXRAFAL on 11/12/17.
// Copyright © 2017 MacOSXRAFAL. All rights reserved.
//
import Foundation
enum HTTPStatusCodes: Int {
// Codes Of Registation
// 20 User Registered
case UserRegistered = 20
// 30 Login Occupied
case LoginOccupied = 30
// 100 Informational
case Continue = 100
case SwitchingProtocols
case Processing
// 200 Success
case OK = 200
case Created
case Accepted
case NonAuthoritativeInformation
case NoContent
case ResetContent
case PartialContent
case MultiStatus
case AlreadyReported
case IMUsed = 226
// 300 Redirection
case MultipleChoices = 300
case MovedPermanently
case Found
case SeeOther
case NotModified
case UseProxy
case SwitchProxy
case TemporaryRedirect
case PermanentRedirect
// 400 Client Error
case BadRequest = 400
case Unauthorized
case PaymentRequired
case Forbidden
case NotFound
case MethodNotAllowed
case NotAcceptable
case ProxyAuthenticationRequired
case RequestTimeout
case Conflict
case Gone
case LengthRequired
case PreconditionFailed
case PayloadTooLarge
case URLTooLong
case UnsupportedMediaType
case RangeNotSatisfiable
case ExpectationFailed
case ImATeapot
case MisdirectedRequest = 421
case UnprocessableEntity
case Locked
case FailedDependency
case UpgradeRequired = 426
case PreconditionRequired = 428
case TooManyRequests
case RequestHeaderFieldsTooLarge = 431
case UnavailableForLegalReasons = 451
// 500 Server Error
case InternalServerError = 500
case NotImplemented
case BadGateway
case ServiceUnavailable
case GatewayTimeout
case HTTPVersionNotSupported
case VariantAlsoNegotiates
case InsufficientStorage
case LoopDetected
case NotExtended = 510
case NetworkAuthenticationRequired
//600 Session Timed Out
case SessionTimedOut = 600
//700 Database error
case DatabaseError = 700
}
|
gpl-3.0
|
b5c17de2cc10fa3de337ffaa9f89d228
| 23.218391 | 54 | 0.719032 | 5.176904 | false | false | false | false |
jovito-royeca/Decktracker
|
ios/Pods/Eureka/Source/Rows/Controllers/SelectorViewController.swift
|
5
|
2366
|
//
// SelectorViewController.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
public class _SelectorViewController<T: Equatable, Row: SelectableRowType where Row: BaseRow, Row: TypedRowType, Row.Value == T, Row.Cell.Value == T>: FormViewController, TypedRowControllerType {
/// The row that pushed or presented this controller
public var row: RowOf<Row.Value>!
/// A closure to be called when the controller disappears.
public var completionCallback : ((UIViewController) -> ())?
public var selectableRowCellUpdate: ((cell: Row.Cell, row: Row) -> ())?
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override func viewDidLoad() {
super.viewDidLoad()
guard let options = row.dataProvider?.arrayData else { return }
form +++ SelectableSection<Row, Row.Value>(row.title ?? "", selectionType: .SingleSelection(enableDeselection: true)) { [weak self] section in
if let sec = section as? SelectableSection<Row, Row.Value> {
sec.onSelectSelectableRow = { _, row in
self?.row.value = row.value
self?.completionCallback?(self!)
}
}
}
for option in options {
form.first! <<< Row.init(String(option)){ lrow in
lrow.title = row.displayValueFor?(option)
lrow.selectableValue = option
lrow.value = row.value == option ? option : nil
}.cellUpdate { [weak self] cell, row in
self?.selectableRowCellUpdate?(cell: cell, row: row)
}
}
}
}
/// Selector Controller (used to select one option among a list)
public class SelectorViewController<T:Equatable> : _SelectorViewController<T, ListCheckRow<T>> {
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience public init(_ callback: (UIViewController) -> ()){
self.init(nibName: nil, bundle: nil)
completionCallback = callback
}
}
|
apache-2.0
|
08efeab3632c23199ae36cdb64330c2b
| 37.145161 | 195 | 0.621142 | 4.89648 | false | false | false | false |
mendesbarreto/IOS
|
UICollectionInUITableViewCell/Pods/Signals/Signals/ios/UIControl+Signals.swift
|
1
|
6468
|
//
// UIControl+Signals.swift
// Signals
//
// Created by Tuomas Artman on 12/23/2015.
// Copyright © 2015 Tuomas Artman. All rights reserved.
//
import UIKit
/// Extends UIControl with signals for all ui control events.
public extension UIControl {
private struct AssociatedKeys {
static var SignalDictionaryKey = "signals_signalKey"
}
static let eventToKey: [UIControlEvents: NSString] = [
.TouchDown: "TouchDown",
.TouchDownRepeat: "TouchDownRepeat",
.TouchDragInside: "TouchDragInside",
.TouchDragOutside: "TouchDragOutside",
.TouchDragEnter: "TouchDragEnter",
.TouchDragExit: "TouchDragExit",
.TouchUpInside: "TouchUpInside",
.TouchUpOutside: "TouchUpOutside",
.TouchCancel: "TouchCancel",
.ValueChanged: "ValueChanged",
.EditingDidBegin: "EditingDidBegin",
.EditingChanged: "EditingChanged",
.EditingDidEnd: "EditingDidEnd",
.EditingDidEndOnExit: "EditingDidEndOnExit"]
// MARK - Public interface
/// A signal that fires for each touch down control event.
public var onTouchDown: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchDown);
}
/// A signal that fires for each touch down repeat control event.
public var onTouchDownRepeat: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchDownRepeat);
}
/// A signal that fires for each touch drag inside control event.
public var onTouchDragInside: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchDragInside);
}
/// A signal that fires for each touch drag outside control event.
public var onTouchDragOutside: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchDragOutside);
}
/// A signal that fires for each touch drag enter control event.
public var onTouchDragEnter: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchDragEnter);
}
/// A signal that fires for each touch drag exit control event.
public var onTouchDragExit: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchDragExit);
}
/// A signal that fires for each touch up inside control event.
public var onTouchUpInside: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchUpInside);
}
/// A signal that fires for each touch up outside control event.
public var onTouchUpOutside: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchUpOutside);
}
/// A signal that fires for each touch cancel control event.
public var onTouchCancel: Signal<()> {
return getOrCreateSignalForUIControlEvent(.TouchCancel);
}
/// A signal that fires for each value changed control event.
public var onValueChanged: Signal<()> {
return getOrCreateSignalForUIControlEvent(.ValueChanged);
}
/// A signal that fires for each editing did begin control event.
public var onEditingDidBegin: Signal<()> {
return getOrCreateSignalForUIControlEvent(.EditingDidBegin);
}
/// A signal that fires for each editing changed control event.
public var onEditingChanged: Signal<()> {
return getOrCreateSignalForUIControlEvent(.EditingChanged);
}
/// A signal that fires for each editing did end control event.
public var onEditingDidEnd: Signal<()> {
return getOrCreateSignalForUIControlEvent(.EditingDidEnd);
}
/// A signal that fires for each editing did end on exit control event.
public var onEditingDidEndOnExit: Signal<()> {
return getOrCreateSignalForUIControlEvent(.EditingDidEndOnExit);
}
// MARK: - Internal interface
private func getOrCreateSignalForUIControlEvent(event: UIControlEvents) -> Signal<()> {
guard let key = UIControl.eventToKey[event] else {
assertionFailure("Event type is not handled")
return Signal()
}
let dictionary = getOrCreateAssociatedObject(self, associativeKey: &AssociatedKeys.SignalDictionaryKey, defaultValue: NSMutableDictionary(), policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let signal = dictionary[key] as? Signal<()> {
return signal
} else {
let signal = Signal<()>()
dictionary[key] = signal
self.addTarget(self, action: Selector("eventHandler\(key)"), forControlEvents: event)
return signal
}
}
private func handleUIControlEvent(uiControlEvent: UIControlEvents) {
getOrCreateSignalForUIControlEvent(uiControlEvent).fire()
}
// MARK: - Event handlers
private dynamic func eventHandlerTouchDown() {
handleUIControlEvent(.TouchDown)
}
private dynamic func eventHandlerTouchDownRepeat() {
handleUIControlEvent(.TouchDownRepeat)
}
private dynamic func eventHandlerTouchDragInside() {
handleUIControlEvent(.TouchDragInside)
}
private dynamic func eventHandlerTouchDragOutside() {
handleUIControlEvent(.TouchDragOutside)
}
private dynamic func eventHandlerTouchDragEnter() {
handleUIControlEvent(.TouchDragEnter)
}
private dynamic func eventHandlerTouchDragExit() {
handleUIControlEvent(.TouchDragExit)
}
private dynamic func eventHandlerTouchUpInside() {
handleUIControlEvent(.TouchUpInside)
}
private dynamic func eventHandlerTouchUpOutside() {
handleUIControlEvent(.TouchUpOutside)
}
private dynamic func eventHandlerTouchCancel() {
handleUIControlEvent(.TouchCancel)
}
private dynamic func eventHandlerValueChanged() {
handleUIControlEvent(.ValueChanged)
}
private dynamic func eventHandlerEditingDidBegin() {
handleUIControlEvent(.EditingDidBegin)
}
private dynamic func eventHandlerEditingChanged() {
handleUIControlEvent(.EditingChanged)
}
private dynamic func eventHandlerEditingDidEnd() {
handleUIControlEvent(.EditingDidEnd)
}
private dynamic func eventHandlerEditingDidEndOnExit() {
handleUIControlEvent(.EditingDidEndOnExit)
}
}
extension UIControlEvents: Hashable {
public var hashValue: Int {
return Int(self.rawValue)
}
}
|
mit
|
72c08c77a398f35e446bd050ce1d2b6d
| 32.682292 | 214 | 0.676975 | 5.687775 | false | false | false | false |
MarioIannotta/SplitViewDragAndDrop
|
DragAndDropDemo/DropViewController.swift
|
1
|
4071
|
//
// DropViewController.swift
// DragAndDropDemo
//
// Created by Mario on 26/05/2017.
// Copyright © 2017 Mario. All rights reserved.
//
import UIKit
class DropViewController: UIViewController {
@IBOutlet private weak var ciaoTargetImageView: UIImageView!
@IBOutlet private weak var helloTargetImageView: UIImageView!
@IBOutlet private weak var alohaTargetImageView: UIImageView!
private func presentAlertController(withMessage message: String) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
private func draggingBeganAnimation(for view: UIView) {
UIView.animate(withDuration: 0.3) {
view.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}
}
private func draggingEndedAnimation(for view: UIView) {
UIView.animate(withDuration: 0.3) {
view.transform = CGAffineTransform.identity
}
}
override func viewDidLoad() {
super.viewDidLoad()
SplitViewDragAndDrop.addDropObserver(
targetView: ciaoTargetImageView,
identifier: "ciao_d&d",
draggingBegan: { frame, draggedViewSnapshotImage, dataTransfered in
self.draggingBeganAnimation(for: self.ciaoTargetImageView)
},
draggingValidation: { frame, draggedViewSnapshotImage, dataTransfered in
self.draggingEndedAnimation(for: self.ciaoTargetImageView)
return self.ciaoTargetImageView.windowRelativeFrame.contains(frame)
},
completion: { frame, draggedViewSnapshotImage, dataTransfered, isValid in
if isValid {
self.ciaoTargetImageView.image = draggedViewSnapshotImage
}
}
)
SplitViewDragAndDrop.addDropObserver(
targetView: helloTargetImageView,
identifier: "hello_d&d",
draggingBegan: { frame, draggedViewSnapshotImage, dataTransfered in
self.draggingBeganAnimation(for: self.helloTargetImageView)
},
draggingValidation: { frame, draggedViewSnapshotImage, dataTransfered in
self.draggingEndedAnimation(for: self.helloTargetImageView)
return self.helloTargetImageView.windowRelativeFrame.contains(frame)
},
completion: { frame, draggedViewSnapshotImage, dataTransfered, isValid in
if isValid {
self.helloTargetImageView.image = draggedViewSnapshotImage
}
}
)
SplitViewDragAndDrop.addDropObserver(
targetView: alohaTargetImageView,
identifier: "aloha_d&d",
draggingBegan: { frame, draggedViewSnapshotImage, dataTransfered in
self.draggingBeganAnimation(for: self.alohaTargetImageView)
},
draggingValidation: { frame, draggedViewSnapshotImage, dataTransfered in
self.draggingEndedAnimation(for: self.alohaTargetImageView)
return self.alohaTargetImageView.windowRelativeFrame.contains(frame)
},
completion: { frame, draggedViewSnapshotImage, dataTransfered, isValid in
if isValid {
self.alohaTargetImageView.image = draggedViewSnapshotImage
}
}
)
}
}
|
mit
|
bd073baff072e4b474596b6d9092ba47
| 32.360656 | 101 | 0.563636 | 5.907112 | false | false | false | false |
sathishkraj/SwiftLazyLoading
|
SwiftLazyLoading/IconDownloader.swift
|
1
|
3388
|
//
// IconDownloader.swift
// SwiftLazyLoading
//
// Copyright (c) 2015 Sathish Kumar
//
// 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
let kAppIconSize: CGFloat = 48.0
class IconDownloader: NSObject {
var appRecord: AppRecord? = nil
var completionHandler: (() -> ())? = nil
var activeDownload: NSMutableData? = nil
var imageConnection: NSURLConnection? = nil
func startDownload() {
self.activeDownload = NSMutableData()
let request: NSURLRequest = NSURLRequest(URL: NSURL(string: self.appRecord!.imageURLString! as String)!)
let conn: NSURLConnection = NSURLConnection(request: request, delegate: self)!
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.imageConnection = conn;
}
func cancelDownload() {
self.imageConnection?.cancel()
self.imageConnection = nil
self.activeDownload = nil
}
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
self.activeDownload?.appendData(data)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.activeDownload = nil
self.imageConnection = nil
}
func connectionDidFinishLoading(connection: NSURLConnection) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let image: UIImage = UIImage(data: self.activeDownload!)!
if image.size.width != kAppIconSize || image.size.width != kAppIconSize {
let itemSize: CGSize = CGSizeMake(kAppIconSize, kAppIconSize)
UIGraphicsBeginImageContext(itemSize)
let imageRect: CGRect = CGRectMake(0, 0, kAppIconSize, kAppIconSize)
image.drawInRect(imageRect)
self.appRecord!.appIcon = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
} else {
self.appRecord!.appIcon = image
}
self.activeDownload = nil
self.imageConnection = nil
if self.completionHandler != nil {
self.completionHandler!()
}
}
}
|
mit
|
1eb36f2a56ab80f1c5d552196516a23c
| 35.826087 | 112 | 0.6768 | 5.220339 | false | false | false | false |
TsuiOS/LoveFreshBeen
|
LoveFreshBeenX/Class/View/Supermarket/XNProductsViewController.swift
|
1
|
2137
|
//
// XNProductsViewController.swift
// LoveFreshBeenX
//
// Created by xuning on 16/7/2.
// Copyright © 2016年 hus. All rights reserved.
//
import UIKit
class XNProductsViewController: UIViewController {
var productsTableView: UITableView?
var supermarketData: XNSupermarket?
var name: String? {
didSet {
if name != nil {
let products = supermarketData?.data?.products
goodArray = products!.valueForKey(name!) as? [XNGoods]
}
}
}
var goodArray: [XNGoods]? {
didSet {
productsTableView?.reloadData()
}
}
var categorySelectedIndexPath: NSIndexPath? {
didSet {
productsTableView?.scrollToRowAtIndexPath(NSIndexPath(forRow: 0,inSection: 0), atScrollPosition: .Top, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = LFBGlobalBackgroundColor
view = buildProductsTableView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func buildProductsTableView() -> UITableView {
productsTableView = UITableView(frame: CGRectMake(ScreenWidth * 0.25, 0, ScreenWidth * 0.75, ScreenHeight - NavigationH - 49), style: .Plain)
productsTableView?.backgroundColor = LFBGlobalBackgroundColor
productsTableView?.dataSource = self
productsTableView?.delegate = self
productsTableView!.separatorStyle = .None
productsTableView?.rowHeight = 85
return productsTableView!
}
}
extension XNProductsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return goodArray?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = XNProductCell.productCellWithTableView(tableView)
cell.goods = goodArray![indexPath.row]
return cell
}
}
|
mit
|
71342d3b4ffd6d2590c9a84dad0bbd33
| 27.453333 | 149 | 0.645736 | 5.16707 | false | false | false | false |
quire-io/SwiftyChrono
|
Sources/Parsers/EN/ENSlashMonthFormatParser.swift
|
1
|
1701
|
//
// ENSlashMonthFormatParser.swift
// SwiftyChrono
//
// Created by Jerry Chen on 1/23/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
/*
Month/Year date format with slash "/" (also "-" and ".") between numbers
- 11/05
- 06/2005
*/
private let PATTERN = "(^|[^\\d/]\\s+|[^\\w\\s])" +
"([0-9]|0[1-9]|1[012])/([0-9]{4})" +
"([^\\d/]|$)"
private let openningGroup = 1
private let endingGroup = 4
private let monthGroup = 2
private let yearGroup = 3
public class ENSlashMonthFormatParser: Parser {
override var pattern: String { return PATTERN }
override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? {
let openGroup = match.isNotEmpty(atRangeIndex: openningGroup) ? match.string(from: text, atRangeIndex: openningGroup) : ""
let endGroup = match.isNotEmpty(atRangeIndex: endingGroup) ? match.string(from: text, atRangeIndex: endingGroup) : ""
let fullMatchText = match.string(from: text, atRangeIndex: 0)
let index = match.range(at: 0).location + match.range(at: openningGroup).length
let matchText = fullMatchText.substring(from: openGroup.count, to: fullMatchText.count - endGroup.count).trimmed()
var result = ParsedResult(ref: ref, index: index, text: matchText)
result.start.imply(.day, to: 1)
result.start.assign(.month, value: Int(match.string(from: text, atRangeIndex: monthGroup)))
result.start.assign(.year, value: Int(match.string(from: text, atRangeIndex: yearGroup)))
result.tags[.enSlashMonthFormatParser] = true
return result
}
}
|
mit
|
47b107701c057a58722137152ed59ccb
| 35.956522 | 137 | 0.658235 | 3.736264 | false | false | false | false |
siejkowski/160
|
onesixty/Source/Control/InjectionSpec.swift
|
2
|
4300
|
import Foundation
import Quick
import Nimble
@testable
import onesixty
import Swinject
import RxSwift
class InjectionSpec: QuickSpec {
override func spec() {
describe("DependencyProvider") {
var sut: DependencyProvider?
beforeEach {
sut = Injection().provider
}
afterEach {
sut = nil
}
it("should provide window") {
expect { try sut?.resolveWithError(UIWindow.self) }.toNot(throwError())
}
it("should provide flow controller") {
expect { try sut?.resolveWithError(FlowController.self) }.toNot(throwError())
}
it("should provide navigation controller") {
expect { try sut?.resolveWithError(NavigationController.self) }.toNot(throwError())
}
it("should provide view controller") {
expect { try sut?.resolveWithError(ViewController.self) }.toNot(throwError())
}
it("should provide window with rootviewcontroller") {
expect {
let window: UIWindow = sut!.provide(UIWindow.self)
return window.rootViewController
}.to(beAKindOf(NavigationController.self))
}
}
describe("extension Resolvable") {
var sut: Resolvable?
beforeEach {
sut = Container()
}
afterEach {
sut = nil
}
context("when the type is registered") {
it("should provide instance for type") {
(sut as? Container)?.register(String.self) { _ in return "test instance" }
expect(sut?.provide(String.self)).to(equal("test instance"))
}
it("should provide instance for type and name") {
(sut as? Container)?.register(Int.self, name: "answer") { _ in return 42 }
expect(sut?.provide(Int.self, name: "answer")).to(equal(42))
}
it("should provide instance for type and argument") {
(sut as? Container)?.register(Array<Double>.self) { (_, count: Int) in
return Array(1...count).map { elem in Double(elem) }
}
expect(sut?.provide(Array<Double>.self, argument: 5)).to(equal([1.0, 2.0, 3.0, 4.0, 5.0]))
}
it("should resolve instance for type") {
(sut as? Container)?.register(String.self) { _ in return "test instance" }
expect { try sut?.resolveWithError(String.self) }.to(equal("test instance"))
}
it("should resolve instance for type and name") {
(sut as? Container)?.register(Int.self, name: "answer") { _ in return 42 }
expect { try sut?.resolveWithError(Int.self, name: "answer") }.to(equal(42))
}
it("should resolve instance for type and argument") {
(sut as? Container)?.register(Array<Double>.self) { (_, count: Int) in
return Array(1...count).map { elem in Double(elem) }
}
expect { try sut?.resolveWithError(Array<Double>.self, argument: 5) }.to(equal([1.0, 2.0, 3.0, 4.0, 5.0]))
}
}
context("when the type is not registered") {
it("should throw injection error for type") {
expect { try sut?.resolveWithError(String.self) }
.to(throwError(errorType: InjectionError.self))
}
it("should throw injection error for type and name") {
expect { try sut?.resolveWithError(Int.self, name: "answer") }
.to(throwError(errorType: InjectionError.self))
}
it("should throw injection error for type and argument") {
expect { try sut?.resolveWithError(Array<Double>.self, argument: 5) }
.to(throwError(errorType: InjectionError.self))
}
}
}
}
}
|
mit
|
979be13a1b52c12e6887a5a0ecf92eec
| 34.545455 | 126 | 0.502326 | 4.988399 | false | false | false | false |
el-hoshino/NotAutoLayout
|
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/TopRightBottom.Individual.swift
|
1
|
1229
|
//
// TopRightBottom.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct TopRightBottom {
let topRight: LayoutElement.Point
let bottom: LayoutElement.Vertical
}
}
// MARK: - Make Frame
extension IndividualProperty.TopRightBottom {
private func makeFrame(topRight: Point, bottom: Float, width: Float) -> Rect {
let x = topRight.x - width
let y = topRight.y
let height = bottom - y
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.TopRightBottom: LayoutPropertyCanStoreWidthToEvaluateFrameType {
public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let topRight = self.topRight.evaluated(from: parameters)
let bottom = self.bottom.evaluated(from: parameters)
let height = bottom - topRight.y
let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height))
return self.makeFrame(topRight: topRight, bottom: bottom, width: width)
}
}
|
apache-2.0
|
44044d05d8ea86cedc0b9739da07d5c7
| 21.481481 | 115 | 0.719934 | 3.853968 | false | false | false | false |
murat8505/FillableLoaders
|
Source/RoundedLoader.swift
|
11
|
2191
|
//
// RoundedLoader.swift
// PQFFillableLoaders
//
// Created by Pol Quintana on 2/8/15.
// Copyright (c) 2015 Pol Quintana. All rights reserved.
//
import Foundation
import UIKit
public class RoundedLoader: FillableLoader {
/// Height of the rounded edge of the spike
public var spikeHeight: CGFloat = 5.0
internal override func generateLoader() {
extraHeight = spikeHeight
layoutPath()
}
internal override func layoutPath() {
super.layoutPath()
shapeLayer.path = shapePath()
}
// MARK: Animate
internal override func startAnimating() {
if !animate { return }
if swing { startswinging() }
startMoving(true)
}
//MARK: Spikes
internal func shapePath() -> CGMutablePath {
let width = loaderView.frame.width
let height = loaderView.frame.height
let path = CGPathCreateMutable()
let waves = 32
CGPathMoveToPoint(path, nil, 0, height/2)
let widthDiff = width/CGFloat(waves*2)
var nextCPX = widthDiff
var nextCPY = height/2 + spikeHeight
var nextX = nextCPX + widthDiff
let nextY = height/2
for i: Int in 1...waves {
CGPathAddQuadCurveToPoint(path, nil, nextCPX, nextCPY, nextX, nextY)
nextCPX = nextX + widthDiff
nextCPY = (i%2 == 0) ? height/2 + spikeHeight : height/2 - spikeHeight
nextX = nextCPX + widthDiff
}
CGPathAddLineToPoint(path, nil, width + 100, height/2)
CGPathAddLineToPoint(path, nil, width + 100, height*2)
CGPathAddLineToPoint(path, nil, 0, height*2)
CGPathCloseSubpath(path)
return path
}
//MARK: Animations Delegate
override public func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if !animate { return }
let key = anim.valueForKey("animation") as! String
if key == "up" {
startMoving(false)
}
if key == "down" {
startMoving(true)
}
if key == "rotation" {
startswinging()
}
}
}
|
mit
|
5d2f981439afef784416c74cadc09fb8
| 26.049383 | 83 | 0.578731 | 4.498973 | false | false | false | false |
uias/Tabman
|
Sources/Tabman/Bar/BarIndicator/Types/TMLineBarIndicator.swift
|
1
|
2882
|
//
// TMLineBarIndicator.swift
// Tabman
//
// Created by Merrick Sapsford on 07/06/2018.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
/// Simple indicator that displays as a horizontal line.
open class TMLineBarIndicator: TMBarIndicator {
// MARK: Types
public enum Weight {
case light
case medium
case heavy
case custom(value: CGFloat)
}
public enum CornerStyle {
case square
case rounded
case eliptical
}
// MARK: Properties
private var weightConstraint: NSLayoutConstraint?
open override var displayMode: TMBarIndicator.DisplayMode {
return .bottom
}
// MARK: Customization
/// Color of the line.
open override var tintColor: UIColor! {
didSet {
backgroundColor = tintColor
}
}
/// Weight of the line.
///
/// Options:
/// - light: 2.0 pt
/// - medium: 4.0 pt
/// - heavy: 8.0 pt
/// - custom: Custom weight.
///
/// Default: `.medium`
open var weight: Weight = .medium {
didSet {
weightConstraint?.constant = weight.rawValue
setNeedsLayout()
}
}
/// Corner style for the ends of the line.
///
/// Options:
/// - square: Corners are squared off.
/// - rounded: Corners are rounded.
/// - eliptical: Corners are completely circular.
///
/// Default: `.square`.
open var cornerStyle: CornerStyle = .square {
didSet {
setNeedsLayout()
}
}
// MARK: Lifecycle
open override func layout(in view: UIView) {
super.layout(in: view)
let heightConstraint = heightAnchor.constraint(equalToConstant: weight.rawValue)
heightConstraint.isActive = true
self.weightConstraint = heightConstraint
backgroundColor = self.tintColor
}
open override func layoutSubviews() {
super.layoutSubviews()
superview?.layoutIfNeeded()
layer.cornerRadius = cornerStyle.cornerRadius(for: weight.rawValue,
in: bounds)
}
}
private extension TMLineBarIndicator.Weight {
var rawValue: CGFloat {
switch self {
case .light:
return 2.0
case .medium:
return 4.0
case .heavy:
return 8.0
case .custom(let value):
return value
}
}
}
private extension TMLineBarIndicator.CornerStyle {
func cornerRadius(for weight: CGFloat, in frame: CGRect) -> CGFloat {
switch self {
case .square:
return 0.0
case .rounded:
return weight / 4.0
case .eliptical:
return frame.size.height / 2.0
}
}
}
|
mit
|
fe3581ac62bffef95c6c7321ddccacbd
| 22.422764 | 88 | 0.552933 | 4.833893 | false | false | false | false |
pisarm/Horizon
|
Tests/EndpointTests.swift
|
1
|
1732
|
//
// EndpointTests.swift
// Horizon
//
// Created by Flemming Pedersen on 14/02/16.
// Copyright © 2016 pisarm.dk. All rights reserved.
//
import XCTest
@testable import Horizon
final class EndpointTests: XCTestCase {
//MARK: Tests
func testFailingInit() {
let endpoint = Endpoint(urlString: " ")
XCTAssertNil(endpoint)
}
func testRequest() {
let urlString = "http://pisarm.io"
let timeout: NSTimeInterval = 5
let token = "1234"
let authorization: Authorization = .Token(token: token)
let endpoint: Endpoint! = Endpoint(urlString: urlString, timeout: timeout, authorization: authorization)
let request = endpoint.request()
XCTAssertEqual(urlString, request.URL!.absoluteString)
XCTAssertEqual(timeout, request.timeoutInterval)
XCTAssertNotNil(request.allHTTPHeaderFields!["Authorization"])
XCTAssertEqual("Bearer \(token)", request.allHTTPHeaderFields!["Authorization"]!)
}
func testEquality() {
let urlString = "http://pisarm.io"
let endpoint: Endpoint! = Endpoint(urlString: urlString)
let anotherEndpoint: Endpoint! = Endpoint(urlString: urlString)
XCTAssertEqual(endpoint, anotherEndpoint)
}
func testLessThan() {
let endpoint: Endpoint! = Endpoint(urlString: "http://pisarm.io")
let anotherEndpoint: Endpoint! = Endpoint(urlString: "http://pisarm.dk")
XCTAssertLessThan(anotherEndpoint, endpoint)
}
func testCustomDebugStringConvertible() {
let urlString = "http://pisarm.io"
let endpoint: Endpoint! = Endpoint(urlString: urlString)
XCTAssertEqual(urlString, endpoint.debugDescription)
}
}
|
mit
|
0ff3f3b9624f0b5d7aee9f5b633055cf
| 30.472727 | 112 | 0.670711 | 4.742466 | false | true | false | false |
farrieta9/ReelCut
|
Reel-Cut/Reel-Cut/CollectionController.swift
|
1
|
12249
|
//
// CollectionController.swift
// Reel-Cut
//
// Created by Francisco Arrieta on 10/24/16.
// Copyright © 2016 lil9porkchop. All rights reserved.
//
import UIKit
import Photos
class CollectionController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private let photoCellId = "photoCellId"
var gallery = [UIImage]()
var upperBound: Int = 50
var lowerBound: Int = 50
var startingFrame: CGRect?
var blackBackGroundView: UIView?
var startingImageView: UIImageView?
var numberOfPhotosInGallery: Int = -1
var imageManager: PHImageManager?
var requestOptions: PHImageRequestOptions?
var fetchOptions: PHFetchOptions?
let indicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView()
view.clipsToBounds = true
view.activityIndicatorViewStyle = .whiteLarge
view.hidesWhenStopped = true
view.backgroundColor = UIColor(white: 0, alpha: 0.7)
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 10
return view
}()
let permissionLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Need access to photos to use app"
label.textAlignment = .center
label.isHidden = true
label.textColor = UIColor(white: 0.1, alpha: 0.5)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = UIColor.rgb(red: 246, green: 246, blue: 246)
collectionView?.register(PhotoCell.self, forCellWithReuseIdentifier: photoCellId)
setupView()
setUpIndicator()
setUpImageManager()
checkPhotoLibraryPermission()
}
private func setupView() {
view.addSubview(permissionLabel)
permissionLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
permissionLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
permissionLabel.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
permissionLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func setUpIndicator() {
view.addSubview(indicator)
// x, y, width, height
indicator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
indicator.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
indicator.widthAnchor.constraint(equalToConstant: 64).isActive = true
indicator.heightAnchor.constraint(equalToConstant: 64).isActive = true
}
func checkPhotoLibraryPermission() {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
prepareToFetchPhotos(10)
break
case .denied, .restricted:
print("denied or restricted. Ask user to give permission")
permissionLabel.isHidden = false
break
case .notDetermined:
askForPermissionToPhotoLibrary()
perform(#selector(prepareToFetchPhotos), with: nil, afterDelay: 0.1)
break
}
}
private func askForPermissionToPhotoLibrary() {
PHPhotoLibrary.requestAuthorization() { (status) -> Void in
switch status {
case .authorized:
self.prepareToFetchPhotos(10)
break
case .denied, .restricted: break
// as above
case .notDetermined: break
// won't happen but still
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
print("Memory warning")
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gallery.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoCellId, for: indexPath) as! PhotoCell
cell.imageView.image = gallery[indexPath.item]
let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.handleSwipeRight(_:)))
let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.handleSwipeRight(_:)))
swipeRightGesture.direction = .right
swipeLeftGesture.direction = .left
cell.addGestureRecognizer(swipeRightGesture)
cell.addGestureRecognizer(swipeLeftGesture)
cell.collectionController = self
return cell
}
func handleSwipeRight(_ sender: UISwipeGestureRecognizer) {
guard let cell = sender.view as? PhotoCell else { return }
if let indexPath = collectionView?.indexPath(for: cell) {
let fetchOptions: PHFetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
let assetToDelete: PHAsset = fetchResult[indexPath.item]
let arrayToDelete = NSArray(object: assetToDelete)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets(arrayToDelete)
}, completionHandler: { (success, error) in
if success {
// user clicked on Allow
DispatchQueue.main.async {
self.gallery.remove(at: indexPath.item)
self.collectionView?.deleteItems(at: [indexPath])
}
}
})
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let image = gallery[indexPath.item]
var width: CGFloat = 0
var height: CGFloat = 0
if UIDevice.current.orientation.isLandscape {
if image.size.width < image.size.height {
// picture is potrait
height = image.size.width / image.size.height * view.frame.width + 80
width = (image.size.width - view.frame.width) / image.size.height * view.frame.width
} else {
// picture is landscape
width = view.frame.width
height = image.size.height / image.size.width * width
}
} else {
if image.size.width < image.size.height {
width = view.frame.width
height = view.frame.height / 2 - 40
} else {
// landscape
width = view.frame.width
height = image.size.height / image.size.width * width
}
}
return CGSize(width: width, height: height)
}
private func setUpImageManager() {
imageManager = PHImageManager()
requestOptions = PHImageRequestOptions()
fetchOptions = PHFetchOptions()
requestOptions?.isSynchronous = true
requestOptions?.deliveryMode = .highQualityFormat
fetchOptions?.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
}
func fetchPhotos() {
gallery.removeAll()
let assets: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
numberOfPhotosInGallery = assets.count
print(assets.count)
print(min(assets.count, upperBound))
upperBound = min(assets.count, upperBound)
lowerBound = max(0, upperBound - 50)
if lowerBound < 0 {
lowerBound = 0
upperBound = min(assets.count, upperBound)
}
if upperBound < 1 {
upperBound = min(assets.count, upperBound + 50)
}
for index in lowerBound..<upperBound {
imageManager?.requestImage(for: assets[index], targetSize: self.view.frame.size, contentMode: .aspectFill, options: requestOptions, resultHandler: { (image, _) in
if let image = image {
self.gallery.append(image)
}
})
}
reloadCollectionView()
indicator.stopAnimating()
}
func prepareToFetchPhotos(_ quantity: Int) {
if upperBound < 0 {
upperBound = quantity
}
if upperBound > numberOfPhotosInGallery && numberOfPhotosInGallery > 0{
return
}
indicator.startAnimating()
perform(#selector(fetchPhotos), with: nil, afterDelay: 0.1)
}
func performZoomInForStartingImageView(startingImageView: UIImageView) {
self.startingImageView = startingImageView
self.startingImageView?.isHidden = true
startingFrame = startingImageView.superview?.convert(startingImageView.frame, to: nil)
let zoomingImageView = UIImageView(frame: startingFrame!)
zoomingImageView.image = startingImageView.image
zoomingImageView.isUserInteractionEnabled = true
zoomingImageView.contentMode = .scaleAspectFit
zoomingImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomOut)))
if let keyWindow = UIApplication.shared.keyWindow {
blackBackGroundView = UIView(frame: keyWindow.frame)
blackBackGroundView?.backgroundColor = .black
blackBackGroundView?.alpha = 0
keyWindow.addSubview(blackBackGroundView!)
keyWindow.addSubview(zoomingImageView)
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
self.blackBackGroundView!.alpha = 1
// Make the image fill up the screen
zoomingImageView.frame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: keyWindow.frame.height)
zoomingImageView.center = keyWindow.center
}, completion: nil)
}
}
func handleZoomOut(tapGesture: UITapGestureRecognizer) {
if let zoomOutImageView = tapGesture.view {
// need to animate back to controller
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
zoomOutImageView.frame = self.startingFrame!
self.blackBackGroundView?.alpha = 0
}, completion: { (completed: Bool) in
zoomOutImageView.removeFromSuperview()
self.startingImageView?.isHidden = false
})
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if UIApplication.shared.statusBarOrientation.isPortrait {
if Int(scrollView.contentOffset.y) >= Int((scrollView.contentSize.height - scrollView.frame.size.height)) {
print("bottom")
upperBound += 30
prepareToFetchPhotos(10)
}
if (scrollView.contentOffset.y < 0){
print("top")
upperBound -= 30
prepareToFetchPhotos(10)
}
}
}
func reloadCollectionView() {
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
}
|
mit
|
d1e9ea49920bd9e66391076e10f596d4
| 34.094556 | 174 | 0.602139 | 5.696744 | false | false | false | false |
luckymarmot/ThemeKit
|
Sources/NSImage+ThemeKit.swift
|
1
|
3598
|
//
// NSImage+ThemeKit.swift
// ThemeKit
//
// Converted to Swift 3 by Nuno Grilo on 02/10/2016.
// Copyright © 2016 Paw & Nuno Grilo. All rights reserved.
//
/*
Based on original work from Mircea "Bobby" Georgescu from:
http://www.bobbygeorgescu.com/2011/08/finding-average-color-of-uiimage/
UIImage+AverageColor.m
Copyright (c) 2010, Mircea "Bobby" Georgescu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Mircea "Bobby" Georgescu nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Mircea "Bobby" Georgescu BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Cocoa
extension NSImage {
/// Find the average color in image.
/// Not the most accurate algorithm, but probably got enough for the purpose.
@objc internal func averageColor() -> NSColor {
// setup a single-pixel image
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)
guard let bitmapData = malloc(4),
let context = CGContext(data: bitmapData, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue),
let cgImage = self.cgImage(forProposedRect: nil, context: NSGraphicsContext(cgContext: context, flipped: false), hints: nil) else {
return NSColor.white
}
// draw the image into a 1x1 image
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: 1, height: 1))
// extract byte colors from single-pixel image
let red = bitmapData.load(fromByteOffset: 0, as: UInt8.self)
let green = bitmapData.load(fromByteOffset: 1, as: UInt8.self)
let blue = bitmapData.load(fromByteOffset: 2, as: UInt8.self)
let alpha = bitmapData.load(fromByteOffset: 3, as: UInt8.self)
// build "average color"
let modifier = alpha > 0 ? CGFloat(alpha) / 255.0 : 1.0
let redFloat: CGFloat = CGFloat(red) * modifier / 255.0
let greenFloat: CGFloat = CGFloat(green) * modifier / 255.0
let blueFloat: CGFloat = CGFloat(blue) * modifier / 255.0
let alphaFloat: CGFloat = CGFloat(alpha) / 255.0
return NSColor(red: redFloat, green: greenFloat, blue: blueFloat, alpha: alphaFloat)
}
}
|
mit
|
b3e4e1d34b4ac88a9b946a4e189dfe87
| 46.328947 | 164 | 0.726439 | 4.429803 | false | false | false | false |
MaartenBrijker/project
|
project/External/AudioKit-master/AudioKit/Common/Nodes/Mixing/Mixer/AKMixer.swift
|
2
|
2069
|
//
// AKMixer.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
import AVFoundation
/// AudioKit version of Apple's Mixer Node
public class AKMixer: AKNode, AKToggleable {
private let mixerAU = AVAudioMixerNode()
/// Output Volume (Default 1)
public var volume: Double = 1.0 {
didSet {
if volume < 0 {
volume = 0
}
mixerAU.outputVolume = Float(volume)
}
}
private var lastKnownVolume: Double = 1.0
/// Determine if the mixer is serving any output or if it is stopped.
public var isStarted: Bool {
return volume != 0.0
}
/// Initialize the mixer node
///
/// - parameter inputs: A varaiadic list of AKNodes
///
public init(_ inputs: AKNode...) {
super.init()
self.avAudioNode = mixerAU
AudioKit.engine.attachNode(self.avAudioNode)
for input in inputs {
connect(input)
}
}
/// Connnect another input after initialization
///
/// - parameter input: AKNode to connect
///
public func connect(input: AKNode) {
var wasRunning = false
if AudioKit.engine.running {
wasRunning = true
AudioKit.stop()
}
input.connectionPoints.append(AVAudioConnectionPoint(node: mixerAU, bus: mixerAU.numberOfInputs))
AudioKit.engine.connect(input.avAudioNode, toConnectionPoints: input.connectionPoints, fromBus: 0, format: AudioKit.format)
if wasRunning {
AudioKit.start()
}
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
if isStopped {
volume = lastKnownVolume
}
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
if isPlaying {
lastKnownVolume = volume
volume = 0
}
}
}
|
apache-2.0
|
d31eb38e4696656da9a2848af9ca3b11
| 25.857143 | 131 | 0.586557 | 4.678733 | false | false | false | false |
qvacua/vimr
|
VimR/VimR/FuzzySearchService.swift
|
1
|
12062
|
/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Commons
import CoreData
import Foundation
import Ignore
import os
import Misc
final class FuzzySearchService {
typealias ScoredUrlsCallback = ([ScoredUrl]) -> Void
var root: URL {
didSet {
self.queue.sync {
self.deleteAllFiles()
self.ensureRootFileInStore()
}
}
}
var usesVcsIgnores = true {
willSet { self.stopScanScore() }
didSet {
self.queue.sync {
self.deleteAllFiles()
self.ensureRootFileInStore()
}
}
}
func cleanUp() {
do {
try self.coreDataStack.deleteStore()
} catch {
self.log.error("Could not delete core data store: \(error)")
}
}
func stopScanScore() {
self.stopLock.lock()
defer { self.stopLock.unlock() }
self.stop = true
}
func scanScore(
for pattern: String,
beginCallback: @escaping () -> Void,
endCallback: @escaping () -> Void,
callback: @escaping ScoredUrlsCallback
) {
self.queue.async {
self.log.info("Starting fuzzy search for \(pattern) in \(self.root)")
beginCallback()
defer { endCallback() }
let ctx = self.writeContext
ctx.performAndWait {
self.stopLock.lock()
self.stop = false
self.stopLock.unlock()
let matcher = FzyMatcher(needle: pattern)
self.scanScoreSavedFiles(matcher: matcher, context: ctx, callback: callback)
if self.shouldStop() { return }
self.scanScoreFilesNeedScanning(matcher: matcher, context: ctx, callback: callback)
}
self.log.info("Finished fuzzy search for \(pattern) in \(self.root)")
}
}
private func scanScoreSavedFiles(
matcher: FzyMatcher,
context: NSManagedObjectContext,
callback: ScoredUrlsCallback
) {
let predicate = NSPredicate(format: "direntType != %d", DT_DIR)
let countReq = FileItem.fetchRequest()
countReq.predicate = predicate
countReq.includesSubentities = false
guard let count = try? context.count(for: countReq) else {
self.log.error("Could not get count of Files")
return
}
self.log.info("Scoring \(count) Files for pattern \(matcher.needle)")
let urlSorter = NSSortDescriptor(key: "url", ascending: true)
let fetchReq = FileItem.fetchRequest()
fetchReq.fetchLimit = coreDataBatchSize
fetchReq.sortDescriptors = [urlSorter]
fetchReq.predicate = predicate
let chunkCount = Int(ceil(Double(count) / Double(coreDataBatchSize)))
for chunkIndex in 0..<chunkCount {
if self.shouldStop({ context.reset() }) { return }
let start = Swift.min(chunkIndex * coreDataBatchSize, count)
fetchReq.fetchOffset = start
do {
self.scoreFiles(
matcher: matcher,
files: try context.fetch(fetchReq),
callback: callback
)
} catch {
self.log.error("Could not fetch \(fetchReq): \(error)")
}
context.reset()
}
}
private func scanScoreFilesNeedScanning(
matcher: FzyMatcher,
context: NSManagedObjectContext,
callback: ([ScoredUrl]) -> Void
) {
let req = self.fileFetchRequest("needsScanChildren == TRUE AND direntType == %d", [DT_DIR])
do {
let foldersToScan = try context.fetch(req)
// We use the ID of objects since we reset in scanScore(), which resets all properties of
// foldersToScan after first folderToScan.
foldersToScan.forEach { folder in
self.scanScore(
matcher: matcher,
folderId: folder.objectID,
context: context,
callback: callback
)
}
} catch {
self.log.error("Could not fetch \(req): \(error)")
}
}
private func scanScore(
matcher: FzyMatcher,
folderId: NSManagedObjectID,
context: NSManagedObjectContext,
callback: ([ScoredUrl]) -> Void
) {
var saveCounter = 1
var counter = 1
guard let folder = context.object(with: folderId) as? FileItem else {
self.log.error("Could not convert object with ID \(folderId) to File")
return
}
let initialBaton = self.ignoreService.ignore(for: folder.url!)
let testIgnores = self.usesVcsIgnores
var stack = [(initialBaton, folder)]
while let iterElement = stack.popLast() {
if self.shouldStop({ self.saveAndReset(context: context) }) { return }
autoreleasepool {
let baton = iterElement.0
let folder = iterElement.1
let urlToScan = folder.url!
let childUrls = FileUtils
.directDescendants(of: urlToScan)
.filter {
guard testIgnores, let ignore = baton else { return true }
let isExcluded = ignore.excludes($0)
if isExcluded { self.log.debug("Ignoring \($0.path)") }
return !isExcluded
}
let childFiles = childUrls
.filter { !$0.isPackage }
.map { url -> FileItem in self.file(fromUrl: url, in: context) }
saveCounter += childFiles.count
counter += childFiles.count
folder.addChildren(Set(childFiles))
folder.needsScanChildren = false
let childFolders = childFiles.filter { $0.direntType == DT_DIR }
let childBatons = childFolders.map { self.ignoreService.ignore(for: $0.url!) }
stack.append(contentsOf: zip(childBatons, childFolders))
if saveCounter > coreDataBatchSize {
self.log.debug(
"Flushing and scoring \(saveCounter) Files, stack has \(stack.count) Files"
)
self.scoreAllRegisteredFiles(
matcher: matcher,
context: context,
callback: callback
)
self.saveAndReset(context: context)
saveCounter = 0
// We have to re-fetch the Files in stack to get the parent-children relationship right.
// Since objectID survives NSManagedObjectContext.reset(), we can re-populate (re-fetch)
// stack using the objectIDs.
let ids = stack.map(\.1.objectID)
stack = Array(zip(
stack.map(\.0),
ids.map { context.object(with: $0) as! FileItem }
))
}
}
}
self.log.debug("Flushing and scoring last \(saveCounter) Files")
self.scoreAllRegisteredFiles(matcher: matcher, context: context, callback: callback)
self.saveAndReset(context: context)
self.log.debug("Stored \(counter) Files")
}
private func saveAndReset(context: NSManagedObjectContext) {
do {
try context.save()
} catch {
self.log.error("There was an error saving the context: \(error)")
}
context.reset()
}
private func shouldStop(_ body: (() -> Void)? = nil) -> Bool {
self.stopLock.lock()
defer { self.stopLock.unlock() }
if self.stop {
body?()
return true
}
return false
}
private func scoreAllRegisteredFiles(
matcher: FzyMatcher,
context: NSManagedObjectContext,
callback: ([ScoredUrl]) -> Void
) {
let files = context.registeredObjects
.compactMap { $0 as? FileItem }
.filter { $0.direntType != DT_DIR }
self.log.debug("Scoring \(files.count) Files")
self.scoreFiles(matcher: matcher, files: files, callback: callback)
}
private func scoreFiles(
matcher: FzyMatcher,
files: [FileItem],
callback: ScoredUrlsCallback
) {
let matchFullPath = matcher.needle.contains("/")
let count = files.count
let chunkCount = Int(ceil(Double(count) / Double(fuzzyMatchChunkSize)))
DispatchQueue.concurrentPerform(iterations: chunkCount) { chunkIndex in
let start = Swift.min(chunkIndex * fuzzyMatchChunkSize, count)
let end = Swift.min(start + fuzzyMatchChunkSize, count)
if self.shouldStop() { return }
let scoreThreshold = 1.0
callback(files[start..<end].compactMap { file in
let url = file.url!
let haystack = matchFullPath ? url.path : url.lastPathComponent
guard matcher.hasMatch(haystack) else { return nil }
let score = matcher.score(haystack)
if score < scoreThreshold { return nil }
return ScoredUrl(url: url, score: score)
})
}
}
init(root: URL) throws {
self.coreDataStack = try CoreDataStack(
modelName: "FuzzySearch",
storeLocation: .temp(UUID().uuidString),
deleteOnDeinit: true
)
self.root = root
self.writeContext = self.coreDataStack.newBackgroundContext()
self.ignoreService = IgnoreService(count: 500, root: root)
self.queue.sync { self.ensureRootFileInStore() }
try self.fileMonitor.monitor(url: root) { [weak self] url in self?.handleChange(in: url) }
}
private func ensureRootFileInStore() {
self.queue.async {
let ctx = self.writeContext
ctx.performAndWait {
let req = self.fileFetchRequest("url == %@", [self.root])
do {
let files = try ctx.fetch(req)
guard files.isEmpty else { return }
_ = self.file(fromUrl: self.root, in: ctx)
try ctx.save()
} catch {
self.log.error("Could not ensure root File in Core Data: \(error)")
}
}
}
}
private func handleChange(in folderUrl: URL) {
self.queue.async {
let ctx = self.writeContext
ctx.performAndWait {
let req = self.fileFetchRequest("url == %@", [folderUrl])
do {
let fetchResult = try ctx.fetch(req)
guard let folder = fetchResult.first else {
return
}
for child in folder.children ?? [] { ctx.delete(child) }
folder.needsScanChildren = true
self.log.trace("Marked \(folder.url!) for scanning")
try ctx.save()
} catch {
self.log.error(
"Could not fetch File with url \(folderUrl) "
+ "or could not save after setting needsScanChildren: \(error)"
)
}
ctx.reset()
}
}
}
private func fileFetchRequest(
_ format: String,
_ arguments: [Any]? = nil
) -> NSFetchRequest<FileItem> {
let req: NSFetchRequest<FileItem> = FileItem.fetchRequest()
req.predicate = NSPredicate(format: format, argumentArray: arguments)
return req
}
/// Call this in self.queue.(a)sync
private func deleteAllFiles() {
let delReq = NSBatchDeleteRequest(
fetchRequest: NSFetchRequest(entityName: String(describing: FileItem.self))
)
let ctx = self.writeContext
ctx.performAndWait {
do {
try ctx.execute(delReq)
} catch {
self.log.error("Could not delete all Files: \(error)")
}
}
}
private func file(fromUrl url: URL, in context: NSManagedObjectContext) -> FileItem {
let file = FileItem(context: context)
file.url = url
file.direntType = url.direntType
file.isHidden = url.isHidden
file.isPackage = url.isPackage
if url.hasDirectoryPath { file.needsScanChildren = true }
return file
}
func debug() {
let req = self.fileFetchRequest("needsScanChildren == TRUE AND direntType == %d", [DT_DIR])
self.queue.async {
let moc = self.writeContext
moc.performAndWait {
do {
let result = try moc.fetch(req)
Swift.print("Files with needsScanChildren = true:")
result.forEach { Swift.print("\t\(String(describing: $0.url))") }
Swift.print("--- \(result.count)")
} catch {
Swift.print(error)
}
}
}
}
private var stop = false
private let stopLock = NSLock()
private let queue = DispatchQueue(
label: "scan-score-queue",
qos: .userInitiated,
target: .global(qos: .userInitiated)
)
private let fileMonitor = FileMonitor()
private let coreDataStack: CoreDataStack
private let writeContext: NSManagedObjectContext
private let ignoreService: IgnoreService
private let log = OSLog(subsystem: Defs.loggerSubsystem, category: Defs.LoggerCategory.service)
}
private let fuzzyMatchChunkSize = 100
private let coreDataBatchSize = 10000
|
mit
|
c6090b84e5886772905b89cc8b02fb4a
| 27.314554 | 98 | 0.625352 | 4.163618 | false | false | false | false |
liutongchao/LCNibBridge
|
Source/LCNibBridge/LCNibBridge.swift
|
1
|
3677
|
//
// LCNibBridge.swift
// LCNibBridge
//
// Created by 刘通超 on 16/5/25.
// Copyright © 2016年 刘通超. All rights reserved.
//
import UIKit
//MARK: 桥接协议
@objc
public protocol LCNibBridge {
}
extension UIView{
open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
if class_conformsToProtocol(self.classForCoder, LCNibBridge.self) {
let version = class_getVersion(self.classForCoder)
if version == 0 {
//标记该类正在桥接
print(self.classForCoder)
class_setVersion(self.classForCoder, 1)
return self.instantiateRealView(self)
}
//标记该类已经桥接完毕
class_setVersion(self.classForCoder, 0)
return self
}
return self
}
func instantiateRealView(_ placeholdView:UIView) -> UIView? {
//从xib中加载真正的视图
let realView = placeholdView.lc_instantiateFromNib()
//迁移View的所有属性
realView?.tag = placeholdView.tag
realView?.frame = placeholdView.frame
realView?.bounds = placeholdView.bounds
realView?.isHidden = placeholdView.isHidden
realView?.clipsToBounds = placeholdView.clipsToBounds
realView?.autoresizingMask = placeholdView.autoresizingMask
realView?.isUserInteractionEnabled = placeholdView.isUserInteractionEnabled
realView?.translatesAutoresizingMaskIntoConstraints = placeholdView.translatesAutoresizingMaskIntoConstraints
if placeholdView.constraints.count > 0{
if realView != nil {
for constraint in placeholdView.constraints {
var newConstraint: NSLayoutConstraint?
if constraint.secondItem == nil {
newConstraint = NSLayoutConstraint.init(item: realView!, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: nil, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant)
}else if(constraint.firstItem === constraint.secondItem){
newConstraint = NSLayoutConstraint.init(item: realView!,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: realView!,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier,
constant: constraint.constant)
}
if newConstraint != nil {
newConstraint?.shouldBeArchived = constraint.shouldBeArchived
newConstraint?.priority = constraint.priority
let version = UIDevice.current.systemVersion as NSString
if version.floatValue >= 7.0 {
newConstraint?.identifier = constraint.identifier
}
realView?.addConstraint(newConstraint!)
}
}
}
}
return realView
}
}
|
mit
|
87eb4a2ea2096343f8fe41de26d5760d
| 38.844444 | 268 | 0.516453 | 6.438061 | false | false | false | false |
brentdax/swift
|
test/SILOptimizer/definite_init_cross_module.swift
|
9
|
7916
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/OtherModule.swiftmodule %S/Inputs/definite_init_cross_module/OtherModule.swift
// RUN: %target-swift-frontend -emit-sil -verify -I %t -swift-version 5 %s > /dev/null -import-objc-header %S/Inputs/definite_init_cross_module/BridgingHeader.h
import OtherModule
extension Point {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: Point) {
// This is OK
self = other
}
init(other: Point, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: Point, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: Point, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: Point, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericPoint {
init(xx: T, yy: T) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: T, yyy: T) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<T>) {
// This is OK
self = other
}
init(other: GenericPoint<T>, x: T) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<T>, xx: T) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: GenericPoint<T>, x: T, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<T>, xx: T, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericPoint where T == Double {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<Double>) {
// This is OK
self = other
}
init(other: GenericPoint<Double>, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<Double>, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: GenericPoint<Double>, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<Double>, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
typealias MyGenericPoint<Q> = GenericPoint<Q>
extension MyGenericPoint {
init(myX: T, myY: T) {
self.x = myX // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = myY // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension CPoint {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: CPoint) {
// This is OK
self = other
}
init(other: CPoint, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: CPoint, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self = other
}
init(other: CPoint, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: CPoint, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension NonnullWrapper {
init(p: UnsafeMutableRawPointer) {
self.ptr = p // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
// No suggestion for "self.init()" because this struct does not support a
// zeroing initializer.
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension PrivatePoint {
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: PrivatePoint) {
// This is OK
self = other
}
init(other: PrivatePoint, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init() {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension Empty {
init(x: Double) {
// This is OK
self.init()
}
init(other: Empty) {
// This is okay
self = other
}
init(other: Empty, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericEmpty {
init(x: Double) {
// This is OK
self.init()
}
init(other: GenericEmpty<T>) {
// This is okay
self = other
}
init(other: GenericEmpty<T>, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
|
apache-2.0
|
cda69c17a738e86cb27f8e6f67917cf2
| 31.310204 | 197 | 0.635801 | 3.484155 | false | false | false | false |
quickthyme/PUTcat
|
Tests/iOS/Variable/VariablePresenterSpy.swift
|
1
|
4216
|
import UIKit
class VariablePresenterSpy : VariablePresenter {
var ucFetchVariableListWasCalled = false
var ucFetchVariableListParameter_environmentID: String?
var ucAddVariableWasCalled = false
var ucAddVariableParameter_environmentID: String?
var ucUpdateVariableWasCalled = false
var ucUpdateVariableParameter_environmentID: String?
var ucUpdateVariableParameter_id: String?
var ucUpdateVariableParameter_name: String?
var ucUpdateVariableParameter_value: String?
var ucDeleteVariableWasCalled = false
var ucDeleteVariableParameter_environmentID: String?
var ucDeleteVariableParameter_variableID: String?
var ucSortVariableListWasCalled = false
var ucSortVariableListParameter_environmentID: String?
var ucSortVariableListParameter_ordinality: [String]?
var ucGetParsedVariableWasCalled = false
var ucGetParsedVariableParameter_environmentID: String?
var ucGetParsedVariableParameter_variableID: String?
override func ucFetchVariableList(environmentID: String) -> Composed.Action<Any, PCList<PCVariable>> {
ucFetchVariableListWasCalled = true
ucFetchVariableListParameter_environmentID = environmentID
return createAction_VariableList()
}
override func ucAddVariable(environmentID: String) -> Composed.Action<Any, PCList<PCVariable>> {
ucAddVariableWasCalled = true
ucAddVariableParameter_environmentID = environmentID
return createAction_VariableList()
}
override func ucUpdateVariable(environmentID: String, name: String, value: String, id: String) -> Composed.Action<Any, PCList<PCVariable>> {
ucUpdateVariableWasCalled = true
ucUpdateVariableParameter_environmentID = environmentID
ucUpdateVariableParameter_id = id
ucUpdateVariableParameter_name = name
ucUpdateVariableParameter_value = value
return createAction_VariableList()
}
override func ucDeleteVariable(environmentID: String, variableID: String) -> Composed.Action<Any, PCList<PCVariable>> {
ucDeleteVariableWasCalled = true
ucDeleteVariableParameter_environmentID = environmentID
ucDeleteVariableParameter_variableID = variableID
return createAction_VariableList()
}
override func ucSortVariableList(environmentID: String, ordinality ids: [String]) -> Composed.Action<Any, PCList<PCVariable>> {
ucSortVariableListWasCalled = true
ucSortVariableListParameter_environmentID = environmentID
ucSortVariableListParameter_ordinality = ids
return createAction_VariableList()
}
override func ucGetParsedVariable(environmentID: String, variableID: String) -> Composed.Action<Any, PCParsedVariable> {
ucGetParsedVariableWasCalled = true
ucGetParsedVariableParameter_environmentID = environmentID
ucGetParsedVariableParameter_variableID = variableID
return createAction_ParsedVariable()
}
// Fake Data
func createAction_VariableList() -> Composed.Action<Any, PCList<PCVariable>> {
return Composed.Action<Any, PCList<PCVariable>> { _, completion in
completion(.success(self.createVariableList()))
}
}
func createAction_Variable() -> Composed.Action<Any, PCVariable> {
return Composed.Action<Any, PCVariable> { _, completion in
completion(.success(self.createVariable()))
}
}
func createAction_ParsedVariable() -> Composed.Action<Any, PCParsedVariable> {
return Composed.Action<Any, PCParsedVariable> { _, completion in
completion(.success(self.createParsedVariable()))
}
}
func createVariableList() -> PCList<PCVariable> {
return PCList<PCVariable>(items: [
PCVariable(id: "987", name: "Title 1", value: "Value 1"),
PCVariable(id: "654", name: "Title 2", value: "Value 2")
]
)
}
func createVariable() -> PCVariable {
return PCVariable(id: "987", name: "Title 1", value: "Value 1")
}
func createParsedVariable() -> PCParsedVariable {
return PCParsedVariable(id: "987", name: "Title 1", value: "Parsed Value 1")
}
}
|
apache-2.0
|
cc62414599ee3384dc58f6b99694e655
| 38.773585 | 144 | 0.712998 | 4.562771 | false | false | false | false |
mansoor92/MaksabComponents
|
MaksabComponents/Classes/Help/SimpleTextView.swift
|
1
|
2623
|
//
// SImpleTextView.swift
// Pods
//
// Created by Incubasys on 19/09/2017.
//
//
import UIKit
import StylingBoilerPlate
public protocol SimpleTextViewDelegate{
func onTapped(tag: Int, view: SimpleTextView)
}
public class SimpleTextView: UIView, NibLoadableView, CustomView {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var leftIcon: UIImageView!
@IBOutlet weak var separatorView: UIView!
@IBOutlet weak var leftIconWidth: NSLayoutConstraint!
@IBOutlet weak var leftIconTrailing: NSLayoutConstraint!
let bundle = Bundle(for: SimpleTextView.classForCoder())
var contentView: UIView!
public var delegate: SimpleTextViewDelegate?
public var isLight: Bool = true{
didSet{
if isLight{
self.backgroundColor = UIColor.appColor(color: .Light)
leftIcon.tintColor = UIColor.appColor(color: .Dark)
title.textColor = UIColor.appColor(color: .DarkText)
}else{
self.backgroundColor = UIColor.appColor(color: .Dark)
leftIcon.tintColor = UIColor.appColor(color: .Light)
title.textColor = UIColor.appColor(color: .LightText)
}
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override public required init(frame: CGRect) {
super.init(frame: frame)
contentView = commonInit(bundle: bundle)
configView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView = commonInit(bundle: bundle)
configView()
}
func configView() {
contentView.backgroundColor = UIColor.clear
isLight = true
separatorView.backgroundColor = UIColor.appColor(color: .Header)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(actViewTapped))
self.addGestureRecognizer(tapGesture)
}
public func config(title:String) {
self.title.text = title
}
public func addLeftView(img: UIImage?) {
leftIcon.image = img
leftIconWidth.constant = 16
leftIconTrailing.constant = 12
}
public func removeLeftView() {
leftIconWidth.constant = 16
leftIconTrailing.constant = 12
leftIcon.image = nil
}
func actViewTapped() {
delegate?.onTapped(tag: self.tag, view: self)
}
}
|
mit
|
d35f4a6be72f6e335cef835230354505
| 28.144444 | 95 | 0.630194 | 4.66726 | false | false | false | false |
SwiftKickMobile/SwiftMessages
|
SwiftMessages/MaskingView.swift
|
1
|
2504
|
//
// MaskingView.swift
// SwiftMessages
//
// Created by Timothy Moose on 3/11/17.
// Copyright © 2017 SwiftKick Mobile. All rights reserved.
//
import UIKit
class MaskingView: PassthroughView {
func install(keyboardTrackingView: KeyboardTrackingView) {
self.keyboardTrackingView = keyboardTrackingView
keyboardTrackingView.translatesAutoresizingMaskIntoConstraints = false
addSubview(keyboardTrackingView)
keyboardTrackingView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
keyboardTrackingView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
keyboardTrackingView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
}
var accessibleElements: [NSObject] = []
weak var backgroundView: UIView? {
didSet {
oldValue?.removeFromSuperview()
if let view = backgroundView {
view.isUserInteractionEnabled = false
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
sendSubviewToBack(view)
}
}
}
override func accessibilityElementCount() -> Int {
return accessibleElements.count
}
override func accessibilityElement(at index: Int) -> Any? {
return accessibleElements[index]
}
override func index(ofAccessibilityElement element: Any) -> Int {
guard let object = element as? NSObject else { return 0 }
return accessibleElements.firstIndex(of: object) ?? 0
}
init() {
super.init(frame: CGRect.zero)
clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
clipsToBounds = true
}
private var keyboardTrackingView: KeyboardTrackingView?
override func addSubview(_ view: UIView) {
super.addSubview(view)
guard let keyboardTrackingView = keyboardTrackingView,
view != keyboardTrackingView,
view != backgroundView else { return }
let offset: CGFloat
if let adjustable = view as? MarginAdjustable {
offset = -adjustable.bounceAnimationOffset
} else {
offset = 0
}
keyboardTrackingView.topAnchor.constraint(
greaterThanOrEqualTo: view.bottomAnchor,
constant: offset
).with(priority: UILayoutPriority(250)).isActive = true
}
}
|
mit
|
ae2d3abc4d398c5987e5afebd2a7a2f7
| 30.683544 | 95 | 0.652018 | 5.280591 | false | false | false | false |
joalbright/Playgrounds
|
NSURLSession.playground/Sources/Parts/Endpoint.swift
|
1
|
1245
|
import Foundation
public typealias Parameters = [String:AnyObject]
public typealias Headers = [String:AnyObject]
public enum Method: String {
case GET,POST,DELETE,PUT,PATCH,OPTIONS
}
public struct Endpoint: Equatable {
public var name: String
public var path: String
public var method: Method
public var body: Parameters = [:]
public var query: Parameters = [:]
public var headers: Headers = [:]
public var requiresToken: Bool = false
public init(name: String, path: String, method: Method) {
self.name = name
self.path = path
self.method = method
}
}
public func == (lhs: Endpoint, rhs: Endpoint) -> Bool {
return lhs.name == rhs.name && lhs.path == rhs.path && lhs.method.rawValue == rhs.method.rawValue
}
public protocol EndpointList: RawRepresentable, Hashable { var endpoints: [Endpoint] { get } }
extension EndpointList {
public static var endpoints: [Endpoint] { return [] }
public typealias RawValue = String
public var choices: [Any] { return Mirror(reflecting: self).children.map({ return $0.1 }) }
public var rawValue: Endpoint { return endpoints[hashValue] }
}
|
apache-2.0
|
18982e625993d6af613c74c53465d54c
| 23.431373 | 101 | 0.639357 | 4.383803 | false | false | false | false |
hanjoes/line-transform
|
lines/lines/ViewController.swift
|
1
|
1548
|
//
// ViewController.swift
// lines
//
// Created by Hanzhou Shi on 3/11/16.
// Copyright © 2016 Hanzhou Shi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private struct Constants {
static let CanvasViewSize = CGSizeMake(200, 200)
}
// MARK: Outlets/Actions
@IBOutlet weak var backView: UIView! {
didSet {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "pan:")
backView.addGestureRecognizer(panGestureRecognizer)
}
}
func pan(gesture: UIPanGestureRecognizer) {
let translation = gesture.translationInView(backView)
switch gesture.state {
case .Began, .Changed:
canvasView.translateAnchorPoint(byTranslation: translation)
default: break
}
}
weak var canvasView: CanvasView!
// MARK: Lifecycles
override func viewDidLoad() {
super.viewDidLoad()
guard canvasView == nil else { return }
let tmpView = CanvasView()
backView.addSubview(tmpView)
canvasView = tmpView
}
override func viewDidLayoutSubviews() {
let size = Constants.CanvasViewSize,
c = backView.convertPoint(backView.center, fromView: view),
origin = CGPointMake(c.x - size.width / 2, c.y - size.height / 2),
canvasFrame = CGRect(origin: origin, size: size)
canvasView.frame = canvasFrame
}
// MARK: Properties
// MARK: Methods
}
|
mit
|
69e87f9dcf8cde7401c87b5b08b1015a
| 24.783333 | 91 | 0.616677 | 4.774691 | false | false | false | false |
softmaxsg/trakt.tv-searcher
|
TraktSearcherTests/TrackSearchAPIMock.swift
|
1
|
1818
|
//
// PopularMoviesViewModelTests.swift
// TraktSearcherTests
//
// Copyright © 2016 Vitaly Chupryk. All rights reserved.
//
import Foundation
import TraktSearchAPI
class TrackSearchAPIMock: TraktSearchAPIProtocol
{
class TraktSearchAPICancelableStub: TraktSearchAPICancelable
{
func cancel()
{
}
}
private let queue = NSOperationQueue()
private let popularMoviesResponse: MoviesResponse?
private let searchMoviesResponse: MoviesResponse?
init(popularMoviesResponse: MoviesResponse?)
{
self.popularMoviesResponse = popularMoviesResponse
self.searchMoviesResponse = nil
}
init(searchMoviesResponse: MoviesResponse?)
{
self.popularMoviesResponse = nil
self.searchMoviesResponse = searchMoviesResponse
}
init(popularMoviesResponse: MoviesResponse?, searchMoviesResponse: MoviesResponse?)
{
self.popularMoviesResponse = popularMoviesResponse
self.searchMoviesResponse = searchMoviesResponse
}
func loadPopularMovies(pageNumber pageNumber: UInt, pageSize: UInt, completionHandler: (MoviesResponse) -> ()) -> TraktSearchAPICancelable
{
if let popularMoviesResponse = self.popularMoviesResponse {
queue.addOperationWithBlock {
completionHandler(popularMoviesResponse)
}
}
return TraktSearchAPICancelableStub()
}
func searchMovies(query: String, pageNumber: UInt, pageSize: UInt, completionHandler: (MoviesResponse) -> ()) -> TraktSearchAPICancelable
{
if let searchMoviesResponse = self.searchMoviesResponse {
queue.addOperationWithBlock {
completionHandler(searchMoviesResponse)
}
}
return TraktSearchAPICancelableStub()
}
}
|
mit
|
6aee7f349e46d6c57f0a6fa3697060b6
| 27.390625 | 142 | 0.694001 | 5.047222 | false | false | false | false |
hooman/swift
|
test/Driver/tools_directory.swift
|
14
|
1546
|
//=================================================
// ** GENERIC UNIX TARGETS - linking via clang **
//=================================================
// RUN: %swiftc_driver -### -target x86_64-linux-unknown -tools-directory %S/Inputs/fake-toolchain %s 2>&1 | %FileCheck -check-prefix CLANGSUB %s
// RUN: %swiftc_driver -### -target x86_64-linux-unknown -tools-directory /Something/obviously/fake %s 2>&1 | %FileCheck -check-prefix BINUTILS %s
// CLANGSUB: swift
// CLANGSUB: -o [[OBJECTFILE:.*]]
// CLANGSUB: swift-autolink-extract{{(\.exe)?"?}} [[OBJECTFILE]]
// CLANGSUB: -o {{"?}}[[AUTOLINKFILE:.*]]
// CLANGSUB: {{[^ ]+(\\\\|/)}}Inputs{{/|\\\\}}fake-toolchain{{/|\\\\}}clang
// CLANGSUB-DAG: [[OBJECTFILE]]
// CLANGSUB-DAG: @[[AUTOLINKFILE]]
// CLANGSUB: -o tools_directory
// BINUTILS: swift
// BINUTILS: -o [[OBJECTFILE:.*]]
// BINUTILS: swift-autolink-extract{{(\.exe)?"?}} [[OBJECTFILE]]
// BINUTILS: -o {{"?}}[[AUTOLINKFILE:.*]]
// BINUTILS: clang
// BINUTILS-DAG: [[OBJECTFILE]]
// BINUTILS-DAG: @[[AUTOLINKFILE]]
// BINUTILS-DAG: -B /Something/obviously/fake
// BINUTILS: -o tools_directory
//======================================
// ** DARWIN TARGETS - linking via ld **
//======================================
// RUN: %swiftc_driver -### -target x86_64-apple-macosx10.9 -tools-directory %S/Inputs/fake-toolchain %s 2>&1 | %FileCheck -check-prefix LDSUB %s
// LDSUB: swift
// LDSUB: -o [[OBJECTFILE:.*]]
// LDSUB: {{[^ ]+(\\\\|/)}}Inputs{{/|\\\\}}fake-toolchain{{(\\\\|/)ld"?}} [[OBJECTFILE]]
// LDSUB: -o tools_directory
|
apache-2.0
|
50d0dd1e974e242ccd308cc41f95d895
| 41.944444 | 146 | 0.552393 | 3.770732 | false | false | true | false |
jeremiahyan/ResearchKit
|
samples/ORKCatalog/ORKCatalog/Tasks/TaskListViewController.swift
|
2
|
8945
|
/*
Copyright (c) 2015, Apple Inc. All rights reserved.
Copyright (c) 2015, Ricardo Sánchez-Sáez.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
/**
This example displays a catalog of tasks, each consisting of one or two steps,
built using the ResearchKit framework. The `TaskListViewController` displays the
available tasks in this catalog.
When you tap a task, it is presented like a participant in a study might
see it. After completing the task, you can see the results generated by
the task by switching to the results tab.
*/
class TaskListViewController: UITableViewController, ORKTaskViewControllerDelegate {
var waitStepViewController: ORKWaitStepViewController?
var waitStepUpdateTimer: Timer?
var waitStepProgress: CGFloat = 0.0
// MARK: Types
enum TableViewCellIdentifier: String {
case `default` = "Default"
}
// MARK: Properties
/**
When a task is completed, the `TaskListViewController` calls this closure
with the created task.
*/
var taskResultFinishedCompletionHandler: ((ORKResult) -> Void)?
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
self.tableView.backgroundColor = UIColor.systemGroupedBackground
}
}
// MARK: UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return TaskListRow.sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TaskListRow.sections[section].rows.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return TaskListRow.sections[section].title
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifier.default.rawValue, for: indexPath)
let taskListRow = TaskListRow.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row]
cell.textLabel!.text = "\(taskListRow)"
if #available(iOS 13.0, *) {
cell.textLabel?.textColor = UIColor.label
}
return cell
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Present the task view controller that the user asked for.
let taskListRow = TaskListRow.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row]
// Create a task from the `TaskListRow` to present in the `ORKTaskViewController`.
let task = taskListRow.representedTask
/*
Passing `nil` for the `taskRunUUID` lets the task view controller
generate an identifier for this run of the task.
*/
let taskViewController = ORKTaskViewController(task: task, taskRun: nil)
// Make sure we receive events from `taskViewController`.
taskViewController.delegate = self
// Assign a directory to store `taskViewController` output.
taskViewController.outputDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
/*
We present the task directly, but it is also possible to use segues.
The task property of the task view controller can be set any time before
the task view controller is presented.
*/
present(taskViewController, animated: true, completion: nil)
}
// MARK: ORKTaskViewControllerDelegate
func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
/*
The `reason` passed to this method indicates why the task view
controller finished: Did the user cancel, save, or actually complete
the task; or was there an error?
The actual result of the task is on the `result` property of the task
view controller.
*/
taskResultFinishedCompletionHandler?(taskViewController.result)
taskViewController.dismiss(animated: true, completion: nil)
}
func taskViewController(_ taskViewController: ORKTaskViewController, stepViewControllerWillAppear stepViewController: ORKStepViewController) {
// Example data processing for the wait step.
if stepViewController.step?.identifier == "WaitStepIndeterminate" ||
stepViewController.step?.identifier == "WaitStep" ||
stepViewController.step?.identifier == "LoginWaitStep" {
delay(5.0, closure: { () -> Void in
if let stepViewController = stepViewController as? ORKWaitStepViewController {
stepViewController.goForward()
}
})
} else if stepViewController.step?.identifier == "WaitStepDeterminate" {
delay(1.0, closure: { () -> Void in
if let stepViewController = stepViewController as? ORKWaitStepViewController {
self.waitStepViewController = stepViewController
self.waitStepProgress = 0.0
self.waitStepUpdateTimer = Timer(timeInterval: 0.1, target: self, selector: #selector(TaskListViewController.updateProgressOfWaitStepViewController), userInfo: nil, repeats: true)
RunLoop.main.add(self.waitStepUpdateTimer!, forMode: RunLoop.Mode.common)
}
})
}
}
func taskViewController(_ taskViewController: ORKTaskViewController, learnMoreButtonPressedWith learnMoreStep: ORKLearnMoreInstructionStep, for stepViewController: ORKStepViewController) {
// FIXME: Temporary fix. This method should not be called if it is only used to present the learnMoreStepViewController, the stepViewController should present the learnMoreStepViewController.
stepViewController.present(UINavigationController(rootViewController: ORKLearnMoreStepViewController(step: learnMoreStep)), animated: true) {
}
}
func delay(_ delay: Double, closure: @escaping () -> Void ) {
let delayTime = DispatchTime.now() + delay
let dispatchWorkItem = DispatchWorkItem(block: closure)
DispatchQueue.main.asyncAfter(deadline: delayTime, execute: dispatchWorkItem)
}
@objc
func updateProgressOfWaitStepViewController() {
if let waitStepViewController = waitStepViewController {
waitStepProgress += 0.01
DispatchQueue.main.async(execute: { () -> Void in
waitStepViewController.setProgress(self.waitStepProgress, animated: true)
})
if waitStepProgress < 1.0 {
return
} else {
self.waitStepUpdateTimer?.invalidate()
waitStepViewController.goForward()
self.waitStepViewController = nil
}
} else {
self.waitStepUpdateTimer?.invalidate()
}
}
}
|
bsd-3-clause
|
abdae112916188ee274b52a0b7ebbe23
| 43.054187 | 206 | 0.687241 | 5.377631 | false | false | false | false |
D8Ge/Jchat
|
Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/ProtobufMessage.swift
|
1
|
6451
|
// ProtobufRuntime/Sources/Protobuf/ProtobufMessage.swift - Message support
//
// 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
//
// -----------------------------------------------------------------------------
///
/// All messages implement some of these protocols: Generated messages output
/// by protoc implement ProtobufGeneratedMessageType, hand-coded messages often
/// implement ProtobufAbstractMessage. The protocol heirarchy here is
/// a little involved due to the variety of requirements and the need to
/// mix in JSON and binary support (see ProtobufBinaryTypes and ProtobufJSONTypes
/// for extensions that support binary and JSON coding).
///
// -----------------------------------------------------------------------------
import Swift
///
/// See ProtobufBinaryTypes and ProtobufJSONTypes for extensions
/// to these protocols for supporting binary and JSON coding.
///
///
/// The core protocol implemented by all messages, whether generated
/// or hand-coded.
///
/// In particular, this has no associated types or self references
/// so can be used as a variable or argument type.
///
public protocol ProtobufMessageBase: CustomDebugStringConvertible, ProtobufTraversable {
init()
// Basic facts about this class and the proto message it was generated from
// Used by various encoders and decoders
var swiftClassName: String { get }
var protoMessageName: String { get }
var protoPackageName: String { get }
var anyTypePrefix: String { get }
var anyTypeURL: String { get }
var jsonFieldNames: [String: Int] {get}
var protoFieldNames: [String: Int] {get}
/// Decode a field identified by a field number (as given in the .proto file).
///
/// This is the core method used by the deserialization machinery.
///
/// Note that this is not specific to protobuf encoding; formats
/// that use textual identifiers translate those to protoFieldNumbers and
/// then invoke this to decode the field value.
mutating func decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool
// The corresponding serialization support is the traverse() method
// declared in ProtobufTraversable
// Decode from an Any (which might itself have been decoded from JSON,
// protobuf, or another Any)
init(any: Google_Protobuf_Any) throws
/// Serialize as an Any object in JSON format
/// For generated message types, this generates the same JSON object
/// as serializeJSON() except it adds an additional `@type` field.
func serializeAnyJSON() throws -> String
// Standard utility properties and methods.
// Most of these are simple wrappers on top of the visitor machinery.
// They are implemented in the protocol, not in the generated structs,
// so can be overridden in user code by defining custom extensions to
// the generated struct.
var hashValue: Int { get }
var debugDescription: String { get }
var customMirror: Mirror { get }
}
public extension ProtobufMessageBase {
var hashValue: Int {return ProtobufHashVisitor(message: self).hashValue}
var debugDescription: String {return ProtobufDebugDescriptionVisitor(message: self).description}
var customMirror: Mirror {return ProtobufMirrorVisitor(message: self).mirror}
// TODO: Add an option to the generator to override this in particular messages.
// TODO: It would be nice if this could default to "" instead; that would save ~20
// bytes on every serialized Any.
var anyTypePrefix: String {return "type.googleapis.com"}
var anyTypeURL: String {
var url = anyTypePrefix
if anyTypePrefix == "" || anyTypePrefix.characters.last! != "/" {
url += "/"
}
if protoPackageName != "" {
url += protoPackageName
url += "."
}
url += protoMessageName
return url
}
}
///
/// ProtobufMessage which extends ProtobufMessageBase with some
/// additional requirements, including serialization extensions.
/// This is used directly by hand-coded message implementations.
///
public protocol ProtobufMessage: ProtobufMessageBase, ProtobufBinaryMessageBase, ProtobufJSONMessageBase, CustomReflectable {
}
public protocol ProtobufAbstractMessage: ProtobufMessage, Hashable, ProtobufMapValueType {
func isEqualTo(other: Self) -> Bool
}
public extension ProtobufAbstractMessage {
static func isEqual(_ lhs: Self, _ rhs: Self) -> Bool {
return lhs == rhs
}
public init(any: Google_Protobuf_Any) throws {
self.init()
try any.unpackTo(target: &self)
}
}
public func ==<M: ProtobufAbstractMessage>(lhs: M, rhs: M) -> Bool {
return lhs.isEqualTo(other: rhs)
}
///
/// Base type for Generated message types
///
/// This provides some basic indirection so end users can override
/// generated methods.
///
public protocol ProtobufGeneratedMessage: ProtobufAbstractMessage {
// The compiler actually generates the following methods.
// Default implementations below redirect the standard names.
// This allows developers to override the standard names to
// customize the behavior.
mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool
func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws
func _protoc_generated_isEqualTo(other: Self) -> Bool
}
public extension ProtobufGeneratedMessage {
// Default implementations simply redirect to the generated versions.
public func traverse(visitor: inout ProtobufVisitor) throws {
try _protoc_generated_traverse(visitor: &visitor)
}
mutating func decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool {
return try _protoc_generated_decodeField(setter: &setter, protoFieldNumber: protoFieldNumber)
}
func isEqualTo(other: Self) -> Bool {
return _protoc_generated_isEqualTo(other: other)
}
}
// TODO: This is a transition aid, remove this in August 2016.
public typealias ProtobufGeneratedMessageType = ProtobufGeneratedMessage
|
mit
|
dfcef1d64991449864e57c3d67fde412
| 38.09697 | 125 | 0.703767 | 4.916921 | false | false | false | false |
benlangmuir/swift
|
test/IRGen/extension_type_metadata_linking.swift
|
4
|
2535
|
// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s
// REQUIRES: objc_interop
// Check that type metadata defined inside extensions of files imported from
// other modules is emitted with the right linkage.
//
// In particular, it should be possible to define types inside extensions of
// types imported from Foundation (rdar://problem/27245620).
import Foundation
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE4BaseCMm" = global
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE4BaseCMn" = constant
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE4BaseCMf" = internal global
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMm" = global
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMn" = constant
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMf" = internal global
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE6StructVMn" = constant
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE6StructVMf" = internal constant
// CHECK-LABEL: "$sSo18NSComparisonResultVMn" = linkonce_odr hidden
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE4BaseCN" = alias
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE7DerivedCN" = alias
// CHECK-LABEL: @"$sSo8NSNumberC31extension_type_metadata_linkingE6StructVN" = alias
// CHECK-LABEL: define swiftcc %swift.metadata_response @"$sSo8NSNumberC31extension_type_metadata_linkingE4BaseCMa"
// CHECK-LABEL: define swiftcc %swift.metadata_response @"$sSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMa"
// FIXME: Not needed
// CHECK-LABEL: define swiftcc %swift.metadata_response @"$sSo8NSNumberC31extension_type_metadata_linkingE6StructVMa"
extension NSNumber {
public class Base : CustomStringConvertible {
public var description: String {
return "Base"
}
}
public class Derived : Base {
override public var description: String {
return "Derived"
}
}
public struct Struct {}
}
// https://github.com/apple/swift/issues/51863
// Not emitting metadata for 'NSComparisonResult'
protocol CommandTypes {
associatedtype Result
associatedtype Message
}
struct EnumCommand: CommandTypes {
typealias Result = ComparisonResult
typealias Message = String
}
struct Command<T: CommandTypes> {
var result: T.Result?
var message: T.Message?
}
func createCommandArray() -> Any {
return [Command<EnumCommand>]()
}
|
apache-2.0
|
2e696589541a8859065dfd6104bea8d9
| 34.208333 | 118 | 0.76568 | 3.744461 | false | false | false | false |
coderZsq/coderZsq.target.swift
|
StudyNotes/Foundation/DesignPatterns/DesignPatterns/CMS/SalesManager.swift
|
1
|
1238
|
//
// SalesManager.swift
// DesignPatterns
//
// Created by 朱双泉 on 2018/4/23.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
class SalesManager: Employee, SalesManInterface, ManagerInterface {
var saleAmount: Float?
var rate: Float?
var fixedSalary: Int?
override func two_stage_init() {
fixedSalary = 5000
Employee.startNumber += 1
num = Employee.startNumber
level = 1
rate = 0.05
print("请输入销售经理的姓名: ", terminator: "")
name = scanf()
print("请输入本月的销售额: ", terminator: "")
saleAmount = Float(scanf())
}
override func promote() {
level! += 3
}
override func calcSalary() {
salary = Float(fixedSalary!) + saleAmount! * rate!
}
override func disInfor() {
print("姓名: \(name!)")
print("工号: \(num!)")
print("级别: \(level!)")
print("本月的固定薪水: \(fixedSalary!)")
print("本月的销售额度: \(saleAmount!)")
print("本月的提成比率: \(rate!)")
print("本月结算的薪水: \(salary!)")
print("========================")
}
}
|
mit
|
4a401dd9bd724d3c8e96993e9d0f930d
| 22.93617 | 67 | 0.534222 | 3.548896 | false | false | false | false |
D-32/MiniTabBar
|
MiniTabBar/Classes/MiniTabBar.swift
|
1
|
3741
|
//
// MiniTabBar.swift
// Pods
//
// Created by Dylan Marriott on 11/01/17.
//
//
import Foundation
import UIKit
public class MiniTabBarItem {
var title: String?
var icon: UIImage?
var customView: UIView?
var offset = UIOffset.zero
public var selectable: Bool = true
public init(title: String, icon:UIImage) {
self.title = title
self.icon = icon
}
public init(customView: UIView, offset: UIOffset = UIOffset.zero) {
self.customView = customView
self.offset = offset
}
}
public protocol MiniTabBarDelegate: class {
func tabSelected(_ index: Int)
}
public class MiniTabBar: UIView {
public weak var delegate: MiniTabBarDelegate?
public let keyLine = UIView()
public override var tintColor: UIColor! {
didSet {
for itv in self.itemViews {
itv.tintColor = self.tintColor
}
}
}
public var font: UIFont? {
didSet {
for itv in self.itemViews {
itv.font = self.font
}
}
}
private let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) as UIVisualEffectView
public var backgroundBlurEnabled: Bool = true {
didSet {
self.visualEffectView.isHidden = !self.backgroundBlurEnabled
}
}
fileprivate var itemViews = [MiniTabBarItemView]()
fileprivate var currentSelectedIndex: Int?
fileprivate let bg = UIView()
public init(items: [MiniTabBarItem]) {
super.init(frame: CGRect.zero)
bg.backgroundColor = UIColor(white: 1.0, alpha: 0.8)
addSubview(bg)
self.addSubview(visualEffectView)
keyLine.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
self.addSubview(keyLine)
var i = 0
for item in items {
let itemView = MiniTabBarItemView(item)
itemView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MiniTabBar.itemTapped(_:))))
self.itemViews.append(itemView)
self.addSubview(itemView)
i += 1
}
self.selectItem(0, animated: false)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
bg.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 1000)
visualEffectView.frame = bg.bounds
keyLine.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 1)
let itemWidth = self.frame.width / CGFloat(self.itemViews.count)
for (i, itemView) in self.itemViews.enumerated() {
let x = itemWidth * CGFloat(i)
itemView.frame = CGRect(x: x, y: 0, width: itemWidth, height: frame.size.height)
}
}
@objc func itemTapped(_ gesture: UITapGestureRecognizer) {
let itemView = gesture.view as! MiniTabBarItemView
let selectedIndex = self.itemViews.index(of: itemView)!
self.selectItem(selectedIndex)
}
public func selectItem(_ selectedIndex: Int, animated: Bool = true) {
if !self.itemViews[selectedIndex].item.selectable {
return
}
if (selectedIndex == self.currentSelectedIndex) {
return
}
self.currentSelectedIndex = selectedIndex
for (index, v) in self.itemViews.enumerated() {
let selected = (index == selectedIndex)
v.setSelected(selected, animated: animated)
}
self.delegate?.tabSelected(selectedIndex)
}
}
|
mit
|
635ffe59bab414fd05f881f47aba681e
| 28.690476 | 125 | 0.601978 | 4.567766 | false | false | false | false |
josherick/DailySpend
|
Logger.swift
|
1
|
5663
|
//
// Logger.swift
// DailySpend
//
// Created by Josh Sherick on 8/19/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import Foundation
class Logger {
static func isTesting() -> Bool {
let bundleID = Bundle.main.bundleIdentifier!
return bundleID.contains("com.joshsherick.DailySpendTesting")
}
static func debug(_ message: String) {
if isTesting() {
print(message)
}
}
static func warning(_ message: String) {
print(message)
}
static func printAllCoreData() {
if !isTesting() {
return
}
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
let context = appDelegate.persistentContainer.viewContext
let sortDesc = NSSortDescriptor(key: "dateCreated_", ascending: true)
let expenses = Expense.get(context: context,sortDescriptors: [sortDesc])!
let goals = Goal.get(context: context, sortDescriptors: [sortDesc])!
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .full
func date(_ d: Date?) -> String {
if let u = d {
return dateFormatter.string(from: u)
} else {
return "nil"
}
}
if (goals.count > 0) {
print("Goals:")
} else {
print("No Goals.")
}
for goal in goals {
print("goal.dateCreated: \(date(goal.dateCreated))")
print("goal.adjustMonthAmountAutomatically: \(goal.adjustMonthAmountAutomatically)")
print("goal.alwaysCarryOver: \(goal.alwaysCarryOver)")
print("goal.amount: \(String(describing: goal.amount))")
print("goal.start: \(date(goal.start?.gmtDate))")
print("goal.end: \(date(goal.end?.gmtDate))")
print("goal.hasIncrementalPayment: \(goal.hasIncrementalPayment)")
print("goal.isRecurring: \(goal.isRecurring)")
print("goal.payFrequency: \(goal.payFrequency)")
print("goal.period: \(goal.period)")
print("goal.shortDescription: \(String(describing: goal.shortDescription))")
print("goal.isArchived: \(goal.isArchived)")
print("goal.hasFutureStart: \(goal.hasFutureStart)")
print("goal.parentGoal: \(goal.parentGoal?.shortDescription ?? "None")")
print("")
}
if (expenses.count > 0) {
print("Expenses:")
} else {
print("No Expenses.")
}
for expense in expenses {
let created = dateFormatter.string(from: expense.dateCreated!)
print("expense.amount: \(expense.amount!)")
print("expense.dateCreated: \(created)")
print("expense.transactionDay: \(date(expense.transactionDay?.start.gmtDate))")
print("expense.notes: \(expense.notes ?? "None")")
print("expense.shortDescription: \(String(describing: expense.shortDescription))")
if (expense.images!.count > 0) {
print("\tImages:")
} else {
print("\tNo Images.")
}
for image in expense.sortedImages! {
let created = dateFormatter.string(from: expense.dateCreated!)
print("\timage.imageName: \(image.imageName!)")
print("\timage.dateCreated: \(created)")
print("")
}
if (expense.goal != nil) {
print("\tGoal: \(expense.goal!.shortDescription!)")
} else {
print("\tNo Goals.")
}
print("")
}
print("")
let pauseSortDesc = NSSortDescriptor(key: "dateCreated_", ascending: true)
let allPauses = Pause.get(context: context, sortDescriptors: [pauseSortDesc])!
print("allPauses:")
print("\(allPauses.count) pauses")
for pause in allPauses {
print("Pause:")
let created = dateFormatter.string(from: pause.dateCreated!)
let first = pause.firstDayEffective!.string(formatter: dateFormatter)
let last = pause.lastDayEffective!.string(formatter: dateFormatter)
print("pause.shortDescription: \(pause.shortDescription!)")
print("pause.dateCreated: \(created)")
print("pause.firstDayEffective: \(first)")
print("pause.lastDayEffective: \(last)")
print("")
}
let adjustmentSortDesc = NSSortDescriptor(key: "dateCreated_", ascending: true)
let allAdjustments = Adjustment.get(context: context, sortDescriptors: [adjustmentSortDesc])!
print("allAdjustments:")
print("\(allAdjustments.count) adjustments")
for adjustment in allAdjustments {
print("Adjustment:")
let created = dateFormatter.string(from: adjustment.dateCreated!)
let first = adjustment.firstDayEffective!.string(formatter: dateFormatter)
let last = adjustment.lastDayEffective!.string(formatter: dateFormatter)
print("adjustment.amountPerDay: \(adjustment.amountPerDay!)")
print("adjustment.shortDescription: \(adjustment.shortDescription!)")
print("adjustment.dateCreated: \(created)")
print("adjustment.firstDayEffective: \(first)")
print("adjustment.lastDayEffective: \(last)")
print("")
}
}
}
|
mit
|
a0a3e59b95cc427dab238c4546829507
| 37 | 101 | 0.563582 | 5.001767 | false | false | false | false |
YMXian/Deliria
|
Deliria/Deliria/Crypto/SHA1.swift
|
1
|
3499
|
//
// SHA1.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 16/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
final class SHA1: DigestType {
static let digestSize: Int = 20 // 160 / 8
private let message: Array<UInt8>
init(_ message: Array<UInt8>) {
self.message = message
}
private let h: Array<UInt32> = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
func calculate() -> Array<UInt8> {
var tmpMessage = bitPadding(to: self.message, blockSize: 64, allowance: 64 / 8)
// hash values
var hh = h
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage += (self.message.count * 8).bytes(totalBytes: 64 / 8)
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 32-bit words into eighty 32-bit words:
var M: Array<UInt32> = Array<UInt32>(repeating: 0, count: 80)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex + (x * MemoryLayout<UInt32>.size)
let end = start + MemoryLayout<UInt32>.size
let le = chunk[start..<end].toUInt32Array()[0]
M[x] = le.bigEndian
break
default:
M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], by: 1)
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
// Main loop
for j in 0...79 {
var f: UInt32 = 0
var k: UInt32 = 0
switch (j) {
case 0...19:
f = (B & C) | ((~B) & D)
k = 0x5A827999
break
case 20...39:
f = B ^ C ^ D
k = 0x6ED9EBA1
break
case 40...59:
f = (B & C) | (B & D) | (C & D)
k = 0x8F1BBCDC
break
case 60...79:
f = B ^ C ^ D
k = 0xCA62C1D6
break
default:
break
}
let temp = (rotateLeft(A, by: 5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff
E = D
D = C
C = rotateLeft(B, by: 30)
B = A
A = temp
}
hh[0] = (hh[0] &+ A) & 0xffffffff
hh[1] = (hh[1] &+ B) & 0xffffffff
hh[2] = (hh[2] &+ C) & 0xffffffff
hh[3] = (hh[3] &+ D) & 0xffffffff
hh[4] = (hh[4] &+ E) & 0xffffffff
}
// Produce the final hash value (big-endian) as a 160 bit number:
var result = Array<UInt8>()
result.reserveCapacity(hh.count / 4)
hh.forEach {
let item = $0.bigEndian
result += [UInt8(item & 0xff), UInt8((item >> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)]
}
return result
}
}
|
mit
|
e77506d01f1082a591f6e9e19ce0e5d9
| 32.605769 | 125 | 0.437768 | 3.836443 | false | false | false | false |
aschwaighofer/swift
|
test/SILOptimizer/optionset.swift
|
2
|
1597
|
// RUN: %target-swift-frontend -parse-as-library -primary-file %s -O -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend -parse-as-library -primary-file %s -Osize -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib
public struct TestOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
static let first = TestOptions(rawValue: 1 << 0)
static let second = TestOptions(rawValue: 1 << 1)
static let third = TestOptions(rawValue: 1 << 2)
static let fourth = TestOptions(rawValue: 1 << 3)
}
// CHECK: sil @{{.*}}returnTestOptions{{.*}}
// CHECK-NEXT: bb0:
// CHECK-NEXT: integer_literal {{.*}}, 15
// CHECK-NEXT: struct $Int
// CHECK-NEXT: struct $TestOptions
// CHECK-NEXT: return
public func returnTestOptions() -> TestOptions {
return [.first, .second, .third, .fourth]
}
// CHECK: sil @{{.*}}returnEmptyTestOptions{{.*}}
// CHECK-NEXT: bb0:
// CHECK-NEXT: integer_literal {{.*}}, 0
// CHECK-NEXT: struct $Int
// CHECK-NEXT: struct $TestOptions
// CHECK-NEXT: return
public func returnEmptyTestOptions() -> TestOptions {
return []
}
// CHECK: alloc_global @{{.*}}globalTestOptions{{.*}}
// CHECK-NEXT: global_addr
// CHECK-NEXT: integer_literal {{.*}}, 15
// CHECK-NEXT: struct $Int
// CHECK-NEXT: struct $TestOptions
// CHECK-NEXT: store
// CHECK-NEXT: tuple
// CHECK-NEXT: return
let globalTestOptions: TestOptions = [.first, .second, .third, .fourth]
|
apache-2.0
|
b54eed91c846c2c764464bcc60a6c87a
| 35.295455 | 133 | 0.653726 | 3.45671 | false | true | false | false |
wanliming11/MurlocAlgorithms
|
Last/Algorithms/插入排序/insertionSort/insertionSort/InsertionSort.swift
|
1
|
1485
|
//
// Created by FlyingPuPu on 02/12/2016.
// Copyright (c) 2016 ___FULLUSERNAME___. All rights reserved.
//
import Foundation
public class InsertionSort<T> {
public var sortArray: [T] = [T]()
public func swapSorted(_ sort: (T, T) -> Bool) -> [T] {
guard sortArray.count > 1 else {
return sortArray
}
for x in 1 ..< sortArray.count {
var y = x
//不断的同以前的一个数进行对比,如果满足反向输入条件情况则交换,直到到达最左边。
//简单的说,不满足条件就交换,但是是拿不满足的情况冒泡了一把
while y > 0 && sort(sortArray[y], sortArray[y - 1]) {
swap(&sortArray[y], &sortArray[y - 1])
y -= 1
}
}
return sortArray
}
public func moveSorted(_ sort: (T, T) -> Bool) -> [T] {
guard sortArray.count > 1 else {
return sortArray
}
for x in 1 ..< sortArray.count {
var y = x
let temp = sortArray[x]
//拿temp与前面的数比较,如果发现满足条件,则继续前移,直到找到不满足的情况
//例如2,1, ----- 4 , 比较条件是> ,则1,4
while y > 0 && sort(temp, sortArray[y - 1]) {
sortArray[y] = sortArray[y - 1]
y -= 1
}
sortArray[y] = temp
}
return sortArray
}
}
|
mit
|
e0b3e3bb6433c82214b6ab4e8edc710d
| 26.326087 | 65 | 0.481305 | 3.299213 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift
|
Example/TLTranstionLib-swift/BaseViewController.swift
|
1
|
1923
|
//
// BaseViewController.swift
// TLTranstionLib-swift
//
// Created by Andrew on 16/5/16.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var navView:UIView!
override func viewDidLoad() {
super.viewDidLoad()
initNavBar()
hideNavView()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "下一步", style:.Plain, target: self, action: #selector(BaseViewController.nextStep(_:)))
}
func nextStep(sender:AnyObject) -> Void {
let vc=getCurrentVC()
self.navigationController?.pushViewController(vc, animated: true)
}
func getCurrentVC() ->UIViewController{
return UIViewController()
}
func showNavView() -> Void {
navView.hidden = false
}
func hideNavView() -> Void {
navView.hidden = true
}
func initNavBar() -> Void {
var rect = CGRect(x: 0, y: 0, width: screen_width, height: 64)
navView = UIView(frame: rect)
navView.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(navView)
rect = CGRect(x: 0, y: 10, width: 50, height: 50)
let btn = UIButton(frame: rect)
btn.setTitleColor(UIColor.redColor(), forState: .Normal)
btn.setTitle("返回", forState: .Normal)
navView.addSubview(btn)
btn.addTarget(self, action: #selector(returnAction(_:)), forControlEvents: .TouchUpInside)
}
func returnAction(btn:UIButton) -> Void {
if self.navigationController == nil{
self.dismissViewControllerAnimated(true, completion: nil)
}else{
self.navigationController?.popViewControllerAnimated(true)
}
}
}
|
mit
|
a8349f070395f967850084ee21255533
| 26.285714 | 158 | 0.615183 | 4.613527 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Course Alerts/Views/SearchResultsCell.swift
|
1
|
3101
|
//
// SearchResultsCell.swift
// PennMobile
//
// Created by Raunaq Singh on 12/26/20.
// Copyright © 2020 PennLabs. All rights reserved.
//
import Foundation
import UIKit
class SearchResultsCell: UITableViewCell {
static let cellHeight: CGFloat = 74
static let noInstructorCellHeight: CGFloat = 60
static let identifier = "searchResultsCell"
fileprivate var detailLabel: UILabel!
fileprivate var courseLabel: UILabel!
fileprivate var instructorsLabel: UILabel!
var section: CourseSection! {
didSet {
setupCell()
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Setup Cell
extension SearchResultsCell {
fileprivate func setupCell() {
if detailLabel == nil || courseLabel == nil {
setupUI()
} else {
courseLabel.text = section.section
detailLabel.text = section.courseTitle
instructorsLabel.text = (section.instructors.map { $0.name }).joined(separator: ", ")
}
}
}
// MARK: - Setup UI
extension SearchResultsCell {
fileprivate func setupUI() {
prepareCourseLabel()
prepareDetailLabel()
prepareInstructorsLabel()
}
fileprivate func prepareCourseLabel() {
courseLabel = UILabel()
courseLabel.font = UIFont.interiorTitleFont
addSubview(courseLabel)
courseLabel.translatesAutoresizingMaskIntoConstraints = false
courseLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 15).isActive = true
courseLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
}
fileprivate func prepareDetailLabel() {
detailLabel = UILabel()
detailLabel.font = UIFont.secondaryInformationFont
detailLabel.textColor = UIColor.grey1
addSubview(detailLabel)
detailLabel.translatesAutoresizingMaskIntoConstraints = false
detailLabel.leadingAnchor.constraint(equalTo: courseLabel.leadingAnchor).isActive = true
detailLabel.topAnchor.constraint(equalTo: courseLabel.bottomAnchor, constant: 4).isActive = true
detailLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -40).isActive = true
}
fileprivate func prepareInstructorsLabel() {
instructorsLabel = UILabel()
instructorsLabel.font = UIFont.footerDescriptionFont
instructorsLabel.textColor = UIColor.grey1
addSubview(instructorsLabel)
instructorsLabel.translatesAutoresizingMaskIntoConstraints = false
instructorsLabel.leadingAnchor.constraint(equalTo: detailLabel.leadingAnchor).isActive = true
instructorsLabel.topAnchor.constraint(equalTo: detailLabel.bottomAnchor, constant: 3).isActive = true
instructorsLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -40).isActive = true
}
}
|
mit
|
4fd3f899c1d798951be60ba1d49f6987
| 33.444444 | 109 | 0.699032 | 5.13245 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceComponents/Sources/ComponentBase/Branding/UIColor+Branding.swift
|
1
|
4149
|
import SwiftUI
import UIKit
extension Color {
public static let pantone330U = Color("Pantone 330U", bundle: .moduleWorkaround)
}
extension UIColor {
// MARK: Branding Colors
public static let pantone330U = unsafelyNamed("Pantone 330U")
public static let pantone330U_45 = unsafelyNamed("Pantone 330U (45%)")
public static let pantone330U_26 = unsafelyNamed("Pantone 330U (26%)")
public static let pantone330U_13 = unsafelyNamed("Pantone 330U (13%)")
public static let pantone330U_5 = unsafelyNamed("Pantone 330U (5%)")
public static let largeActionButton = unsafelyNamed("Large Action Button")
// MARK: Semantic Control Colors
public static let efTintColor = adaptive(light: .pantone330U, dark: .pantone330U_45)
public static let disabledColor = safeSystemGray
public static let navigationBar = barColor
public static let tabBar = barColor
public static let searchBarTint = pantone330U
public static let refreshControl = pantone330U_13
public static let selectedTabBarItem = adaptive(light: .white, dark: .pantone330U_13)
public static let unselectedTabBarItem = adaptive(light: .pantone330U_45, dark: .systemGray3)
public static let primary = adaptive(light: .pantone330U, dark: .black)
public static let secondary = adaptive(light: .pantone330U_45, dark: .secondaryDarkColor)
public static let buttons = pantone330U
public static let tableIndex = pantone330U
public static let iconographicTint = pantone330U
public static let unreadIndicator = pantone330U
public static let selectedSegmentText = adaptive(light: .pantone330U, dark: .white)
public static let selectedSegmentBackground = adaptive(light: .white, dark: .safeSystemGray)
public static let unselectedSegmentText = adaptive(light: .white, dark: .white)
public static let unselectedSegmentBackground = adaptive(light: .pantone330U_45, dark: .safeSystemGray3)
public static let segmentSeperator = adaptive(light: .white, dark: .safeSystemGray)
public static let dayPickerSelectedBackground = adaptive(light: .pantone330U_45, dark: .systemGray3)
public static let safariBarTint = navigationBar
public static let safariControlTint = white
public static let userPrompt = adaptive(
light: UIColor(white: 0.5, alpha: 1.0),
dark: .safeSystemGray
)
public static let userPromptWithUnreadMessages = pantone330U
private static let barColor: UIColor = adaptive(light: .pantone330U, dark: calendarStyleBarColor)
private static var calendarStyleBarColor: UIColor {
scaled(red: 18, green: 19, blue: 18)
}
private static var secondaryDarkColor = UIColor.opaqueSeparator
private static var safeSystemGray = UIColor.systemGray
private static var safeSystemGray3 = UIColor.systemGray3
private static func scaled(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
let scale: (CGFloat) -> CGFloat = { $0 / 255.0 }
return UIColor(red: scale(red), green: scale(green), blue: scale(blue), alpha: 1.0)
}
func makeColoredImage(size: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image { (context) in
setFill()
context.fill(CGRect(origin: .zero, size: size))
}
}
func makePixel() -> UIImage {
makeColoredImage(size: CGSize(width: 1, height: 1))
}
private static var safeSystemGray2 = UIColor.systemGray2
private static func unsafelyNamed(_ name: String) -> UIColor {
guard let color = UIColor(named: name, in: .module, compatibleWith: nil) else {
fatalError("Color named \(name) missing from xcassets")
}
return color
}
public static func adaptive(light: UIColor, dark: UIColor) -> UIColor {
return UIColor(dynamicProvider: { (traitCollection) in
if traitCollection.userInterfaceStyle == .light {
return light
} else {
return dark
}
})
}
}
|
mit
|
1e6e2283e8713ab57184ebe8cc20e3e3
| 40.079208 | 108 | 0.685948 | 4.317378 | false | false | false | false |
huangboju/Moots
|
UICollectionViewLayout/uicollectionview-layouts-kit-master/spinner/Core/Layout/CircularLayout.swift
|
1
|
6910
|
//
// CircularLayout.swift
// spinner
//
// Created by Astemir Eleev on 17/04/2018.
// Copyright © 2018 Astemir Eleev. All rights reserved.
//
import UIKit
protocol CircularLayoutDelegate: class {
func collectionView(_ collectionView:UICollectionView, widthForItemAtIndexPath indexPath:IndexPath) -> CGFloat
}
class CircularLayout: UICollectionViewLayout {
// MARK: - Properties
weak var delegate: CircularLayoutDelegate!
let itemSize = CGSize(width: 500.0, height: 700.0) // 133, 173
var radius: CGFloat = 1700 { // 500
didSet {
invalidateLayout()
}
}
var anglePerItem: CGFloat {
return atan(itemSize.width / radius)
}
var angleAtExtreme: CGFloat {
guard let collectionView = collectionView else {
debugPrint(#function + " could not unwrap collection view, the calculated value fot the property will be set to 0.0")
return 0.0
}
let numberOfItemsInZeroSection = collectionView.numberOfItems(inSection: 0)
return numberOfItemsInZeroSection > 0 ? -CGFloat(numberOfItemsInZeroSection - 1) * anglePerItem : 0
}
var angle: CGFloat {
guard let collectionView = collectionView else {
debugPrint(#function + " could not unwrap collection view, the calculated value fot the property will be set to 0.0")
return 0.0
}
return angleAtExtreme * collectionView.contentOffset.x / (collectionViewContentSize.width - collectionView.bounds.width)
}
var attributesList = [CircularCollectionViewLayoutAttributes]()
// MARKK: - Overrides
override static var layoutAttributesClass: AnyClass {
return CircularCollectionViewLayoutAttributes.self
}
override var collectionViewContentSize: CGSize {
guard let collectionView = collectionView else {
fatalError(#function + " could not unwrap collectionView instnace - it is nil")
}
let numberOfItemsInZeroSection = CGFloat(collectionView.numberOfItems(inSection: 0))
let width = CGFloat(numberOfItemsInZeroSection * itemSize.width)
let height = CGFloat(collectionView.bounds.height)
let size = CGSize(width: width, height: height)
return size
}
override func prepare() {
super.prepare()
guard let collectionView = collectionView else {
debugPrint(#function + " could not unwrap collection view because it is nil")
return
}
let centerX = collectionView.contentOffset.x + (collectionView.bounds.width / 2.0)
let anchorPointY = ((itemSize.height / 2.0) + radius) / itemSize.height
let padding: CGFloat = 8
let boundsWidth = collectionView.bounds.width
let boundsHeight = collectionView.bounds.height
let itemsInSectionZero = collectionView.numberOfItems(inSection: 0)
let theta = atan2(boundsWidth / 2.0, radius + (itemSize.height / 2.0) - (boundsHeight / 2.0))
var startIndex = 0
var endIndex = itemsInSectionZero - 1
// If the angular position of the 0th item is less than -theta, then it lies outside the screen. In that case, the first item on the screen will be the difference between -θ and angle divided by anglePerItem;
if (angle < -theta) {
startIndex = Int(floor((-theta - angle) / anglePerItem))
}
// Similarly, the last element on the screen will be the difference between θ and angle divided by anglePerItem, and min serves as an additional check to ensure endIndex doesn’t go beyond the total number of items;
endIndex = min(endIndex, Int(ceil((theta - angle) / anglePerItem)))
// Lastly, you add a safety check to make the range 0...0 if endIndex is less than startIndex. This edge case occurs when you scroll with a very high velocity and all the cells go completely off-screen.
if (endIndex < startIndex) {
endIndex = 0
startIndex = 0
}
attributesList = (startIndex...endIndex).map({ index -> CircularCollectionViewLayoutAttributes in
let indexPath = IndexPath(item: index, section: 0)
let attributes = CircularCollectionViewLayoutAttributes(forCellWith: indexPath)
let size = CGSize(width: padding * 2 + self.itemSize.width, height: self.itemSize.height)
attributes.size = size
// Position each item at the center of the screen
attributes.center = CGPoint(x: centerX, y: collectionView.bounds.midY)
// Rotate each item at an angle per item times positional index
attributes.angle = self.angle + (self.anglePerItem * CGFloat(index))
// Override the defualt anchor point
attributes.anchorPoint = CGPoint(x: 0.5, y: anchorPointY)
return attributes
})
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attributesList
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return attributesList[indexPath.row]
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
// Returning true from this method tells the collection view to invalidate it’s layout as it scrolls, which in turn calls prepare() where you can recalculate the cells’ layout with updated angular positions.
return true
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
guard let collectionView = collectionView else {
fatalError(#function + " could not unwrap collection view since it is nil")
}
// Adds suport for snapping behaviour. For for the main implementation of circular layout it is not important and has no direct relation. Feel free to remove this method.
var finalContentOffset = proposedContentOffset
let factor = -angleAtExtreme / (collectionViewContentSize.width - collectionView.bounds.width)
let proposedAngle = proposedContentOffset.x * factor
let ratio = proposedAngle/anglePerItem
var multiplier: CGFloat
if (velocity.x > 0) {
multiplier = ceil(ratio)
} else if (velocity.x < 0) {
multiplier = floor(ratio)
} else {
multiplier = round(ratio)
}
finalContentOffset.x = multiplier * anglePerItem / factor
return finalContentOffset
}
}
|
mit
|
7994dd9eb90aac08d7245273af43e835
| 41.863354 | 222 | 0.661788 | 5.235964 | false | false | false | false |
aotian16/SwiftGameDemo
|
Cat/Cat/PointContainer.swift
|
1
|
11675
|
//
// PointContainer.swift
// Cat
//
// Created by 童进 on 15/11/25.
// Copyright © 2015年 qefee. All rights reserved.
//
import UIKit
import SpriteKit
class PointContainer: SKSpriteNode {
/// 青纹理
let textPoint1 = SKTexture(imageNamed: "point1")
/// 橙纹理
let textPoint2 = SKTexture(imageNamed: "point2")
// 猫
let cat = Cat(imageNamed: "cat")
// 所有移动点
var arrPoint = [EkoPoint]()
/// 初始点
let startIndex = 40
/// 当前点
var currentIndex = 40
/// 是否找到边缘点
var isFind = false
/// 每次搜索的消耗次数
var stepNum = 0
/// 广度优先外圈点
var arrNext = [Int]()
/// 分数节点: 显示分数
var score = SKLabelNode(text: "0")
/// 状态节点: 显示输赢
var status = SKLabelNode(text: "")
func onInit() {
initScoreNode()
initRestartNode()
initStatusNode()
initMoveableNodes()
initCatNode()
initArroundNodeIndex()
createRandomRedNodes()
}
/**
初始化分数节点
*/
func initScoreNode() {
score.name = "score"
score.position = CGPointMake(CGFloat(score.frame.width / 2 + 20), CGFloat(self.size.height - 100))
score.zPosition = 11
addChild(score)
}
/**
初始化重新开始节点
*/
func initRestartNode() {
let restart = SKLabelNode(text: "重新开始")
restart.name = "restart"
restart.position = CGPointMake(CGFloat(self.size.width - restart.frame.width / 2 - 20), CGFloat(self.size.height - 100))
restart.zPosition = 11
addChild(restart)
}
/**
初始化状态节点
*/
func initStatusNode() {
status.name = "status"
status.position = CGPointMake(CGFloat(self.size.width / 2), CGFloat(20))
status.zPosition = 11
addChild(status)
}
/**
初始化移动节点
*/
func initMoveableNodes() {
let width = self.size.width / 9.5
let size = CGSizeMake(CGFloat(width), CGFloat(width))
for i in 0...80 {
let point = EkoPoint(texture: textPoint2)
point.name = "node.\(i)"
point.size = size
let row = i/9
let col = i%9
var gap: CGFloat = 0
if row%2 == 0 {
gap = width / 2.0
} else {
gap = width
}
// 判断边缘节点
if row == 0 || row == 8 || col == 0 || col == 8 {
point.isEdge = true
}
let x = CGFloat(col) * width + gap
let y = CGFloat(row) * width + 160
point.position = CGPointMake(CGFloat(x), CGFloat(y))
point.index = i
point.zPosition = 10
addChild(point)
arrPoint.append(point)
}
}
/**
初始化猫节点
*/
func initCatNode() {
let width = self.size.width / 9.5
let size = CGSizeMake(CGFloat(width), CGFloat(width))
cat.size = size
cat.position = arrPoint[startIndex].position
cat.zPosition = 20
addChild(cat)
}
/**
初始化邻近节点
*/
func initArroundNodeIndex() {
for p in arrPoint {
let i = p.index
let row = i / 9
let leftPointIndex = i - 1
let rightPointIndex = i + 1
var leftTopPointIndex = i + 9
var rightTopPointIndex = i + 10
var leftBottomPointIndex = i - 9
var rightBottomPointIndex = i - 8
// 偶数和奇数行的邻近节点不一样
if row % 2 == 0 {
leftTopPointIndex -= 1
rightTopPointIndex -= 1
leftBottomPointIndex -= 1
rightBottomPointIndex -= 1
}
let array = [0, 1, 2, 3, 4, 5]
let randomArray = array.sort({ (_, _) -> Bool in
arc4random() < arc4random()
})
print(randomArray)
for i in randomArray {
switch i {
case 0:
if isSameRowIndexOk(leftPointIndex, centerPointRow: row) {
p.arrPoint.append(leftPointIndex)
}
case 1:
if isSameRowIndexOk(rightPointIndex, centerPointRow: row) {
p.arrPoint.append(rightPointIndex)
}
case 2:
if isTopIndexOk(leftTopPointIndex, centerPointRow: row) {
p.arrPoint.append(leftTopPointIndex)
}
case 3:
if isTopIndexOk(rightTopPointIndex, centerPointRow: row) {
p.arrPoint.append(rightTopPointIndex)
}
case 4:
if isBottomIndexOk(leftBottomPointIndex, centerPointRow: row) {
p.arrPoint.append(leftBottomPointIndex)
}
case 5:
if isBottomIndexOk(rightBottomPointIndex, centerPointRow: row) {
p.arrPoint.append(rightBottomPointIndex)
}
default:
print("do nothing")
}
}
}
}
/**
index是否正确
- parameter index: index
- returns: 判断结果
*/
private func isIndexOk(index: Int) -> Bool {
return index>=0 && index<=80
}
/**
上方index是否正确
- parameter index: index
- returns: 判断结果
*/
private func isTopIndexOk(index: Int, centerPointRow: Int) -> Bool {
if isIndexOk(index) {
let row = index / 9
return row == centerPointRow + 1
} else {
return false
}
}
/**
下方index是否正确
- parameter index: index
- returns: 判断结果
*/
private func isBottomIndexOk(index: Int, centerPointRow: Int) -> Bool {
if isIndexOk(index) {
let row = index / 9
return row == centerPointRow - 1
} else {
return false
}
}
/**
同行index是否正确
- parameter index: index
- returns: 判断结果
*/
private func isSameRowIndexOk(index: Int, centerPointRow: Int) -> Bool {
if isIndexOk(index) {
let row = index / 9
return row == centerPointRow
} else {
return false
}
}
/**
创建随机红节点
*/
private func createRandomRedNodes() {
srandom(UInt32(time(nil)))
for i in 0...8 {
let r1 = random() % 9 + i * 9
// let r2 = random() % 9 + i * 9
if r1 != startIndex {
onSetRed(r1)
}
// 这里注释掉可以减少难度
// if r2 != startIndex {
// onSetRed(r2)
// }
}
}
/**
设置为红色节点
- parameter index: index
*/
private func onSetRed(index: Int) {
let p = arrPoint[index]
p.type = PointType.red
p.texture = textPoint1
p.userInteractionEnabled = true
}
func onGetNextPoint(index: Int) {
onSetRed(index)
let currentPoint = arrPoint[currentIndex]
for pIndex in currentPoint.arrPoint {
if arrPoint[pIndex].isEdge && arrPoint[pIndex].type == PointType.gray {
cat.position = arrPoint[pIndex].position
status.text = "失败啦"
enableAllPoints(true)
return
}
}
onResetStep()
// enableAllPoints(false)
currentPoint.onSetLabel("0")
currentPoint.step = 0
let oldValue = Int(score.text!)!
let newValue = oldValue + 1
score.text = "\(newValue)"
arrNext.append(currentIndex)
onFind(arrNext)
if !isFind {
status.text = "你赢啦"
enableAllPoints(true)
}
}
private func enableAllPoints(enable: Bool) {
for p in arrPoint {
p.userInteractionEnabled = enable
}
}
func onGetNexts(nextIndexs: [Int]) -> [Int] {
let step = arrPoint[nextIndexs[0]].step + 1
var tempPointIndexs = [Int]()
for nextIndex in nextIndexs {
let pointIn = arrPoint[nextIndex]
if isFind {
break
} else {
for p in pointIn.arrPoint {
let pointOut = arrPoint[p]
self.stepNum += 1
// let point = arrPoint[p]
if pointOut.isEdge && pointOut.type == PointType.gray {
arrPoint[p].onSetLabel("end")
isFind = true
onGetPrePoint(arrPoint[p])
break
} else {
if pointOut.type == PointType.gray
&& pointOut.step > pointIn.step
&& pointOut.prePointIndex == -1 {
pointOut.step = step
pointOut.onSetLabel("\(step)")
pointOut.prePointIndex = pointIn.index
// if arrPoint[p].index != arrPoint[nextP].prePointIndex {
tempPointIndexs.append(p)
// }
}
}
}
}
}
return tempPointIndexs
}
func onFind(arrPointIndexs: [Int]) {
if !isFind {
let arrNexts = onGetNexts(arrPointIndexs)
if arrNexts.count != 0 {
onFind(arrNexts)
}
}
}
func onGetPrePoint(point: EkoPoint) {
var p2 = point.arrPoint[0]
for p in point.arrPoint {
if arrPoint[p].step < arrPoint[p2].step {
p2 = p
}
}
if arrPoint[p2].step == 0 {
point.onSetLabel("next")
cat.position = arrPoint[point.index].position
self.currentIndex = point.index
} else {
onGetPrePoint(arrPoint[p2])
}
}
func onResetStep() {
arrNext = [Int]()
isFind = false
stepNum = 0
for p in arrPoint {
p.step = 99
p.prePointIndex = -1
p.onSetLabel("")
}
}
/**
重新开始游戏
*/
func restart() {
self.score.text = "0"
self.status.text = ""
self.cat.position = self.arrPoint[self.startIndex].position
for p in self.arrPoint {
p.type = PointType.gray
p.texture = self.textPoint2
p.userInteractionEnabled = false
}
self.currentIndex = self.startIndex
self.createRandomRedNodes()
self.onResetStep()
}
}
|
mit
|
1e38bd6a8b5c6bec01add698ddfd0326
| 25.833333 | 128 | 0.454392 | 4.524287 | false | false | false | false |
huangboju/Moots
|
UICollectionViewLayout/SpreadsheetView-master/Framework/Sources/CellRange.swift
|
3
|
2065
|
//
// CellRange.swift
// SpreadsheetView
//
// Created by Kishikawa Katsumi on 3/16/17.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import UIKit
public final class CellRange {
public let from: Location
public let to: Location
public let columnCount: Int
public let rowCount: Int
var size: CGSize?
public convenience init(from: (row: Int, column: Int), to: (row: Int, column: Int)) {
self.init(from: Location(row: from.row, column: from.column),
to: Location(row: to.row, column: to.column))
}
public convenience init(from: IndexPath, to: IndexPath) {
self.init(from: Location(row: from.row, column: from.column),
to: Location(row: to.row, column: to.column))
}
init(from: Location, to: Location) {
guard from.column <= to.column && from.row <= to.row else {
fatalError("the value of `from` must be less than or equal to the value of `to`")
}
self.from = from
self.to = to
columnCount = to.column - from.column + 1
rowCount = to.row - from.row + 1
}
public func contains(_ indexPath: IndexPath) -> Bool {
return from.column <= indexPath.column && to.column >= indexPath.column &&
from.row <= indexPath.row && to.row >= indexPath.row
}
public func contains(_ cellRange: CellRange) -> Bool {
return from.column <= cellRange.from.column && to.column >= cellRange.to.column &&
from.row <= cellRange.from.row && to.row >= cellRange.to.row
}
}
extension CellRange: Hashable {
public var hashValue: Int {
return from.hashValue
}
public static func ==(lhs: CellRange, rhs: CellRange) -> Bool {
return lhs.from == rhs.from
}
}
extension CellRange: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "R\(from.row)C\(from.column):R\(to.row)C\(to.column)"
}
public var debugDescription: String {
return description
}
}
|
mit
|
c06969605e5587bbe2b9b171a8ff39ef
| 28.913043 | 93 | 0.618702 | 3.909091 | false | false | false | false |
spark/photon-tinker-ios
|
Photon-Tinker/Mesh/StepEnsureNotOnMeshNetwork.swift
|
1
|
6860
|
//
// Created by Raimundas Sakalauskas on 2019-03-04.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class StepEnsureNotOnMeshNetwork: Gen3SetupStep {
private var meshNetworkInfoLoaded = false
private var leftNetworkOnAPI = false
private var leftNetworkOnDevice = false
private var apiNetworksLoaded = false
override func reset() {
meshNetworkInfoLoaded = false
leftNetworkOnAPI = false
leftNetworkOnDevice = false
apiNetworksLoaded = false
}
override func start() {
guard let context = self.context else {
return
}
guard context.targetDevice.supportsMesh == nil || context.targetDevice.supportsMesh! == true else {
self.stepCompleted()
return
}
if (!meshNetworkInfoLoaded) {
self.getTargetDeviceMeshNetworkInfo()
} else if (context.userSelectedToLeaveNetwork == nil) {
self.getUserSelectedToLeaveNetwork()
} else if (context.userSelectedToLeaveNetwork! == false) {
//user decided to cancel setup, and we want to get his device in normal mode.
self.log("stopping listening mode?")
self.stopTargetDeviceListening()
} else if (!leftNetworkOnAPI) { //context.userSelectedToLeaveNetwork! == true
//forcing this command even on devices with no network info helps with the joining process
self.targetDeviceLeaveAPINetwork()
} else if (!leftNetworkOnDevice) {
self.targetDeviceLeaveMeshNetwork()
} else if (!apiNetworksLoaded) {
self.getAPINetworks()
} else {
self.stepCompleted()
}
}
private func getTargetDeviceMeshNetworkInfo() {
context?.targetDevice.transceiver?.sendGetNetworkInfo { [weak self, weak context] result, networkInfo in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("targetDevice.sendGetNetworkInfo: \(result.description())")
self.log("\(networkInfo as Optional)");
guard result != .NOT_SUPPORTED else {
context.targetDevice.supportsMesh = false
context.targetDevice.meshNetworkInfo = nil
self.stepCompleted()
return
}
if (result == .NOT_FOUND) {
self.meshNetworkInfoLoaded = true
context.targetDevice.meshNetworkInfo = nil
self.start()
} else if (result == .NONE) {
self.meshNetworkInfoLoaded = true
context.targetDevice.meshNetworkInfo = networkInfo
self.start()
} else {
self.handleBluetoothErrorResult(result)
}
}
}
private func getUserSelectedToLeaveNetwork() {
guard let context = self.context else {
return
}
if let network = context.targetDevice.meshNetworkInfo {
if (network.networkID.count == 0) {
let _ = self.setTargetDeviceLeaveNetwork(leave: true)
} else {
context.delegate.gen3SetupDidRequestToLeaveNetwork(self, network: network)
}
} else {
let _ = self.setTargetDeviceLeaveNetwork(leave: true)
}
}
func setTargetDeviceLeaveNetwork(leave: Bool) -> Gen3SetupFlowError? {
guard let context = self.context else {
return nil
}
context.userSelectedToLeaveNetwork = leave
self.log("setTargetDeviceLeaveNetwork: \(leave)")
self.start()
return nil
}
override func rewindTo(context: Gen3SetupContext) {
super.rewindTo(context: context)
guard let context = self.context else {
return
}
context.userSelectedToLeaveNetwork = nil
context.targetDevice.meshNetworkInfo = nil
}
private func targetDeviceLeaveAPINetwork() {
guard let context = self.context else {
return
}
self.log("sening remove device network info to API")
ParticleCloud.sharedInstance().removeDeviceNetworkInfo(context.targetDevice.deviceId!) {
[weak self, weak context] error in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("removeDevice error: \(error as Optional)")
guard error == nil else {
self.fail(withReason: .UnableToLeaveNetwork, nsError: error)
return
}
self.leftNetworkOnAPI = true
self.start()
}
}
private func targetDeviceLeaveMeshNetwork() {
context?.targetDevice.transceiver?.sendLeaveNetwork { [weak self, weak context] result in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("targetDevice.didReceiveLeaveNetworkReply: \(result.description())")
if (result == .NONE) {
self.leftNetworkOnDevice = true
context.targetDevice.meshNetworkInfo = nil
context.targetDevice.isListeningMode = nil
self.start()
} else {
self.handleBluetoothErrorResult(result)
}
}
}
func getAPINetworks() {
ParticleCloud.sharedInstance().getNetworks { [weak self, weak context] networks, error in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("getNetworks: \(networks as Optional), error: \(error as Optional)")
guard error == nil else {
self.fail(withReason: .UnableToRetrieveNetworks, nsError: error)
return
}
self.apiNetworksLoaded = true
if let networks = networks {
context.apiNetworks = networks
} else {
context.apiNetworks = []
}
self.stepCompleted()
}
}
private func stopTargetDeviceListening() {
context?.targetDevice.transceiver?.sendStopListening { [weak self, weak context] result in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("targetDevice.sendStopListening: \(result.description())")
if (context.canceled) {
return
}
if (result == .NONE) {
context.delegate.gen3SetupDidEnterState(self, state: .SetupCanceled)
} else {
self.handleBluetoothErrorResult(result)
}
}
}
}
|
apache-2.0
|
3306d3f99c2df403c958a89998130376
| 31.358491 | 112 | 0.578717 | 5.193036 | false | false | false | false |
tonystone/coherence
|
Sources/Connect/Internal/Queues/ActionContianer.swift
|
1
|
3621
|
///
/// ActionContainer.swift
///
/// Copyright 2017 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 1/19/17.
///
import Foundation
import TraceLog
import CoreData
internal class ActionContainer: Operation, ActionProxy {
private let notificationService: NotificationService
private let completion: ((_ actionProxy: ActionProxy) -> Void)?
public let action: Action
public internal(set) var state: ActionState {
willSet {
if newValue == .executing {
self._statistics.start()
} else if newValue == .finished {
self._statistics.stop()
}
}
didSet {
/// Notify the service that this action state changed
self.notificationService.actionProxy(self, didChangeState: state)
}
}
public private(set) var completionStatus: ActionCompletionStatus
public private(set) var error: Error?
public var statistics: ActionStatistics {
return _statistics
}
internal let _statistics: Statistics
internal init(action: Action, notificationService: NotificationService, completionBlock: ((_ actionProxy: ActionProxy) -> Void)?) {
self.action = action
self.notificationService = notificationService
self.completionStatus = .unknown
self.state = .created
self.error = nil
self.completion = completionBlock
self._statistics = ActionContainer.Statistics()
super.init()
}
internal func execute() throws {}
override func main() {
logInfo("\(type(of: self.action))") { "\(self.action) started." }
self.state = .executing
defer {
self.state = .finished
logInfo("\(type(of: self.action))") { "\(self.action) \(self.completionStatus), execution statistics: \(self.statistics)" }
self.completion?(self)
}
guard completionStatus != .canceled else {
return
}
///
/// Execute the action
///
do {
try autoreleasepool {
try self.execute()
}
///
/// If canceled, we must maintain the canceled state
///
if completionStatus != .canceled {
completionStatus = .successful
}
} catch {
self.error = error
///
/// If canceled, we must maintain the canceled state
///
if completionStatus != .canceled {
completionStatus = .failed
}
logError("\(type(of: self.action))") { "\(self.action) threw error: \(error)." }
}
}
override func cancel() {
self.completionStatus = .canceled
self.action.cancel()
}
}
extension ActionContainer {
public override var description: String {
return "<\(type(of: self)): \(Unmanaged.passUnretained(self).toOpaque())>)"
}
}
|
apache-2.0
|
2260cf5d421262b596cb60da95a9bf4a
| 27.738095 | 135 | 0.582712 | 4.960274 | false | false | false | false |
simonbs/bemyeyes-ios
|
BeMyEyes/Source/Controllers/VideoViewController.swift
|
1
|
2581
|
//
// VideoViewController.swift
// BeMyEyes
//
// Created by Tobias DM on 07/10/14.
// Copyright (c) 2014 Be My Eyes. All rights reserved.
//
import UIKit
import MediaPlayer
import AVFoundation
class VideoViewController: BaseViewController {
@IBOutlet weak var doneButton: UIButton!
lazy var moviePlayerController: MPMoviePlayerController = {
let moviePlayerController = MPMoviePlayerController()
moviePlayerController.controlStyle = .None
return moviePlayerController
}()
var didFinishPlaying: (() -> ())?
let defaultAudioCategory = AVAudioSession.sharedInstance().category
override func viewDidLoad() {
super.viewDidLoad()
if let movieView = moviePlayerController.view {
view.insertSubview(movieView, belowSubview: doneButton)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let movieView = moviePlayerController.view {
movieView.frame = view.bounds
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
ignoreMuteSwitch()
if moviePlayerController.playbackState != .Playing {
moviePlayerController.play()
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlaying", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self) // Don't call finishedPlaying()
moviePlayerController.stop()
resetAudioCategory()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
extension VideoViewController {
func finishedPlaying() {
if let didFinishPlaying = didFinishPlaying {
didFinishPlaying()
}
}
func ignoreMuteSwitch() {
self.useAudioCategory(AVAudioSessionCategoryPlayback)
}
func resetAudioCategory() {
self.useAudioCategory(defaultAudioCategory)
}
func useAudioCategory(audioCategory: String) {
var error: NSError? = nil
let success = AVAudioSession.sharedInstance().setCategory(audioCategory, error: &error)
if !success {
if let error = error {
println("Could not set audio category to '%@': %@", audioCategory, error)
}
}
}
}
|
mit
|
a2fa792c45dc16eb376afaeaa15fe9d8
| 27.677778 | 155 | 0.649361 | 5.46822 | false | false | false | false |
cayugasoft/FreestylerCore
|
Playground.playground/Contents.swift
|
1
|
2962
|
/*:
# FreestylerCore
Please build scheme *FreestylerCore_iOS* before using this playground.
---
*/
import UIKit
import PlaygroundSupport
import FreestylerCore_iOS
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 540))
let button1 = UIButton(type: .custom)
let button2 = UIButton(type: .custom)
button1.frame = CGRect(x: 0, y: 0, width: 160, height: 44)
button2.frame = CGRect(x: 160, y: 0, width: 160, height: 44)
button1.setTitle("First button", for: .normal)
button2.setTitle("Second button", for: .normal)
let label = UILabel(frame: CGRect(x: 0, y: 60, width: 320, height: 44))
label.textColor = .white
label.text = "Label"
[button1, button2, label].forEach {
mainView.addSubview($0)
}
PlaygroundPage.current.liveView = mainView
/*:
## _FreestylerCore_ lets you create *styles* and apply them to `UIView`s and `UIBarButtonItem`s.
`Style` is a class which basically wraps array of closures. Closures take 1 argument – some `Styleable`. `Styleable` is protocol for types that support styling. In iOS, these are `UIView` and `UIBarButtonItem`.
Style can be applied to styleable using `apply(to:)` method or `<~` operator. When style is applied, its closures are called one by one with this styleable passed as argument.
Styles can be combined using `Style.combine(_:)` method or `<~` operator. This creates new style which has all closures of given styles. Order of closures is preserved.
It's possible to apply style to array of styleables; or apply array of styles to styleable; or even apply array of styles to array of styleables - everything could be done (surprise-surprise) using `<~` operator.
## Examples
- Create style
*/
let redBackground = Style {
(view: UIView) in
view.backgroundColor = .red
}
let grayBackground = Style {
(view: UIView) in
view.backgroundColor = .gray
}
/*:
Styles may have name. It's useful for debugging.
*/
let roundedCorners = Style("Rounded corners") {
(view: UIView) in
view.layer.cornerRadius = 5.0
}
/*:
- Combine styles
You can use `<~` operator for that.*/
let redAndRounded = redBackground <~ roundedCorners
/*: Or you can initialize style from array literal of other styles (note you have to explicitly declare type in this case).*/
let grayAndRounded: Style = [grayBackground, roundedCorners]
/*:
- Apply styles
Try to uncomment these lines one by one and see how they work in **Timeline**.
*/
//button1 <~ redBackground
//button2 <~ grayBackground
//label <~ redBackground <~ grayBackground
//button2 <~ [redBackground, roundedCorners]
//[button1, button2] <~ roundedCorners
//[button1, button2] <~ [roundedCorners, redBackground]
//[button1, button2] <~ redAndRounded
/*:
- If you apply style to wrong object (such as style for `UILabel` to `UIButton`), crash will happen. Try to uncomment these lines to see.
*/
//let greenText = Style {
// (label: UILabel) in
// label.textColor = .green
//}
//button1 <~ greenText
|
mit
|
bb9da62ffb035f4ecdd6ec2a1ce08989
| 32.258427 | 213 | 0.716216 | 3.737374 | false | false | false | false |
tristanchu/FlavorFinder
|
FlavorFinder/FlavorFinder/Globals.swift
|
1
|
5035
|
//
// Globals.swift
// FlavorFinder
//
// Created by Jon on 10/29/15.
// Copyright © 2015 TeamFive. All rights reserved.
//
import UIKit
import FontAwesome_swift
// Keychain wrapping:
let MyKeychainWrapper = KeychainWrapper()
// Keychain / NSUserDefaults keys:
let IS_LOGGED_IN_KEY = "isLoggedInKey"
let USERNAME_KEY = "username"
// Controller Identifiers:
let ProfileViewControllerIdentifier = "ProfileViewControllerIdentifier"
let MatchTableViewControllerIdentifier = "MatchTableViewControllerIdentifier"
let LoginViewControllerIdentifier = "LoginViewControllerIdentifier"
// DB Labels:
let TITLE_ALL_INGREDIENTS = "All Ingredients"
let CELLIDENTIFIER_MATCH = "MatchTableViewCell"
let CELLIDENTIFIER_MENU = "menuCell"
// Filters:
let F_KOSHER = "kosher"
let F_DAIRY = "no dairy"
let F_VEG = "vegetarian"
let F_NUTS = "no nuts"
// TOAST:
let TOAST_DURATION = 1.0
// Colors:
let BACKGROUND_COLOR = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: CGFloat(1))
let ACCENT_COLOR = UIColor(red: 27/255.0, green: 149/255.0, blue: 148/255.0, alpha: CGFloat(1))
let LIGHTGRAY_COLOR = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: CGFloat(1))
let MATCH_CELL_IMAGE_COLOR = UIColor.blackColor()
let NAVI_COLOR = UIColor(red: 101/255.0, green: 219/255.0, blue: 204/255.0, alpha: CGFloat(1))
let NAVI_LIGHT_COLOR = UIColor(red: 27/255.0, green: 151/255.0, blue: 150/255.0, alpha: CGFloat(1))
let FILTER_BUTTON_COLOR = NAVI_LIGHT_COLOR
let NAVI_BUTTON_COLOR = UIColor.whiteColor()
// UIColor(red: 51/255.0, green: 202/255.0, blue: 252/255.0, alpha: CGFloat(1))
let NAVI_BUTTON_DARK_COLOR = UIColor(red: 135/255.0, green: 212/255.0, blue: 186/255.0, alpha: CGFloat(1))
let SEARCH_RESULTS_CELL_COLOR = UIColor.whiteColor()
let FAV_CELL_BTN_COLOR = UIColor(red: 249/255.0, green: 181/255.0, blue: 255/255.0, alpha: CGFloat(1))
let DOWNVOTE_CELL_BTN_COLOR = UIColor(red: 252/255.0, green: 200/255.0, blue: 183/255.0, alpha: CGFloat(1))
let UPVOTE_CELL_BTN_COLOR = UIColor(red: 185/255.0, green: 250/255.0, blue: 177/255.0, alpha: CGFloat(1))
let ADD_TO_SEARCH_CELL_BTN_COLOR = UIColor(red: 218/255.0, green: 239/255.0, blue: 247/255.0, alpha: CGFloat(1))
let ADD_TO_LIST_CELL_BTN_COLOR = UIColor(red: 247/255.0, green: 246/255.0, blue: 218/255.0, alpha: CGFloat(1))
let CELL_BTN_OFF_COLOR = UIColor.grayColor()
let CELL_BTN_ON_COLOR = UIColor.blackColor()
let HOTPOT_COLLECTION_COLOR = UIColor(red: 121/255.0, green: 217/255.0, blue: 255/255.0, alpha: CGFloat(0.3))
let EMPTY_SET_TEXT_COLOR = UIColor.darkGrayColor()
//let EMPTY_SET_TEXT_COLOR = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
// Fonts:
let attributes = [NSFontAttributeName: UIFont.fontAwesomeOfSize(15)] as Dictionary!
let CELL_FONT_AWESOME = UIFont.fontAwesomeOfSize(16)
let CELL_FONT = UIFont(name: "Avenir Next Medium", size: 17)
let FILTER_BUTTON_FONT = UIFont(name: "Avenir Next Medium", size: 15)
let EMPTY_SET_FONT = UIFont(name: "Avenir Next Regular", size: 15)
// Sizes:
let MATCH_CELL_IMAGE_SIZE = CGSizeMake(30, 30)
let UNIFORM_ROW_HEIGHT: CGFloat = 68.0 // for favs, lists, list details
let K_CELL_HEIGHT : CGFloat = 40.0
// Displayed error messages:
// --> "add it yourself" can be added when feature exists
let SEARCH_GENERIC_ERROR_TEXT = "There was an error with the search."
let MATCHES_NOT_FOUND_TEXT = "No matches for this search!"
// Displayed generic text:
let OK_TEXT = "Ok"
// Search Bar Formattng:
let ROUNDED_SIZE : CGFloat = 15.0 // searchbar.layer.cornerRadius = 15
let ROUNDED_EDGES = true // searchbar.clipsToBounds = true
// Button formatting ---------------------------:
// Use setDefaultButtonUI() For these settings:
let DEFAULT_BUTTON_BORDER_WIDTH : CGFloat = 2.0
let DEFAULT_BUTTON_BORDER_COLOR : CGColorRef = ACCENT_COLOR.CGColor
let DEFAULT_BUTTON_FONT_COLOR : UIColor = ACCENT_COLOR
// Use setSecondaryButtonUI() for these settings:
let SECONDARY_BUTTON_BORDER_WIDTH : CGFloat = 1.0
let SECONDARY_BUTTON_BORDER_COLOR : CGColorRef = ACCENT_COLOR.CGColor
let SECONDARY_BUTTON_FONT_COLOR : UIColor = ACCENT_COLOR
let ROUNDED_BUTTON_SIZE : CGFloat = 10.0
// STORYBOARD STYLE GUIDE:
// StackViews with Prompts - make top 60 from Top Layout Guide.bottom
// Text
// - font = Anvier Next
// - page prompt = medium
// -
// - color = Dark Grey
// - size = (page prompt - 22
// Buttons ->
// Login - font size = 20
// All other buttons - font size = 15
// font = Anvier next
// - primary = medium
// - secondary = regular
// padding - 5 on all sides
// -- OR - make stack view width of
// text bar nad have buttons
// fill equally with 20 spacing
// Search bars:
// - width = 0.8 of superview
// - height =
|
mit
|
35233c30a00e99f4b3950d0fcdd08ccb
| 37.136364 | 112 | 0.664482 | 3.29666 | false | false | false | false |
laerador/barista
|
Barista/Application/MenuController.swift
|
1
|
10510
|
//
// StatusBarMenu.swift
// Barista
//
// Created by Franz Greiling on 29.05.17.
// Copyright © 2018 Franz Greiling. All rights reserved.
//
import Cocoa
import Foundation
private enum MenuItemTag: Int {
case hidden = 1
case temporary = 2
case interval = 3
}
class MenuController: NSObject {
// MARK: - UI Outlets
let statusItem: NSStatusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
@IBOutlet var menu: NSMenu!
@IBOutlet weak var stateItem: NSMenuItem!
@IBOutlet weak var timeRemainingItem: NSMenuItem!
@IBOutlet weak var activateItem: NSMenuItem!
@IBOutlet weak var activateForItem: NSMenuItem!
@IBOutlet weak var indefinitlyItem: NSMenuItem!
@IBOutlet weak var uptimeItem: NSMenuItem!
@IBOutlet weak var awakeForItem: NSMenuItem!
@IBOutlet weak var infoSeparator: NSMenuItem!
@IBOutlet weak var appListItem: NSMenuItem!
@IBOutlet weak var appListSeparator: NSMenuItem!
@IBOutlet weak var powerMgmtController: PowerMgmtController!
// MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
// Setup Status Bar
self.statusItem.button!.title = "zZ"
self.statusItem.button?.appearsDisabled = !(powerMgmtController.assertion?.enabled ?? false)
self.statusItem.button?.target = self
self.statusItem.button?.action = #selector(toggleAssertionAction(_:))
self.statusItem.menu = self.menu
self.statusItem.behavior = .terminationOnRemoval
powerMgmtController.addObserver(self)
// Setup "Activate for" Submenu
for item in (activateForItem.submenu?.items)! {
if item.tag == MenuItemTag.interval.rawValue {
let ti = TimeInterval(item.title)!
item.representedObject = ti
item.title = ti.simpleFormat(maxCount: 1)!
item.target = self
item.action = #selector(activateForAction(_:))
}
}
}
deinit {
powerMgmtController.removeObserver(self)
self.timer?.invalidate()
}
// MARK: - Update Menu Items
private var timer: Timer?
private var override: Bool = false
func updateMenu() {
let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName")!
// Set Standart Elements
stateItem.title = "\(appName): " + (powerMgmtController.assertion?.enabled ?? false ? "On" : "Off")
timeRemainingItem.isHidden = true
activateItem.title = "Turn \(appName) " + (powerMgmtController.assertion?.enabled ?? false ? "Off" : "On")
activateForItem.title = powerMgmtController.assertion?.enabled ?? false ? "Turn Off in..." : "Activate for..."
indefinitlyItem.title = powerMgmtController.assertion?.enabled ?? false ? "Never" : "Indefinitely"
// Reset Item
for item in menu.items {
if let tag = MenuItemTag(rawValue: item.tag) {
switch tag {
case .hidden:
item.isHidden = true
case .temporary:
menu.removeItem(item)
default: break
}
}
}
// Update Time Remaining
if let tl = powerMgmtController.assertion?.timeLeft, tl > 0 {
let title = TimeInterval(tl).simpleFormat(style: .short, units: [.day, .hour, .minute],
maxCount: 2, timeRemaining: true)!
timeRemainingItem.title = title
timeRemainingItem.isHidden = false
}
// Update List of Apps if wanted
menuShowApps(override: self.override)
menuShowInfo(override: self.override)
}
private func menuShowInfo(override: Bool) {
guard override || UserDefaults.standard.showUptime else { return }
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
let uptime = SystemTime.systemUptime.simpleFormat(style: .short, units: [.day, .hour, .minute, .second], maxCount: 3)!
uptimeItem.isHidden = false
uptimeItem.title = "Uptime: \(uptime)"
uptimeItem.toolTip = "Booted at \(dateFormatter.string(from: SystemTime.boot!))"
let awakeSince: String
if let lastWake = SystemTime.lastWake {
let ti = Date().timeIntervalSince(lastWake)
awakeSince = ti.simpleFormat(style: .short, units: [.day, .hour, .minute, .second], maxCount: 3)!
} else {
awakeSince = uptime
}
awakeForItem.isHidden = false
awakeForItem.title = "Awake For: \(awakeSince)"
infoSeparator.isHidden = false
}
private func menuShowApps(override: Bool) {
guard override || UserDefaults.standard.showAppList else { return }
let infos = AssertionInfo.byProcess()
let numString = String.localizedStringWithFormat(
NSLocalizedString("number_apps", comment: ""), infos.count)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
dateFormatter.doesRelativeDateFormatting = true
appListItem.isHidden = false
appListSeparator.isHidden = false
appListItem.title = "\(numString) Preventing Sleep"
guard override || (UserDefaults.standard.showAppList && UserDefaults.standard.appListDetail >= 1)
else { return }
for info in infos {
let index = menu.index(of: appListSeparator)
let numString = String.localizedStringWithFormat(
NSLocalizedString("number_assertions", comment: ""), info.ids.count)
let pdsString = "Prevents \(info.preventsDisplaySleep ? "Display" : "Idle") Sleep"
let appItem = NSMenuItem()
appItem.tag = MenuItemTag.temporary.rawValue
appItem.title = info.name
appItem.toolTip = numString + "; " + pdsString
appItem.image = info.icon
appItem.image?.size = CGSize(width: 16, height: 16)
appItem.representedObject = info
appItem.target = self
appItem.action = #selector(applicationAction(_:))
menu.insertItem(appItem, at: index)
// Add Verbose Information if wanted
guard override || UserDefaults.standard.appListDetail >= 2 else { continue }
let desc1Item = NSMenuItem()
desc1Item.tag = MenuItemTag.temporary.rawValue
desc1Item.title = pdsString
desc1Item.indentationLevel = 1
desc1Item.isEnabled = false
menu.insertItem(desc1Item, at: index+1)
let desc2Item = NSMenuItem()
desc2Item.tag = MenuItemTag.temporary.rawValue
desc2Item.title = "Started: \(dateFormatter.string(from: info.timeStarted))"
desc2Item.indentationLevel = 1
desc2Item.isEnabled = false
menu.insertItem(desc2Item, at: index+2)
if let timeRemaining = info.timeLeft, timeRemaining > 0 {
let timeoutString = TimeInterval(timeRemaining).simpleFormat(
style: .short, units: [.day, .hour, .minute], maxCount: 2)!
let desc3Item = NSMenuItem()
desc3Item.tag = MenuItemTag.temporary.rawValue
desc3Item.title = "Timeout in: \(timeoutString)"
desc3Item.indentationLevel = 1
desc3Item.isEnabled = false
menu.insertItem(desc3Item, at: index+3)
}
}
}
// MARK: - Actions
@IBAction func applicationAction(_ sender: NSMenuItem) {
guard let pid = (sender.representedObject as? AssertionInfo)?.pid,
let app = NSRunningApplication(processIdentifier: pid)
else { return }
if let cmdKey = NSApp.currentEvent?.modifierFlags.contains(.command), cmdKey {
app.terminate() // Doesn't Work
} else {
app.activate(options: [.activateIgnoringOtherApps])
}
}
@IBAction func toggleAssertionAction(_ sender: NSObject) {
if let isEnabled = powerMgmtController.assertion?.enabled, isEnabled {
powerMgmtController.stopPreventingSleep()
} else {
powerMgmtController.preventSleep()
}
}
@IBAction func togglePreventDisplaySleep(_ sender: NSMenuItem){
guard let assertion = powerMgmtController.assertion else { return }
assertion.preventsDisplaySleep = !(sender.state == .on)
}
@IBAction func activateForAction(_ sender: NSMenuItem) {
guard let ti = sender.representedObject as? TimeInterval else { return }
powerMgmtController.preventSleep(withTimeout: UInt(ti))
}
@IBAction func activateIndefinitlyAction(_ sender: NSMenuItem) {
powerMgmtController.preventSleep(withTimeout: 0)
}
@IBAction func activateEndOfDayAction(_ sender: NSMenuItem) {
powerMgmtController.preventSleepUntilEndOfDay()
}
}
// MARK: - AssertionObserver Protocol
extension MenuController: PowerMgmtObserver {
func startedPreventingSleep(for: TimeInterval) {
self.statusItem.button?.appearsDisabled = false
}
func stoppedPreventingSleep(after: TimeInterval, because reason: StoppedPreventingSleepReason) {
self.statusItem.button?.appearsDisabled = true
}
}
// MARK: - NSMenuDelegate Protocol
extension MenuController: NSMenuDelegate {
func menuNeedsUpdate(_ menu: NSMenu) {
guard menu == self.menu else { return }
self.override = (NSApp.currentEvent?.modifierFlags.contains(.option))!
self.updateMenu()
}
func menuWillOpen(_ menu: NSMenu) {
guard self.timer == nil else { return }
self.timer = Timer(timeInterval: 1.0, repeats: true) { _ in self.updateMenu() }
RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.eventTracking)
}
func menuDidClose(_ menu: NSMenu) {
self.override = false
self.statusItem.button?.highlight(false)
self.timer?.invalidate()
self.timer = nil
}
}
|
bsd-2-clause
|
47df5b65a51c02898a92afae279f9fea
| 36.134276 | 126 | 0.610429 | 4.818432 | false | false | false | false |
uasys/swift
|
test/SILOptimizer/definite_init_failable_initializers.swift
|
1
|
68896
|
// RUN: %target-swift-frontend -emit-sil -enable-sil-ownership -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// High-level tests that DI handles early returns from failable and throwing
// initializers properly. The main complication is conditional release of self
// and stored properties.
// FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases
// are fully covered, though.
////
// Structs with failable initializers
////
protocol Pachyderm {
init()
}
class Canary : Pachyderm {
required init() {}
}
// <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer
struct TrivialFailableStruct {
init?(blah: ()) { }
init?(wibble: ()) {
self.init(blah: wibble)
}
}
struct FailableStruct {
let x, y: Canary
init(noFail: ()) {
x = Canary()
y = Canary()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt24failBeforeInitialization_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: br bb1
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[SELF]]
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt30failAfterPartialInitialization_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY]] to [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: strong_release [[CANARY]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[SELF]]
init?(failAfterPartialInitialization: ()) {
x = Canary()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt27failAfterFullInitialization_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY1:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK: [[CANARY2:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[SELF:%.*]] = struct $FailableStruct ([[CANARY1]] : $Canary, [[CANARY2]] : $Canary)
// CHECK-NEXT: release_value [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
x = Canary()
y = Canary()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt46failAfterWholeObjectInitializationByAssignment_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: release_value [[CANARY]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[SELF_VALUE]]
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableStruct(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt46failAfterWholeObjectInitializationByDelegation_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: release_value [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt20failDuringDelegation_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructVACSgyt24failBeforeInitialization_tcfC
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: br [[FAIL_EPILOG_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>)
//
// CHECK: [[FAIL_EPILOG_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableStruct>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableStruct>)
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
init!(failDuringDelegation3: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation4: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation5: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableStruct {
init?(failInExtension: ()) {
self.init(failInExtension: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableStruct(noFail: ())
}
}
struct FailableAddrOnlyStruct<T : Pachyderm> {
var x, y: T
init(noFail: ()) {
x = T()
y = T()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failBeforeInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: br bb1
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: return
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterPartialInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[X_ADDR]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: return
init?(failAfterPartialInitialization: ()) {
x = T()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterFullInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[Y_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: return
init?(failAfterFullInitialization: ()) {
x = T()
y = T()
return nil
}
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableAddrOnlyStruct(noFail: ())
return nil
}
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation3: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation4: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableAddrOnlyStruct {
init?(failInExtension: ()) {
self.init(failBeforeInitialization: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableAddrOnlyStruct(noFail: ())
}
}
////
// Structs with throwing initializers
////
func unwrap(_ x: Int) throws -> Int { return x }
struct ThrowStruct {
var x: Canary
init(fail: ()) throws { x = Canary() }
init(noFail: ()) { x = Canary() }
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi20failBeforeDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi28failBeforeOrDuringDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi29failBeforeOrDuringDelegation2_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACSi20failBeforeDelegation_tKcfC
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi20failDuringDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi19failAfterDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: release_value [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi27failDuringOrAfterDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi27failBeforeOrAfterDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSgSi16throwsToOptional_tcfC
// CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACSi20failDuringDelegation_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]]([[ARG1]], [[ARG2]]) : $@convention(method) (Int, @thin ThrowStruct.Type) -> (@owned ThrowStruct, @error Error), normal [[TRY_APPLY_SUCC_BB:bb[0-9]+]], error [[TRY_APPLY_FAIL_BB:bb[0-9]+]]
//
// CHECK: [[TRY_APPLY_SUCC_BB]]([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[NEW_SELF]]
// CHECK-NEXT: br [[TRY_APPLY_CONT:bb[0-9]+]]([[SELF_OPTIONAL]] : $Optional<ThrowStruct>)
//
// CHECK: [[TRY_APPLY_CONT]]([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>):
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: br [[FAIL_EPILOG_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[FAIL_EPILOG_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<ThrowStruct>):
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct>
//
// CHECK: [[TRY_APPLY_FAIL_TRAMPOLINE_BB:bb[0-9]+]]:
// CHECK-NEXT: strong_release [[ERROR:%.*]] : $Error
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[TRY_APPLY_CONT]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[TRY_APPLY_FAIL_BB]]([[ERROR]] : $Error):
// CHECK-NEXT: br [[TRY_APPLY_FAIL_TRAMPOLINE_BB]]
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsToOptionalThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowStruct(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi25failDuringSelfReplacement_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
// CHECK-NEXT: try_apply [[INIT_FN]]([[SELF_TYPE]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
// CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringSelfReplacement: Int) throws {
try self = ThrowStruct(fail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi24failAfterSelfReplacement_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
// CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: release_value [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterSelfReplacement: Int) throws {
self = ThrowStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
try self = ThrowStruct(fail: ())
}
}
struct ThrowAddrOnlyStruct<T : Pachyderm> {
var x : T
init(fail: ()) throws { x = T() }
init(noFail: ()) { x = T() }
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsOptionalToThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowAddrOnlyStruct(noFail: ())
}
init(failAfterSelfReplacement: Int) throws {
self = ThrowAddrOnlyStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowAddrOnlyStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
self = ThrowAddrOnlyStruct(noFail: ())
}
}
////
// Classes with failable initializers
////
class FailableBaseClass {
var member: Canary
init(noFail: ()) {
member = Canary()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt28failBeforeFullInitialization_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type
// CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]]
// CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK: return [[RESULT]]
init?(failBeforeFullInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt27failAfterFullInitialization_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Canary
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
member = Canary()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt20failBeforeDelegation_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick FailableBaseClass.Type, %0 : $FailableBaseClass
// CHECK-NEXT: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] : $@thick FailableBaseClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[RESULT]]
convenience init?(failBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt19failAfterDelegation_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: strong_release [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[RESULT]]
convenience init?(failAfterDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt20failDuringDelegation_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK: release_value [[SELF_OPTIONAL]]
// CHECK: br [[FAIL_TRAMPOLINE_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableBaseClass>)
//
// CHECK: [[FAIL_TRAMPOLINE_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableBaseClass>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>):
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
convenience init?(failDuringDelegation: ()) {
self.init(failBeforeFullInitialization: ())
}
// IUO to optional
convenience init!(failDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
convenience init!(noFailDuringDelegation: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
convenience init(noFailDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // necessary '!'
}
}
extension FailableBaseClass {
convenience init?(failInExtension: ()) throws {
self.init(failBeforeFullInitialization: failInExtension)
}
}
// Chaining to failable initializers in a superclass
class FailableDerivedClass : FailableBaseClass {
var otherMember: Canary
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassCACSgyt27derivedFailBeforeDelegation_tcfc
// CHECK: bb0(%0 : $FailableDerivedClass):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %0 : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[RESULT]]
init?(derivedFailBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassCACSgyt27derivedFailDuringDelegation_tcfc
// CHECK: bb0(%0 : $FailableDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Canary
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt28failBeforeFullInitialization_tcfc
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: br [[FAIL_TRAMPOLINE_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableDerivedClass>)
//
// CHECK: [[FAIL_TRAMPOLINE_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableDerivedClass>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>):
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass>
init?(derivedFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failBeforeFullInitialization: ())
}
init?(derivedFailAfterDelegation: ()) {
self.otherMember = Canary()
super.init(noFail: ())
return nil
}
// non-optional to IUO
init(derivedNoFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // necessary '!'
}
// IUO to IUO
init!(derivedFailDuringDelegation2: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!'
}
}
extension FailableDerivedClass {
convenience init?(derivedFailInExtension: ()) throws {
self.init(derivedFailDuringDelegation: derivedFailInExtension)
}
}
////
// Classes with throwing initializers
////
class ThrowBaseClass {
required init() throws {}
init(noFail: ()) {}
}
class ThrowDerivedClass : ThrowBaseClass {
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK: bb0(%0 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
required init() throws {
try super.init()
}
override init(noFail: ()) {
try! super.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h6DuringjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int)
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %2 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failAfterFullInitialization_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[DERIVED_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int) throws {
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failAfterFullInitialization_Si0h6DuringjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws {
try super.init()
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h5AfterjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
// CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%1)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND:%.*]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h6DuringjK0Si0h5AfterjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %3 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %3
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%2)
// CHECK: bb3([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb6([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb8, bb9
// CHECK: bb8:
// CHECK-NEXT: br bb13
// CHECK: bb9:
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb10, bb11
// CHECK: bb10:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb12
// CHECK: bb11:
// CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb12
// CHECK: bb12:
// CHECK-NEXT: br bb13
// CHECK: bb13:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
try unwrap(failAfterFullInitialization)
}
convenience init(noFail2: ()) {
try! self.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failBeforeDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failDuringDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
convenience init(failDuringDelegation: Int) throws {
try self.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeOrDuringDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2)
// CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi29failBeforeOrDuringDelegation2_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failBeforeDelegation_tKcfc
// CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: store %1 to [[SELF_BOX]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb5([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2)
// CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[RELOADED_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, [[RELOADED_SELF]] : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref [[RELOADED_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR2]]
convenience init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi19failAfterDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failDuringOrAfterDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %1 to [[SELF_BOX]]
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failDuringOrAfterDelegation: Int) throws {
try self.init()
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failBeforeOrAfterDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[OLD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, [[OLD_SELF]] : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref [[OLD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
}
////
// Enums with failable initializers
////
enum FailableEnum {
case A
init?(a: Int64) { self = .A }
init!(b: Int64) {
self.init(a: b)! // unnecessary-but-correct '!'
}
init(c: Int64) {
self.init(a: c)! // necessary '!'
}
init(d: Int64) {
self.init(b: d)! // unnecessary-but-correct '!'
}
}
////
// Protocols and protocol extensions
////
// Delegating to failable initializers from a protocol extension to a
// protocol.
protocol P1 {
init?(p1: Int64)
}
extension P1 {
init!(p1a: Int64) {
self.init(p1: p1a)! // unnecessary-but-correct '!'
}
init(p1b: Int64) {
self.init(p1: p1b)! // necessary '!'
}
}
protocol P2 : class {
init?(p2: Int64)
}
extension P2 {
init!(p2a: Int64) {
self.init(p2: p2a)! // unnecessary-but-correct '!'
}
init(p2b: Int64) {
self.init(p2: p2b)! // necessary '!'
}
}
@objc protocol P3 {
init?(p3: Int64)
}
extension P3 {
init!(p3a: Int64) {
self.init(p3: p3a)! // unnecessary-but-correct '!'
}
init(p3b: Int64) {
self.init(p3: p3b)! // necessary '!'
}
}
// Delegating to failable initializers from a protocol extension to a
// protocol extension.
extension P1 {
init?(p1c: Int64) {
self.init(p1: p1c)
}
init!(p1d: Int64) {
self.init(p1c: p1d)! // unnecessary-but-correct '!'
}
init(p1e: Int64) {
self.init(p1c: p1e)! // necessary '!'
}
}
extension P2 {
init?(p2c: Int64) {
self.init(p2: p2c)
}
init!(p2d: Int64) {
self.init(p2c: p2d)! // unnecessary-but-correct '!'
}
init(p2e: Int64) {
self.init(p2c: p2e)! // necessary '!'
}
}
////
// type(of: self) with uninitialized self
////
func use(_ a : Any) {}
class DynamicTypeBase {
var x: Int
init() {
use(type(of: self))
x = 0
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
class DynamicTypeDerived : DynamicTypeBase {
override init() {
use(type(of: self))
super.init()
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
struct DynamicTypeStruct {
var x: Int
init() {
use(type(of: self))
x = 0
}
init(a : Int) {
use(type(of: self))
self.init()
}
}
|
apache-2.0
|
300cf88525784a7544cb3e5a8804245d
| 41.792547 | 227 | 0.619426 | 3.251345 | false | false | false | false |
briancordanyoung/GeekSpeak-Show-Timer
|
Views Play.playground/Contents.swift
|
1
|
456
|
//: A UIKit based Playground to present user interface
import UIKit
import PlaygroundSupport
//import TimerViewsGear
class myViewController : UIViewController {
override func loadView() {
let view = UIView()
let label = UILabel()
label.text = "Hello World!"
label.textColor = .white
view.addSubview(label)
self.view = view
}
}
PlaygroundPage.current.liveView = myViewController()
|
mit
|
70ee65fd3faaacc6aca332b3d4244764
| 19.727273 | 54 | 0.649123 | 4.851064 | false | false | false | false |
Vaseltior/OYThisUI
|
Sources/OYTDateStackView.swift
|
1
|
5474
|
/*
Copyright 2011-present Samuel GRAU
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
@IBDesignable
public class OYTDateStackView: OYTView {
private static let fontName = "KohinoorDevanagari-Medium"
// MARK: - Properties
/// The date represented by the view
@IBInspectable public var date: NSDate = NSDate() {
didSet {
// Get a date formatter
let f = NSDateFormatter()
f.dateFormat = "dd" // Set the day style
self.dayLabel.text = f.stringFromDate(self.date) // set the day representation
f.dateFormat = "MMMM yyyy" // update the format
self.monthLabel.text = f.stringFromDate(self.date) // the the month representation
// self.setNeedsLayout() // No need, automatic update for those properties
}
}
/// The text color used by the views
@IBInspectable public var textColor: UIColor = UIColor.whiteColor() {
didSet {
self.dayLabel.textColor = self.textColor
self.monthLabel.textColor = self.textColor
}
}
/// The font used to display the views (at least one font for now)
@IBInspectable public var dayFontSize: CGFloat = 15.0 {
didSet {
self.dayLabel.font = UIFont(name: OYTDateStackView.fontName, size: self.dayFontSize)
self.setNeedsLayout()
self.setNeedsDisplay()
}
}
@IBInspectable public var monthFontSize: CGFloat = 15.0 {
didSet {
self.monthLabel.font = UIFont(name: OYTDateStackView.fontName, size: self.monthFontSize)
self.setNeedsLayout()
self.setNeedsDisplay()
}
}
@IBInspectable var lineWidth: CGFloat = 1.0 {
didSet {
// Ask to redraw the view in the next drawing loop
self.setNeedsDisplay()
}
}
// The padding at the left and right of the horizontal line
@IBInspectable var linePadding: CGFloat = 12.0 { didSet { self.setNeedsDisplay() } }
/// Day view representation
private lazy var dayLabel: UILabel = {
let l = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
l.textAlignment = .Center
return l
}()
/// Month view representation
private lazy var monthLabel: UILabel = {
let l = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
l.textAlignment = .Center
return l
}()
// MARK: - Initialization
/**
This function is called by the init(frame) and the init(coder) methods,
so that there is no need to implement further methods in the subclasses.
*/
public override func commonInitialization() {
super.commonInitialization()
// Adding labels to the view hierarchy
self.addSubview(self.dayLabel)
self.addSubview(self.monthLabel)
}
// Only called in interface builder
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.date = NSDate() // test because did set is not called
/*self.textColor = UIColor.whiteColor()
self.dayFontSize = 90.0
self.monthFontSize = 16.0*/
//self.dayLabel.backgroundColor = UIColor.greenColor()
//self.monthLabel.backgroundColor = UIColor.blueColor()
}
// MARK: - Layout
/**
Lays out subviews.
*/
public override func layoutSubviews() {
super.layoutSubviews()
let width = CGRectGetWidth(self.bounds)
let halfHeight = CGRectGetHeight(self.bounds)/2.0
var f = self.dayLabel.frame
f.origin = CGPoint(x: 0, y: halfHeight - self.dayLabel.oytSizeWithView(self).height)
f.size = CGSize(
width: width,
height: self.dayLabel.oytSizeWithView(self).height
)
self.dayLabel.frame = f
f = self.monthLabel.frame
f.origin = CGPoint(x: 0, y: halfHeight + self.lineWidth / 2.0)
f.size = CGSize(
width: width,
height: self.monthLabel.oytSizeWithView(self).height
)
self.monthLabel.frame = f
}
/**
Draws the receiver’s image within the passed-in rectangle.
- parameter rect: The portion of the view’s bounds that needs to be updated.
The first time your view is drawn, this rectangle is typically the entire
visible bounds of your view. However, during subsequent drawing operations,
the rectangle may specify only part of your view.
*/
public override func drawRect(rect: CGRect) {
super.drawRect(rect)
// Drawing a line in the middle
guard let context = UIGraphicsGetCurrentContext() else {
// Can't get a graphic context, no need to continue here
return
}
let scaleRatio = 1.0/UIScreen.mainScreen().scale
let bWidth: CGFloat = scaleRatio*self.lineWidth
let halfHeight = CGRectGetHeight(rect)/2.0
let width = CGRectGetWidth(rect)
CGContextSetStrokeColorWithColor(context, self.textColor.CGColor)
CGContextSetFillColorWithColor(context, self.textColor.CGColor)
CGContextSetLineWidth(context, bWidth)
CGContextMoveToPoint(context, self.linePadding, halfHeight)
CGContextAddLineToPoint(context, width-self.linePadding, halfHeight)
CGContextStrokePath(context)
}
}
|
apache-2.0
|
e7b33bf69caef305f8a0cc02f060fa3f
| 31.366864 | 94 | 0.69287 | 4.358566 | false | false | false | false |
carambalabs/Paparajote
|
Paparajote/Classes/Providers/GitHubProvider.swift
|
1
|
2988
|
import Foundation
import NSURL_QueryDictionary
public struct GitHubProvider: OAuth2Provider {
// MARK: - Attributes
fileprivate let clientId: String
fileprivate let clientSecret: String
fileprivate let redirectUri: String
fileprivate let scope: [String]
fileprivate let state: String
fileprivate let allowSignup: Bool
// MARK: - Init
public init(clientId: String, clientSecret: String, redirectUri: String, allowSignup: Bool = true, scope: [String] = [], state: String = String.random()) {
self.clientId = clientId
self.clientSecret = clientSecret
self.redirectUri = redirectUri
self.allowSignup = allowSignup
self.scope = scope
self.state = state
}
// MARK: - Oauth2Provider
public var authorization: Authorization {
get {
return { () -> URL in
var allowSignUpString = "false"
if self.allowSignup {
allowSignUpString = "true"
}
return (URL(string: "https://github.com/login/oauth/authorize")! as NSURL)
.uq_URL(byAppendingQueryDictionary: [
"client_id": self.clientId,
"state": self.state,
"scope": self.scope.joined(separator: " "),
"allow_signup": allowSignUpString
])
}
}
}
public var authentication: Authentication {
get {
return { url -> URLRequest? in
if !url.absoluteString.contains(self.redirectUri) { return nil }
guard let code = (url as NSURL).uq_queryDictionary()["code"] as? String,
let state = (url as NSURL).uq_queryDictionary()["state"] as? String else { return nil }
if state != self.state { return nil }
let authenticationUrl: URL = (URL(string: "https://github.com/login/oauth/access_token")! as NSURL)
.uq_URL(byAppendingQueryDictionary: [
"client_id" : self.clientId,
"client_secret": self.clientSecret,
"code": code,
"redirect_uri": self.redirectUri,
"state": self.state
])
let request = NSMutableURLRequest()
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.url = authenticationUrl
return request.copy() as? URLRequest
}
}
}
public var sessionAdapter: SessionAdapter = { (data, _) -> OAuth2Session? in
let json = try? JSONSerialization.jsonObject(with: data, options: [])
guard let dictionary = json as? [String: String] else { return nil }
return dictionary["access_token"].map {OAuth2Session(accessToken: $0, refreshToken: nil)}
}
}
|
mit
|
072a25ff3f52795b20e6c8f8065462b4
| 38.315789 | 159 | 0.554886 | 4.971714 | false | false | false | false |
AlphaJian/PaperCalculator
|
PaperCalculator/PaperCalculator/Views/Report/QuestionReportTableViewCell.swift
|
1
|
2701
|
//
// QuestionReportTableViewCell.swift
// PaperCalculator
//
// Created by appledev018 on 10/11/16.
// Copyright © 2016 apple. All rights reserved.
//
import UIKit
class QuestionReportTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func initUI (index: IndexPath) {
let numOfPaper: Float = Float(DataManager.shareManager.paperNum - 1)
let result = DataManager.shareManager.getQuestionStates(section: index.section, row: index.row)
let label = UILabel.init(frame: CGRect(x: 10, y: 0, width: 50, height: 40))
label.text = "(\(index.row))"
label.textColor = darkBlue
label.textAlignment = NSTextAlignment.center
let markLabel1 = UILabel.init(frame: CGRect(x: 80, y: 0, width: 100, height: 40))
let a = String(format: "%.1f", result.realScore/numOfPaper)
let b = String(format: "%.1f", result.score/numOfPaper)
markLabel1.text = "\(a)/\(b)"
markLabel1.textColor = lightBlue
markLabel1.font = UIFont.systemFont(ofSize: 16)
markLabel1.alpha = CGFloat(Float(1.3) - Float(result.realScore/result.score))
let markLabel2 = UILabel.init(frame: CGRect(x: 180, y: 0, width: 100, height: 40))
markLabel2.text = "\(result.realScore/result.score)"
if result.realScore/result.score < 0.5 {
markLabel2.textColor = darkRed
} else {
markLabel2.textColor = lightBlue
}
markLabel2.font = UIFont.systemFont(ofSize: 16)
markLabel2.alpha = CGFloat(Float(1.3) - Float(result.realScore/result.score))
let markLabel3 = UILabel.init(frame: CGRect(x: 300, y: 0, width: 100, height: 40))
markLabel3.text = "\(result.faultNum)人"
if Float(result.faultNum)/numOfPaper > 0.5 {
markLabel3.textColor = darkRed
} else {
markLabel3.textColor = lightBlue
}
markLabel3.font = UIFont.systemFont(ofSize: 16)
markLabel3.alpha = CGFloat(Double(result.faultNum)/Double(DataManager.shareManager.papersArray.count) + 0.3)
self.contentView.addSubview(label)
self.contentView.addSubview(markLabel1)
self.contentView.addSubview(markLabel2)
self.contentView.addSubview(markLabel3)
}
func clearCell(){
for view in self.contentView.subviews {
view.removeFromSuperview()
}
}
}
|
gpl-3.0
|
36af33d6e5e9f8658166629747e5200c
| 31.902439 | 116 | 0.63195 | 4.008915 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.