repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LeonZong/throb | Throb/Throb/LineView.swift | 1 | 897 | //
// LineView.swift
// Throb
//
// Created by 宗健平 on 2017/4/9.
// Copyright © 2017年 Leon Zong. All rights reserved.
//
import Foundation
import UIKit
class LineView: UIView {
var points:[CGPoint] = []
var yMid:CGFloat = 0.0
var x:Int = 0
func initPoints() {
self.x = Int(self.frame.width)
self.yMid = self.frame.height / 2
self.points.removeAll()
for i in 0..<x {
self.points.append(CGPoint(x: CGFloat(i), y: self.yMid))
}
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.beginPath()
context?.move(to: CGPoint(x: 0.0, y: self.yMid))
for p in self.points {
context?.addLine(to: p)
}
context?.setLineWidth(1.0)
context?.setStrokeColor(UIColor.white.cgColor)
context?.strokePath()
}
}
| mit | 215aefabfc3098cce8c90f9de41d7279 | 24.371429 | 68 | 0.577703 | 3.52381 | false | false | false | false |
ajaybeniwal/SwiftTransportApp | TransitFare/UIAlertAPI.swift | 1 | 1940 | //
// UIAlertAPI.swift
// TransitFare
//
// Created by ajaybeniwal203 on 19/2/16.
// Copyright © 2016 ajaybeniwal203. All rights reserved.
//
import UIKit
protocol ShowsAlert {}
extension UIViewController : ShowsAlert{
func showAlert(title:String = "Error", message: String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
func showAlertWithAction(title:String="Error" , message:String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title:"Cancel",style: .Cancel){
(action) in
}
alertController.addAction(cancelAction)
let OkAction = UIAlertAction(title: "OK", style: .Default){
(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(OkAction)
presentViewController(alertController, animated: true, completion: nil)
}
func showAlertWithActionCallback(title:String="Error" , message:String,callback:(UIAlertAction) -> Void){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title:"Cancel",style: .Cancel){
(action) in
}
alertController.addAction(cancelAction)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: callback)
alertController.addAction(OkAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | b8a3120eb38b9690a92704fe2a954d93 | 32.431034 | 109 | 0.637958 | 5.12963 | false | false | false | false |
FabrizioBrancati/BFKit-Swift | Sources/BFKit/Apple/UIKit/UITextField+Extensions.swift | 1 | 5815 | //
// UITextField+Extensions.swift
// BFKit-Swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2019 Fabrizio Brancati.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
// MARK: - UITextField extension
/// This extesion adds some useful functions to UITextField.
public extension UITextField {
// MARK: - Functions
/// Create an UITextField and set some parameters.
///
/// - Parameters:
/// - frame: TextField frame.
/// - placeholder: TextField text placeholder.
/// - font: TextField text font.
/// - textColor: TextField text color.
/// - returnKeyType: TextField return key type.
/// - keyboardType: TextField keyboard type.
/// - secure: Set if the TextField is secure or not.
/// - borderStyle: TextField border style.
/// - autocapitalizationType: TextField text capitalization.
/// - keyboardAppearance: TextField keyboard appearence.
/// - enablesReturnKeyAutomatically: Set if the TextField has to automatically enables the return key.
/// - clearButtonMode: TextField clear button mode.
/// - autoCorrectionType: TextField auto correction type.
/// - delegate: TextField delegate. Set nil if it has no delegate.
convenience init(frame: CGRect, placeholder: String, font: UIFont, textColor: UIColor, returnKeyType: UIReturnKeyType, keyboardType: UIKeyboardType, secure: Bool, borderStyle: UITextField.BorderStyle, autocapitalizationType: UITextAutocapitalizationType, keyboardAppearance: UIKeyboardAppearance, enablesReturnKeyAutomatically: Bool, clearButtonMode: UITextField.ViewMode, autocorrectionType: UITextAutocorrectionType, delegate: UITextFieldDelegate?) {
self.init(frame: frame)
self.borderStyle = borderStyle
self.autocorrectionType = autocorrectionType
self.clearButtonMode = clearButtonMode
self.keyboardType = keyboardType
self.autocapitalizationType = autocapitalizationType
self.placeholder = placeholder
self.textColor = textColor
self.returnKeyType = returnKeyType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
isSecureTextEntry = secure
self.keyboardAppearance = keyboardAppearance
self.font = font
self.delegate = delegate
}
/// Create an UITextField and set some parameters.
///
/// - Parameters:
/// - frame: TextField frame.
/// - placeholder: TextField text placeholder.
/// - font: TextField text font name.
/// - fontSize: TextField text size.
/// - textColor: TextField text color.
/// - returnKeyType: TextField return key type.
/// - keyboardType: TextField keyboard type.
/// - secure: Set if the TextField is secure or not.
/// - borderStyle: TextField border style.
/// - autocapitalizationType: TextField text capitalization.
/// - keyboardAppearance: TextField keyboard appearence.
/// - enablesReturnKeyAutomatically: Set if the TextField has to automatically enables the return key.
/// - clearButtonMode: TextField clear button mode.
/// - autoCorrectionType: TextField auto correction type.
/// - delegate: TextField delegate. Set nil if it has no delegate.
convenience init(frame: CGRect, placeholder: String, font: FontName, fontSize: CGFloat, textColor: UIColor, returnKeyType: UIReturnKeyType, keyboardType: UIKeyboardType, secure: Bool, borderStyle: UITextField.BorderStyle, autocapitalizationType: UITextAutocapitalizationType, keyboardAppearance: UIKeyboardAppearance, enablesReturnKeyAutomatically: Bool, clearButtonMode: UITextField.ViewMode, autocorrectionType: UITextAutocorrectionType, delegate: UITextFieldDelegate?) {
self.init(frame: frame)
self.borderStyle = borderStyle
self.autocorrectionType = autocorrectionType
self.clearButtonMode = clearButtonMode
self.keyboardType = keyboardType
self.autocapitalizationType = autocapitalizationType
self.placeholder = placeholder
self.textColor = textColor
self.returnKeyType = returnKeyType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
isSecureTextEntry = secure
self.keyboardAppearance = keyboardAppearance
self.font = UIFont(fontName: font, size: fontSize)
self.delegate = delegate
}
/// Paste the pasteboard text to UITextField.
func pasteFromPasteboard() {
text = UIPasteboard.getString()
}
/// Copy UITextField text to pasteboard.
func copyToPasteboard() {
guard let text = text else {
return
}
UIPasteboard.copy(text: text)
}
}
| mit | a74aaa6dcfdba175557d7d0c5e2c1b5a | 48.279661 | 477 | 0.71092 | 5.399257 | false | false | false | false |
AbelSu131/ios-charts | Charts/Classes/Data/BarChartDataSet.swift | 2 | 3753 | //
// BarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class BarChartDataSet: BarLineScatterCandleChartDataSet
{
/// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
public var barSpace: CGFloat = 0.15
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
public var barShadowColor = UIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
public var highLightAlpha = CGFloat(120.0 / 255.0)
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// array of labels used to describe the different values of the stacked bars
public var stackLabels: [String] = ["Stack"]
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label);
self.highlightColor = UIColor.blackColor();
self.calcStackSize(yVals as! [BarChartDataEntry]?);
self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry]?);
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! BarChartDataSet;
copy.barSpace = barSpace;
copy._stackSize = _stackSize;
copy.barShadowColor = barShadowColor;
copy.highLightAlpha = highLightAlpha;
copy._entryCountStacks = _entryCountStacks;
copy.stackLabels = stackLabels;
return copy;
}
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!)
{
_entryCountStacks = 0;
for (var i = 0; i < yVals.count; i++)
{
var vals = yVals[i].values;
if (vals == nil)
{
_entryCountStacks++;
}
else
{
_entryCountStacks += vals.count;
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(yVals: [BarChartDataEntry]!)
{
for (var i = 0; i < yVals.count; i++)
{
var vals = yVals[i].values;
if (vals != nil && vals.count > _stackSize)
{
_stackSize = vals.count;
}
}
}
/// Returns the maximum number of bars that can be stacked upon another in this DataSet.
public var stackSize: Int
{
return _stackSize;
}
/// Returns true if this DataSet is stacked (stacksize > 1) or not.
public var isStacked: Bool
{
return _stackSize > 1 ? true : false;
}
/// returns the overall entry count, including counting each stack-value individually
public var entryCountStacks: Int
{
return _entryCountStacks;
}
} | apache-2.0 | 4120f2da96a77fcfc85d725a945270d0 | 31.643478 | 148 | 0.620037 | 4.793103 | false | false | false | false |
Tsiems/mobile-sensing-apps | DrumTrainer/DrumTrainer/ViewController.swift | 1 | 7810 | //
// ViewController.swift
// DrumTrainer
//
// Created by Danh Nguyen on 12/6/16.
// Copyright © 2016 Danh Nguyen. All rights reserved.
//
import UIKit
import CoreMotion
class ViewController: UIViewController, URLSessionTaskDelegate {
@IBOutlet weak var gestureLabel: UILabel!
@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var secondButton: UIButton!
@IBOutlet weak var thirdButton: UIButton!
@IBOutlet weak var fourthButton: UIButton!
@IBOutlet weak var fifthButton: UIButton!
@IBOutlet weak var dsidLabel: UITextField!
var session = URLSession()
let cmMotionManager = CMMotionManager()
let backQueue = OperationQueue()
var ringBuffer = RingBuffer()
var orientationBuffer = RingBuffer()
let magValue = 1.0
var numDataPoints = 0
let gestures = ["Gesture 1", "Gesture 2", "Gesture 3", "Gesture 4", "Gesture 5"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print()
// setup URLSession
let sessionConfig = URLSessionConfiguration.ephemeral
sessionConfig.timeoutIntervalForRequest = 5.0
sessionConfig.timeoutIntervalForResource = 8.0
sessionConfig.httpMaximumConnectionsPerHost = 1
self.session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
self.startCMMonitoring()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
override func viewWillDisappear(_ animated: Bool) {
self.cmMotionManager.stopDeviceMotionUpdates()
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prepareForSample(gestureName:String) {
self.gestureLabel.text = "\(gestureName)"
let fftVector = (self.orientationBuffer.getDataAsVector()) as NSArray
self.sendFeatureArray(data: fftVector, label: self.gestureLabel.text!)
}
func handleMotion(motion:CMDeviceMotion?, error:Error?)->Void{
self.ringBuffer.addNewData(Float((motion?.userAcceleration.x)!), withY: Float((motion?.userAcceleration.y)!), withZ: Float((motion?.userAcceleration.z)!))
//
self.orientationBuffer.addNewData(Float((motion?.attitude.pitch)!), withY: Float((motion?.attitude.roll)!), withZ: Float((motion?.attitude.yaw)!))
// let mag = fabs((motion?.userAcceleration.x)!)+fabs((motion?.userAcceleration.y)!)+fabs((motion?.userAcceleration.z)!)
//
// if(mag > self.magValue) {
// print(mag)
// self.backQueue.addOperation({() -> Void in self.motionEventOccurred()})
// }
}
func startCMMonitoring(){
if self.cmMotionManager.isDeviceMotionAvailable {
// update from this queue
self.cmMotionManager.deviceMotionUpdateInterval = UPDATE_INTERVAL
self.cmMotionManager.startDeviceMotionUpdates(to: backQueue, withHandler:self.handleMotion)
}
}
func motionEventOccurred() {
// let data = self.ringBuffer.getDataAsVector() as NSArray
//
// if data[0] as! Double == 0.0 {
// print("not full full")
// } else {
//
// //get the FFT of both buffers and add them up for feature data
// let fftVector = (self.orientationBuffer.getDataAsVector()) as NSArray
//
// self.sendFeatureArray(data: fftVector, label: self.gestureLabel.text!)
// //self.sendFeatureArray(data: data, label: self.gestureLabel.text!)
// }
}
func postFeatureHandler(data:Data?, urlResponse:URLResponse?, error:Error?) -> Void{
if(!(error != nil)){
print(urlResponse!)
let responseData = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
print(responseData ?? "No data")
} else{
print(error!)
}
}
func sendFeatureArray(data:NSArray, label:String) {
let baseUrl = "\(SERVER_URL)/AddDataPoint"
let postUrl = NSURL(string: baseUrl)
self.numDataPoints = self.numDataPoints + 1
let jsonUpload:NSDictionary = ["feature": data, "label": label, "dsid": DSID]
let requestBody = try! JSONSerialization.data(withJSONObject: jsonUpload, options: JSONSerialization.WritingOptions.prettyPrinted)
var request = URLRequest(url: postUrl as! URL)
request.httpBody = requestBody
request.httpMethod = "POST"
let postTask = self.session.dataTask(with: request, completionHandler: postFeatureHandler)
postTask.resume()
print(self.numDataPoints)
}
@IBAction func sendUpdate(_ sender: Any) {
let baseUrl = "\(SERVER_URL)/UpdateModel"
let postUrl = NSURL(string: baseUrl)
self.numDataPoints = self.numDataPoints + 1
let jsonUpload:NSDictionary = ["dsid": DSID]
let requestBody = try! JSONSerialization.data(withJSONObject: jsonUpload, options: JSONSerialization.WritingOptions.prettyPrinted)
var request = URLRequest(url: postUrl as! URL)
request.httpBody = requestBody
request.httpMethod = "POST"
let postTask = self.session.dataTask(with: request, completionHandler: postFeatureHandler)
postTask.resume()
}
@IBAction func trainFirst(_ sender: Any) {
// self.firstButton.isEnabled = false
// self.secondButton.isEnabled = true
// self.thirdButton.isEnabled = true
// self.fourthButton.isEnabled = true
// self.fifthButton.isEnabled = true
prepareForSample(gestureName: gestures[0])
}
@IBAction func trainSecond(_ sender: Any) {
// self.firstButton.isEnabled = true
// self.secondButton.isEnabled = false
// self.thirdButton.isEnabled = true
// self.fourthButton.isEnabled = true
// self.fifthButton.isEnabled = true
prepareForSample(gestureName: gestures[1])
}
@IBAction func trainThird(_ sender: Any) {
// self.firstButton.isEnabled = true
// self.secondButton.isEnabled = true
// self.thirdButton.isEnabled = false
// self.fourthButton.isEnabled = true
// self.fifthButton.isEnabled = true
prepareForSample(gestureName: gestures[2])
}
@IBAction func trainFourth(_ sender: Any) {
// self.firstButton.isEnabled = true
// self.secondButton.isEnabled = true
// self.thirdButton.isEnabled = true
// self.fourthButton.isEnabled = false
// self.fifthButton.isEnabled = true
prepareForSample(gestureName: gestures[3])
}
@IBAction func trainFifth(_ sender: Any) {
// self.firstButton.isEnabled = true
// self.secondButton.isEnabled = true
// self.thirdButton.isEnabled = true
// self.fourthButton.isEnabled = true
// self.fifthButton.isEnabled = false
prepareForSample(gestureName: gestures[4])
}
@IBAction func updateDSID(_ sender: Any) {
DSID = Int(self.dsidLabel.text!)!
view.endEditing(true)
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
}
| mit | 4653780b9ae6635cf865622083b8e3d5 | 34.495455 | 162 | 0.633116 | 4.741348 | false | false | false | false |
DianQK/TransitionTreasury | TransitionAnimation/TransitionAnimationHelper.swift | 1 | 3510 | //
// TransitionAnimationHelper.swift
// TransitionTreasury
//
// Created by DianQK on 12/30/15.
// Copyright © 2016 TransitionTreasury. All rights reserved.
//
import UIKit
/**
TransitionTreasury's CAAnimation Enum.
- opacity: layer.opacity
*/
public enum TRKeyPath: String {
case opacity = "opacity"
case bounds = "bounds"
case bounds_size = "bounds.size"
case bounds_height = "bounds.height"
case bounds_width = "bounds.width"
case position = "position"
case transform = "transform"
case strokeEnd = "strokeEnd"
case path = "path"
}
// MARK: - Safety CAAnimation
public extension CABasicAnimation {
/**
TransitionTreasury's CABasicAnimation Init Method.
- parameter path: TRKeyPath
- returns: CAAnimation
*/
convenience init(tr_keyPath path: TRKeyPath?) {
self.init(keyPath: path?.rawValue)
}
}
public extension CGSize {
/**
Fit width without shape change.
*/
func tr_widthFit(_ width: CGFloat) -> CGSize {
let widthPresent = width / self.width
return CGSize(width: width, height: widthPresent * height)
}
/**
Fit height without shape change.
*/
func tr_heightFit(_ height: CGFloat) -> CGSize {
let heightPresent = height / self.height
return CGSize(width: heightPresent * width, height: height)
}
/**
Fill width without shape change.
*/
func tr_widthFill(_ width: CGFloat) -> CGSize {
switch self.width >= width {
case true :
return self
case false :
return tr_widthFit(width)
}
}
/**
Fit height without shape change.
*/
func tr_heightFill(_ height: CGFloat) -> CGSize {
switch self.height >= height {
case true :
return self
case false :
return tr_heightFit(height)
}
}
}
public extension UIScreen {
/// Get screen center.
var tr_center: CGPoint {
get {
return CGPoint(x: bounds.width / 2, y: bounds.height / 2)
}
}
}
public extension CGRect {
/**
Return a rectangle that precent the source rectangle, with the same center point.
*/
func tr_shape(_ precent: CGFloat) -> CGRect {
return self.insetBy(dx: width * (1 - precent), dy: height * (1 - precent))
}
/**
Just F**k Xcode.
*/
var tr_ns_value: NSValue {
get {
return NSValue(cgRect: self)
}
}
}
public extension UIView {
/**
Create copy contents view.
*/
func tr_copyWithContents() -> UIView {
let view = UIView(frame: frame)
view.layer.contents = layer.contents
view.layer.contentsGravity = layer.contentsGravity
view.layer.contentsScale = layer.contentsScale
view.tag = tag
return view
}
/**
Create copy snapshot view.
*/
func tr_copyWithSnapshot() -> UIView {
let view = snapshotView(afterScreenUpdates: false)
view?.frame = frame
return view!
}
/**
Add view with convert point.
*/
func tr_addSubview(_ view: UIView, convertFrom fromView: UIView) {
view.layer.position = convert(fromView.layer.position, from: fromView.superview)
addSubview(view)
}
}
public extension CATransform3D {
/**
Just F**k Xcode.
*/
var tr_ns_value: NSValue {
get {
return NSValue(caTransform3D: self)
}
}
}
| mit | 14ef16f55e3f7322766235cde6214a4c | 23.368056 | 88 | 0.588202 | 4.279268 | false | false | false | false |
ltebean/LTInfiniteScrollView-Swift | LTInfiniteScrollView-Swift/ViewController.swift | 1 | 2790 | //
// ViewController.swift
// LTInfiniteScrollView-Swift
//
// Created by ltebean on 16/1/8.
// Copyright © 2016年 io. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let screenWidth = UIScreen.main.bounds.size.width
@IBOutlet weak var scrollView: LTInfiniteScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
scrollView.dataSource = self
scrollView.delegate = self
scrollView.maxScrollDistance = 5
let size = screenWidth / CGFloat(numberOfVisibleViews())
scrollView.contentInset.left = screenWidth / 2 - size / 2
scrollView.contentInset.right = screenWidth / 2 - size / 2
view.addSubview(scrollView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
scrollView.reloadData(initialIndex: 0)
}
}
extension ViewController: LTInfiniteScrollViewDataSource {
func viewAtIndex(_ index: Int, reusingView view: UIView?) -> UIView {
if let label = view as? UILabel {
label.text = "\(index)"
return label
}
else {
let size = screenWidth / CGFloat(numberOfVisibleViews())
let label = UILabel(frame: CGRect(x: 0, y: 0, width: size, height: size))
label.textAlignment = .center
label.backgroundColor = UIColor.darkGray
label.textColor = UIColor.white
label.layer.cornerRadius = size / 2
label.layer.masksToBounds = true
label.text = "\(index)"
return label
}
}
func numberOfViews() -> Int {
return 10
}
func numberOfVisibleViews() -> Int {
return 5
}
}
extension ViewController: LTInfiniteScrollViewDelegate {
func updateView(_ view: UIView, withProgress progress: CGFloat, scrollDirection direction: LTInfiniteScrollView.ScrollDirection) {
let size = screenWidth / CGFloat(numberOfVisibleViews())
var transform = CGAffineTransform.identity
// scale
let scale = (1.4 - 0.3 * (fabs(progress)))
transform = transform.scaledBy(x: scale, y: scale)
// translate
var translate = size / 4 * progress
if progress > 1 {
translate = size / 4
}
else if progress < -1 {
translate = -size / 4
}
transform = transform.translatedBy(x: translate, y: 0)
view.transform = transform
}
func scrollViewDidScrollToIndex(_ scrollView: LTInfiniteScrollView, index: Int) {
print("scroll to index: \(index)")
}
}
| mit | f2e6f0be5fcf3f422b20cd2b596f9623 | 28.03125 | 134 | 0.603516 | 5.01259 | false | false | false | false |
kstaring/swift | test/IRGen/sil_witness_tables.swift | 4 | 3824 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module -o %t %S/sil_witness_tables_external_conformance.swift
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -I %t -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
import sil_witness_tables_external_conformance
// FIXME: This should be a SIL test, but we can't parse sil_witness_tables
// yet.
protocol A {}
protocol P {
associatedtype Assoc: A
static func staticMethod()
func instanceMethod()
}
protocol Q : P {
func qMethod()
}
protocol QQ {
func qMethod()
}
struct AssocConformer: A {}
struct Conformer: Q, QQ {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@_TWPV39sil_witness_tables_external_conformance17ExternalConformerS_9ExternalPS_]] = external global i8*, align 8
// CHECK: [[CONFORMER_Q_WITNESS_TABLE:@_TWPV18sil_witness_tables9ConformerS_1QS_]] = hidden constant [2 x i8*] [
// CHECK: i8* bitcast ([4 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@_TWPV18sil_witness_tables9ConformerS_1PS_]] to i8*),
// CHECK: i8* bitcast (void (%V18sil_witness_tables9Conformer*, %swift.type*, i8**)* @_TTWV18sil_witness_tables9ConformerS_1QS_FS1_7qMethod{{.*}} to i8*)
// CHECK: ]
// CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden constant [4 x i8*] [
// CHECK: i8* bitcast (%swift.type* ()* @_TMaV18sil_witness_tables14AssocConformer to i8*),
// CHECK: i8* bitcast (i8** ()* @_TWaV18sil_witness_tables14AssocConformerS_1AS_ to i8*)
// CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @_TTWV18sil_witness_tables9ConformerS_1PS_ZFS1_12staticMethod{{.*}} to i8*),
// CHECK: i8* bitcast (void (%V18sil_witness_tables9Conformer*, %swift.type*, i8**)* @_TTWV18sil_witness_tables9ConformerS_1PS_FS1_14instanceMethod{{.*}} to i8*)
// CHECK: ]
// CHECK: [[CONFORMER2_P_WITNESS_TABLE:@_TWPV18sil_witness_tables10Conformer2S_1PS_]] = hidden constant [4 x i8*]
struct Conformer2: Q {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK-LABEL: define hidden void @_TF18sil_witness_tables7erasureFT1cVS_9Conformer_PS_2QQ_(%P18sil_witness_tables2QQ_* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %P18sil_witness_tables2QQ_, %P18sil_witness_tables2QQ_* %0, i32 0, i32 2
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@_TWP.*]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8
func erasure(c c: Conformer) -> QQ {
return c
}
// CHECK-LABEL: define hidden void @_TF18sil_witness_tables15externalErasureFT1cV39sil_witness_tables_external_conformance17ExternalConformer_PS0_9ExternalP_(%P39sil_witness_tables_external_conformance9ExternalP_* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %P39sil_witness_tables_external_conformance9ExternalP_, %P39sil_witness_tables_external_conformance9ExternalP_* %0, i32 0, i32 2
// CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8
func externalErasure(c c: ExternalConformer) -> ExternalP {
return c
}
// FIXME: why do these have different linkages?
// CHECK-LABEL: define hidden %swift.type* @_TMaV18sil_witness_tables14AssocConformer()
// CHECK: ret %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @_TMfV18sil_witness_tables14AssocConformer, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define hidden i8** @_TWaV18sil_witness_tables9ConformerS_1PS_()
// CHECK: ret i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @_TWPV18sil_witness_tables9ConformerS_1PS_, i32 0, i32 0)
| apache-2.0 | 10f75b867d8680a22762d755b30e59d3 | 46.8 | 237 | 0.710513 | 3.273973 | false | false | false | false |
ikesyo/Swiftz | Swiftz/Const.swift | 3 | 1085 | //
// Const.swift
// Swiftz
//
// Created by Robert Widmann on 8/19/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
// The Constant Functor ignores fmap.
public struct Const<V, I> {
private let a : () -> V
public init(@autoclosure(escaping) _ aa : () -> V) {
a = aa
}
public var runConst : V {
return a()
}
}
extension Const : Bifunctor {
public typealias L = V
public typealias R = I
public typealias D = Any
public typealias PAC = Const<L, R>
public typealias PAD = Const<V, D>
public typealias PBC = Const<B, R>
public typealias PBD = Const<B, D>
public func bimap<B, D>(f : V -> B, _ : I -> D) -> Const<B, D> {
return Const<B, D>(f(self.runConst))
}
public func leftMap<B>(f : V -> B) -> Const<B, I> {
return self.bimap(f, identity)
}
public func rightMap<D>(g : I -> D) -> Const<V, D> {
return self.bimap(identity, g)
}
}
extension Const : Functor {
public typealias A = V
public typealias B = Any
public typealias FB = Const<V, I>
public func fmap<B>(f : V -> B) -> Const<V, I> {
return Const<V, I>(self.runConst)
}
}
| bsd-3-clause | 8e42ddd469142feb95a12a2233c22b0e | 19.45283 | 65 | 0.618081 | 2.751269 | false | false | false | false |
mossila/SwiftRealtimeUpdateFromSocket | SocketBase/ViewController.swift | 1 | 1782 | //
// ViewController.swift
// SocketBase
//
// Created by Sutean Rutjanalard on 4/29/2559 BE.
// Copyright © 2559 Sutean Rutjanalard. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
lazy var mySocket: MySocket! = MySocket.sharedInstance
private var myContext = 0
@IBOutlet var labels: [UILabel]!
private var alreadyUpdateUI = false
private var waitForUpdateUI = false
private let framePerSecond = 60.0
private var lastUpdateIndex = 0
private var maxUpdateIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
mySocket.startConnect("localhost", port: 1234)
maxUpdateIndex = labels.count
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setupKVO()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
teardownKVO()
}
private func setupKVO() {
mySocket?.addObserver(self, forKeyPath: "lastMessage", options: .New, context: &myContext)
}
private func teardownKVO() {
mySocket?.removeObserver(self, forKeyPath: "lastMessage")
}
private func update() {
if alreadyUpdateUI { return }
labels[lastUpdateIndex].text = mySocket.lastMessage
lastUpdateIndex = (lastUpdateIndex + 1) % maxUpdateIndex
alreadyUpdateUI = true
RunAfterDelay(1.0 / framePerSecond) {
[unowned self] in self.alreadyUpdateUI = false
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &myContext {
print("\(mySocket.lastMessage)")
dispatch_async(dispatch_get_main_queue()) {
[unowned self] in self.update()
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
}
| apache-2.0 | 250b32ad9df55b4c098d4203e8fd1877 | 29.186441 | 153 | 0.737226 | 3.679752 | false | false | false | false |
uber/RIBs | ios/tutorials/tutorial3/TicTacToe/LoggedIn/LoggedInBuilder.swift | 1 | 1884 | //
// Copyright (c) 2017. Uber Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import RIBs
protocol LoggedInDependency: Dependency {
var loggedInViewController: LoggedInViewControllable { get }
}
final class LoggedInComponent: Component<LoggedInDependency> {
fileprivate var loggedInViewController: LoggedInViewControllable {
return dependency.loggedInViewController
}
}
// MARK: - Builder
protocol LoggedInBuildable: Buildable {
func build(withListener listener: LoggedInListener) -> LoggedInRouting
}
final class LoggedInBuilder: Builder<LoggedInDependency>, LoggedInBuildable {
override init(dependency: LoggedInDependency) {
super.init(dependency: dependency)
}
func build(withListener listener: LoggedInListener) -> LoggedInRouting {
let component = LoggedInComponent(dependency: dependency)
let interactor = LoggedInInteractor()
interactor.listener = listener
let offGameBuilder = OffGameBuilder(dependency: component)
let ticTacToeBuilder = TicTacToeBuilder(dependency: component)
return LoggedInRouter(interactor: interactor,
viewController: component.loggedInViewController,
offGameBuilder: offGameBuilder,
ticTacToeBuilder: ticTacToeBuilder)
}
}
| apache-2.0 | 41102a0922c5a58622661a48eb3e3ba4 | 33.888889 | 79 | 0.717622 | 5.010638 | false | false | false | false |
jathu/UIImageColors | UIImageColors/Sources/UIImageColors.swift | 1 | 11091 | //
// UIImageColors.swift
// https://github.com/jathu/UIImageColors
//
// Created by Jathu Satkunarajah (@jathu) on 2015-06-11 - Toronto
// Based on Cocoa version by Panic Inc. - Portland
//
#if os(OSX)
import AppKit
public typealias UIImage = NSImage
public typealias UIColor = NSColor
#else
import UIKit
#endif
public struct UIImageColors {
public var background: UIColor!
public var primary: UIColor!
public var secondary: UIColor!
public var detail: UIColor!
public init(background: UIColor, primary: UIColor, secondary: UIColor, detail: UIColor) {
self.background = background
self.primary = primary
self.secondary = secondary
self.detail = detail
}
}
public enum UIImageColorsQuality: CGFloat {
case lowest = 50 // 50px
case low = 100 // 100px
case high = 250 // 250px
case highest = 0 // No scale
}
fileprivate struct UIImageColorsCounter {
let color: Double
let count: Int
init(color: Double, count: Int) {
self.color = color
self.count = count
}
}
/*
Extension on double that replicates UIColor methods. We DO NOT want these
exposed outside of the library because they don't make sense outside of the
context of UIImageColors.
*/
fileprivate extension Double {
private var r: Double {
return fmod(floor(self/1000000),1000000)
}
private var g: Double {
return fmod(floor(self/1000),1000)
}
private var b: Double {
return fmod(self,1000)
}
var isDarkColor: Bool {
return (r*0.2126) + (g*0.7152) + (b*0.0722) < 127.5
}
var isBlackOrWhite: Bool {
return (r > 232 && g > 232 && b > 232) || (r < 23 && g < 23 && b < 23)
}
func isDistinct(_ other: Double) -> Bool {
let _r = self.r
let _g = self.g
let _b = self.b
let o_r = other.r
let o_g = other.g
let o_b = other.b
return (fabs(_r-o_r) > 63.75 || fabs(_g-o_g) > 63.75 || fabs(_b-o_b) > 63.75)
&& !(fabs(_r-_g) < 7.65 && fabs(_r-_b) < 7.65 && fabs(o_r-o_g) < 7.65 && fabs(o_r-o_b) < 7.65)
}
func with(minSaturation: Double) -> Double {
// Ref: https://en.wikipedia.org/wiki/HSL_and_HSV
// Convert RGB to HSV
let _r = r/255
let _g = g/255
let _b = b/255
var H, S, V: Double
let M = fmax(_r,fmax(_g, _b))
var C = M-fmin(_r,fmin(_g, _b))
V = M
S = V == 0 ? 0:C/V
if minSaturation <= S {
return self
}
if C == 0 {
H = 0
} else if _r == M {
H = fmod((_g-_b)/C, 6)
} else if _g == M {
H = 2+((_b-_r)/C)
} else {
H = 4+((_r-_g)/C)
}
if H < 0 {
H += 6
}
// Back to RGB
C = V*minSaturation
let X = C*(1-fabs(fmod(H,2)-1))
var R, G, B: Double
switch H {
case 0...1:
R = C
G = X
B = 0
case 1...2:
R = X
G = C
B = 0
case 2...3:
R = 0
G = C
B = X
case 3...4:
R = 0
G = X
B = C
case 4...5:
R = X
G = 0
B = C
case 5..<6:
R = C
G = 0
B = X
default:
R = 0
G = 0
B = 0
}
let m = V-C
return (floor((R + m)*255)*1000000)+(floor((G + m)*255)*1000)+floor((B + m)*255)
}
func isContrasting(_ color: Double) -> Bool {
let bgLum = (0.2126*r)+(0.7152*g)+(0.0722*b)+12.75
let fgLum = (0.2126*color.r)+(0.7152*color.g)+(0.0722*color.b)+12.75
if bgLum > fgLum {
return 1.6 < bgLum/fgLum
} else {
return 1.6 < fgLum/bgLum
}
}
var uicolor: UIColor {
return UIColor(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
}
var pretty: String {
return "\(Int(self.r)), \(Int(self.g)), \(Int(self.b))"
}
}
extension UIImage {
#if os(OSX)
private func resizeForUIImageColors(newSize: CGSize) -> UIImage? {
let frame = CGRect(origin: .zero, size: newSize)
guard let representation = bestRepresentation(for: frame, context: nil, hints: nil) else {
return nil
}
let result = NSImage(size: newSize, flipped: false, drawingHandler: { (_) -> Bool in
return representation.draw(in: frame)
})
return result
}
#else
private func resizeForUIImageColors(newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
defer {
UIGraphicsEndImageContext()
}
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
guard let result = UIGraphicsGetImageFromCurrentImageContext() else {
fatalError("UIImageColors.resizeForUIImageColors failed: UIGraphicsGetImageFromCurrentImageContext returned nil.")
}
return result
}
#endif
public func getColors(quality: UIImageColorsQuality = .high, _ completion: @escaping (UIImageColors?) -> Void) {
DispatchQueue.global().async {
let result = self.getColors(quality: quality)
DispatchQueue.main.async {
completion(result)
}
}
}
public func getColors(quality: UIImageColorsQuality = .high) -> UIImageColors? {
var scaleDownSize: CGSize = self.size
if quality != .highest {
if self.size.width < self.size.height {
let ratio = self.size.height/self.size.width
scaleDownSize = CGSize(width: quality.rawValue/ratio, height: quality.rawValue)
} else {
let ratio = self.size.width/self.size.height
scaleDownSize = CGSize(width: quality.rawValue, height: quality.rawValue/ratio)
}
}
guard let resizedImage = self.resizeForUIImageColors(newSize: scaleDownSize) else { return nil }
#if os(OSX)
guard let cgImage = resizedImage.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return nil }
#else
guard let cgImage = resizedImage.cgImage else { return nil }
#endif
let width: Int = cgImage.width
let height: Int = cgImage.height
let threshold = Int(CGFloat(height)*0.01)
var proposed: [Double] = [-1,-1,-1,-1]
guard let data = CFDataGetBytePtr(cgImage.dataProvider!.data) else {
fatalError("UIImageColors.getColors failed: could not get cgImage data.")
}
let imageColors = NSCountedSet(capacity: width*height)
for x in 0..<width {
for y in 0..<height {
let pixel: Int = (y * cgImage.bytesPerRow) + (x * 4)
if 127 <= data[pixel+3] {
imageColors.add((Double(data[pixel+2])*1000000)+(Double(data[pixel+1])*1000)+(Double(data[pixel])))
}
}
}
let sortedColorComparator: Comparator = { (main, other) -> ComparisonResult in
let m = main as! UIImageColorsCounter, o = other as! UIImageColorsCounter
if m.count < o.count {
return .orderedDescending
} else if m.count == o.count {
return .orderedSame
} else {
return .orderedAscending
}
}
var enumerator = imageColors.objectEnumerator()
var sortedColors = NSMutableArray(capacity: imageColors.count)
while let K = enumerator.nextObject() as? Double {
let C = imageColors.count(for: K)
if threshold < C {
sortedColors.add(UIImageColorsCounter(color: K, count: C))
}
}
sortedColors.sort(comparator: sortedColorComparator)
var proposedEdgeColor: UIImageColorsCounter
if 0 < sortedColors.count {
proposedEdgeColor = sortedColors.object(at: 0) as! UIImageColorsCounter
} else {
proposedEdgeColor = UIImageColorsCounter(color: 0, count: 1)
}
if proposedEdgeColor.color.isBlackOrWhite && 0 < sortedColors.count {
for i in 1..<sortedColors.count {
let nextProposedEdgeColor = sortedColors.object(at: i) as! UIImageColorsCounter
if Double(nextProposedEdgeColor.count)/Double(proposedEdgeColor.count) > 0.3 {
if !nextProposedEdgeColor.color.isBlackOrWhite {
proposedEdgeColor = nextProposedEdgeColor
break
}
} else {
break
}
}
}
proposed[0] = proposedEdgeColor.color
enumerator = imageColors.objectEnumerator()
sortedColors.removeAllObjects()
sortedColors = NSMutableArray(capacity: imageColors.count)
let findDarkTextColor = !proposed[0].isDarkColor
while var K = enumerator.nextObject() as? Double {
K = K.with(minSaturation: 0.15)
if K.isDarkColor == findDarkTextColor {
let C = imageColors.count(for: K)
sortedColors.add(UIImageColorsCounter(color: K, count: C))
}
}
sortedColors.sort(comparator: sortedColorComparator)
for color in sortedColors {
let color = (color as! UIImageColorsCounter).color
if proposed[1] == -1 {
if color.isContrasting(proposed[0]) {
proposed[1] = color
}
} else if proposed[2] == -1 {
if !color.isContrasting(proposed[0]) || !proposed[1].isDistinct(color) {
continue
}
proposed[2] = color
} else if proposed[3] == -1 {
if !color.isContrasting(proposed[0]) || !proposed[2].isDistinct(color) || !proposed[1].isDistinct(color) {
continue
}
proposed[3] = color
break
}
}
let isDarkBackground = proposed[0].isDarkColor
for i in 1...3 {
if proposed[i] == -1 {
proposed[i] = isDarkBackground ? 255255255:0
}
}
return UIImageColors(
background: proposed[0].uicolor,
primary: proposed[1].uicolor,
secondary: proposed[2].uicolor,
detail: proposed[3].uicolor
)
}
}
| mit | a7b6fc242591410b87ed9b4a91a8e5de | 30.688571 | 134 | 0.514291 | 4.404686 | false | false | false | false |
kathypizza330/RamMap | ARKit+CoreLocation/Source/LocationNode.swift | 1 | 4692 | //
// LocationNode.swift
// ARKit+CoreLocation
//
// Created by Andrew Hart on 02/07/2017.
// Copyright © 2017 Project Dent. All rights reserved.
//
import Foundation
import SceneKit
import CoreLocation
///A location node can be added to a scene using a coordinate.
///Its scale and position should not be adjusted, as these are used for scene layout purposes
///To adjust the scale and position of items within a node, you can add them to a child node and adjust them there
open class LocationNode: SCNNode {
///Location can be changed and confirmed later by SceneLocationView.
public var location: CLLocation!
///Whether the location of the node has been confirmed.
///This is automatically set to true when you create a node using a location.
///Otherwise, this is false, and becomes true once the user moves 100m away from the node,
///except when the locationEstimateMethod is set to use Core Location data only,
///as then it becomes true immediately.
public var locationConfirmed = false
///Whether a node's position should be adjusted on an ongoing basis
///based on its' given location.
///This only occurs when a node's location is within 100m of the user.
///Adjustment doesn't apply to nodes without a confirmed location.
///When this is set to false, the result is a smoother appearance.
///When this is set to true, this means a node may appear to jump around
///as the user's location estimates update,
///but the position is generally more accurate.
///Defaults to true.
public var continuallyAdjustNodePositionWhenWithinRange = false
///Whether a node's position and scale should be updated automatically on a continual basis.
///This should only be set to false if you plan to manually update position and scale
///at regular intervals. You can do this with `SceneLocationView`'s `updatePositionOfLocationNode`.
public var continuallyUpdatePositionAndScale = true
public init(location: CLLocation?) {
self.location = location
self.locationConfirmed = location != nil
super.init()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
open class LocationAnnotationNode: LocationNode {
///An image to use for the annotation
///When viewed from a distance, the annotation will be seen at the size provided
///e.g. if the size is 100x100px, the annotation will take up approx 100x100 points on screen.
public let image: UIImage
///Subnodes and adjustments should be applied to this subnode
///Required to allow scaling at the same time as having a 2D 'billboard' appearance
public let annotationNode: SCNNode
public let textNode: SCNNode
///Whether the node should be scaled relative to its distance from the camera
///Default value (false) scales it to visually appear at the same size no matter the distance
///Setting to true causes annotation nodes to scale like a regular node
///Scaling relative to distance may be useful with local navigation-based uses
///For landmarks in the distance, the default is correct
public var scaleRelativeToDistance = true
public init(location: CLLocation?, image: UIImage, name: String) {
self.image = image
// adjust the size of image
let plane = SCNPlane(width: image.size.width / 900, height: image.size.height / 900)
plane.firstMaterial!.diffuse.contents = image
plane.firstMaterial!.lightingModel = .constant
annotationNode = SCNNode()
textNode = SCNNode()
textNode.geometry = SCNText(string: " " + name, extrusionDepth:0.0)
textNode.name = name
// adjust the size of text
textNode.scale = SCNVector3(0.08, 0.08, 0)
// textNode.position = SCNVector3(0, -3, 0)
// center the textNode
let (min, max) = textNode.boundingBox
let dx = min.x + 0.5 * (max.x - min.x)
let dy = min.y + 0.5 * (max.y - min.y)
let dz = min.z + 0.5 * (max.z - min.z)
textNode.pivot = SCNMatrix4MakeTranslation(0, dy, dz)
annotationNode.geometry = plane
super.init(location: location)
let billboardConstraint = SCNBillboardConstraint()
billboardConstraint.freeAxes = SCNBillboardAxis.Y
constraints = [billboardConstraint]
addChildNode(annotationNode)
addChildNode(textNode)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 4e02640a4f53485b94a60b855345eff6 | 41.645455 | 114 | 0.683223 | 4.585533 | false | false | false | false |
mshhmzh/firefox-ios | SyncTests/HistorySynchronizerTests.swift | 5 | 8832 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Storage
@testable import Sync
import XCGLogger
import Deferred
import XCTest
private let log = Logger.syncLogger
class MockSyncDelegate: SyncDelegate {
func displaySentTabForURL(URL: NSURL, title: String) {
}
}
class DBPlace: Place {
var isDeleted = false
var shouldUpload = false
var serverModified: Timestamp? = nil
var localModified: Timestamp? = nil
}
class MockSyncableHistory {
var wasReset: Bool = false
var places = [GUID: DBPlace]()
var remoteVisits = [GUID: Set<Visit>]()
var localVisits = [GUID: Set<Visit>]()
init() {
}
private func placeForURL(url: String) -> DBPlace? {
return findOneValue(places) { $0.url == url }
}
}
extension MockSyncableHistory: ResettableSyncStorage {
func resetClient() -> Success {
self.wasReset = true
return succeed()
}
}
extension MockSyncableHistory: SyncableHistory {
// TODO: consider comparing the timestamp to local visits, perhaps opting to
// not delete the local place (and instead to give it a new GUID) if the visits
// are newer than the deletion.
// Obviously this'll behave badly during reconciling on other devices:
// they might apply our new record first, renaming their local copy of
// the old record with that URL, and thus bring all the old visits back to life.
// Desktop just finds by GUID then deletes by URL.
func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Deferred<Maybe<()>> {
self.remoteVisits.removeValueForKey(guid)
self.localVisits.removeValueForKey(guid)
self.places.removeValueForKey(guid)
return succeed()
}
func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
let has = self.places.values.contains({ $0.serverModified != nil })
return deferMaybe(has)
}
/**
* This assumes that the provided GUID doesn't already map to a different URL!
*/
func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success {
// Find by URL.
if let existing = self.placeForURL(url) {
let p = DBPlace(guid: guid, url: url, title: existing.title)
p.isDeleted = existing.isDeleted
p.serverModified = existing.serverModified
p.localModified = existing.localModified
self.places.removeValueForKey(existing.guid)
self.places[guid] = p
}
return succeed()
}
func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success {
// Strip out existing local visits.
// We trust that an identical timestamp and type implies an identical visit.
var remote = Set<Visit>(visits)
if let local = self.localVisits[guid] {
remote.subtractInPlace(local)
}
// Visits are only ever added.
if var r = self.remoteVisits[guid] {
r.unionInPlace(remote)
} else {
self.remoteVisits[guid] = remote
}
return succeed()
}
func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// See if we've already applied this one.
if let existingModified = self.places[place.guid]?.serverModified {
if existingModified == modified {
log.debug("Already seen unchanged record \(place.guid).")
return deferMaybe(place.guid)
}
}
// Make sure that we collide with any matching URLs -- whether locally
// modified or not. Then overwrite the upstream and merge any local changes.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> {
if let existingLocal = self.places[place.guid] {
if existingLocal.shouldUpload {
log.debug("Record \(existingLocal.guid) modified locally and remotely.")
log.debug("Local modified: \(existingLocal.localModified); remote: \(modified).")
// Should always be a value if marked as changed.
if existingLocal.localModified! > modified {
// Nothing to do: it's marked as changed.
log.debug("Discarding remote non-visit changes!")
self.places[place.guid]?.serverModified = modified
return deferMaybe(place.guid)
} else {
log.debug("Discarding local non-visit changes!")
self.places[place.guid]?.shouldUpload = false
}
} else {
log.debug("Remote record exists, but has no local changes.")
}
} else {
log.debug("Remote record doesn't exist locally.")
}
// Apply the new remote record.
let p = DBPlace(guid: place.guid, url: place.url, title: place.title)
p.localModified = NSDate.now()
p.serverModified = modified
p.isDeleted = false
self.places[place.guid] = p
return deferMaybe(place.guid)
}
}
func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// TODO.
return deferMaybe([])
}
func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// TODO.
return deferMaybe([])
}
func markAsSynchronized(_: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// TODO
return deferMaybe(0)
}
func markAsDeleted(_: [GUID]) -> Success {
// TODO
return succeed()
}
func onRemovedAccount() -> Success {
// TODO
return succeed()
}
func doneApplyingRecordsAfterDownload() -> Success {
return succeed()
}
func doneUpdatingMetadataAfterUpload() -> Success {
return succeed()
}
}
class HistorySynchronizerTests: XCTestCase {
private func applyRecords(records: [Record<HistoryPayload>], toStorage storage: protocol<SyncableHistory, ResettableSyncStorage>) -> (synchronizer: HistorySynchronizer, prefs: Prefs, scratchpad: Scratchpad) {
let delegate = MockSyncDelegate()
// We can use these useless values because we're directly injecting decrypted
// payloads; no need for real keys etc.
let prefs = MockProfilePrefs()
let scratchpad = Scratchpad(b: KeyBundle.random(), persistingTo: prefs)
let synchronizer = HistorySynchronizer(scratchpad: scratchpad, delegate: delegate, basePrefs: prefs)
let expectation = expectationWithDescription("Waiting for application.")
var succeeded = false
synchronizer.applyIncomingToStorage(storage, records: records)
.upon({ result in
succeeded = result.isSuccess
expectation.fulfill()
})
waitForExpectationsWithTimeout(10, handler: nil)
XCTAssertTrue(succeeded, "Application succeeded.")
return (synchronizer, prefs, scratchpad)
}
func testApplyRecords() {
let earliest = NSDate.now()
let empty = MockSyncableHistory()
let noRecords = [Record<HistoryPayload>]()
// Apply no records.
self.applyRecords(noRecords, toStorage: empty)
// Hey look! Nothing changed.
XCTAssertTrue(empty.places.isEmpty)
XCTAssertTrue(empty.remoteVisits.isEmpty)
XCTAssertTrue(empty.localVisits.isEmpty)
// Apply one remote record.
let jA = "{\"id\":\"aaaaaa\",\"histUri\":\"http://foo.com/\",\"title\": \"ñ\",\"visits\":[{\"date\":1222222222222222,\"type\":1}]}"
let pA = HistoryPayload.fromJSON(JSON.parse(jA))!
let rA = Record<HistoryPayload>(id: "aaaaaa", payload: pA, modified: earliest + 10000, sortindex: 123, ttl: 1000000)
let (_, prefs, _) = self.applyRecords([rA], toStorage: empty)
// The record was stored. This is checking our mock implementation, but real storage should work, too!
XCTAssertEqual(1, empty.places.count)
XCTAssertEqual(1, empty.remoteVisits.count)
XCTAssertEqual(1, empty.remoteVisits["aaaaaa"]!.count)
XCTAssertTrue(empty.localVisits.isEmpty)
// Test resetting now that we have a timestamp.
XCTAssertFalse(empty.wasReset)
XCTAssertTrue(HistorySynchronizer.resetSynchronizerWithStorage(empty, basePrefs: prefs, collection: "history").value.isSuccess)
XCTAssertTrue(empty.wasReset)
}
} | mpl-2.0 | 6bfb8ab9a6cb165722f8b2eb5c683fd0 | 35.8 | 212 | 0.614087 | 4.961236 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/ArrayBufferProtocol.swift | 5 | 8282 | //===--- ArrayBufferProtocol.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// The underlying buffer for an ArrayType conforms to
/// `_ArrayBufferProtocol`. This buffer does not provide value semantics.
@usableFromInline
internal protocol _ArrayBufferProtocol
: MutableCollection, RandomAccessCollection
where Indices == Range<Int> {
/// Create an empty buffer.
init()
/// Adopt the entire buffer, presenting it at the provided `startIndex`.
init(_buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int)
init(copying buffer: Self)
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@discardableResult
__consuming func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element>
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self`
/// buffer store `minimumCapacity` elements, returns that buffer.
/// Otherwise, returns `nil`.
///
/// - Note: The result's firstElementAddress may not match ours, if we are a
/// _SliceBuffer.
///
/// - Note: This function must remain mutating; otherwise the buffer
/// may acquire spurious extra references, which will cause
/// unnecessary reallocation.
mutating func requestUniqueMutableBackingBuffer(
minimumCapacity: Int
) -> _ContiguousArrayBuffer<Element>?
/// Returns `true` if this buffer is backed by a uniquely-referenced mutable
/// _ContiguousArrayBuffer; otherwise, returns `false`.
///
/// - Note: This function must remain mutating; otherwise the buffer
/// may acquire spurious extra references, which will cause
/// unnecessary reallocation.
mutating func isMutableAndUniquelyReferenced() -> Bool
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>?
/// Replace the given `subRange` with the first `newCount` elements of
/// the given collection.
///
/// - Precondition: This buffer is backed by a uniquely-referenced
/// `_ContiguousArrayBuffer`.
mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newCount: Int,
elementsOf newValues: __owned C
) where C: Collection, C.Element == Element
/// Returns a `_SliceBuffer` containing the elements in `bounds`.
subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get }
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R
/// The number of elements the buffer stores.
override var count: Int { get set }
/// The number of elements the buffer can store without reallocation.
var capacity: Int { get }
/// An object that keeps the elements stored in this buffer alive.
var owner: AnyObject { get }
/// A pointer to the first element.
///
/// - Precondition: The elements are known to be stored contiguously.
var firstElementAddress: UnsafeMutablePointer<Element> { get }
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { get }
/// Returns a base address to which you can add an index `i` to get the
/// address of the corresponding element at `i`.
var subscriptBaseAddress: UnsafeMutablePointer<Element> { get }
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
var identity: UnsafeRawPointer { get }
}
extension _ArrayBufferProtocol {
@inlinable
internal var subscriptBaseAddress: UnsafeMutablePointer<Element> {
return firstElementAddress
}
// Make sure the compiler does not inline _copyBuffer to reduce code size.
@inline(never)
@inlinable // This code should be specializable such that copying an array is
// fast and does not end up in an unspecialized entry point.
internal init(copying buffer: Self) {
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: buffer.count, minimumCapacity: buffer.count)
buffer._copyContents(
subRange: buffer.indices,
initializing: newBuffer.firstElementAddress)
self = Self( _buffer: newBuffer, shiftedToStartIndex: buffer.startIndex)
}
@inlinable
internal mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newCount: Int,
elementsOf newValues: __owned C
) where C: Collection, C.Element == Element {
_internalInvariant(startIndex == 0, "_SliceBuffer should override this function.")
let oldCount = self.count
let eraseCount = subrange.count
let growth = newCount - eraseCount
// This check will prevent storing a 0 count to the empty array singleton.
if growth != 0 {
self.count = oldCount + growth
}
let elements = self.subscriptBaseAddress
let oldTailIndex = subrange.upperBound
let oldTailStart = elements + oldTailIndex
let newTailIndex = oldTailIndex + growth
let newTailStart = oldTailStart + growth
let tailCount = oldCount - subrange.upperBound
if growth > 0 {
// Slide the tail part of the buffer forwards, in reverse order
// so as not to self-clobber.
newTailStart.moveInitialize(from: oldTailStart, count: tailCount)
// Assign over the original subrange
var i = newValues.startIndex
for j in subrange {
elements[j] = newValues[i]
newValues.formIndex(after: &i)
}
// Initialize the hole left by sliding the tail forward
for j in oldTailIndex..<newTailIndex {
(elements + j).initialize(to: newValues[i])
newValues.formIndex(after: &i)
}
_expectEnd(of: newValues, is: i)
}
else { // We're not growing the buffer
// Assign all the new elements into the start of the subrange
var i = subrange.lowerBound
var j = newValues.startIndex
for _ in 0..<newCount {
elements[i] = newValues[j]
i += 1
newValues.formIndex(after: &j)
}
_expectEnd(of: newValues, is: j)
// If the size didn't change, we're done.
if growth == 0 {
return
}
// Move the tail backward to cover the shrinkage.
let shrinkage = -growth
if tailCount > shrinkage { // If the tail length exceeds the shrinkage
// Assign over the rest of the replaced range with the first
// part of the tail.
newTailStart.moveAssign(from: oldTailStart, count: shrinkage)
// Slide the rest of the tail back
oldTailStart.moveInitialize(
from: oldTailStart + shrinkage, count: tailCount - shrinkage)
}
else { // Tail fits within erased elements
// Assign over the start of the replaced range with the tail
newTailStart.moveAssign(from: oldTailStart, count: tailCount)
// Destroy elements remaining after the tail in subrange
(newTailStart + tailCount).deinitialize(
count: shrinkage - tailCount)
}
}
}
}
| apache-2.0 | 2f1bd8d0ea489be89c63176e005b40d2 | 36.645455 | 86 | 0.680874 | 4.854631 | false | false | false | false |
cafielo/iOS_BigNerdRanch_5th | Chap14_Homepwner_bronze_silver_gold/Homepwner/DetailViewController.swift | 1 | 4181 | //
// DetailViewController.swift
// Homepwner
//
// Created by Joonwon Lee on 8/6/16.
// Copyright © 2016 Joonwon Lee. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var serialNumberField: UITextField!
@IBOutlet weak var valueField: UITextField!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet var imageView: UIImageView!
@IBOutlet weak var cameraOverlayView: UIView!
var item: Item! {
didSet {
navigationItem.title = item.name
}
}
var imageStore: ImageStore!
let numberFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
return formatter
}()
let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nameField.text = item.name
serialNumberField.text = item.serialNumber
valueField.text = numberFormatter.stringFromNumber(item.valueInDollars)
dateLabel.text = dateFormatter.stringFromDate(item.dateCreated)
//load image
let key = item.itemKey
let imageToDisplay = imageStore.imageForKey(key)
imageView.image = imageToDisplay
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
item.name = nameField.text ?? ""
item.serialNumber = serialNumberField.text
if let valueText = valueField.text, value = numberFormatter.numberFromString(valueText) {
item.valueInDollars = value.integerValue
} else {
item.valueInDollars = 0
}
valueField.text = numberFormatter.stringFromNumber(item.valueInDollars)
dateLabel.text = dateFormatter.stringFromDate(item.dateCreated)
}
}
//IBAction
extension DetailViewController {
@IBAction func takePicture(sender: UIBarButtonItem) {
let imagePicker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
imagePicker.sourceType = .Camera
} else {
imagePicker.sourceType = .PhotoLibrary
}
imagePicker.delegate = self
imagePicker.allowsEditing = true
//camera view area has always same ratio 3:4
cameraOverlayView.frame = CGRectMake(0, 44, self.view.bounds.width, self.view.bounds.width * 4/3)
imagePicker.cameraOverlayView = cameraOverlayView
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func deleteImage(sender: UIBarButtonItem) {
//delete image
let key = item.itemKey
imageView.image = nil
imageStore.deleteImageForKey(key)
}
@IBAction func backgroundTapped(sender: UITapGestureRecognizer) {
view.endEditing(true)
}
}
extension DetailViewController: UINavigationControllerDelegate {
}
extension DetailViewController: UIImagePickerControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// get selected image from info Dictionary
let image = info[UIImagePickerControllerEditedImage] as! UIImage
imageStore.setImage(image, forKey: item.itemKey)
imageView.image = image
//gotta dismiss imagepicker
dismissViewControllerAnimated(true, completion: nil)
}
}
extension DetailViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 0f3b71a3e10888e867a2d503a6996d47 | 29.510949 | 123 | 0.661722 | 5.610738 | false | false | false | false |
haawa799/WaniKani-iOS | WaniKani/ViewControllers/KanjiStrokesViewController.swift | 1 | 3573 | //
// KanjiViewController.swift
// WaniKani-Kanji-Strokes
//
// Created by Andriy K. on 12/28/15.
// Copyright © 2015 Andriy K. All rights reserved.
//
import UIKit
import StrokeDrawingView
import DataKit
class KanjiStrokesViewController: UIViewController {
let paperColor = UIColor(red:1, green:0.99, blue:0.97, alpha:1)
var firstView: UIView!
var strokeDrawingView: StrokeDrawingView! {
didSet {
strokeDrawingView?.delegate = self
if let kanji = kanji {
strokeDrawingView?.dataSource = kanji
}
}
}
var showingBack = true
@IBOutlet weak var container: KanjiMetaDataView!
override func viewDidLoad() {
super.viewDidLoad()
firstView = UIView(frame: CGRectZero)
firstView.backgroundColor = UIColor.redColor()
firstView.hidden = true
container.addSubview(firstView)
container.backgroundColor = paperColor
strokeDrawingView = StrokeDrawingView(frame: CGRectZero)
strokeDrawingView.backgroundColor = paperColor
let singleTap = UITapGestureRecognizer(target: self, action: Selector("tapped"))
singleTap.numberOfTapsRequired = 1
container.addGestureRecognizer(singleTap)
container.setupWithKanji(kanjiInfo)
}
override func updateUserActivityState(activity: NSUserActivity) {
guard let userInfo = kanjiInfo?.userActivityUserInfo else { return }
activity.addUserInfoEntriesFromDictionary(userInfo)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
strokeDrawingView.frame = container.bounds
firstView.frame = container.bounds
}
func tapped() {
if (showingBack == false) {
UIView.transitionFromView(strokeDrawingView, toView: firstView, duration: 1, options: [UIViewAnimationOptions.TransitionFlipFromRight, .AllowAnimatedContent], completion: nil)
showingBack = true
} else {
UIView.transitionFromView(firstView, toView: strokeDrawingView, duration: 1, options: [UIViewAnimationOptions.TransitionFlipFromRight, .AllowAnimatedContent], completion: nil)
showingBack = false
}
}
private var kanji: KanjiGraphicInfo? {
didSet {
guard let kanji = kanji else { return }
strokeDrawingView?.stopForeverAnimation()
strokeDrawingView?.clean()
strokeDrawingView?.dataSource = kanji
}
}
var kanjiInfo: Kanji? {
didSet {
if let kanjiInfo = kanjiInfo {
container?.setupWithKanji(kanjiInfo)
kanji = KanjiGraphicInfo(kanji: kanjiInfo.character)
// let activity = kanjiInfo.userActivity
// if #available(iOS 9.0, *) {
// activity.eligibleForSearch = true
// }
// userActivity = activity
}
}
}
}
extension KanjiStrokesViewController: StrokeDrawingViewDataDelegate {
func layersAreNowReadyForAnimation() {
self.strokeDrawingView.playForever(1.5)
}
}
extension KanjiGraphicInfo: StrokeDrawingViewDataSource {
func sizeOfDrawing() -> CGSize {
return CGSize(width: 109, height: 109)
}
func numberOfStrokes() -> Int {
return bezierPathes.count
}
func pathForIndex(index: Int) -> UIBezierPath {
let path = bezierPathes[index]
path.lineWidth = 3
return path
}
func animationDurationForStroke(index: Int) -> CFTimeInterval {
return 0.6
}
func colorForStrokeAtIndex(index: Int) -> UIColor {
return color0
}
func colorForUnderlineStrokes() -> UIColor? {
return UIColor(red: 119/255, green: 119/255, blue: 119/255, alpha: 0.5)
}
} | gpl-3.0 | 1aa13e2781eeb383000720810c994002 | 25.272059 | 181 | 0.690929 | 4.743692 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/UserProfile/ProfileActionsFactory.swift | 1 | 7882 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCommonComponents
import WireDataModel
/**
* The actions that can be performed from the profile details or devices.
*/
enum ProfileAction: Equatable {
case createGroup
case mute(isMuted: Bool)
case manageNotifications
case archive
case deleteContents
case block(isBlocked: Bool)
case openOneToOne
case removeFromGroup
case connect
case cancelConnectionRequest
case openSelfProfile
/// The text of the button for this action.
var buttonText: String {
switch self {
case .createGroup: return "profile.create_conversation_button_title".localized
case .mute(let isMuted): return isMuted
? "meta.menu.silence.unmute".localized
: "meta.menu.silence.mute".localized
case .manageNotifications: return "meta.menu.configure_notifications".localized
case .archive: return "meta.menu.archive".localized
case .deleteContents: return "meta.menu.clear_content".localized
case .block(let isBlocked): return isBlocked
? "profile.unblock_button_title_action".localized
: "profile.block_button_title".localized
case .openOneToOne: return "profile.open_conversation_button_title".localized
case .removeFromGroup: return "profile.remove_dialog_button_remove".localized
case .connect: return "profile.connection_request_dialog.button_connect".localized
case .cancelConnectionRequest: return "meta.menu.cancel_connection_request".localized
case .openSelfProfile: return "meta.menu.open_self_profile".localized
}
}
/// The icon of the button for this action, if it's eligible to be a key action.
var keyActionIcon: StyleKitIcon? {
switch self {
case .createGroup: return .createConversation
case .manageNotifications, .mute: return nil
case .archive: return nil
case .deleteContents: return nil
case .block: return nil
case .openOneToOne: return .conversation
case .removeFromGroup: return nil
case .connect: return .plus
case .cancelConnectionRequest: return .undo
case .openSelfProfile: return .personalProfile
}
}
/// Whether the action can be used as a key action.
var isEligibleForKeyAction: Bool {
return keyActionIcon != nil
}
}
/**
* An object that returns the actions that a user can perform in the scope
* of a conversation.
*/
final class ProfileActionsFactory {
// MARK: - Environmemt
/// The user that is displayed in the profile details.
let user: UserType
/// The user that wants to perform the actions.
let viewer: UserType
/// The conversation that the user wants to perform the actions in.
let conversation: ZMConversation?
/// The context of the Profile VC
let context: ProfileViewControllerContext
// MARK: - Initialization
/**
* Creates the action controller with the specified environment.
* - parameter user: The user that is displayed in the profile details.
* - parameter viewer: The user that wants to perform the actions.
* - parameter conversation: The conversation that the user wants to
* perform the actions in.
*/
init(user: UserType, viewer: UserType, conversation: ZMConversation?, context: ProfileViewControllerContext) {
self.user = user
self.viewer = viewer
self.conversation = conversation
self.context = context
}
// MARK: - Calculating the Actions
/// Calculates the list of actions to display to the user.
///
/// - Returns: array of availble actions
func makeActionsList() -> [ProfileAction] {
// Do nothing if the user was deleted
if user.isAccountDeleted {
return []
}
// if the user is viewing their own profile, add the open self-profile screen button
if viewer.isSelfUser && user.isSelfUser {
return [.openSelfProfile]
}
// Do not show any action if the user is blocked
if user.isBlocked {
return user.canBeUnblocked ? [.block(isBlocked: true)] : []
}
var conversation: ZMConversation?
// If there is no conversation and open profile from a conversation, offer to connect to the user if possible
if let selfConversation = self.conversation {
conversation = selfConversation
} else if context == .profileViewer {
conversation = nil
} else if !user.isConnected {
if user.isPendingApprovalByOtherUser {
return [.cancelConnectionRequest]
} else if !user.isPendingApprovalBySelfUser {
return [.connect]
}
}
var actions: [ProfileAction] = []
switch (context, conversation?.conversationType) {
case (_, .oneOnOne?):
if viewer.canCreateConversation(type: .group) {
actions.append(.createGroup)
}
// Notifications, Archive, Delete Contents if available for every 1:1
if let conversation = conversation {
let notificationAction: ProfileAction = viewer.isTeamMember ? .manageNotifications : .mute(isMuted: conversation.mutedMessageTypes != .none)
actions.append(contentsOf: [notificationAction, .archive, .deleteContents])
}
// If the viewer is not on the same team as the other user, allow blocking
if !viewer.canAccessCompanyInformation(of: user) && !user.isWirelessUser {
actions.append(.block(isBlocked: false))
}
case (.profileViewer, .none),
(.search, .none),
(_, .group?):
// Do nothing if the viewer is a wireless user because they can't have 1:1's
if viewer.isWirelessUser {
break
}
let isOnSameTeam = viewer.isOnSameTeam(otherUser: user)
// Show connection request actions for unconnected users from different teams.
if user.isPendingApprovalByOtherUser {
actions.append(.cancelConnectionRequest)
} else if user.isConnected || isOnSameTeam {
actions.append(.openOneToOne)
} else if user.canBeConnected && !user.isPendingApprovalBySelfUser {
actions.append(.connect)
}
// Only non-guests and non-partners are allowed to remove
if let conversation = conversation, viewer.canRemoveUser(from: conversation) {
actions.append(.removeFromGroup)
}
// If the user is not from the same team as the other user, allow blocking
if user.isConnected && !isOnSameTeam && !user.isWirelessUser {
actions.append(.block(isBlocked: false))
}
default:
break
}
return actions
}
}
extension UserType {
var canBeUnblocked: Bool {
switch blockState {
case .blockedMissingLegalholdConsent:
return false
default:
return true
}
}
}
| gpl-3.0 | a93bc3bd2a250dab293a85cc9cc823fa | 33.722467 | 156 | 0.645775 | 4.898695 | false | false | false | false |
phatblat/realm-cocoa | RealmSwift/Tests/SortDescriptorTests.swift | 4 | 2922 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import RealmSwift
class SortDescriptorTests: TestCase {
let sortDescriptor = SortDescriptor(keyPath: "property")
func testAscendingDefaultsToTrue() {
XCTAssertTrue(sortDescriptor.ascending)
}
func testReversedReturnsReversedDescriptor() {
let reversed = sortDescriptor.reversed()
XCTAssertEqual(reversed.keyPath, sortDescriptor.keyPath, "Key path should stay the same when reversed.")
XCTAssertFalse(reversed.ascending)
XCTAssertTrue(reversed.reversed().ascending)
}
func testDescription() {
XCTAssertEqual(sortDescriptor.description, "SortDescriptor(keyPath: property, direction: ascending)")
}
func testStringLiteralConvertible() {
let literalSortDescriptor: RealmSwift.SortDescriptor = "property"
XCTAssertEqual(sortDescriptor, literalSortDescriptor,
"SortDescriptor should conform to StringLiteralConvertible")
}
func testComparison() {
let sortDescriptor1 = SortDescriptor(keyPath: "property1", ascending: true)
let sortDescriptor2 = SortDescriptor(keyPath: "property1", ascending: false)
let sortDescriptor3 = SortDescriptor(keyPath: "property2", ascending: true)
let sortDescriptor4 = SortDescriptor(keyPath: "property2", ascending: false)
// validate different
XCTAssertNotEqual(sortDescriptor1, sortDescriptor2, "Should not match")
XCTAssertNotEqual(sortDescriptor1, sortDescriptor3, "Should not match")
XCTAssertNotEqual(sortDescriptor1, sortDescriptor4, "Should not match")
XCTAssertNotEqual(sortDescriptor2, sortDescriptor3, "Should not match")
XCTAssertNotEqual(sortDescriptor2, sortDescriptor4, "Should not match")
XCTAssertNotEqual(sortDescriptor3, sortDescriptor4, "Should not match")
let sortDescriptor5 = SortDescriptor(keyPath: "property1", ascending: true)
let sortDescriptor6 = SortDescriptor(keyPath: "property2", ascending: true)
// validate same
XCTAssertEqual(sortDescriptor1, sortDescriptor5, "Should match")
XCTAssertEqual(sortDescriptor3, sortDescriptor6, "Should match")
}
}
| apache-2.0 | 64064425c81c557f3e034720e39b62cd | 40.742857 | 112 | 0.693018 | 5.461682 | false | true | false | false |
beretis/SwipeToDeleteCollectionView | Example Project/CollectionViewSwipeToDelete/ViewModel.swift | 1 | 1500 | //
// ViewModel.swift
// CollectionViewSwipeToDelete
//
// Created by Jozef Matus on 09/05/2017.
// Copyright © 2017 o2. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class ViewModel: RxViewModel {
var sections: Variable<[SectionOfItemModels]> = Variable([])
override init() {
super.init()
self.setupRx()
}
func setupRx() {
self.didBecomeActive.do(onNext: { _ in
self.randomData.bind(to: self.sections).disposed(by: self.disposeBag)
}).subscribe().disposed(by: self.disposeBag)
}
var randomData: Observable<[SectionOfItemModels]> {
get {
let count = arc4random_uniform(30)
var arrayOfData: [ItemCellVM] = []
for _ in 0...count {
let randomItem = ItemCellVM(itemModel: ItemModel())
arrayOfData.append(randomItem)
}
return Observable.just([SectionOfItemModels(header: "HEADER", items: arrayOfData)])
}
}
}
func randomString(length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
| mit | 749da63030f82e1ce30374c9a27c6a81 | 25.298246 | 95 | 0.610407 | 4.421829 | false | false | false | false |
niuxinghua/beauties | beauties/BeautyCollectionViewCell.swift | 13 | 1947 | //
// BeautyCollectionViewCell.swift
// beauties
//
// Created by Shuai Liu on 15/7/1.
// Copyright (c) 2015年 Shuai Liu. All rights reserved.
//
import Foundation
import UIKit
import Kingfisher
class BeautyCollectionViewCell: UICollectionViewCell {
var imageView: UIImageView
override init(frame: CGRect) {
imageView = UIImageView()
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
imageView = UIImageView()
super.init(coder: aDecoder)
commonInit()
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.alpha = 0
}
func commonInit() -> Void {
self.clipsToBounds = false
self.layer.borderWidth = 10
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.shadowColor = UIColor(red: 187 / 255.0, green: 187 / 255.0, blue: 187 / 255.0, alpha: 1).CGColor
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSizeMake(2, 6)
self.imageView.clipsToBounds = true
self.imageView.frame = self.bounds
self.imageView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
self.imageView.contentMode = .ScaleAspectFill
self.addSubview(self.imageView)
}
func bindData(entity: BeautyImageEntity) -> Void {
if let urlString = entity.imageUrl {
if let url = NSURL(string: urlString) {
self.imageView.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: nil, completionHandler: {
[weak self](image, error, cacheType, imageURL) -> () in
UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseIn, animations: { () -> Void in
self?.imageView.alpha = 1
}, completion: nil)
})
}
}
}
} | mit | 75eadac89285c6f78022be0dc727ad1b | 30.387097 | 116 | 0.6 | 4.720874 | false | false | false | false |
LoopKit/LoopKit | LoopKitUI/View Controllers/TextFieldTableViewController.swift | 1 | 3273 | //
// TextFieldTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 8/30/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import UIKit
public protocol TextFieldTableViewControllerDelegate: AnyObject {
func textFieldTableViewControllerDidEndEditing(_ controller: TextFieldTableViewController)
func textFieldTableViewControllerDidReturn(_ controller: TextFieldTableViewController)
}
open class TextFieldTableViewController: UITableViewController, UITextFieldDelegate {
private weak var textField: UITextField?
public var indexPath: IndexPath?
public var placeholder: String?
public var unit: String?
public var value: String? {
didSet {
delegate?.textFieldTableViewControllerDidEndEditing(self)
}
}
public var contextHelp: String?
public var keyboardType = UIKeyboardType.default
public var autocapitalizationType = UITextAutocapitalizationType.sentences
open weak var delegate: TextFieldTableViewControllerDelegate?
public convenience init() {
self.init(style: .grouped)
}
open override func viewDidLoad() {
super.viewDidLoad()
tableView.cellLayoutMarginsFollowReadableWidth = true
tableView.register(TextFieldTableViewCell.nib(), forCellReuseIdentifier: TextFieldTableViewCell.className)
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textField?.becomeFirstResponder()
}
// MARK: - UITableViewDataSource
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TextFieldTableViewCell.className, for: indexPath) as! TextFieldTableViewCell
textField = cell.textField
cell.textField.delegate = self
cell.textField.text = value
cell.textField.keyboardType = keyboardType
cell.textField.placeholder = placeholder
cell.textField.autocapitalizationType = autocapitalizationType
cell.unitLabel?.text = unit
return cell
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return contextHelp
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath == IndexPath(row: 0, section: 0), let textField = textField {
if textField.isFirstResponder {
textField.resignFirstResponder()
} else {
textField.becomeFirstResponder()
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - UITextFieldDelegate
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
value = textField.text
return true
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
value = textField.text
textField.delegate = nil
delegate?.textFieldTableViewControllerDidReturn(self)
return false
}
}
| mit | 75cceeaa00e5203d77838b2ac5a2c3f5 | 27.955752 | 141 | 0.7011 | 5.970803 | false | false | false | false |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModelTests/Dealers/WhenObservingDealersAfterLoadingFromStore_ApplicationShould.swift | 1 | 820 | import EurofurenceModel
import EurofurenceModelTestDoubles
import XCTest
class WhenObservingDealersAfterLoadingFromStore_ApplicationShould: XCTestCase {
func testUpdateTheDelegateWithDealersGroupedByDisplayName() {
let syncResponse = ModelCharacteristics.randomWithoutDeletions
let dataStore = InMemoryDataStore(response: syncResponse)
let context = EurofurenceSessionTestBuilder().with(dataStore).build()
let dealersIndex = context.dealersService.makeDealersIndex()
let delegate = CapturingDealersIndexDelegate()
dealersIndex.setDelegate(delegate)
AlphabetisedDealersGroupAssertion(groups: delegate.capturedAlphabetisedDealerGroups,
fromDealerCharacteristics: syncResponse.dealers.changed).assertGroups()
}
}
| mit | 992106544ad5a5df2e2b7c6662b45dc1 | 42.157895 | 113 | 0.760976 | 6.40625 | false | true | false | false |
maurovc/MyMarvel | MyMarvel/CustomPalette.swift | 1 | 3420 | //
// CustomPalette.swift
// MyMarvel
//
// Created by Mauro Vime Castillo on 25/10/16.
// Copyright © 2016 Mauro Vime Castillo. All rights reserved.
//
import Foundation
import UIKit
//MARK: Extension of UIColor that adds hex functionalities and custom colors.
extension UIColor {
private class func createScanner(hexString string: String) -> NSScanner {
let scanner = NSScanner(string: string)
if let _ = string.rangeOfString("#") {
scanner.scanLocation = 1
}
return scanner
}
public convenience init(rgb string: String, alpha: CGFloat = 1.0) {
var rgbValue: UInt32 = 0;
let scanner = UIColor.createScanner(hexString: string)
scanner.scanHexInt(&rgbValue)
let div = CGFloat(255)
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / div
let green = CGFloat((rgbValue & 0x00FF00) >> 8) / div
let blue = CGFloat( rgbValue & 0x0000FF ) / div
self.init(red: red, green: green, blue: blue, alpha: 1.0)
}
public convenience init(rgba string: String) {
var rgbaValue: UInt32 = 0;
let scanner = UIColor.createScanner(hexString: string)
scanner.scanHexInt(&rgbaValue)
let div = CGFloat(255)
let red = CGFloat((rgbaValue & 0xFF000000) >> 24) / div
let green = CGFloat((rgbaValue & 0x00FF0000) >> 16) / div
let blue = CGFloat((rgbaValue & 0x0000FF00) >> 8) / div
let alpha = CGFloat( rgbaValue & 0x000000FF ) / div
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
public func hexString(alpha: Bool) -> String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
var result = String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
if (alpha) {
result += String(format: "%02X",Int(a * 255))
}
return result
}
class func appColor() -> UIColor {
return UIColor(rgb: "#E22130")
}
func midColorWith(color: UIColor, atPoint: CGFloat) -> UIColor {
var r1: CGFloat = 0
var g1: CGFloat = 0
var b1: CGFloat = 0
var a1: CGFloat = 0
var r2: CGFloat = 0
var g2: CGFloat = 0
var b2: CGFloat = 0
var a2: CGFloat = 0
self.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
color.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
let red = r1 + ((r2 - r1) * atPoint)
let green = g1 + ((g2 - g1) * atPoint)
let blue = b1 + ((b2 - b1) * atPoint)
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
class func randomColor() -> UIColor {
var red = CGFloat(0.0)
while red < 0.1 || red > 0.84 {
red = CGFloat(Float(arc4random()) / Float(UINT32_MAX))
}
var green = CGFloat(0.0)
while green < 0.1 || green > 0.84 {
green = CGFloat(Float(arc4random()) / Float(UINT32_MAX))
}
var blue = CGFloat(0.0)
while blue < 0.1 || blue > 0.84 {
blue = CGFloat(Float(arc4random()) / Float(UINT32_MAX))
}
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
| mit | 7f80b97ffe75a9ef15cc91f4c6feb954 | 32.519608 | 94 | 0.543726 | 3.637234 | false | false | false | false |
therealbnut/swift | benchmark/single-source/DictionaryLiteral.swift | 21 | 814 | //===--- DictionaryLiteral.swift ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Dictionary creation from literals benchmark
// rdar://problem/19804127
import TestsUtils
@inline(never)
func makeDictionary() -> [Int: Int] {
return [1: 3, 2: 2, 3: 1]
}
@inline(never)
public func run_DictionaryLiteral(_ N: Int) {
for _ in 1...10000*N {
_ = makeDictionary()
}
}
| apache-2.0 | 05881bc820a2552b5ce91f6264016282 | 29.148148 | 80 | 0.589681 | 4.26178 | false | false | false | false |
koteus/ParalaxViewController | Source/ParalaxViewController.swift | 2 | 9418 | //
// ParalaxViewController.swift
//
// Copyright (c) 2015 Konstantin Kalbazov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
protocol ParalaxViewControllerDelegate: NSObjectProtocol {
func didTapHeaderImageView(imageView: UIImageView)
}
class ParalaxViewController: UIViewController, UIScrollViewDelegate {
let INVIS_DELTA = 50.0
let HEADER_HEIGHT = 44.0
var showStatusBarMargin = false
var backgroundScrollViewHeight: CGFloat {
get {
return view.bounds.size.width * 0.74
}
}
var useImageZoomEffect = true
var mainScrollView: UIScrollView!
private var backgroundScrollView: UIScrollView!
var delegate: ParalaxViewControllerDelegate!
var headerHeight: CGFloat {
get {
return CGRectGetHeight(backgroundScrollView.frame)
}
}
var contentView = UIScrollView(frame: CGRectZero)
var floatingHeaderView: UIView!
var headerImageView: UIImageView!
var originalImageView: UIImage!
var scrollViewContainer: UIView!
var headerOverlayViews = [UIView]()
var offsetHeight:CGFloat {
get {
return CGFloat(HEADER_HEIGHT) + navBarHeight
}
}
var navBarHeight:CGFloat {
get {
if navigationController != nil && navigationController?.navigationBarHidden != true {
// Include 20 for the status bar
return CGRectGetHeight(navigationController!.navigationBar.frame) + 20
}
return 0.0
}
}
func setNeedsScrollViewAppearanceUpdate() {
mainScrollView.contentSize = CGSizeMake(CGRectGetWidth(view.frame), contentView.contentSize.height + CGRectGetHeight(backgroundScrollView.frame))
}
func setHeaderImage(headerImage: UIImage) {
originalImageView = headerImage
headerImageView.image = headerImage
}
func addHeaderOverlayView(overlay: UIView) {
headerOverlayViews += [overlay]
floatingHeaderView.addSubview(overlay)
}
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
mainScrollView = UIScrollView(frame: view.frame)
view = mainScrollView
mainScrollView.delegate = self
mainScrollView.bounces = useImageZoomEffect
mainScrollView.alwaysBounceVertical = mainScrollView.bounces
mainScrollView.contentSize = CGSizeMake(view.frame.size.width, 1000)
mainScrollView.showsVerticalScrollIndicator = false
mainScrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
mainScrollView.autoresizesSubviews = true
backgroundScrollView = UIScrollView(frame: CGRectMake(0, 0, CGRectGetWidth(view.frame), backgroundScrollViewHeight))
backgroundScrollView.scrollEnabled = false
backgroundScrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
backgroundScrollView.autoresizesSubviews = true
backgroundScrollView.contentSize = CGSizeMake(view.frame.size.width, 1000)
mainScrollView.addSubview(backgroundScrollView)
headerImageView = UIImageView(frame: CGRectMake(
0, 0, CGRectGetWidth(backgroundScrollView.frame), CGRectGetHeight(backgroundScrollView.frame)))
headerImageView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
headerImageView.contentMode = .ScaleAspectFill
headerImageView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
headerImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "headerImageTapped:"))
headerImageView.userInteractionEnabled = true
backgroundScrollView.addSubview(headerImageView)
floatingHeaderView = UIView(frame: backgroundScrollView.frame)
floatingHeaderView.backgroundColor = UIColor.clearColor()
floatingHeaderView.userInteractionEnabled = true
scrollViewContainer = UIView(frame: CGRectMake(0, CGRectGetHeight(backgroundScrollView.frame), CGRectGetWidth(view.frame), CGRectGetHeight(view.frame) - offsetHeight))
scrollViewContainer.autoresizingMask = UIViewAutoresizing.FlexibleWidth
contentView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
scrollViewContainer.addSubview(contentView)
mainScrollView.addSubview(floatingHeaderView)
mainScrollView.addSubview(scrollViewContainer)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setNeedsScrollViewAppearanceUpdate()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
contentView.frame = CGRectMake(0, 0, CGRectGetWidth(scrollViewContainer.frame),
CGRectGetHeight(self.view.frame) - offsetHeight)
}
func headerImageTapped(tapGesture: UITapGestureRecognizer) {
if delegate.respondsToSelector("didTapHeaderImageView:") {
delegate.didTapHeaderImageView(headerImageView)
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
var delta = CGFloat(0.0)
let rect = CGRectMake(0.0, 0.0, CGRectGetWidth(scrollViewContainer.frame), backgroundScrollViewHeight)
let backgroundScrollViewLimit = backgroundScrollView.frame.size.height - offsetHeight - (showStatusBarMargin ? 20.0 : 0.0)
// Here is where I do the "Zooming" image and the quick fade out the text and toolbar
if (scrollView.contentOffset.y < 0.0) {
if useImageZoomEffect {
// calculate delta
delta = fabs(min(0.0, mainScrollView.contentOffset.y + navBarHeight))
backgroundScrollView.frame = CGRectMake(CGRectGetMinX(rect) - delta / 2.0, CGRectGetMinY(rect) - delta, CGRectGetWidth(scrollViewContainer.frame) + delta, CGRectGetHeight(rect) + delta)
// floatingHeaderView.alpha = (CGFloat(INVIS_DELTA) - delta) / CGFloat(INVIS_DELTA)
}
else {
backgroundScrollView.frame = CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height)
}
}
else {
delta = mainScrollView.contentOffset.y
// set alfas
floatingHeaderView.alpha = 1.0
// Here I check whether or not the user has scrolled passed the limit where I want to stick the header,
// if they have then I move the frame with the scroll view
// to give it the sticky header look
if (delta > backgroundScrollViewLimit) {
backgroundScrollView.frame = CGRectMake(0.0, delta - backgroundScrollView.frame.size.height + offsetHeight + (showStatusBarMargin ? 20.0 : 0.0),
CGRectGetWidth(scrollViewContainer.frame), backgroundScrollViewHeight)
floatingHeaderView.frame = CGRectMake(0.0, delta - floatingHeaderView.frame.size.height + offsetHeight + (showStatusBarMargin ? 20.0 : 0.0),
CGRectGetWidth(scrollViewContainer.frame), backgroundScrollViewHeight)
scrollViewContainer.frame = CGRectMake(0.0, CGRectGetMinY(backgroundScrollView.frame) + CGRectGetHeight(backgroundScrollView.frame),
scrollViewContainer.frame.size.width, scrollViewContainer.frame.size.height)
contentView.contentOffset = CGPointMake(0, delta - backgroundScrollViewLimit)
let contentOffsetY = -backgroundScrollViewLimit * 0.5
backgroundScrollView.setContentOffset(CGPointMake(0, contentOffsetY), animated: false)
}
else {
backgroundScrollView.frame = rect
floatingHeaderView.frame = rect
scrollViewContainer.frame = CGRectMake(0, CGRectGetMinY(rect) + CGRectGetHeight(rect),
scrollViewContainer.frame.size.width, scrollViewContainer.frame.size.height)
contentView.setContentOffset(CGPointMake(0, 0), animated: false)
backgroundScrollView.setContentOffset(CGPointMake(0, -delta * 0.5), animated: false)
}
}
}
}
| mit | eb4eb7c4ad719a9b4ff6d2686432d5a2 | 45.623762 | 201 | 0.68815 | 5.774372 | false | false | false | false |
ta2yak/loqui | loqui/ViewControllers/ProfileEditViewController.swift | 1 | 4557 | //
// ProfileEditViewController.swift
// loqui
//
// Created by Kawasaki Tatsuya on 2017/07/08.
// Copyright © 2017年 Kawasaki Tatsuya. All rights reserved.
//
import UIKit
import Eureka
import MaterialComponents
import Cartography
import RxSwift
import RxCocoa
class ProfileEditViewController: FormViewController {
let vm = ProfileEditViewModel()
var disposeBag = DisposeBag()
let saveButton = MDCFloatingButton()
let activityIndicator = MDCActivityIndicator()
override func viewDidLoad() {
super.viewDidLoad()
self.form = self.vm.form
vm.setProfileForm()
// 保存ボタン
saveButton.setTitle(String.fontAwesomeIcon("check"), for: UIControlState())
saveButton.titleLabel?.font = UIFont.icon(from: .FontAwesome, ofSize: 34)
saveButton.sizeToFit()
saveButton.translatesAutoresizingMaskIntoConstraints = false
saveButton.customTitleColor = UIColor.white
view.addSubview(saveButton)
MDCButtonColorThemer.apply((UIApplication.shared.delegate as! AppDelegate).mainColorScheme,
to: saveButton)
constrain(view, saveButton) { view, toProfileEditButton in
toProfileEditButton.width == view.width / 6
toProfileEditButton.height == view.width / 6
toProfileEditButton.right == view.right - 12
toProfileEditButton.bottom == view.bottom - 12
}
saveButton.rx.tap.subscribe(onNext: { [weak self] in
guard let this = self else { return }
if this.form.validate().count > 0 {
print("エラーがあります")
} else {
this.vm.saveProfile()
}
})
.addDisposableTo(disposeBag)
vm.isSaved.asObservable().subscribe(onNext: { (isSaved) in
if isSaved {
self.dismiss(animated: true, completion: nil)
}
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
// Loading
activityIndicator.radius = 40
view.addSubview(activityIndicator)
constrain(view, activityIndicator) { view, activityIndicator in
activityIndicator.width == view.width / 3
activityIndicator.height == view.width / 3
activityIndicator.center == view.center
}
vm.isLoading.asObservable().subscribe(onNext: { (isLoading) in
isLoading ? self.activityIndicator.startAnimating() : self.activityIndicator.stopAnimating()
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
setupNavigationBar()
}
func setupNavigationBar() {
// ナビゲーションバーの制御
let navigationbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 72))
self.view.addSubview(navigationbar)
navigationbar.setBackgroundImage(UIImage.colorImage(color: UIColor.white,
size: CGSize(width: UIScreen.main.bounds.size.width,
height: 72 )),
for: UIBarPosition.any,
barMetrics: UIBarMetrics.default)
navigationbar.shadowImage = UIImage()
let titleAttributes = [NSForegroundColorAttributeName: UIColor.mainTextColor()] as Dictionary!
navigationbar.titleTextAttributes = titleAttributes
let navigationItem = UINavigationItem(title: "Loqui")
let leftBarButton = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(back))
let leftBarButtonAttributes = [NSFontAttributeName: UIFont.icon(from: .FontAwesome, ofSize: 22.0),
NSForegroundColorAttributeName: UIColor.mainTextColor()] as Dictionary!
leftBarButton.setTitleTextAttributes(leftBarButtonAttributes, for: UIControlState())
leftBarButton.title = String.fontAwesomeIcon("close")
navigationItem.leftBarButtonItem = leftBarButton
navigationbar.setItems([navigationItem], animated: true)
}
}
extension ProfileEditViewController {
func back(){
self.dismiss(animated: true, completion: nil)
}
}
| mit | a0ef019b79229117f4f1a5b8b8a6d94b | 35.032 | 122 | 0.605018 | 5.64411 | false | false | false | false |
DAloG/BlueCap | Examples/CentralWithProfile/CentralWithProfile/SetUpdatePeriodViewController.swift | 1 | 2192 | //
// SetUpdatePeriodViewController.swift
// Central
//
// Created by Troy Stribling on 5/2/15.
// Copyright (c) 2015 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class SetUpdatePeriodViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet var updatePeriodTextField : UITextField!
var characteristic : Characteristic?
var isRaw : Bool?
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let isRaw = self.isRaw, data = self.characteristic?.stringValue, period = data["period"], rawPeriod = data["periodRaw"] {
if isRaw {
self.updatePeriodTextField.text = rawPeriod
} else {
self.updatePeriodTextField.text = period
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
// UITextFieldDelegate
func textFieldShouldReturn(textField:UITextField) -> Bool {
if let enteredPeriod = self.updatePeriodTextField.text, isRaw = self.isRaw, value = UInt16(enteredPeriod) where !enteredPeriod.isEmpty {
let rawValue : String
if isRaw {
rawValue = enteredPeriod
} else {
rawValue = "\(value / 10)"
}
let writeFuture = self.characteristic?.writeString(["periodRaw":rawValue], timeout:10.0)
writeFuture?.onSuccess {_ in
textField.resignFirstResponder()
self.navigationController?.popViewControllerAnimated(true)
}
writeFuture?.onFailure {error in
self.presentViewController(UIAlertController.alertOnError(error), animated:true) {action in
textField.resignFirstResponder()
self.navigationController?.popViewControllerAnimated(true)
}
}
return true
} else {
return false
}
}
}
| mit | ed53e0af8b7a087d281dbc4e69234819 | 31.716418 | 144 | 0.607208 | 5.320388 | false | false | false | false |
sina-kh/Swift-Auto-Image-Flipper | Example/AutoImageFlipper/ViewController.swift | 1 | 1720 | //
// ViewController.swift
// AutoImageFlipper
//
// Created by SinaKH on 05/21/2016.
// Copyright (c) 2016 SinaKH. All rights reserved.
//
import UIKit
import AutoImageFlipper
class ViewController: UIViewController, AutoImageFlipperDelegate {
@IBOutlet weak var autoImageFlipper: AutoImageFlipper!
override func viewDidLoad() {
super.viewDidLoad()
autoImageFlipper.delegate = self
autoImageFlipper.addImage(UIImage(named: "Images/image1")!)
autoImageFlipper.addImage(UIImage(named: "Images/image3")!)
autoImageFlipper.playNext()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
func autoImageFlipper(autoImageFlipper: AutoImageFlipper, lastPlayed: Int) -> UIImage? {
// This function calls when the image is fading out and next image is going to play
// If we pass any UIImage here, the next image will be what we passed, else the flipper will check the images we have added to it before
// last played is the index of image played from list or -1 if it's passed from here
// we want to change the direction when all images of our list where played
if lastPlayed == autoImageFlipper.images.count - 1 {
if autoImageFlipper.moveDirection == .Left {
autoImageFlipper.moveDirection = .Right
} else {
autoImageFlipper.moveDirection = .Left
}
}
// to test passing images from here
if lastPlayed == 0 {
return UIImage(named: "Images/image2")
}
return nil
}
}
| mit | 519b2738e0491f2b9e3e2103bd926dda | 31.45283 | 144 | 0.637791 | 5.276074 | false | false | false | false |
emilstahl/swift | test/SILGen/builtins.swift | 7 | 30627 | // RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | FileCheck %s
// RUN: %target-swift-frontend -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | FileCheck -check-prefix=CANONICAL %s
import Swift
protocol ClassProto : class { }
struct Pointer {
var value: Builtin.RawPointer
}
// CHECK-LABEL: sil hidden @_TF8builtins3foo
func foo(x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 {
// CHECK: builtin "cmp_eq_Int1"
return Builtin.cmp_eq_Int1(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8load_pod
func load_pod(x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8load_obj
func load_obj(x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK: retain [[VAL]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8load_gen
func load_gen<T>(x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}}
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8move_pod
func move_pod(x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8move_obj
func move_obj(x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK-NOT: retain [[VAL]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8move_gen
func move_gen<T>(x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}}
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins11destroy_pod
func destroy_pod(x: Builtin.RawPointer) {
var x = x
// CHECK: [[X:%[0-9]+]] = alloc_box
// CHECK-NOT: pointer_to_address
// CHECK-NOT: destroy_addr
// CHECK-NOT: release
// CHECK: release [[X]]#0 : $@box
// CHECK-NOT: release
return Builtin.destroy(Builtin.Int64, x)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8builtins11destroy_obj
func destroy_obj(x: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(Builtin.NativeObject, x)
}
// CHECK-LABEL: sil hidden @_TF8builtins11destroy_gen
func destroy_gen<T>(x: Builtin.RawPointer, _: T) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(T.self, x)
}
// CHECK-LABEL: sil hidden @_TF8builtins10assign_pod
func assign_pod(x: Builtin.Int64, y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: alloc_box
// CHECK: alloc_box
// CHECK-NOT: alloc_box
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: release
// CHECK: release
// CHECK-NOT: release
Builtin.assign(x, y)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8builtins10assign_obj
func assign_obj(x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: release
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins12assign_tuple
func assign_tuple(x: (Builtin.Int64, Builtin.NativeObject),
y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*(Builtin.Int64, Builtin.NativeObject)
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: release
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins10assign_gen
func assign_gen<T>(x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [take] {{%.*}} to [[ADDR]] :
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8init_pod
func init_pod(x: Builtin.Int64, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: store {{%.*}} to [[ADDR]]
// CHECK-NOT: release [[ADDR]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8init_obj
func init_obj(x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK-NOT: load [[ADDR]]
// CHECK: store [[SRC:%.*]] to [[ADDR]]
// CHECK-NOT: release [[SRC]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8init_gen
func init_gen<T>(x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [take] {{%.*}} to [initialization] [[ADDR]]
Builtin.initialize(x, y)
}
class C {}
class D {}
// CHECK-LABEL: sil hidden @_TF8builtins22class_to_native_object
func class_to_native_object(c:C) -> Builtin.NativeObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins23class_to_unknown_object
func class_to_unknown_object(c:C) -> Builtin.UnknownObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToUnknownObject(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins32class_archetype_to_native_object
func class_archetype_to_native_object<T : C>(t: T) -> Builtin.NativeObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins33class_archetype_to_unknown_object
func class_archetype_to_unknown_object<T : C>(t: T) -> Builtin.UnknownObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToUnknownObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins34class_existential_to_native_object
func class_existential_to_native_object(t:ClassProto) -> Builtin.NativeObject {
// CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto
// CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins35class_existential_to_unknown_object
func class_existential_to_unknown_object(t:ClassProto) -> Builtin.UnknownObject {
// CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto
// CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject
return Builtin.castToUnknownObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins24class_from_native_object
func class_from_native_object(p: Builtin.NativeObject) -> C {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins25class_from_unknown_object
func class_from_unknown_object(p: Builtin.UnknownObject) -> C {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins34class_archetype_from_native_object
func class_archetype_from_native_object<T : C>(p: Builtin.NativeObject) -> T {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins35class_archetype_from_unknown_object
func class_archetype_from_unknown_object<T : C>(p: Builtin.UnknownObject) -> T {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins41objc_class_existential_from_native_object
func objc_class_existential_from_native_object(p: Builtin.NativeObject) -> AnyObject {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins42objc_class_existential_from_unknown_object
func objc_class_existential_from_unknown_object(p: Builtin.UnknownObject) -> AnyObject {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins20class_to_raw_pointer
func class_to_raw_pointer(c: C) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
func class_archetype_to_raw_pointer<T : C>(t: T) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(t)
}
protocol CP: class {}
func existential_to_raw_pointer(p: CP) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins18obj_to_raw_pointer
func obj_to_raw_pointer(c: Builtin.NativeObject) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins22class_from_raw_pointer
func class_from_raw_pointer(p: Builtin.RawPointer) -> C {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
func class_archetype_from_raw_pointer<T : C>(p: Builtin.RawPointer) -> T {
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins20obj_from_raw_pointer
func obj_from_raw_pointer(p: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins28unknown_obj_from_raw_pointer
func unknown_obj_from_raw_pointer(p: Builtin.RawPointer) -> Builtin.UnknownObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins28existential_from_raw_pointer
func existential_from_raw_pointer(p: Builtin.RawPointer) -> AnyObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins5gep64
func gep64(p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gep_Int64(p, i)
}
// CHECK-LABEL: sil hidden @_TF8builtins5gep32
func gep32(p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gep_Int32(p, i)
}
// CHECK-LABEL: sil hidden @_TF8builtins8condfail
func condfail(i: Builtin.Int1) {
Builtin.condfail(i)
// CHECK: cond_fail {{%.*}} : $Builtin.Int1
}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: sil hidden @_TF8builtins10canBeClass
func canBeClass<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(O.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(OP1.self)
// -- FIXME: protocol<...> doesn't parse as a value
typealias ObjCCompo = protocol<OP1, OP2>
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(ObjCCompo.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(S.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(C.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(P.self)
typealias MixedCompo = protocol<OP1, P>
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompo.self)
// CHECK: builtin "canBeClass"<T>
Builtin.canBeClass(T.self)
}
// FIXME: "T.Type.self" does not parse as an expression
// CHECK-LABEL: sil hidden @_TF8builtins18canBeClassMetatype
func canBeClassMetatype<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 0
typealias OT = O.Type
Builtin.canBeClass(OT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias OP1T = OP1.Type
Builtin.canBeClass(OP1T.self)
// -- FIXME: protocol<...> doesn't parse as a value
typealias ObjCCompoT = protocol<OP1, OP2>.Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(ObjCCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias ST = S.Type
Builtin.canBeClass(ST.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias CT = C.Type
Builtin.canBeClass(CT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias PT = P.Type
Builtin.canBeClass(PT.self)
typealias MixedCompoT = protocol<OP1, P>.Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias TT = T.Type
Builtin.canBeClass(TT.self)
}
// CHECK-LABEL: sil hidden @_TF8builtins11fixLifetime
func fixLifetime(c: C) {
// CHECK: fix_lifetime %0 : $C
Builtin.fixLifetime(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins20assert_configuration
func assert_configuration() -> Builtin.Int32 {
return Builtin.assert_configuration()
// CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32
// CHECK: return [[APPLY]] : $Builtin.Int32
}
// CHECK-LABEL: sil hidden @_TF8builtins17assumeNonNegativeFBwBw
func assumeNonNegative(x: Builtin.Word) -> Builtin.Word {
return Builtin.assumeNonNegative_Word(x)
// CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word
// CHECK: return [[APPLY]] : $Builtin.Word
}
// CHECK-LABEL: sil hidden @_TF8builtins11autorelease
// CHECK: autorelease_value %0
func autorelease(o: O) {
Builtin.autorelease(o)
}
// The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during
// diagnostics.
// CHECK-LABEL: sil hidden @_TF8builtins11unreachable
// CHECK: builtin "unreachable"()
// CHECK: return
// CANONICAL-LABEL: sil hidden @_TF8builtins11unreachableFT_T_ : $@convention(thin) @noreturn () -> () {
// CANONICAL-NOT: builtin "unreachable"
// CANONICAL-NOT: return
// CANONICAL: unreachable
@noreturn func unreachable() {
Builtin.unreachable()
}
// CHECK-LABEL: sil hidden @_TF8builtins15reinterpretCastFTCS_1C1xBw_TBwCS_1DGSqS0__S0__ : $@convention(thin) (@owned C, Builtin.Word) -> @owned (Builtin.Word, D, Optional<C>, C)
// CHECK: bb0(%0 : $C, %1 : $Builtin.Word):
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value
// CHECK-NEXT: strong_retain %0 : $C
// CHECK-NEXT: unchecked_trivial_bit_cast %0 : $C to $Builtin.Word
// CHECK-NEXT: unchecked_ref_cast %0 : $C to $D
// CHECK-NEXT: unchecked_ref_cast %0 : $C to $Optional<C>
// CHECK-NEXT: unchecked_bitwise_cast %1 : $Builtin.Word to $C
// CHECK-NEXT: strong_retain %{{.*}} : $C
// CHECK-NOT: strong_retain
// CHECK-NOT: strong_release
// CHECK-NOT: release_value
// CHECK: return
func reinterpretCast(c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) {
return (Builtin.reinterpretCast(c) as Builtin.Word,
Builtin.reinterpretCast(c) as D,
Builtin.reinterpretCast(c) as C?,
Builtin.reinterpretCast(x) as C)
}
// CHECK-LABEL: sil hidden @_TF8builtins19reinterpretAddrOnly
func reinterpretAddrOnly<T, U>(t: T) -> U {
// CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins28reinterpretAddrOnlyToTrivial
func reinterpretAddrOnlyToTrivial<T>(t: T) -> Int {
// CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int
// CHECK: [[VALUE:%.*]] = load [[ADDR]]
// CHECK: destroy_addr [[INPUT]]
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins27reinterpretAddrOnlyLoadable
func reinterpretAddrOnlyLoadable<T>(a: Int, _ b: T) -> (T, Int) {
// CHECK: [[BUF:%.*]] = alloc_stack $Int
// CHECK: store {{%.*}} to [[BUF]]#1
// CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]]#1 : $*Int to $*T
// CHECK: copy_addr [[RES1]] to [initialization]
return (Builtin.reinterpretCast(a) as T,
// CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int
// CHECK: load [[RES]]
Builtin.reinterpretCast(b) as Int)
}
// CHECK-LABEL: sil hidden @_TF8builtins18castToBridgeObject
// CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word
// CHECK: return [[BO]]
func castToBridgeObject(c: C, _ w: Builtin.Word) -> Builtin.BridgeObject {
return Builtin.castToBridgeObject(c, w)
}
// CHECK-LABEL: sil hidden @_TF8builtins23castRefFromBridgeObject
// CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C
func castRefFromBridgeObject(bo: Builtin.BridgeObject) -> C {
return Builtin.castReferenceFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden @_TF8builtins30castBitPatternFromBridgeObject
// CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word
// CHECK: release [[BO]]
func castBitPatternFromBridgeObject(bo: Builtin.BridgeObject) -> Builtin.Word {
return Builtin.castBitPatternFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden @_TF8builtins14markDependence
// CHECK: [[T0:%.*]] = mark_dependence %0 : $Pointer on %1 : $ClassProto
// CHECK-NEXT: strong_release %1 : $ClassProto
// CHECK-NEXT: return [[T0]] : $Pointer
func markDependence(v: Pointer, _ base: ClassProto) -> Pointer {
return Builtin.markDependence(v, base)
}
// CHECK-LABEL: sil hidden @_TF8builtins8pinUnpin
// CHECK: bb0(%0 : $Builtin.NativeObject):
// CHECK-NEXT: debug_value
func pinUnpin(object : Builtin.NativeObject) {
// CHECK-NEXT: strong_retain %0 : $Builtin.NativeObject
// CHECK-NEXT: [[HANDLE:%.*]] = strong_pin %0 : $Builtin.NativeObject
// CHECK-NEXT: debug_value
// CHECK-NEXT: strong_release %0 : $Builtin.NativeObject
let handle : Builtin.NativeObject? = Builtin.tryPin(object)
// CHECK-NEXT: retain_value [[HANDLE]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_unpin [[HANDLE]] : $Optional<Builtin.NativeObject>
Builtin.unpin(handle)
// CHECK-NEXT: tuple ()
// CHECK-NEXT: release_value [[HANDLE]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_release %0 : $Builtin.NativeObject
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
}
// CHECK-LABEL: sil hidden @_TF8builtins19allocateValueBuffer
// CHECK: bb0([[BUFFER:%.*]] : $*Builtin.UnsafeValueBuffer):
// CHECK-NEXT: debug_value_addr %0 : $*Builtin.UnsafeValueBuffer // var buffer, argno: 1
// CHECK-NEXT: metatype $@thin Int.Type
// CHECK-NEXT: [[T0:%.*]] = alloc_value_buffer $Int in [[BUFFER]] : $*Builtin.UnsafeValueBuffer
// CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK-NEXT: return [[T1]] : $Builtin.RawPointer
func allocateValueBuffer(inout buffer: Builtin.UnsafeValueBuffer) -> Builtin.RawPointer {
return Builtin.allocValueBuffer(&buffer, Int.self)
}
// CHECK-LABEL: sil hidden @_TF8builtins18projectValueBuffer
// CHECK: bb0([[BUFFER:%.*]] : $*Builtin.UnsafeValueBuffer):
// CHECK-NEXT: debug_value_addr %0 : $*Builtin.UnsafeValueBuffer // var buffer, argno: 1
// CHECK-NEXT: metatype $@thin Int.Type
// CHECK-NEXT: [[T0:%.*]] = project_value_buffer $Int in [[BUFFER]] : $*Builtin.UnsafeValueBuffer
// CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK-NEXT: return [[T1]] : $Builtin.RawPointer
func projectValueBuffer(inout buffer: Builtin.UnsafeValueBuffer) -> Builtin.RawPointer {
return Builtin.projectValueBuffer(&buffer, Int.self)
}
// CHECK-LABEL: sil hidden @_TF8builtins18deallocValueBuffer
// CHECK: bb0([[BUFFER:%.*]] : $*Builtin.UnsafeValueBuffer):
//CHECK-NEXT: debug_value_addr %0 : $*Builtin.UnsafeValueBuffer // var buffer, argno: 1
// CHECK-NEXT: metatype $@thin Int.Type
// CHECK-NEXT: dealloc_value_buffer $Int in [[BUFFER]] : $*Builtin.UnsafeValueBuffer
// CHECK-NEXT: tuple ()
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
func deallocValueBuffer(inout buffer: Builtin.UnsafeValueBuffer) -> () {
Builtin.deallocValueBuffer(&buffer, Int.self)
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// NativeObject
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.NativeObject>
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Builtin.NativeObject>
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.NativeObject?) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// NativeObject nonNull
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.NativeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.NativeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.NativeObject
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.NativeObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// NativeObject pinned
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.NativeObject>
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Builtin.NativeObject>
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.NativeObject?) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// NativeObject pinned nonNull
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.NativeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.NativeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.NativeObject
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.NativeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// UnknownObject (ObjC)
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Optional<Builtin.UnknownObject>):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.UnknownObject>
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Optional<Builtin.UnknownObject>
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Optional<Builtin.UnknownObject>
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Optional<Builtin.UnknownObject>
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Builtin.UnknownObject>
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.UnknownObject?) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// UnknownObject (ObjC) nonNull
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Builtin.UnknownObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.UnknownObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.UnknownObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.UnknownObject
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.UnknownObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// UnknownObject (ObjC) pinned nonNull
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Builtin.UnknownObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.UnknownObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.UnknownObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.UnknownObject
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.UnknownObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// BridgeObject nonNull
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// BridgeObject pinned nonNull
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// BridgeObject nonNull native
// CHECK-LABEL: sil hidden @_TF8builtins15isUnique_native
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[CAST:%.*]] = unchecked_addr_cast [[BOX]]#1 : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[CAST]] : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUnique_native(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUnique_native(&ref))
}
// BridgeObject pinned nonNull native
// CHECK-LABEL: sil hidden @_TF8builtins23isUniqueOrPinned_native
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[CAST:%.*]] = unchecked_addr_cast [[BOX]]#1 : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUniqueOrPinned_native(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned_native(&ref))
}
// ----------------------------------------------------------------------------
// Builtin.castReference
// ----------------------------------------------------------------------------
class A {}
protocol PUnknown {}
protocol PClass : class {}
// CHECK-LABEL: sil hidden @_TF8builtins19refcast_generic_any
// CHECK: unchecked_ref_cast_addr T in %{{.*}}#1 : $*T to AnyObject in %{{.*}}#1 : $*AnyObject
func refcast_generic_any<T>(o: T) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins17refcast_class_any
// CHECK: unchecked_ref_cast %0 : $A to $AnyObject
// CHECK-NEXT: return
func refcast_class_any(o: A) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins20refcast_punknown_any
// CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}}#1 : $*PUnknown to AnyObject in %{{.*}}#1 : $*AnyObject
func refcast_punknown_any(o: PUnknown) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins18refcast_pclass_any
// CHECK: unchecked_ref_cast %0 : $PClass to $AnyObject
// CHECK-NEXT: return
func refcast_pclass_any(o: PClass) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins20refcast_any_punknown
// CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}}#1 : $*AnyObject to PUnknown in %{{.*}}#1 : $*PUnknown
func refcast_any_punknown(o: AnyObject) -> PUnknown {
return Builtin.castReference(o)
}
| apache-2.0 | e8bde4fb0436501a28daa46ae8969186 | 38.827048 | 178 | 0.66412 | 3.466161 | false | false | false | false |
hermantai/samples | ios/SwiftUI-Cookbook-2nd-Edition/Chapter07-Drawing-with-SwiftUI/05-Implementing-a-progress-ring/ProgressRings/ProgressRings/ContentView.swift | 1 | 2692 | //
// ContentView.swift
// ProgressRings
//
// Created by Giordano Scalzo on 02/07/2021.
//
import SwiftUI
struct ProgressRing: Shape {
private let startAngle = Angle.radians(1.5 * .pi)
@Binding
var progress: Double
func path(in rect: CGRect) -> Path {
Path() { path in
path.addArc(
center: CGPoint(x: rect.midX,
y: rect.midY),
radius: rect.width / 2,
startAngle: startAngle,
endAngle: startAngle +
Angle(
radians: 2 * .pi * progress),
clockwise: false
)
}
}
}
struct ProgressRingsView: View {
private let ringPadding = 5.0
private let ringWidth = 40.0
private var ringStrokeStyle: StrokeStyle {
StrokeStyle(lineWidth: ringWidth,
lineCap: .round,
lineJoin: .round)
}
@Binding
var progressExternal: Double
@Binding
var progressCentral: Double
@Binding
var progressInternal: Double
var body: some View {
ZStack {
ProgressRing(progress: $progressInternal)
.stroke(.blue,
style: ringStrokeStyle)
.padding(2*(ringWidth + ringPadding))
ProgressRing(progress: $progressCentral)
.stroke(.red,
style: ringStrokeStyle)
.padding(ringWidth + ringPadding)
ProgressRing(progress: $progressExternal)
.stroke(.green,
style: ringStrokeStyle)
}
.padding(ringWidth)
}
}
struct ContentView: View {
@State
private var progressExternal = 0.3
@State
private var progressCentral = 0.7
@State
private var progressInternal = 0.5
var body: some View {
ZStack {
ProgressRingsView(progressExternal: $progressExternal,
progressCentral: $progressCentral,
progressInternal: $progressInternal)
.aspectRatio(contentMode: .fit)
VStack(spacing: 10) {
Spacer()
Slider(value: $progressInternal,
in: 0...1, step: 0.01)
Slider(value: $progressCentral,
in: 0...1, step: 0.01)
Slider(value: $progressExternal,
in: 0...1, step: 0.01)
}
.padding(30)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| apache-2.0 | 5230f177390ee09ca74d8717d4ba2e23 | 26.469388 | 66 | 0.507058 | 4.930403 | false | false | false | false |
djtarazona/Toucan | ToucanPlayground.playground/section-1.swift | 12 | 4069 | // ToucanPlayground.playground
//
// Copyright (c) 2014 Gavin Bunney, Bunney Apps (http://bunney.net.au)
//
// 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
import Toucan
//
// Toucan Playground!
//
// Note: Due to a current limitation in Xcode6, you need to first Build the
// Toucan.framework for a 64bit device before running this playground :)
//
let portraitImage = UIImage(named: "Portrait.jpg")
let landscapeImage = UIImage(named: "Landscape.jpg")
let octagonMask = UIImage(named: "OctagonMask.png")
// ------------------------------------------------------------
// Resizing
// ------------------------------------------------------------
// Crop will resize to fit one dimension, then crop the other
Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Crop).image
// Clip will resize so one dimension is equal to the size, the other shrunk down to retain aspect ratio
Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Clip).image
// Scale will resize so the image fits exactly, altering the aspect ratio
Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Scale).image
// ------------------------------------------------------------
// Masking
// ------------------------------------------------------------
let landscapeCropped = Toucan(image: landscapeImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Crop).image
// We can mask with an ellipse!
Toucan(image: landscapeImage!).maskWithEllipse().image
// Demonstrate creating a circular mask -> resizes to a square image then mask with an ellipse
Toucan(image: landscapeCropped).maskWithEllipse().image
// Mask with borders too!
Toucan(image: landscapeCropped).maskWithEllipse(borderWidth: 10, borderColor: UIColor.yellowColor()).image
// Rounded Rects are all in style
Toucan(image: landscapeCropped).maskWithRoundedRect(cornerRadius: 30).image
// And can be fancy with borders
Toucan(image: landscapeCropped).maskWithRoundedRect(cornerRadius: 30, borderWidth: 10, borderColor: UIColor.purpleColor()).image
// Masking with an custom image mask
Toucan(image: landscapeCropped).maskWithImage(maskImage: octagonMask!).image
//testing the path stuff
let path = UIBezierPath()
path.moveToPoint(CGPointMake(0, 50))
path.addLineToPoint(CGPointMake(50, 0))
path.addLineToPoint(CGPointMake(100, 50))
path.addLineToPoint(CGPointMake(50, 100))
path.closePath()
Toucan(image: landscapeCropped).maskWithPath(path: path).image
Toucan(image: landscapeCropped).maskWithPathClosure(path: {(rect) -> (UIBezierPath) in
return UIBezierPath(roundedRect: rect, cornerRadius: 50.0)
}).image
// ------------------------------------------------------------
// Layers
// ------------------------------------------------------------
// We can draw ontop of another image
Toucan(image: portraitImage!).layerWithOverlayImage(octagonMask!, overlayFrame: CGRectMake(450, 400, 200, 200)).image
| mit | ef7fa60afa1a0b4e99e3a02463d189c2 | 41.831579 | 136 | 0.69796 | 4.551454 | false | false | false | false |
Henryforce/KRActivityIndicatorView | KRActivityIndicatorView/KRActivityIndicatorAnimationBallScaleMultiple.swift | 1 | 3124 | //
// KRActivityIndicatorAnimationBallScaleMultiple.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// 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 Cocoa
class KRActivityIndicatorAnimationBallScaleMultiple: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let duration: CFTimeInterval = 1
let beginTime = CACurrentMediaTime()
let beginTimes = [0, 0.2, 0.4]
// Scale animation
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.duration = duration
scaleAnimation.fromValue = 0
scaleAnimation.toValue = 1
// Opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.duration = duration
opacityAnimation.keyTimes = [0, 0.05, 1]
opacityAnimation.values = [0, 1, 0]
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw balls
for i in 0 ..< 3 {
let circle = KRActivityIndicatorShape.circle.layerWith(size: size, color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.opacity = 0
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
| mit | 9169bf38454d4a2123848539074b91e9 | 40.105263 | 96 | 0.666773 | 5.155116 | false | false | false | false |
khizkhiz/swift | stdlib/public/core/CompilerProtocols.swift | 1 | 8556 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Intrinsic protocols shared with the compiler
//===----------------------------------------------------------------------===//
/// A type that represents a Boolean value.
///
/// Types that conform to the `Boolean` protocol can be used as
/// the condition in control statements (`if`, `while`, C-style `for`)
/// and other logical value contexts (e.g., `case` statement guards).
///
/// Only three types provided by Swift, `Bool`, `DarwinBoolean`, and `ObjCBool`,
/// conform to `Boolean`. Expanding this set to include types that
/// represent more than simple boolean values is discouraged.
public protocol Boolean {
/// The value of `self`, expressed as a `Bool`.
var boolValue: Bool { get }
}
/// A type that can be converted to an associated "raw" type, then
/// converted back to produce an instance equivalent to the original.
public protocol RawRepresentable {
/// The "raw" type that can be used to represent all values of `Self`.
///
/// Every distinct value of `self` has a corresponding unique
/// value of `RawValue`, but `RawValue` may have representations
/// that do not correspond to a value of `Self`.
associatedtype RawValue
/// Convert from a value of `RawValue`, yielding `nil` iff
/// `rawValue` does not correspond to a value of `Self`.
init?(rawValue: RawValue)
/// The corresponding value of the "raw" type.
///
/// `Self(rawValue: self.rawValue)!` is equivalent to `self`.
var rawValue: RawValue { get }
}
/// Returns `true` iff `lhs.rawValue == rhs.rawValue`.
@warn_unused_result
public func == <
T : RawRepresentable where T.RawValue : Equatable
>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// Returns `true` iff `lhs.rawValue != rhs.rawValue`.
@warn_unused_result
public func != <
T : RawRepresentable where T.RawValue : Equatable
>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue != rhs.rawValue
}
// This overload is needed for ambiguity resolution against the
// implementation of != for T : Equatable
/// Returns `true` iff `lhs.rawValue != rhs.rawValue`.
@warn_unused_result
public func != <
T : Equatable where T : RawRepresentable, T.RawValue : Equatable
>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue != rhs.rawValue
}
/// Conforming types can be initialized with `nil`.
public protocol NilLiteralConvertible {
/// Create an instance initialized with `nil`.
init(nilLiteral: ())
}
public protocol _BuiltinIntegerLiteralConvertible {
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType)
}
/// Conforming types can be initialized with integer literals.
public protocol IntegerLiteralConvertible {
associatedtype IntegerLiteralType : _BuiltinIntegerLiteralConvertible
/// Create an instance initialized to `value`.
init(integerLiteral value: IntegerLiteralType)
}
public protocol _BuiltinFloatLiteralConvertible {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
/// Conforming types can be initialized with floating point literals.
public protocol FloatLiteralConvertible {
associatedtype FloatLiteralType : _BuiltinFloatLiteralConvertible
/// Create an instance initialized to `value`.
init(floatLiteral value: FloatLiteralType)
}
public protocol _BuiltinBooleanLiteralConvertible {
init(_builtinBooleanLiteral value: Builtin.Int1)
}
/// Conforming types can be initialized with the Boolean literals
/// `true` and `false`.
public protocol BooleanLiteralConvertible {
associatedtype BooleanLiteralType : _BuiltinBooleanLiteralConvertible
/// Create an instance initialized to `value`.
init(booleanLiteral value: BooleanLiteralType)
}
public protocol _BuiltinUnicodeScalarLiteralConvertible {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
}
/// Conforming types can be initialized with string literals
/// containing a single [Unicode scalar value](http://www.unicode.org/glossary/#unicode_scalar_value).
public protocol UnicodeScalarLiteralConvertible {
associatedtype UnicodeScalarLiteralType : _BuiltinUnicodeScalarLiteralConvertible
/// Create an instance initialized to `value`.
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
public protocol _BuiltinExtendedGraphemeClusterLiteralConvertible
: _BuiltinUnicodeScalarLiteralConvertible {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// Conforming types can be initialized with string literals
/// containing a single [Unicode extended grapheme cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster).
public protocol ExtendedGraphemeClusterLiteralConvertible
: UnicodeScalarLiteralConvertible {
associatedtype ExtendedGraphemeClusterLiteralType
: _BuiltinExtendedGraphemeClusterLiteralConvertible
/// Create an instance initialized to `value`.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
public protocol _BuiltinStringLiteralConvertible
: _BuiltinExtendedGraphemeClusterLiteralConvertible {
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
public protocol _BuiltinUTF16StringLiteralConvertible
: _BuiltinStringLiteralConvertible {
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word)
}
/// Conforming types can be initialized with arbitrary string literals.
public protocol StringLiteralConvertible
: ExtendedGraphemeClusterLiteralConvertible {
// FIXME: when we have default function implementations in protocols, provide
// an implementation of init(extendedGraphemeClusterLiteral:).
associatedtype StringLiteralType : _BuiltinStringLiteralConvertible
/// Create an instance initialized to `value`.
init(stringLiteral value: StringLiteralType)
}
/// Conforming types can be initialized with array literals.
public protocol ArrayLiteralConvertible {
associatedtype Element
/// Create an instance initialized with `elements`.
init(arrayLiteral elements: Element...)
}
/// Conforming types can be initialized with dictionary literals.
public protocol DictionaryLiteralConvertible {
associatedtype Key
associatedtype Value
/// Create an instance initialized with `elements`.
init(dictionaryLiteral elements: (Key, Value)...)
}
/// Conforming types can be initialized with string interpolations
/// containing `\(`...`)` clauses.
public protocol StringInterpolationConvertible {
/// Create an instance by concatenating the elements of `strings`.
init(stringInterpolation strings: Self...)
/// Create an instance containing `expr`'s `print` representation.
init<T>(stringInterpolationSegment expr: T)
}
/// Conforming types can be initialized with color literals (e.g.
/// `[#Color(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1)#]`).
public protocol _ColorLiteralConvertible {
init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)
}
/// Conforming types can be initialized with image literals (e.g.
/// `[#Image(imageLiteral: "hi.png")#]`).
public protocol _ImageLiteralConvertible {
init(imageLiteral: String)
}
/// Conforming types can be initialized with strings (e.g.
/// `[#FileReference(fileReferenceLiteral: "resource.txt")#]`).
public protocol _FileReferenceLiteralConvertible {
init(fileReferenceLiteral: String)
}
/// A container is destructor safe if whether it may store to memory on
/// destruction only depends on its type parameters.
/// For example, whether `Array<Element>` may store to memory on destruction
/// depends only on `Element`.
/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory
/// during destruction. If `Element` is an arbitrary class
/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may
/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s
/// destructor may store to memory on destruction.
public protocol _DestructorSafeContainer {
}
@available(*, unavailable, renamed="Boolean")
public typealias BooleanType = Boolean
| apache-2.0 | f37410163f0c59f6eedd29c3acc4ded4 | 36.2 | 120 | 0.739598 | 5.029982 | false | false | false | false |
JGiola/swift-corelibs-foundation | TestFoundation/TestURLProtocol.swift | 4 | 6779 | // 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
//
class TestURLProtocol : LoopbackServerTest {
static var allTests: [(String, (TestURLProtocol) -> () throws -> Void)] {
return [
("test_interceptResponse", test_interceptResponse),
("test_interceptRequest", test_interceptRequest),
("test_multipleCustomProtocols", test_multipleCustomProtocols),
("test_customProtocolResponseWithDelegate", test_customProtocolResponseWithDelegate),
("test_customProtocolSetDataInResponseWithDelegate", test_customProtocolSetDataInResponseWithDelegate),
]
}
func test_interceptResponse() {
let urlString = "http://127.0.0.1:\(TestURLProtocol.serverPort)/USA"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.protocolClasses = [CustomProtocol.self]
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): with a custom protocol")
let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
return
}
let httpResponse = response as! HTTPURLResponse?
XCTAssertEqual(429, httpResponse!.statusCode, "HTTP response code is not 429")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_interceptRequest() {
let urlString = "ssh://127.0.0.1:\(TestURLProtocol.serverPort)/USA"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.protocolClasses = [InterceptableRequest.self]
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let expect = expectation(description: "GET \(urlString): with a custom protocol")
let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
return
}
let httpResponse = response as! HTTPURLResponse?
let responseURL = URL(string: "http://google.com")
XCTAssertEqual(responseURL, httpResponse?.url, "Unexpected url")
XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_multipleCustomProtocols() {
let urlString = "http://127.0.0.1:\(TestURLProtocol.serverPort)/Nepal"
let url = URL(string: urlString)!
let config = URLSessionConfiguration.default
config.protocolClasses = [InterceptableRequest.self, CustomProtocol.self]
let expect = expectation(description: "GET \(urlString): with a custom protocol")
let session = URLSession(configuration: config)
let task = session.dataTask(with: url) { data, response, error in
defer { expect.fulfill() }
if let e = error as? URLError {
XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
return
}
let httpResponse = response as! HTTPURLResponse
print(httpResponse.statusCode)
XCTAssertEqual(429, httpResponse.statusCode, "Status code is not 429")
}
task.resume()
waitForExpectations(timeout: 12)
}
func test_customProtocolResponseWithDelegate() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Peru"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self])
d.responseReceivedExpectation = expectation(description: "GET \(urlString): response received")
d.run(with: url)
waitForExpectations(timeout: 12)
}
func test_customProtocolSetDataInResponseWithDelegate() {
let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
let url = URL(string: urlString)!
let d = DataTask(with: expectation(description: "GET \(urlString): with a custom protocol and delegate"), protocolClasses: [CustomProtocol.self])
d.run(with: url)
waitForExpectations(timeout: 12)
if !d.error {
XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result")
}
}
}
class InterceptableRequest : URLProtocol {
override class func canInit(with request: URLRequest) -> Bool {
return request.url?.scheme == "ssh"
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
let urlString = "http://google.com"
let url = URL(string: urlString)!
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])
self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {
return
}
}
class CustomProtocol : URLProtocol {
override class func canInit(with request: URLRequest) -> Bool {
return true
}
func sendResponse(statusCode: Int, headers: [String: String] = [:], data: Data) {
let response = HTTPURLResponse(url: self.request.url!, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers)
let capital = "Kathmandu"
let data = capital.data(using: .utf8)
self.client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocol(self, didLoad: data!)
self.client?.urlProtocolDidFinishLoading(self)
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
sendResponse(statusCode: 429, data: Data())
}
override func stopLoading() {
return
}
}
| apache-2.0 | 47ede071c505a68c9719d6ef8a354927 | 41.905063 | 153 | 0.647441 | 4.876978 | false | true | false | false |
TongjiUAppleClub/WeCitizens | WeCitizens/VoiceModel.swift | 1 | 13712 | //
// VoiceModel.swift
// WeCitizens
//
// Created by Teng on 3/27/16.
// Copyright © 2016 Tongji Apple Club. All rights reserved.
//
import Foundation
import Parse
import PromiseKit
// TODO:1. Voice添加赞同数量
class VoiceModel: DataModel {
//获取指定数量Voice,code completed
func getVoice(queryNum: Int, queryTimes: Int, cityName:String, needStore:Bool, resultHandler: ([Voice]?, NSError?) -> Void) {
let query = PFQuery(className:"Voice")
query.whereKey("city", equalTo: cityName)
query.limit = queryNum
query.skip = queryNum * queryTimes
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
print("Successfully retrieved \(objects!.count) voice from remote.")
if let results = objects {
if needStore {
PFObject.pinAllInBackground(results)
}
let voice = self.convertPFObjectToVoice(results)
let emails = voice.map({ (tmp) -> String in
return tmp.userEmail
})
UserModel().getUsersInfo(emails, needStore: needStore, resultHandler: { (users, userError) -> Void in
if let _ = userError {
resultHandler(voice, userError)
}
if let newUsers = users {
voice.forEach({ (currentVoice) -> () in
for user in newUsers {
if user.userEmail == currentVoice.userEmail {
currentVoice.user = user
break
}
}
})
resultHandler(voice, nil)
}
})
} else {
resultHandler(nil, nil)
}
} else {
print("Get voice from remote Error: \(error!) \(error!.userInfo)")
resultHandler(nil, error)
}
}
}
func getVoice(city:String, fromLocal resultHandler: ([Voice]?, NSError?) -> Void) {
let query = PFQuery(className: "Voice")
query.fromLocalDatastore()
query.whereKey("city", equalTo: city)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
print("Successfully retrieved \(objects!.count) voice from local")
if let results = objects {
let voice = self.convertPFObjectToVoice(results)
let emails = voice.map({ (tmp) -> String in
return tmp.userEmail
})
let userModel = UserModel()
userModel.getUsersInfo(fromLocal: emails, resultHandler: { (users, userError) -> Void in
if let _ = userError {
resultHandler(voice, userError)
}
if let newUsers = users {
voice.forEach({ (currentVoice) -> () in
for user in newUsers {
if user.userEmail == currentVoice.userEmail {
currentVoice.user = user
break
}
}
})
resultHandler(voice, nil)
} else {
print("get user from local fail when getting voice")
userModel.getUsersInfo(emails, needStore: false, resultHandler: { (users, userError) -> Void in
if let _ = userError {
resultHandler(voice, userError)
}
if let newUsers = users {
voice.forEach({ (currentVoice) -> () in
for user in newUsers {
if user.userEmail == currentVoice.userEmail {
currentVoice.user = user
break
}
}
})
resultHandler(voice, nil)
}
})
}
})
} else {
resultHandler(nil, nil)
}
} else {
print("Get voice from local Error: \(error!) \(error!.userInfo)")
resultHandler(nil, error)
}
}
}
func convertPFObjectToVoice(objects: [PFObject]) -> [Voice] {
var voice = [Voice]()
for result in objects {
let name = result.objectForKey("userName") as! String
let email = result.objectForKey("userEmail") as! String
let id = result.objectId!
let time = result.createdAt!
let title = result.objectForKey("title") as! String
let abstract = result.objectForKey("abstract") as! String
let content = result.objectForKey("content") as! String
let status = result.objectForKey("status") as! Bool
let classifyStr = result.objectForKey("classify") as! String
let focusNum = result.objectForKey("focusNum") as! Int
let city = result.objectForKey("city") as! String
let isReplied = result.objectForKey("isReplied") as! Bool
let replyId = result.objectForKey("replyId") as! String
let lat = result.objectForKey("latitude") as! Double
let lon = result.objectForKey("longitude") as! Double
let images = result.objectForKey("images") as! NSArray
let imageList = super.convertArrayToImages(images)
let newVoice = Voice(voiceIdFromRemote: id, email: email, name: name, date: time, title: title, abstract: abstract, content: content, status: status, classify: classifyStr, focusNum: focusNum, city: city, replied: isReplied, replyId: replyId, latitude: lat, longitude: lon, images: imageList)
voice.append(newVoice)
}
return voice
}
//新建Voice
func addNewVoice(newVoice: Voice) -> Promise<Bool> {
let voice = PFObject(className: "Voice")
//给voice赋值...
voice["userName"] = newVoice.userName
voice["userEmail"] = newVoice.userEmail
voice["title"] = newVoice.title
voice["abstract"] = newVoice.abstract
voice["content"] = newVoice.content
voice["status"] = newVoice.status
voice["classify"] = newVoice.classify
voice["focusNum"] = newVoice.focusNum
voice["city"] = newVoice.city
voice["isReplied"] = newVoice.isReplied
voice["replyId"] = newVoice.replyId
voice["latitude"] = newVoice.latitude
voice["longitude"] = newVoice.longitude
voice["images"] = self.convertImageToPFFile(newVoice.images)
return Promise { fulfill, reject in
voice.saveInBackgroundWithBlock{ isSuccess, error in
if nil != error {
reject(error!)
} else {
if isSuccess {
fulfill(true)
} else {
let err = NSError(domain: "新建voice失败", code: 101, userInfo: nil)
reject(err)
}
}
}
}
}
//为Voice增加一个关注,code complete
func addFocusNum(voiceId: String, resultHandler:(Bool, NSError?) -> Void) {
let query = PFQuery(className: "Voice")
query.whereKey("objectId", equalTo: voiceId)
do {
let result = try query.getFirstObject()
var currentNum = result.valueForKey("focusNum") as! Int
print("current number:\(currentNum)")
currentNum += 1
result.setValue(currentNum, forKey: "focusNum")
result.saveInBackgroundWithBlock(resultHandler)
} catch {
print("there is error")
resultHandler(false, nil)
}
}
//为Voice减少一个关注,code complete
func minusFocusNum(voiceId:String, resultHandler:(Bool, NSError?) -> Void) {
let query = PFQuery(className: "Voice")
query.whereKey("objectId", equalTo: voiceId)
do {
let result = try query.getFirstObject()
var currentNum = result.valueForKey("focusNum") as! Int
print("current number:\(currentNum)")
currentNum -= 1
result.setValue(currentNum, forKey: "focusNum")
result.saveInBackgroundWithBlock(resultHandler)
} catch {
print("there is error")
resultHandler(false, nil)
}
}
//根据voiceId获取voice
func getVoice(withId voiceId:String, resultHandler: (Voice?, NSError?) -> Void) {
let query = PFQuery(className: "Voice")
query.getObjectInBackgroundWithId(voiceId) { (object, error) -> Void in
if nil == error {
if let result = object {
let name = result.objectForKey("userName") as! String
let email = result.objectForKey("userEmail") as! String
let id = result.objectId!
let time = result.createdAt!
let title = result.objectForKey("title") as! String
let abstract = result.objectForKey("abstract") as! String
let content = result.objectForKey("content") as! String
let status = result.objectForKey("status") as! Bool
let classifyStr = result.objectForKey("classify") as! String
let focusNum = result.objectForKey("focusNum") as! Int
let city = result.objectForKey("city") as! String
let isReplied = result.objectForKey("isReplied") as! Bool
let replyId = result.objectForKey("replyId") as! String
let lat = result.objectForKey("latitude") as! Double
let lon = result.objectForKey("longitude") as! Double
let images = result.objectForKey("images") as! NSArray
let imageList = super.convertArrayToImages(images)
let newVoice = Voice(voiceIdFromRemote: id, email: email, name: name, date: time, title: title, abstract: abstract, content: content, status: status, classify: classifyStr, focusNum: focusNum, city: city, replied: isReplied, replyId: replyId, latitude: lat, longitude: lon, images: imageList)
UserModel().getUserInfo(email, resultHandler: { (newUser, error) in
if let _ = error {
print("get user error when get voice with id")
resultHandler(nil, error)
} else {
if let user = newUser {
newVoice.user = user
resultHandler(newVoice, nil)
} else {
print("do not get user when get voice with id")
resultHandler(nil, nil)
}
}
})
} else {
//没找到voice
resultHandler(nil, nil)
}
} else {
resultHandler(nil, error)
}
}
}
// 根据voiceID获取voicetitle数组,用于在关注列表里显示
func getVoiceTitles(voiceIds:[String]) -> Promise<[(String, String)]> {
let query = PFQuery(className: "Voice")
query.whereKey("objectId", containedIn: voiceIds)
return Promise { fulfill, reject in
query.findObjectsInBackgroundWithBlock { objects, error in
if error == nil {
if let results = objects {
let voices = results.map { (voice) -> (String, String) in
let title = voice.valueForKey("title") as! String
return (title:title, id: voice.objectId!)
}
fulfill(voices)
} else {
let err = NSError(domain: "没有获取到Voice的Title", code: 100, userInfo: nil)
reject(err)
}
} else {
reject(error!)
}
}
}
}
} | mit | b62800259a6fedeece29e4169360d389 | 41.576803 | 313 | 0.466534 | 5.884315 | false | false | false | false |
Incipia/Conduction | Conduction/Classes/ConductionWrapper.swift | 1 | 2637 | //
// ConductionWrapper.swift
// Bindable
//
// Created by Gregory Klein on 6/28/17.
//
import Foundation
open class StaticConductionWrapper<DataModel> {
// MARK: - Public Properties
public let model: DataModel
// MARK: - Init
public init(model: DataModel) {
self.model = model
}
}
public protocol ConductionWrapperObserverType: class {
// MARK: - Associated Types
associatedtype DataModel
typealias ModelChangeBlock = (_ old: DataModel, _ new: DataModel) -> Void
// MARK: - Public Properties
var model: DataModel! { get }
var _modelChangeBlocks: [ConductionObserverHandle : ModelChangeBlock] { get set }
// MARK: - Public
@discardableResult func addModelObserver(_ changeBlock: @escaping ModelChangeBlock) -> ConductionObserverHandle
func removeModelObserver(handle: ConductionObserverHandle)
func modelChanged(oldModel: DataModel?)
}
public extension ConductionWrapperObserverType {
@discardableResult public func addModelObserver(_ changeBlock: @escaping ModelChangeBlock) -> ConductionObserverHandle {
if let model = model {
changeBlock(model, model)
}
return _modelChangeBlocks.add(newValue: changeBlock)
}
public func removeModelObserver(handle: ConductionObserverHandle) {
_modelChangeBlocks[handle] = nil
}
public func modelChanged(oldModel: DataModel? = nil) {
guard oldModel != nil || model != nil else { return }
_modelChangeBlocks.forEach { $0.value(oldModel ?? model, model ?? oldModel!) }
}
}
open class StatelessConductionWrapper<DataModel>: ConductionWrapperObserverType {
// MARK: - Nested Types
public typealias ModelChangeBlock = (_ old: DataModel, _ new: DataModel) -> Void
// MARK: - Private Properties
public var _modelChangeBlocks: [ConductionObserverHandle : ModelChangeBlock] = [:]
// MARK: - Public Properties
public var model: DataModel! {
didSet { modelChanged(oldModel: oldValue) }
}
public var hasModel: Bool { return model != nil }
// MARK: - Init
public init(model: DataModel?) {
self.model = model
}
}
open class ConductionWrapper<DataModel, State: ConductionState>: StatelessConductionWrapper<DataModel>, ConductionStateObserverType {
// MARK: - Nested Types
public typealias StateChangeBlock = (_ old: State, _ new: State) -> Void
// MARK: - Private Properties
public var _stateChangeBlocks: [ConductionObserverHandle : StateChangeBlock] = [:]
// MARK: - Public Properties
public var state: State = State() {
didSet { stateChanged(oldState: oldValue) }
}
}
| mit | c3a5fa6e80434b86e4ea0d5e3cb37b27 | 29.310345 | 133 | 0.693591 | 4.725806 | false | false | false | false |
xivol/MCS-V3-Mobile | examples/networking/firebase-test/firebase-test/Model/Note.swift | 1 | 1742 | //
// Note.swift
// firebase-test
//
// Created by Илья Лошкарёв on 15.11.2017.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import Foundation
import FirebaseDatabase
import UIKit
extension DateFormatter {
static var defaultFormatter: DateFormatter {
let df = DateFormatter()
df.timeZone = TimeZone.current
df.dateFormat = "HH:mm:ss dd.MM.yyyy"
return df
}
}
struct Note: Codable, FireDataRepresentable {
let date: Date
let title: String
let text: String
static var path: String {
return "notes"
}
let fireId: String!
static func decode(fromSnapshot snapshot: DataSnapshot) -> Note? {
guard let values = snapshot.value as? [String:Any] else {return nil}
let date = DateFormatter.defaultFormatter.date(from: values[CodingKeys.date.stringValue] as! String)
let title = values[CodingKeys.title.stringValue] as! String
let text = values[CodingKeys.text.stringValue] as! String
return Note(date: date ?? Date(), title: title, text: text, fireId: snapshot.key)
}
func encode(toChild child: DatabaseReference) {
child.setValue([CodingKeys.date.stringValue : DateFormatter.defaultFormatter.string(from: date),
CodingKeys.title.stringValue : title,
CodingKeys.text.stringValue : text])
}
}
extension Note: UIViewRepresentable {
func setup(view: UIReusableType) {
if let cell = view as? UITableViewCell {
cell.detailTextLabel?.text = DateFormatter.defaultFormatter.string(for: self.date)
cell.textLabel?.text = self.title
}
}
}
| mit | 6fa0b2110d00b3a76ede78aece9b827f | 28.101695 | 108 | 0.641817 | 4.436693 | false | false | false | false |
slepcat/mint | MINT/MintLeafPrimitives.swift | 1 | 19338 | //
// MintLeafPrimitives.swift
// MINT
//
// Created by NemuNeko on 2015/03/09.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
// Primitive class
// Base class for all primitive solids. For example, cube, sphere, cylinder, and so on.
// This class itself will not be instantiated
class Primitive:Leaf {
var mesh : Mesh?
override init(newID: Int) {
super.init(newID: newID)
args = [Vector(x: 0, y: 0, z: 0)]
argLabels = ["center"]
argTypes = ["Vector"]
returnType = "Mesh"
name = "null_mesh"
}
override func initArg(label: String) {
super.initArg(label)
if label == "center" {
setArg("center", value: Vector(x: 0, y: 0, z: 0))
} else {
MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label))
}
}
}
class Cube:Primitive{
override init(newID: Int) {
super.init(newID: newID)
args += [10.0, 10.0, 10.0]
argLabels += ["width", "height", "depth"]
argTypes += ["Double", "Double", "Double"]
let count = BirthCount.get.count("Cube")
name = "Cube\(count)"
}
override func initArg(label: String) {
super.initArg(label)
if let err = MintErr.exc.catch {
switch label {
case "width":
setArg("width", value:10.0)
case "height":
setArg("height", value:10.0)
case "depth":
setArg("depth", value:10.0)
case "all":
super.initArg("center")
setArg("width", value:10.0)
setArg("height", value:10.0)
setArg("depth", value:10.0)
default:
MintErr.exc.raise(err)
}
}
}
override func solve() -> Any? {
if mesh != nil && needUpdate == false {
return mesh
}
if let err = MintErr.exc.catch {
MintErr.exc.raise(err)
return nil
}
//type cast args
if let width = eval("width") as? Double, let height = eval("height") as? Double, let depth = eval("depth") as? Double, let center = eval("center") as? Vector {
let left = -width/2 + center.x
let right = width/2 + center.x
let front = -depth/2 + center.z
let back = depth/2 + center.z
let bottom = -height/2 + center.y
let top = height/2 + center.y
var vertices : [Vertex] = []
vertices += [Vertex(pos: Vector(x: right, y: back, z: bottom))] //bottom
vertices += [Vertex(pos: Vector(x: right, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: back, z: bottom))]
vertices += [Vertex(pos: Vector(x: right, y: back, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: bottom))] // front
vertices += [Vertex(pos: Vector(x: right, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: right, y: front, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: front, z: top))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: top))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: right, y: front, z: bottom))] //right
vertices += [Vertex(pos: Vector(x: right, y: back, z: bottom))]
vertices += [Vertex(pos: Vector(x: right, y: back, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: back, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: front, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: right, y: back, z: top))] // back
vertices += [Vertex(pos: Vector(x: right, y: back, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: back, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: back, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: back, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: back, z: top))]
vertices += [Vertex(pos: Vector(x: left, y: back, z: top))] //left
vertices += [Vertex(pos: Vector(x: left, y: back, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: bottom))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: top))]
vertices += [Vertex(pos: Vector(x: left, y: back, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: back, z: top))] // top
vertices += [Vertex(pos: Vector(x: left, y: front, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: front, z: top))]
vertices += [Vertex(pos: Vector(x: right, y: back, z: top))]
vertices += [Vertex(pos: Vector(x: left, y: back, z: top))]
vertices += [Vertex(pos: Vector(x: left, y: front, z: top))]
var poly : [Polygon] = []
for var i = 0; i < vertices.count; i += 3 {
poly += [Polygon(vertices: [vertices[i], vertices[i + 1], vertices[i + 2]])]
}
mesh = Mesh(m: poly)
needUpdate = false
return mesh
}
MintErr.exc.raise(MintEXC.SolverFailed(leafName: name, leafID: leafID))
return nil
}
}
// Construct a solid sphere
// Solve() implementation came from OpenJSCAD
//
// Parameters:
// center: center of sphere (default [0,0,0])
// radius: radius of sphere (default 1), must be a scalar
// resolution: determines the number of polygons per 360 degree revolution (default 12)
// axes: (optional) an array with 3 vectors for the x, y and z base vectors
class Sphere:Primitive{
override init(newID: Int) {
super.init(newID: newID)
args += [5.0, 32]
argLabels += ["radius", "resolution"]
argTypes += ["Double", "Int"]
let count = BirthCount.get.count("Sphere")
name = "Sphere\(count)"
}
override func initArg(label: String) {
super.initArg(label)
if let err = MintErr.exc.catch {
switch label {
case "radius":
setArg("radius", value:5.0)
default:
MintErr.exc.raise(err)
}
}
}
override func solve() -> Any? {
if mesh != nil && needUpdate == false {
return mesh
}
if let err = MintErr.exc.catch {
MintErr.exc.raise(err)
return nil
}
//type cast args
if var radius = eval("radius") as? Double, let center = eval("center") as? Vector, var resolution = eval("resolution") as? Int {
if radius < 0 {
radius = -radius
}
if resolution < 4 {
resolution = 4
}
var xvector = Vector(x: 1, y: 0, z: 0).times(radius)
var yvector = Vector(x: 0, y: -1, z: 0).times(radius)
var zvector = Vector(x: 0, y: 0, z: 1).times(radius)
var qresolution = Int(round(Double(resolution / 4)))
var prevcylinderpoint : Vector = Vector(x: 0, y: 0, z: 0)
var polygons : [Polygon] = []
for var slice1 = 0; slice1 <= resolution; slice1++ {
var angle = M_PI * 2.0 * Double(slice1) / Double(resolution)
var cylinderpoint = xvector.times(cos(angle)) + yvector.times(sin(angle))
if slice1 > 0 {
// cylinder vertices:
var prevcospitch : Double = 0
var prevsinpitch : Double = 0
for var slice2 = 0; slice2 <= qresolution; slice2++ {
var pitch = 0.5 * M_PI * Double(slice2) / Double(qresolution)
var cospitch = cos(pitch)
var sinpitch = sin(pitch)
if(slice2 > 0) {
var vertices : [Vertex] = []
vertices.append(Vertex(pos: center + (prevcylinderpoint.times(prevcospitch) - zvector.times(prevsinpitch))))
vertices.append(Vertex(pos: center + (cylinderpoint.times(prevcospitch) - zvector.times(prevsinpitch))))
if slice2 < qresolution {
vertices.append(Vertex(pos: center + (cylinderpoint.times(cospitch) - zvector.times(sinpitch))))
}
vertices.append(Vertex(pos: center + (prevcylinderpoint.times(cospitch) - zvector.times(sinpitch))))
polygons.append(Polygon(vertices: vertices))
vertices = []
vertices.append(Vertex(pos: center + (prevcylinderpoint.times(prevcospitch) + zvector.times(prevsinpitch))))
vertices.append(Vertex(pos: center + (cylinderpoint.times(prevcospitch) + zvector.times(prevsinpitch))))
if(slice2 < qresolution) {
vertices.append(Vertex(pos: center + (cylinderpoint.times(cospitch) + zvector.times(sinpitch))))
}
vertices.append(Vertex(pos: center + (prevcylinderpoint.times(cospitch) + zvector.times(sinpitch))))
polygons.append(Polygon(vertices: vertices.reverse()))
}
prevcospitch = cospitch
prevsinpitch = sinpitch
}
}
prevcylinderpoint = cylinderpoint
}
mesh = Mesh(m: polygons)
needUpdate = false
return mesh
}
MintErr.exc.raise(MintEXC.SolverFailed(leafName: name, leafID: leafID))
return nil
}
}
// Construct a solid cylinder.
// Solve() implementation came from OpenJSCAD
//
// Parameters:
// height: height of cylinder
// radius: radius of cylinder (default 5), must be a scalar
// resolution: determines the number of polygons per 360 degree revolution (default 12)
class Cylinder:Primitive{
override init(newID: Int) {
super.init(newID: newID)
args += [5.0, 10.0, 32]
argLabels += ["radius", "height", "resolution"]
argTypes += ["Double", "Double", "Int"]
let count = BirthCount.get.count("Cylinder")
name = "Cylinder\(count)"
}
override func initArg(label: String) {
super.initArg(label)
if let err = MintErr.exc.catch {
switch label {
case "radius":
setArg("radius", value:5.0)
case "height":
setArg("height", value:10.0)
default:
MintErr.exc.raise(err)
}
}
}
override func solve() -> Any? {
if mesh != nil && needUpdate == false {
return mesh
}
if let err = MintErr.exc.catch {
MintErr.exc.raise(err)
return nil
}
//type cast args
if var radius = eval("radius") as? Double, var height = eval("height") as? Double, let center = eval("center") as? Vector, var resolution = eval("resolution") as? Int {
// handle minus values
if height < 0 {
height = -height
}
if radius < 0 {
radius = -radius
}
if resolution < 4 {
resolution = 4
}
var s = Vector(x: 0, y: 0, z: -1).times(height/2) + center
var e = Vector(x: 0, y: 0, z: 1).times(height/2) + center
var r = radius
var rEnd = radius
var rStart = radius
var slices = resolution
var ray = e - s
var axisZ = ray.unit() //, isY = (Math.abs(axisZ.y) > 0.5);
var axisX = axisZ.randomNonParallelVector().unit()
// var axisX = new CSG.Vector3D(isY, !isY, 0).cross(axisZ).unit();
var axisY = axisX.cross(axisZ).unit()
var start = Vertex(pos: s)
var end = Vertex(pos: e)
var polygons : [Polygon] = []
func point(stack : Double, slice : Double, radius : Double) -> Vertex {
var angle = slice * M_PI * 2
var out = axisX.times(cos(angle)) + axisY.times(sin(angle))
var pos = s + ray.times(stack) + out.times(radius)
return Vertex(pos: pos)
}
for(var i = 0; i < slices; i++) {
var t0 = Double(i) / Double(slices)
var t1 = Double(i + 1) / Double(slices)
//if rEnd == rStart { // current arguments cannot take 'rEnd' & 'rStart'
polygons.append(Polygon(vertices: [start, point(0, t0, rEnd), point(0, t1, rEnd)]))
polygons.append(Polygon(vertices: [point(0, t1, rEnd), point(0, t0, rEnd), point(1, t0, rEnd), point(1, t1, rEnd)]))
polygons.append(Polygon(vertices: [end, point(1, t1, rEnd), point(1, t0, rEnd)]))
/*} else {
if(rStart > 0) {
polygons.append(Polygon(vertices: [start, point(0, t0, rStart), point(0, t1, rStart)]))
polygons.append(Polygon(vertices: [point(0, t0, rStart), point(1, t0, rEnd), point(0, t1, rStart)]))
}
if(rEnd > 0) {
polygons.append(Polygon(vertices: [end, point(1, t1, rEnd), point(1, t0, rEnd)]))
polygons.append(Polygon(vertices: [point(1, t0, rEnd), point(1, t1, rEnd), point(0, t1, rStart)]))
}
}*/
}
mesh = Mesh(m: polygons)
needUpdate = false
return mesh
}
MintErr.exc.raise(MintEXC.SolverFailed(leafName: name, leafID: leafID))
return nil
}
}
/*
// Cylinder Solid
// Derived from Sphere of OpenJSCAD, Inferior mesh quality. use above ver.
class Cylinder:Primitive{
override init(newID: Int) {
super.init(newID: newID)
args += [5.0, 10.0, 32]
argLabels += ["radius", "height", "resolution"]
argTypes += ["Double", "Double", "Int"]
let count = BirthCount.get.count("Cylinder")
name = "Cylinder\(count)"
}
override func initArg(label: String) {
super.initArg(label)
if let err = MintErr.exc.catch {
switch label {
case "radius":
setArg("radius", value:5.0)
case "height":
setArg("height", value:10.0)
default:
MintErr.exc.raise(err)
}
}
}
override func solve() -> Any? {
if mesh != nil && needUpdate == false {
return mesh
}
if let err = MintErr.exc.catch {
MintErr.exc.raise(err)
return nil
}
//type cast args
if var radius = eval("radius") as? Double, var height = eval("height") as? Double, let center = eval("center") as? Vector, var resolution = eval("resolution") as? Int {
// handle minus values
if height < 0 {
height = -height
}
if radius < 0 {
radius = -radius
}
if resolution < 4 {
resolution = 4
}
var xvector = Vector(x: 1, y: 0, z: 0).times(radius)
var yvector = Vector(x: 0, y: 1, z: 0).times(radius)
var zvector = Vector(x: 0, y: 0, z: 1).times(height / 2)
var qresolution = Int(round(Double(resolution / 4)))
var prevcylinderpoint : Vector = Vector(x: 0, y: 0, z: 0)
var polygons : [Polygon] = []
for var slice1 = 0; slice1 <= resolution; slice1++ {
var angle = M_PI * 2.0 * Double(slice1) / Double(resolution)
var cylinderpoint = xvector.times(cos(angle)) + yvector.times(sin(angle))
if slice1 > 0 {
var vertices : [Vertex] = []
// construct top
vertices.append(Vertex(pos: center + zvector))
vertices.append(Vertex(pos: center + prevcylinderpoint + zvector))
vertices.append(Vertex(pos: center + cylinderpoint + zvector))
polygons.append(Polygon(vertices: vertices))
// construct wall
vertices.append(Vertex(pos: center + prevcylinderpoint + zvector))
vertices.append(Vertex(pos: center + cylinderpoint + zvector))
vertices.append(Vertex(pos: center + cylinderpoint - zvector))
vertices.append(Vertex(pos: center + prevcylinderpoint - zvector))
polygons.append(Polygon(vertices: vertices.reverse()))
// construct bottom
vertices.append(Vertex(pos: center - zvector))
vertices.append(Vertex(pos: center + prevcylinderpoint - zvector))
vertices.append(Vertex(pos: center + cylinderpoint - zvector))
polygons.append(Polygon(vertices: vertices.reverse()))
}
prevcylinderpoint = cylinderpoint
}
mesh = Mesh(m: polygons)
needUpdate = false
return mesh
}
MintErr.exc.raise(MintEXC.SolverFailed(leafName: name, leafID: leafID))
return nil
}
}
*/
| gpl-3.0 | 9907fb82ab2b7a939aa5fb9252ff6f0f | 35.830476 | 176 | 0.473728 | 4.467652 | false | false | false | false |
AlexLittlejohn/Weight | Weight/Views/Picker/PickerItemView.swift | 1 | 1220 | //
// PickerItemView.swift
// Weight
//
// Created by Alex Littlejohn on 2016/03/02.
// Copyright © 2016 Alex Littlejohn. All rights reserved.
//
import UIKit
class PickerItemView: UICollectionViewCell {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
addSubview(label)
label.textAlignment = .center
label.font = Typography.PickerView.item.font
label.textColor = Colors.PickerView.item.color
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = bounds.insetBy(dx: 0, dy: 5)
}
override var isSelected: Bool {
didSet {
if isSelected {
label.textColor = Colors.PickerView.itemSelected.color
backgroundColor = Colors.PickerView.itemSelectedBackground.color
} else {
label.textColor = Colors.PickerView.item.color
backgroundColor = Colors.PickerView.itemBackground.color
}
}
}
}
| mit | 74cd1cb7e14b54fcef0f41495eb57c97 | 24.395833 | 80 | 0.59639 | 4.799213 | false | false | false | false |
gabriel-dynamo/rstudio | Sources/App/EmailMailgun.swift | 1 | 1028 | import Vapor
import HTTP
final class EmailMailgun {
public func sendEmail() throws -> Response {
let message = "This is the body of the email. \(Date())"
let parameters = [
"from": "[email protected]",
"to": "[email protected]",
"subject": "Test of the navigation",
"text": message
]
let header : [HeaderKey : String] = ["Authorization": "Basic QVBJOmtleS0zNjFlNmIyMTNlYTc2YWU4ODViZjllOTVhNWNmOWQyZA==",
"Content-Type" : "application/x-www-form-urlencoded"]
let url = "https://api.mailgun.net/v3/mailgun.advancio.se/messages"
let httpRequest = Request(method: .post, uri: url)
httpRequest.headers = header
httpRequest.formURLEncoded = try Node(node: parameters)
guard let drop = currentDroplet.sharedInstance.droplet else { throw Abort.badRequest }
return try drop.client.respond(to: httpRequest)
}
}
| mit | 4a43e2d9933a4f61367abffc7dadd781 | 40.12 | 127 | 0.603113 | 4.015625 | false | false | false | false |
kyouko-taiga/anzen | Sources/AST/Operator.swift | 1 | 1536 | /// Enumeration of the prefix operators.
public enum PrefixOperator: String, CustomStringConvertible {
case not
case add = "+"
case sub = "-"
public var description: String {
return rawValue
}
}
/// Enumeration of the prefix operators.
public enum InfixOperator: String, CustomStringConvertible {
// MARK: Casting precedence
case `as`
// MARK: Multiplication precedence
case mul = "*"
case div = "/"
case mod = "%"
// MARK: Addition precedence
case add = "+"
case sub = "-"
// MARK: Comparison precedence
case lt = "<"
case le = "<="
case ge = ">="
case gt = ">"
// MARK: Equivalence precedence
case eq = "=="
case ne = "!="
case refeq = "==="
case refne = "!=="
case `is`
// MARK: Logical conjunction precedence
case and
// MARK: Logical disjunction precedence
case or
/// Returns the precedence group of the operator.
public var precedence: Int {
switch self {
case .or:
return 0
case .and:
return 1
case .eq, .ne, .refeq, .refne, .is:
return 2
case .lt, .le, .ge, .gt:
return 3
case .add, .sub:
return 4
case .mul, .div, .mod:
return 5
case .as:
return 6
}
}
public var description: String {
return rawValue
}
}
/// Enumeration of the binding operators.
public enum BindingOperator: String, CustomStringConvertible {
case copy = ":="
case ref = "&-"
case move = "<-"
public var description: String {
return rawValue
}
}
| apache-2.0 | 1752bf482d4f51a50713320047b412bd | 15.695652 | 62 | 0.591146 | 3.938462 | false | false | false | false |
mottx/XCGLogger | Sources/XCGLogger/Extensions/URL+XCGAdditions.swift | 6 | 3064 | //
// URL+ExtendedAttributes.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2017-04-04.
// Copyright © 2017 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
// Based on code by Martin-R here: https://stackoverflow.com/a/38343753/144857
import Foundation
extension URL {
/// Get extended attribute.
func extendedAttribute(forName name: String) throws -> Data? {
let data: Data? = try self.withUnsafeFileSystemRepresentation { (fileSystemPath: (UnsafePointer<Int8>?)) -> Data? in
// Determine attribute size
let length = getxattr(fileSystemPath, name, nil, 0, 0, 0)
guard length >= 0 else { return nil }
// Create buffer with required size
var data = Data(count: length)
// Retrieve attribute
let result = data.withUnsafeMutableBytes {
getxattr(fileSystemPath, name, $0, data.count, 0, 0)
}
guard result >= 0 else { throw URL.posixError(errno) }
return data
}
return data
}
/// Set extended attribute.
func setExtendedAttribute(data: Data, forName name: String) throws {
try self.withUnsafeFileSystemRepresentation { fileSystemPath in
let result = data.withUnsafeBytes {
setxattr(fileSystemPath, name, $0, data.count, 0, 0)
}
guard result >= 0 else { throw URL.posixError(errno) }
}
}
/// Remove extended attribute.
func removeExtendedAttribute(forName name: String) throws {
try self.withUnsafeFileSystemRepresentation { fileSystemPath in
let result = removexattr(fileSystemPath, name, 0)
guard result >= 0 else { throw URL.posixError(errno) }
}
}
/// Get list of all extended attributes.
func listExtendedAttributes() throws -> [String] {
let list = try self.withUnsafeFileSystemRepresentation { (fileSystemPath: (UnsafePointer<Int8>?)) -> [String] in
let length = listxattr(fileSystemPath, nil, 0, 0)
guard length >= 0 else { throw URL.posixError(errno) }
// Create buffer with required size
var data = Data(count: length)
// Retrieve attribute list
let result = data.withUnsafeMutableBytes {
listxattr(fileSystemPath, $0, data.count, 0)
}
guard result >= 0 else { throw URL.posixError(errno) }
// Extract attribute names
let list = data.split(separator: 0).flatMap {
String(data: Data($0), encoding: .utf8)
}
return list
}
return list
}
/// Helper function to create an NSError from a Unix errno.
private static func posixError(_ err: Int32) -> NSError {
return NSError(domain: NSPOSIXErrorDomain, code: Int(err), userInfo: [NSLocalizedDescriptionKey: String(cString: strerror(err))])
}
}
| mit | acd0f22be1f1c0f275da639ba5b8439c | 36.353659 | 137 | 0.614757 | 4.726852 | false | false | false | false |
DavidSkrundz/Lua | Sources/Lua/Value/CustomType.swift | 1 | 1060 | //
// CustomType.swift
// Lua
//
/// Holds a type's metatable and statictable
public final class CustomType<T: LuaConvertible> {
private let metaTable: Table
private let staticTable: Table
internal init(lua: Lua, type: T.Type) throws {
try lua.raw.createMetatable(name: String(describing: T.typeName))
self.metaTable = lua.pop() as! Table
self.staticTable = lua.createTable()
lua.globals[String(describing: T.typeName)] = self.staticTable
if let initializer = T.initializer {
self.staticTable["new"] = lua.createFunction(Lua.wrap(initializer))
}
T.functions.forEach { self.staticTable[$0] = lua.createFunction($1) }
self.metaTable["__name"] = String(describing: T.typeName)
self.metaTable["__index"] = self.metaTable
T.methods.forEach {
self.metaTable[$0] = lua.createFunction(Lua.wrap($1))
}
self.metaTable["__gc"] = lua.createFunction({ (lua) -> [Value] in
let userdata = lua.pop() as! UserData
let pointer: UnsafeMutablePointer<T> = userdata.pointer()
pointer.deinitialize()
return []
})
}
}
| lgpl-3.0 | 0bafd377ad4c0daaad2a11bcd1cfd068 | 28.444444 | 71 | 0.691509 | 3.375796 | false | false | false | false |
simeonpp/home-hunt | ios-client/Pods/SwinjectStoryboard/Sources/Container+SwinjectStoryboard.swift | 6 | 2295 | //
// Container+SwinjectStoryboard.swift
// Swinject
//
// Created by Yoichi Tagaya on 11/28/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Swinject
#if os(iOS) || os(OSX) || os(tvOS)
extension Container {
/// Adds a registration of the specified view or window controller that is configured in a storyboard.
///
/// - Note: Do NOT explicitly resolve the controller registered by this method.
/// The controller is intended to be resolved by `SwinjectStoryboard` implicitly.
///
/// - Parameters:
/// - controllerType: The controller type to register as a service type.
/// The type is `UIViewController` in iOS, `NSViewController` or `NSWindowController` in OS X.
/// - name: A registration name, which is used to differenciate from other registrations
/// that have the same view or window controller type.
/// - initCompleted: A closure to specifiy how the dependencies of the view or window controller are injected.
/// It is invoked by the `Container` when the view or window controller is instantiated by `SwinjectStoryboard`.
public func storyboardInitCompleted<C: Controller>(_ controllerType: C.Type, name: String? = nil, initCompleted: @escaping (Resolver, C) -> ()) {
// Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7.
// https://github.com/Swinject/Swinject/issues/10
let factory = { (_: Resolver, controller: Controller) in controller }
let wrappingClosure: (Resolver, Controller) -> () = { r, c in initCompleted(r, c as! C) }
let option = SwinjectStoryboardOption(controllerType: controllerType)
_register(Controller.self, factory: factory, name: name, option: option)
.initCompleted(wrappingClosure)
}
}
#endif
extension Container {
#if os(iOS) || os(tvOS)
/// The typealias to UIViewController.
public typealias Controller = UIViewController
#elseif os(OSX)
/// The typealias to AnyObject, which should be actually NSViewController or NSWindowController.
/// See the reference of NSStoryboard.instantiateInitialController method.
public typealias Controller = Any
#endif
}
| mit | b59d50b3452acd096a835f5bdbd31e2b | 45.816327 | 149 | 0.677419 | 4.720165 | false | false | false | false |
wayfair/brickkit-ios | Example/Source/Examples/HorizontalScroll/HorizontalCollectionViewController.swift | 1 | 3501 | //
// HorizontalCollectionViewController.swift
// BrickKit iOS Example
//
// Created by Ruben Cagnie on 10/13/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import UIKit
import BrickKit
class HorizontalCollectionViewController: BrickViewController, HasTitle {
class var brickTitle: String {
return "Collection Horizontal Scroll"
}
class var subTitle: String {
return "Horizontally scrolling of CollectionBricks"
}
var collectionSection: BrickSection!
let numberOfCollections = 9
struct Identifiers {
static let collectionBrick = "CollectionBrick"
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .brickBackground
self.layout.scrollDirection = .horizontal
self.brickCollectionView.registerBrickClass(ImageBrick.self)
self.view.backgroundColor = .brickBackground
collectionSection = BrickSection(bricks: [
ImageBrick(width: .ratio(ratio: 1/2), height: .ratio(ratio: 1), dataSource: self),
BrickSection(width: .ratio(ratio: 1/2), bricks: [
LabelBrick(RepeatCollectionBrickViewController.Identifiers.titleLabel, backgroundColor: .brickGray2, dataSource: self),
LabelBrick(RepeatCollectionBrickViewController.Identifiers.subTitleLabel, backgroundColor: .brickGray4, dataSource: self)
])
], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5), alignRowHeights: true)
self.registerBrickClass(CollectionBrick.self)
let section = BrickSection(bricks: [
CollectionBrick(HorizontalCollectionViewController.Identifiers.collectionBrick, width: .ratio(ratio: 1/2), backgroundColor: .brickSection, dataSource: self, brickTypes: [LabelBrick.self, ImageBrick.self])
], inset: 20)
section.repeatCountDataSource = self
self.setSection(section)
}
}
extension HorizontalCollectionViewController: BrickRepeatCountDataSource {
func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int {
if identifier == HorizontalCollectionViewController.Identifiers.collectionBrick {
return numberOfCollections
} else {
return 1
}
}
}
extension HorizontalCollectionViewController: CollectionBrickCellDataSource {
func sectionForCollectionBrickCell(_ cell: CollectionBrickCell) -> BrickSection {
return collectionSection
}
}
extension HorizontalCollectionViewController: ImageBrickDataSource {
func imageForImageBrickCell(_ imageBrickCell: ImageBrickCell) -> UIImage? {
return UIImage(named: "image\(imageBrickCell.collectionIndex)")
}
func contentModeForImageBrickCell(_ imageBrickCell: ImageBrickCell) -> UIView.ContentMode {
return .scaleAspectFill
}
}
extension HorizontalCollectionViewController: LabelBrickCellDataSource {
func configureLabelBrickCell(_ cell: LabelBrickCell) {
let identifier = cell.brick.identifier
let collectionIndex = cell.collectionIndex + 1
if identifier == RepeatCollectionBrickViewController.Identifiers.titleLabel {
cell.label.text = "Title \(collectionIndex)".uppercased()
} else if identifier == RepeatCollectionBrickViewController.Identifiers.subTitleLabel {
cell.label.text = "SubTitle \(collectionIndex)".uppercased()
}
}
}
| apache-2.0 | 8a9f8ac588ffffb958a8e1e30691668d | 32.980583 | 216 | 0.707429 | 5.529226 | false | false | false | false |
AlexZd/ApplicationSupport | ApplicationSupport/Helpers/ClassFromString.swift | 1 | 538 | //
// ClassFromString.swift
// Pods
//
// Created by Alex Zdorovets on 6/19/16.
//
//
import Foundation
public func ClassFromString(className: String) -> AnyClass {
var cls : AnyClass? = NSClassFromString(className)
if let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleExecutable") as? String where cls == nil {
let name = appName + "." + className
cls = NSClassFromString(name)
if cls == nil {
fatalError("Unable to find `\(name)`")
}
}
return cls!
} | mit | 47341caa79f03481a8afbf33576d3777 | 24.666667 | 121 | 0.63197 | 4.269841 | false | false | false | false |
iOSTestApps/CardsAgainst | CardsAgainst/View Controllers/MenuViewController.swift | 3 | 6176 | //
// MenuViewController.swift
// CardsAgainst
//
// Created by JP Simard on 10/25/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import UIKit
import Cartography
final class MenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
// MARK: Properties
private let startGameButton = UIButton.buttonWithType(.System) as UIButton
private let separator = UIView()
private let collectionView = UICollectionView(frame: CGRectZero,
collectionViewLayout: UICollectionViewFlowLayout())
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// UI
setupNavigationBar()
setupLaunchImage()
setupStartGameButton()
setupSeparator()
setupCollectionView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
ConnectionManager.onConnect { _ in
self.updatePlayers()
}
ConnectionManager.onDisconnect { _ in
self.updatePlayers()
}
ConnectionManager.onEvent(.StartGame) { _, object in
let dict = object as [String: NSData]
let blackCard = Card(mpcSerialized: dict["blackCard"]!)
let whiteCards = CardArray(mpcSerialized: dict["whiteCards"]!).array
self.startGame(blackCard: blackCard, whiteCards: whiteCards)
}
}
override func viewWillDisappear(animated: Bool) {
ConnectionManager.onConnect(nil)
ConnectionManager.onDisconnect(nil)
ConnectionManager.onEvent(.StartGame, run: nil)
super.viewWillDisappear(animated)
}
// MARK: UI
private func setupNavigationBar() {
navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navigationController!.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.translucent = true
}
private func setupLaunchImage() {
view.addSubview(UIImageView(image: UIImage.launchImage()))
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
blurView.frame = view.bounds
view.addSubview(blurView)
}
private func setupStartGameButton() {
// Button
startGameButton.setTranslatesAutoresizingMaskIntoConstraints(false)
startGameButton.titleLabel!.font = startGameButton.titleLabel!.font.fontWithSize(25)
startGameButton.setTitle("Waiting For Players", forState: .Disabled)
startGameButton.setTitle("Start Game", forState: .Normal)
startGameButton.addTarget(self, action: "startGame", forControlEvents: .TouchUpInside)
startGameButton.enabled = false
view.addSubview(startGameButton)
// Layout
layout(startGameButton) { button in
button.top == button.superview!.top + 60
button.centerX == button.superview!.centerX
}
}
private func setupSeparator() {
// Separator
separator.setTranslatesAutoresizingMaskIntoConstraints(false)
separator.backgroundColor = lightColor
view.addSubview(separator)
// Layout
layout(separator, startGameButton) { separator, startGameButton in
separator.top == startGameButton.bottom + 10
separator.centerX == separator.superview!.centerX
separator.width == separator.superview!.width - 40
separator.height == (1 / Float(UIScreen.mainScreen().scale))
}
}
private func setupCollectionView() {
// Collection View
let cvLayout = collectionView.collectionViewLayout as UICollectionViewFlowLayout
cvLayout.itemSize = CGSizeMake(separator.frame.size.width, 50)
cvLayout.minimumLineSpacing = 0
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.clearColor()
collectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
collectionView.registerClass(PlayerCell.self,
forCellWithReuseIdentifier: PlayerCell.reuseID)
collectionView.alwaysBounceVertical = true
view.addSubview(collectionView)
// Layout
layout(collectionView, separator) { collectionView, separator in
collectionView.top == separator.bottom
collectionView.left == separator.left
collectionView.right == separator.right
collectionView.bottom == collectionView.superview!.bottom
}
}
// MARK: Actions
func startGame() {
let blackCard = CardManager.nextCardsWithType(.Black).first!
let whiteCards = CardManager.nextCardsWithType(.White, count: 10)
sendBlackCard(blackCard)
startGame(blackCard: blackCard, whiteCards: whiteCards)
}
private func startGame(#blackCard: Card, whiteCards: [Card]) {
let gameVC = GameViewController(blackCard: blackCard, whiteCards: whiteCards)
navigationController!.pushViewController(gameVC, animated: true)
}
// MARK: Multipeer
private func sendBlackCard(blackCard: Card) {
ConnectionManager.sendEventForEach(.StartGame) {
let whiteCards = CardManager.nextCardsWithType(.White, count: 10)
let whiteCardsArray = CardArray(array: whiteCards)
return ["blackCard": blackCard, "whiteCards": whiteCardsArray]
}
}
private func updatePlayers() {
startGameButton.enabled = (ConnectionManager.otherPlayers.count > 0)
collectionView.reloadData()
}
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ConnectionManager.otherPlayers.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PlayerCell.reuseID, forIndexPath: indexPath) as PlayerCell
cell.label.text = ConnectionManager.otherPlayers[indexPath.row].name
return cell
}
}
| mit | f26beafe185beca3f3ef90d4f5f727b9 | 35.329412 | 131 | 0.684424 | 5.681693 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Notes/HATNotes.swift | 1 | 3686 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATNotes: HATObject, HatApiType {
// MARK: - JSON Fields
/**
The JSON fields used by the hat
The Fields are the following:
* `endpoint` in JSON is `endpoint`
* `recordID` in JSON is `recordId`
* `data` in JSON is `data`
*/
private enum CodingKeys: String, CodingKey {
case endpoint = "endpoint"
case recordID = "recordId"
case data = "data"
}
// MARK: - Variables
/// the author data
public var endpoint: String = ""
/// the photo data
public var recordID: String = ""
/// the location data
public var data: HATNotesData = HATNotesData()
// MARK: - Initialiser
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public init(dict: Dictionary<String, JSON>) {
self.init()
self.inititialize(dict: dict)
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public mutating func inititialize(dict: Dictionary<String, JSON>) {
if let tempEndpoint: String = dict[CodingKeys.endpoint.rawValue]?.string {
endpoint = tempEndpoint
}
if let tempRecordId: String = dict[CodingKeys.recordID.rawValue]?.string {
recordID = tempRecordId
}
if let tempData: [String: JSON] = dict[CodingKeys.data.rawValue]?.dictionaryValue {
data = HATNotesData(dict: tempData)
}
}
// MARK: - HatApiType Protocol
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [ CodingKeys.endpoint.rawValue: endpoint,
CodingKeys.recordID.rawValue: recordID,
CodingKeys.data.rawValue: data.toJSON()
]
}
/**
It initialises everything from the received Dictionary file from the cache
- fromCache: The dictionary file received from the cache
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
let dictionary: JSON = JSON(fromCache)
self.inititialize(dict: dictionary.dictionaryValue)
}
// MARK: - Override decoding code to parse old notes as well
public static func decode<T: HATObject>(from: Dictionary<String, JSON>) -> T? {
let decoder: JSONDecoder = JSONDecoder()
do {
let data: Data = try JSON(from).rawData()
let object: T = try decoder.decode(T.self, from: data)
return object
} catch {
if from[CodingKeys.data.rawValue]?["notablesv1"].dictionaryValue != nil {
let tst: T? = self.init(dict: from) as? T
return tst!
}
return nil
}
}
}
| mpl-2.0 | 7e3c6e2a5ea4f802a8064aebaaf3fb97 | 25.328571 | 91 | 0.563483 | 4.830931 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Notifications/Notification.Name+ManagedObjectObservation.swift | 1 | 2085 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
extension Notification.Name {
static let ConversationChange = Notification.Name("ZMConversationChangedNotification")
static let MessageChange = Notification.Name("ZMMessageChangedNotification")
static let UserChange = Notification.Name("ZMUserChangedNotification")
static let SearchUserChange = Notification.Name("ZMSearchUserChangedNotification")
static let ConnectionChange = Notification.Name("ZMConnectionChangeNotification")
static let UserClientChange = Notification.Name("ZMUserClientChangeNotification")
static let NewUnreadMessage = Notification.Name("ZMNewUnreadMessageNotification")
static let NewUnreadKnock = Notification.Name("ZMNewUnreadKnockNotification")
static let NewUnreadUnsentMessage = Notification.Name("ZMNewUnreadUnsentMessageNotification")
static let VoiceChannelStateChange = Notification.Name("ZMVoiceChannelStateChangeNotification")
static let VoiceChannelParticipantStateChange = Notification.Name("ZMVoiceChannelParticipantStateChangeNotification")
static let TeamChange = Notification.Name("TeamChangeNotification")
static let LabelChange = Notification.Name("LabelChangeNotification")
static let ParticipantRoleChange = Notification.Name("ParticipantRoleChange")
public static let NonCoreDataChangeInManagedObject = Notification.Name("NonCoreDataChangeInManagedObject")
}
| gpl-3.0 | 2f8b870bebcd755fde50cefcd605f796 | 51.125 | 121 | 0.798561 | 5.148148 | false | false | false | false |
daisysomus/swift-algorithm-club | Rootish Array Stack/RootishArrayStack.playground/Contents.swift | 4 | 4600 | //: Playground - noun: a place where people can play
import Darwin
public struct RootishArrayStack<T> {
// MARK: - Instance variables
fileprivate var blocks = [Array<T?>]()
fileprivate var internalCount = 0
// MARK: - Init
public init() { }
// MARK: - Calculated variables
var count: Int {
return internalCount
}
var capacity: Int {
return blocks.count * (blocks.count + 1) / 2
}
var isEmpty: Bool {
return blocks.count == 0
}
var first: T? {
guard capacity > 0 else { return nil }
return blocks[0][0]
}
var last: T? {
guard capacity > 0 else { return nil }
let block = self.block(fromIndex: count - 1)
let innerBlockIndex = self.innerBlockIndex(fromIndex: count - 1, fromBlock: block)
return blocks[block][innerBlockIndex]
}
// MARK: - Equations
fileprivate func block(fromIndex index: Int) -> Int {
let block = Int(ceil((-3.0 + sqrt(9.0 + 8.0 * Double(index))) / 2))
return block
}
fileprivate func innerBlockIndex(fromIndex index: Int, fromBlock block: Int) -> Int {
return index - block * (block + 1) / 2
}
// MARK: - Behavior
fileprivate mutating func growIfNeeded() {
if capacity - blocks.count < count + 1 {
let newArray = [T?](repeating: nil, count: blocks.count + 1)
blocks.append(newArray)
}
}
fileprivate mutating func shrinkIfNeeded() {
if capacity + blocks.count >= count {
while blocks.count > 0 && (blocks.count - 2) * (blocks.count - 1) / 2 >= count {
blocks.remove(at: blocks.count - 1)
}
}
}
public subscript(index: Int) -> T {
get {
let block = self.block(fromIndex: index)
let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block)
return blocks[block][innerBlockIndex]!
}
set(newValue) {
let block = self.block(fromIndex: index)
let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block)
blocks[block][innerBlockIndex] = newValue
}
}
public mutating func insert(element: T, atIndex index: Int) {
growIfNeeded()
internalCount += 1
var i = count - 1
while i > index {
self[i] = self[i - 1]
i -= 1
}
self[index] = element
}
public mutating func append(element: T) {
insert(element: element, atIndex: count)
}
fileprivate mutating func makeNil(atIndex index: Int) {
let block = self.block(fromIndex: index)
let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block)
blocks[block][innerBlockIndex] = nil
}
public mutating func remove(atIndex index: Int) -> T {
let element = self[index]
for i in index..<count - 1 {
self[i] = self[i + 1]
}
internalCount -= 1
makeNil(atIndex: count)
shrinkIfNeeded()
return element
}
// MARK: - Struct to string
public var memoryDescription: String {
var description = "{\n"
for block in blocks {
description += "\t["
for index in 0..<block.count {
description += "\(block[index])"
if index + 1 != block.count {
description += ", "
}
}
description += "]\n"
}
return description + "}"
}
}
extension RootishArrayStack: CustomStringConvertible {
public var description: String {
var description = "["
for index in 0..<count {
description += "\(self[index])"
if index + 1 != count {
description += ", "
}
}
return description + "]"
}
}
var list = RootishArrayStack<String>()
list.isEmpty // true
list.first // nil
list.last // nil
list.count // 0
list.capacity // 0
list.memoryDescription
// {
// }
list.append(element: "Hello")
list.isEmpty // false
list.first // "Hello"
list.last // "hello"
list.count // 1
list.capacity // 1
list.memoryDescription
// {
// [Optional("Hello")]
// }
list.append(element: "World")
list.isEmpty // false
list.first // "Hello"
list.last // "World"
list.count // 2
list.capacity // 3
list[0] // "Hello"
list[1] // "World"
//list[2] // crash!
list.memoryDescription
// {
// [Optional("Hello")]
// [Optional("World"), nil]
// }
list.insert(element: "Swift", atIndex: 1)
list.isEmpty // false
list.first // "Hello"
list.last // "World"
list.count // 3
list.capacity // 6
list[0] // "Hello"
list[1] // "Swift"
list[2] // "World"
list.memoryDescription
// {
// [Optional("Hello")]
// [Optional("Swift"), Optional("World")]
// [nil, nil, nil]
// }
list.remove(atIndex: 2) // "World"
list.isEmpty // false
list.first // "Hello"
list.last // "Swift"
list.count // 2
list.capacity // 3
list[0] // "Hello"
list[1] // "Swift"
//list[2] // crash!
list[0] = list[1]
list[1] = "is awesome"
list // ["Swift", "is awesome"]
| mit | 5261aec951bfc26debf2d69075a0c67c | 20.004566 | 86 | 0.629565 | 3.101821 | false | false | false | false |
ReSwift/ReSwift-Router | ReSwiftRouter/NavigationActions.swift | 2 | 623 | //
// NavigationAction.swift
// Meet
//
// Created by Benjamin Encz on 11/27/15.
// Copyright © ReSwift Community. All rights reserved.
//
import ReSwift
public struct SetRouteAction: Action {
let route: Route
let animated: Bool
public static let type = "RE_SWIFT_ROUTER_SET_ROUTE"
public init (_ route: Route, animated: Bool = true) {
self.route = route
self.animated = animated
}
}
public struct SetRouteSpecificData: Action {
let route: Route
let data: Any
public init(route: Route, data: Any) {
self.route = route
self.data = data
}
}
| mit | 8e176824ecd5e05ae1ab5d93b4239552 | 18.4375 | 57 | 0.631833 | 3.792683 | false | false | false | false |
esttorhe/SwiftObjLoader | SwiftObjLoaderTests/GeometryTests.swift | 1 | 2219 | //
// GeometryTests.swift
// SwiftObjLoader
//
// Created by Hugo Tunius on 02/09/15.
// Copyright © 2015 Hugo Tunius. All rights reserved.
//
import XCTest
@testable import SwiftObjLoader
class GeometryTests: XCTestCase {
func testSimpleShapeEquality() {
var s1 = Shape(name: "Shape", vertices: [[]], normals: [[]], textureCoords: [[]], faces : [[]])
var s2 = Shape(name: "Shape", vertices: [[]], normals: [[]], textureCoords: [[]], faces : [[]])
XCTAssertEqual(s1, s2)
s1 = Shape(name: "Shape1", vertices: [[]], normals: [[]], textureCoords: [[]], faces : [[]])
s2 = Shape(name: "Shape2", vertices: [[]], normals: [[]], textureCoords: [[]], faces : [[]])
XCTAssertNotEqual(s1, s2)
let v1 = [0.1, 0.3, 0.5]
let v2 = [0.1, 0.2, 0.5]
s1 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces: [[]])
s2 = Shape(name: "Shape", vertices: [v2], normals: [v1], textureCoords: [v1], faces : [[]])
XCTAssertNotEqual(s1, s2)
s1 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
s2 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
XCTAssertEqual(s1, s2)
s1 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
s2 = Shape(name: "Shape", vertices: [v1], normals: [v2], textureCoords: [v1], faces : [[]])
XCTAssertNotEqual(s1, s2)
s1 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
s2 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
XCTAssertEqual(s1, s2)
s1 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
s2 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v2], faces : [[]])
XCTAssertNotEqual(s1, s2)
s1 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
s2 = Shape(name: "Shape", vertices: [v1], normals: [v1], textureCoords: [v1], faces : [[]])
XCTAssertEqual(s1, s2)
}
}
| mit | 9cf2704ef90fa608c76f66f284ac728c | 43.36 | 103 | 0.557259 | 3.33033 | false | true | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | Playground Collection/Part 7 - Alien Adventure 4/MapAndReduce/MapAndReduce.playground/Pages/MapExample_TrailingClosures.xcplaygroundpage/Contents.swift | 1 | 873 | //: [Previous](@previous)
//: ## Trailing Closures
let tripContributions = ["Andy": 25, "Kathleen": 50, "Janhavi": 45, "Sebastian": 10, "Chrisna": 50]
let averageTripCost = (25 + 50 + 45 + 10 + 50)/5
// In trailing closure syntax the final parenthesis comes before the closure
let tripDebts = tripContributions.map(){ (key, value) -> String in
let amountOwed = averageTripCost - value
if amountOwed > 0 {
return "\(key) owes $\(amountOwed)"
} else {
return "\(key) is owed $\(-amountOwed)"
}
}
// Here's what it looked like before with the parenthesis at the end
let moreTripDebts = tripContributions.map({ (key, value) -> String in
let amountOwed = averageTripCost - value
if amountOwed > 0 {
return "\(key) owes $\(amountOwed)"
} else {
return "\(key) is owed $\(-amountOwed)"
}
})
//: [Next](@next)
| mit | 71c1e42b1d5d1c53551cb9262ffbb00a | 28.1 | 99 | 0.62543 | 3.534413 | false | false | false | false |
modernpal/HPShowcase | HPShowcase/Classes/TriangleView.swift | 1 | 1517 | //
// TriangleView.swift
// HPShowCase
//
// Created by Mehdi Gilanpour on 9/2/17.
// Copyright © 2017 Arash Farahani & Mehdi Gilanpour. All rights reserved.
//
import UIKit
public class TriangleView : UIView {
var color: UIColor!
init(frame: CGRect, color: UIColor) {
super.init(frame: frame)
self.color = color
backgroundColor = UIColor.clear
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func draw(_ rect: CGRect) {
var fRed : CGFloat = 0
var fGreen : CGFloat = 0
var fBlue : CGFloat = 0
var fAlpha: CGFloat = 0
if color.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
let iRed = Int(fRed * 255.0)
let iGreen = Int(fGreen * 255.0)
let iBlue = Int(fBlue * 255.0)
let iAlpha = Int(fAlpha * 255.0)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.beginPath()
context.move(to: CGPoint(x: rect.minX, y: rect.maxY))
context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY))
context.closePath()
context.setFillColor(red: CGFloat(iRed), green: CGFloat(iGreen), blue: CGFloat(iBlue), alpha: CGFloat(iAlpha))
context.fillPath()
}
}
}
| mit | 30616233d5f916eb9292c704f064c221 | 29.32 | 122 | 0.559367 | 3.867347 | false | false | false | false |
satorun/designPattern | Builder/Builder/HtmlBuilder.swift | 1 | 728 | //
// HtmlBuilder.swift
// Builder
//
// Created by satorun on 2016/02/03.
// Copyright © 2016年 satorun. All rights reserved.
//
class HtmlBuilder: Builder {
private var buffer = ""
func makeTitle(title: String) {
buffer += "<html><head><title>\(title)</title></head><body>\n"
buffer += "<h1>\(title)</h1>\n"
}
func makeString(str: String) {
buffer += "<p>\(str)</p>\n"
}
func makeItems(items: [String]) {
buffer += "<ul>\n"
for item in items {
buffer += "<li>\(item)</li>\n"
}
buffer += "</ul>\n"
}
func close() {
buffer += "</body></html>\n"
}
func getResult() -> String {
return buffer
}
} | mit | 094b027d646ae8221359c500992139a4 | 22.419355 | 70 | 0.503448 | 3.519417 | false | false | false | false |
amdaza/HackerBooks | HackerBooks/HackerBooks/CoreDataTableViewController.swift | 1 | 5410 | //
// CoreDataTableViewController.swift
//
//
// Created by Fernando Rodríguez Romero on 22/02/16.
// Copyright © 2016
//
import UIKit
import CoreData
class CoreDataTableViewController: UITableViewController {
// MARK: - Properties
var fetchedResultsController : NSFetchedResultsController<NSFetchRequestResult>?{
didSet{
// Whenever the frc changes, we execute the search and
// reload the table
fetchedResultsController?.delegate = self
executeSearch()
tableView.reloadData()
}
}
init(fetchedResultsController fc : NSFetchedResultsController<NSFetchRequestResult>,
style : UITableViewStyle = .plain){
// Will not execute didSet, "afraid" of nil
//fetchedResultsController = fc
super.init(style: style)
defer {
fetchedResultsController = fc
}
}
// Do not worry about this initializer. I has to be implemented
// because of the way Swift interfaces with an Objective C
// protocol called NSArchiving. It's not relevant.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: - View lifecycle
override func viewDidLoad(){
super.viewDidLoad()
}
}
// MARK: - Subclass responsability
extension CoreDataTableViewController{
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
fatalError("This method MUST be implemented by a subclass of CoreDataTableViewController")
}
}
// MARK: - Table Data Source
extension CoreDataTableViewController{
override func numberOfSections(in tableView: UITableView) -> Int {
if let fc = fetchedResultsController{
guard let sections = fc.sections else {
return 1
}
return sections.count
}else{
return 0
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let fc = fetchedResultsController{
return fc.sections![section].numberOfObjects;
}else{
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let fc = fetchedResultsController{
return fc.sections?[section].name;
}else{
return nil
}
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if let fc = fetchedResultsController{
return fc.section(forSectionIndexTitle: title, at: index)
}else{
return 0
}
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if let fc = fetchedResultsController{
return fc.sectionIndexTitles
}else{
return nil
}
}
}
// MARK: - Fetches
extension CoreDataTableViewController{
func executeSearch(){
if let fc = fetchedResultsController{
do{
try fc.performFetch()
}catch let e as NSError{
print("Error while trying to perform a search: \n\(e)\n\(fetchedResultsController)")
}
}
}
}
// MARK: - Delegate
extension CoreDataTableViewController: NSFetchedResultsControllerDelegate{
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange sectionInfo: NSFetchedResultsSectionInfo,
atSectionIndex sectionIndex: Int,
for type: NSFetchedResultsChangeType) {
let set = IndexSet(integer: sectionIndex)
switch (type){
case .insert:
tableView.insertSections(set, with: .fade)
case .delete:
tableView.deleteSections(set, with: .fade)
default:
// irrelevant in our case
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
switch(type){
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .fade)
case .move:
tableView.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
| gpl-3.0 | 366ddc5c51fe60837c2a9024f076bd93 | 25.125604 | 120 | 0.576923 | 6.022272 | false | false | false | false |
onekiloparsec/SwiftAA | Sources/SwiftAA/JupiterMoons.swift | 2 | 3208 | //
// JupiterMoons.swift
// SwiftAA
//
// Created by Cédric Foellmi on 06/11/2016.
// MIT Licence. See LICENCE file.
//
import Foundation
import ObjCAA
typealias JupiterEquatorialRadius = Double
/// These coordinates describe the position of the four great satellites of Jupiter, with respect to the planet,
/// as seen from the Earth. These apparent rectangular coordinates Z and Y are measured from the center of the disk
/// of Jupiter, in units of the planet's equatorial radius.
/// X is measured positively to the west of Jupiter, the axis coinciding with equator of the planet.
/// Y is measured positively to the north, the axis coinciding with the rotation axis of the planet.
/// Z is negative if the satellite is closer to the Earth than Jupiter, and positive otherwise.
public struct GalileanMoonRectangularCoordinates {
fileprivate(set) var X: JupiterEquatorialRadius
fileprivate(set) var Y: JupiterEquatorialRadius
fileprivate(set) var Z: Double
init(components: KPCAA3DCoordinateComponents) {
self.X = components.X
self.Y = components.Y
self.Z = components.Z
}
}
/// The GalileanMoon struct encompasses all properties of Galilean moons
public struct GalileanMoon {
fileprivate var details: KPCAAGalileanMoonDetails
/// The name of the Moon
public var name: String
public var MeanLongitude: Degree { get { return Degree(self.details.MeanLongitude) } }
public var TrueLongitude: Degree { get { return Degree(self.details.TrueLongitude) } }
public var TropicalLongitude: Degree { get { return Degree(self.details.TropicalLongitude) } }
public var EquatorialLatitude: Degree { get { return Degree(self.details.EquatorialLatitude) } }
public var radiusVector: AstronomicalUnit { get { return AstronomicalUnit(self.details.r) } }
/// Returns whether the Moon is in transit or not (i.e. in front of Jupiter disk).
public var inTransit: Bool { get { return self.details.inTransit.boolValue } }
/// Returns whether the Moon is in occultation or not (i.e. behind the Jupiter disk).
public var inOccultation: Bool { get { return self.details.inOccultation.boolValue } }
/// Returns whether the Moon is eclipsing Jupiter.
public var inEclipse: Bool { get { return self.details.inEclipse.boolValue } }
/// Returns whether the Moon is eclipsed by Jupiter.
public var inShadowTransit: Bool { get { return self.details.inShadowTransit.boolValue } }
/// Returns a GalileanMoon object
///
/// - Parameters:
/// - name: the name of the Moon
/// - details: the details of the moon. See Jupiter class.
init(name: String, details: KPCAAGalileanMoonDetails) {
self.name = name
self.details = details
}
// TODO: Improve this by not returning KPCAA3DCoordinateComponents and also add doc.
public func rectangularCoordinates(_ apparent: Bool = true) -> GalileanMoonRectangularCoordinates {
let components = (apparent == true) ? self.details.ApparentRectangularCoordinateComponents : self.details.TrueRectangularCoordinateComponents
return GalileanMoonRectangularCoordinates(components: components)
}
}
| mit | 62d57a981cadb70b29eb07cd6c5182c6 | 41.76 | 149 | 0.726848 | 4.381148 | false | false | false | false |
hossamghareeb/flappybird-spritekit-swift | FlappyBird/GameScene.swift | 1 | 5490 | //
// GameScene.swift
// FlappyBird
//
// Created by Hossam Ghareeb on 9/5/14.
// Copyright (c) 2014 AppCoda. All rights reserved.
//
import SpriteKit
enum ObstacleType : Int
{
case Top = 0,
Bottom
}
class GameScene: SKScene {
//This variable is used to know if the game started or not
var gameStarted = false
//set to true when collison happened to stop the game
var gameOver = false
// accumelate this in update function till we reach the horizontal spacing
// to add a new obstacle
var spacing:CGFloat = 0.0
//The speed of obstacle
let kSpeed : CGFloat = 1.5
//Save the size of obstacle to used in logic of removing of screen
var obstacleSize : CGSize = CGSizeMake(0, 0);
var verticalSplaceBetweenObstacles = 180
//Array of current obstacles. The mutable version used to add new obstacles
// or remove from screen
var obstacles:NSMutableArray
var bird : SKSpriteNode
init(coder aDecoder: NSCoder!)
{
bird = SKSpriteNode();
obstacles = NSMutableArray()
super.init(coder: aDecoder);
}
override func didMoveToView(view: SKView) {
/* Setup your scene here */
//Scene physics, create edge loop
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
//our bird
bird = self.childNodeWithName("bird") as SKSpriteNode
bird.physicsBody.density = 0.25;
bird.physicsBody.dynamic = false
}
func bounceMyBird()
{
let birdDirection = bird.zRotation + M_PI_2
let bounceImpulse: CFloat = 20.5
bird.physicsBody.velocity = CGVectorMake(0, 0);
var vec = CGVectorMake(CGFloat( bounceImpulse*cosf(CFloat(birdDirection))), CGFloat(
bounceImpulse*sinf(CFloat(birdDirection))));
bird.physicsBody.applyImpulse(vec);
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch : AnyObject in touches
{
if !gameStarted{
gameStarted = true
bird.physicsBody.dynamic = true
}
else
{
// bounce my bird
bounceMyBird();
}
}
}
let kObstacleImageTop = "obstacle0.png"
let kObstacleImageBottom = "obstacle1.png"
let kHorizontalSpace : CGFloat = 200
//The horizontal space between obstacles
func createObstacle(type: ObstacleType) -> SKSpriteNode
{
var fileName = kObstacleImageTop
if type == ObstacleType.Bottom{
fileName = kObstacleImageBottom
}
var obstacle = SKSpriteNode(imageNamed: fileName)
return obstacle
}
func randomInt(min: Int, max:Int) -> Int {
return Int(rand()) % (max - min);
}
func addObstacle()
{
//The top and bottom obstacle
var top : SKSpriteNode = createObstacle(ObstacleType.Top);
var bottom : SKSpriteNode = createObstacle(ObstacleType.Bottom);
//Set the size of obstacle
obstacleSize = top.size;
var screenSize : CGSize = self.frame.size;
var p1 : CGPoint = CGPointMake(screenSize.width + obstacleSize.width / 2, screenSize.height + obstacleSize.height / 2);
top.position = p1
var p2 : CGPoint = CGPointMake(top.position.x, -obstacleSize.height / 2);
bottom.position = p2
var minimum = screenSize.height / 8
var maximum = screenSize.height / 2
var randomTopHeight : Int = randomInt(Int(minimum), max: Int( maximum))
//Add margin to top and bottom obstacles
top.position = CGPointMake(p1.x, p1.y - CGFloat( randomTopHeight));
var bottomHeight = Int(screenSize.height) - randomTopHeight - verticalSplaceBetweenObstacles
bottom.position = CGPointMake(p2.x, p2.y + CGFloat( bottomHeight));
self.addChild(top);
self.addChild(bottom);
obstacles.addObject(top)
obstacles.addObject(bottom)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if (!gameOver && gameStarted) {
var toBeRemovedFromScene : NSMutableArray = NSMutableArray()
spacing += kSpeed;
if (spacing > (kHorizontalSpace + obstacleSize.width)) {
spacing = 0;
addObstacle();
}
for ob in obstacles
{
var obstacle = ob as SKSpriteNode
obstacle.position = CGPointMake(obstacle.position.x - kSpeed, obstacle.position.y)
if obstacle.intersectsNode(self.bird)
{
gameOver = true
self.bird.physicsBody.dynamic = false
}
if (obstacle.position.x < -obstacleSize.width) {
//remove
obstacle.removeFromParent()
toBeRemovedFromScene.addObject(obstacle)
}
}
self.obstacles.removeObjectsInArray(toBeRemovedFromScene)
}
}
}
| mit | e7b57ad2b281581ee27cb77348865cec | 28.516129 | 127 | 0.56612 | 5 | false | false | false | false |
stripysock/SwiftGen | GenumKit/Stencil/SwiftIdentifier.swift | 1 | 3873 | //
// GenumKit
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Foundation
func swiftIdentifier(fromString string: String, forbiddenChars exceptions: String = "", replaceWithUnderscores underscores: Bool = false) -> String {
let (head, tail) : (NSMutableCharacterSet, NSMutableCharacterSet) = {
let addRange: (NSMutableCharacterSet, Range<Int>) -> Void = { (mcs, range) in
mcs.addCharactersInRange(NSRange(location: range.startIndex, length: range.endIndex-range.startIndex))
}
let addChars: (NSMutableCharacterSet, String) -> Void = { (mcs, string) in
mcs.addCharactersInString(string)
}
// Official list from: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
let head = NSMutableCharacterSet()
addRange(head, 0x41...0x5A) // A-Z
addRange(head, 0x61...0x7A) // a-z
addChars(head, "_")
addChars(head, "\u{00A8}\u{00AA}\u{00AD}\u{00AF}")
addRange(head, 0x00B2...0x00B5)
addRange(head, 0x00B7...0x00BA)
addRange(head, 0x00BC...0x00BE)
addRange(head, 0x00C0...0x00D6)
addRange(head, 0x00D8...0x00F6)
addRange(head, 0x00F8...0x00FF)
addRange(head, 0x0100...0x02FF)
addRange(head, 0x0370...0x167F)
addRange(head, 0x1681...0x180D)
addRange(head, 0x180F...0x1DBF)
addRange(head, 0x1E00...0x1FFF)
addRange(head, 0x200B...0x200D)
addRange(head, 0x202A...0x202E)
addRange(head, 0x203F...0x2040)
addChars(head, "\u{2054}")
addRange(head, 0x2060...0x206F)
addRange(head, 0x2070...0x20CF)
addRange(head, 0x2100...0x218F)
addRange(head, 0x2460...0x24FF)
addRange(head, 0x2776...0x2793)
addRange(head, 0x2C00...0x2DFF)
addRange(head, 0x2E80...0x2FFF)
addRange(head, 0x3004...0x3007)
addRange(head, 0x3021...0x302F)
addRange(head, 0x3031...0x303F)
addRange(head, 0x3040...0xD7FF)
addRange(head, 0xF900...0xFD3D)
addRange(head, 0xFD40...0xFDCF)
addRange(head, 0xFDF0...0xFE1F)
addRange(head, 0xFE30...0xFE44)
addRange(head, 0xFE47...0xFFFD)
addRange(head, 0x10000...0x1FFFD)
addRange(head, 0x20000...0x2FFFD)
addRange(head, 0x30000...0x3FFFD)
addRange(head, 0x40000...0x4FFFD)
addRange(head, 0x50000...0x5FFFD)
addRange(head, 0x60000...0x6FFFD)
addRange(head, 0x70000...0x7FFFD)
addRange(head, 0x80000...0x8FFFD)
addRange(head, 0x90000...0x9FFFD)
addRange(head, 0xA0000...0xAFFFD)
addRange(head, 0xB0000...0xBFFFD)
addRange(head, 0xC0000...0xCFFFD)
addRange(head, 0xD0000...0xDFFFD)
addRange(head, 0xE0000...0xEFFFD)
let tail = head.mutableCopy() as! NSMutableCharacterSet
addChars(tail, "0123456789")
addRange(tail, 0x0300...0x036F)
addRange(tail, 0x1DC0...0x1DFF)
addRange(tail, 0x20D0...0x20FF)
addRange(tail, 0xFE20...0xFE2F)
return (head, tail)
}()
head.removeCharactersInString(exceptions)
tail.removeCharactersInString(exceptions)
let chars = string.unicodeScalars
let firstChar = chars[chars.startIndex]
let prefix = !head.longCharacterIsMember(firstChar.value) && tail.longCharacterIsMember(firstChar.value) ? "_" : ""
let parts = string.componentsSeparatedByCharactersInSet(tail.invertedSet)
let replacement = underscores ? "_" : ""
return prefix + parts.map({ string in
// Can't use capitalizedString here because it will lowercase all letters after the first
// e.g. "SomeNiceIdentifier".capitalizedString will because "Someniceidentifier" which is not what we want
let ns = string as NSString
if ns.length > 0 {
let firstLetter = ns.substringToIndex(1)
let rest = ns.substringFromIndex(1)
return firstLetter.uppercaseString + rest
} else {
return ""
}
}).joinWithSeparator(replacement)
}
| mit | 451a8db60ae481614b36e772ccff3df1 | 36.970588 | 188 | 0.690163 | 3.246438 | false | false | false | false |
apple/swift-format | Sources/swift-format/Subcommands/LintFormatOptions.swift | 1 | 3994 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import Foundation
/// Common arguments used by the `lint` and `format` subcommands.
struct LintFormatOptions: ParsableArguments {
/// The path to the JSON configuration file that should be loaded.
///
/// If not specified, the default configuration will be used.
@Option(
name: .customLong("configuration"),
help: "The path to a JSON file containing the configuration of the linter/formatter.")
var configurationPath: String?
/// The filename for the source code when reading from standard input, to include in diagnostic
/// messages.
///
/// If not specified and standard input is used, a dummy filename is used for diagnostic messages
/// about the source from standard input.
@Option(help: "When using standard input, the filename of the source to include in diagnostics.")
var assumeFilename: String?
/// Whether or not to run the formatter/linter recursively.
///
/// If set, we recursively run on all ".swift" files in any provided directories.
@Flag(
name: .shortAndLong,
help: "Recursively run on '.swift' files in any provided directories.")
var recursive: Bool = false
/// Whether unparsable files, due to syntax errors or unrecognized syntax, should be ignored or
/// treated as containing an error. When ignored, unparsable files are output verbatim in format
/// mode and no diagnostics are raised in lint mode. When not ignored, unparsable files raise a
/// diagnostic in both format and lint mode.
@Flag(help: """
Ignores unparsable files, disabling all diagnostics and formatting for files that contain \
invalid syntax.
""")
var ignoreUnparsableFiles: Bool = false
/// Whether or not to run the formatter/linter in parallel.
@Flag(
name: .shortAndLong,
help: "Process files in parallel, simultaneously across multiple cores.")
var parallel: Bool = false
/// Whether colors should be used in diagnostics printed to standard error.
///
/// If nil, color usage will be automatically detected based on whether standard error is
/// connected to a terminal or not.
@Flag(
inversion: .prefixedNo,
help: """
Enables or disables color diagnostics when printing to standard error. The default behavior \
if this flag is omitted is to use colors if standard error is connected to a terminal, and \
to not use colors otherwise.
""")
var colorDiagnostics: Bool?
/// The list of paths to Swift source files that should be formatted or linted.
@Argument(help: "Zero or more input filenames.")
var paths: [String] = []
@Flag(help: .hidden) var debugDisablePrettyPrint: Bool = false
@Flag(help: .hidden) var debugDumpTokenStream: Bool = false
mutating func validate() throws {
if recursive && paths.isEmpty {
throw ValidationError("'--recursive' is only valid when formatting or linting files")
}
if assumeFilename != nil && !paths.isEmpty {
throw ValidationError("'--assume-filename' is only valid when reading from stdin")
}
if !paths.isEmpty && !recursive {
for path in paths {
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: path, isDirectory: &isDir), isDir.boolValue {
throw ValidationError(
"""
'\(path)' is a path to a directory, not a Swift source file.
Use the '--recursive' option to handle directories.
"""
)
}
}
}
}
}
| apache-2.0 | 496d584466a6397cd7bb5aaceb4efb93 | 38.544554 | 99 | 0.668503 | 4.800481 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | Example/Example/TextViewAttachmentDelegateProvider.swift | 2 | 14110 | import Foundation
import Aztec
import UIKit
import AVFoundation
import AVKit
class TextViewAttachmentDelegateProvider: NSObject, TextViewAttachmentDelegate {
fileprivate var currentSelectedAttachment: MediaAttachment?
let baseController: UIViewController
let attachmentTextAttributes: [NSAttributedString.Key: Any]
init(baseController: UIViewController, attachmentTextAttributes: [NSAttributedString.Key: Any]) {
self.baseController = baseController
self.attachmentTextAttributes = attachmentTextAttributes
}
func textView(_ textView: TextView, attachment: NSTextAttachment, imageAt url: URL, onSuccess success: @escaping (UIImage) -> Void, onFailure failure: @escaping () -> Void) {
switch attachment {
case let videoAttachment as VideoAttachment:
guard let posterURL = videoAttachment.posterURL else {
// Let's get a frame from the video directly
if let videoURL = videoAttachment.mediaURL {
exportPreviewImageForVideo(atURL: videoURL, onCompletion: success, onError: failure)
} else {
exportPreviewImageForVideo(atURL: url, onCompletion: success, onError: failure)
}
return
}
downloadImage(from: posterURL, success: success, onFailure: failure)
case let imageAttachment as ImageAttachment:
if let imageURL = imageAttachment.url {
downloadImage(from: imageURL, success: success, onFailure: failure)
}
default:
failure()
}
}
func textView(_ textView: TextView, placeholderFor attachment: NSTextAttachment) -> UIImage {
return placeholderImage(for: attachment)
}
func placeholderImage(for attachment: NSTextAttachment) -> UIImage {
var placeholderImage: UIImage
switch attachment {
case _ as ImageAttachment:
placeholderImage = UIImage.systemImage("photo")
case _ as VideoAttachment:
placeholderImage = UIImage.systemImage("video")
default:
placeholderImage = UIImage.systemImage("paperclip")
}
if #available(iOS 13.0, *) {
placeholderImage = placeholderImage.withTintColor(.label)
}
return placeholderImage
}
func textView(_ textView: TextView, urlFor imageAttachment: ImageAttachment) -> URL? {
guard let image = imageAttachment.image else {
return nil
}
return image.saveToTemporaryFile()
}
func textView(_ textView: TextView, deletedAttachment attachment: MediaAttachment) {
print("Attachment \(attachment.identifier) removed.\n")
}
func textView(_ textView: TextView, selected attachment: NSTextAttachment, atPosition position: CGPoint) {
switch attachment {
case let attachment as HTMLAttachment:
displayUnknownHtmlEditor(for: attachment, in: textView)
case let attachment as MediaAttachment:
selected(in: textView, textAttachment: attachment, atPosition: position)
default:
break
}
}
func textView(_ textView: TextView, deselected attachment: NSTextAttachment, atPosition position: CGPoint) {
deselected(in: textView, textAttachment: attachment, atPosition: position)
}
fileprivate func resetMediaAttachmentOverlay(_ mediaAttachment: MediaAttachment) {
mediaAttachment.overlayImage = nil
mediaAttachment.message = nil
}
func selected(in textView: TextView, textAttachment attachment: MediaAttachment, atPosition position: CGPoint) {
if (currentSelectedAttachment == attachment) {
displayActions(in: textView, forAttachment: attachment, position: position)
} else {
if let selectedAttachment = currentSelectedAttachment {
resetMediaAttachmentOverlay(selectedAttachment)
textView.refresh(selectedAttachment)
}
// and mark the newly tapped attachment
if attachment.message == nil {
let message = NSLocalizedString("Options", comment: "Options to show when tapping on a media object on the post/page editor.")
attachment.message = NSAttributedString(string: message, attributes: attachmentTextAttributes)
}
attachment.overlayImage = UIImage.init(systemName: "square.and.pencil")!.withRenderingMode(.alwaysTemplate)
textView.refresh(attachment)
currentSelectedAttachment = attachment
}
}
func deselected(in textView: TextView,textAttachment attachment: NSTextAttachment, atPosition position: CGPoint) {
currentSelectedAttachment = nil
if let mediaAttachment = attachment as? MediaAttachment {
resetMediaAttachmentOverlay(mediaAttachment)
textView.refresh(mediaAttachment)
}
}
func displayVideoPlayer(for videoURL: URL) {
let asset = AVURLAsset(url: videoURL)
let controller = AVPlayerViewController()
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
controller.showsPlaybackControls = true
controller.player = player
player.play()
baseController.present(controller, animated:true, completion: nil)
}
}
// MARK: - Media fetch methods
//
private extension TextViewAttachmentDelegateProvider {
func exportPreviewImageForVideo(atURL url: URL, onCompletion: @escaping (UIImage) -> (), onError: @escaping () -> ()) {
DispatchQueue.global(qos: .background).async {
let asset = AVURLAsset(url: url)
guard asset.isExportable else {
onError()
return
}
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: CMTimeMake(value: 2, timescale: 1))],
completionHandler: { (time, cgImage, actualTime, result, error) in
guard let cgImage = cgImage else {
DispatchQueue.main.async {
onError()
}
return
}
let image = UIImage(cgImage: cgImage)
DispatchQueue.main.async {
onCompletion(image)
}
})
}
}
func downloadImage(from url: URL, success: @escaping (UIImage) -> Void, onFailure failure: @escaping () -> Void) {
let task = URLSession.shared.dataTask(with: url) { [weak self] (data, _, error) in
DispatchQueue.main.async {
guard self != nil else {
return
}
guard error == nil, let data = data, let image = UIImage(data: data, scale: UIScreen.main.scale) else {
failure()
return
}
success(image)
}
}
task.resume()
}
}
// MARK: - Media attachments actions
//
extension TextViewAttachmentDelegateProvider {
func displayActions(in textView: TextView, forAttachment attachment: MediaAttachment, position: CGPoint) {
let mediaID = attachment.identifier
let title: String = NSLocalizedString("Media Options", comment: "Title for action sheet with media options.")
let message: String? = nil
let alertController = UIAlertController(title: title, message:message, preferredStyle: .actionSheet)
let dismissAction = UIAlertAction(title: NSLocalizedString("Dismiss", comment: "User action to dismiss media options."),
style: .cancel,
handler: { [weak self] (action) in
self?.resetMediaAttachmentOverlay(attachment)
textView.refresh(attachment)
}
)
alertController.addAction(dismissAction)
let removeAction = UIAlertAction(title: NSLocalizedString("Remove Media", comment: "User action to remove media."),
style: .destructive,
handler: { (action) in
textView.remove(attachmentID: mediaID)
})
alertController.addAction(removeAction)
if let imageAttachment = attachment as? ImageAttachment {
let detailsAction = UIAlertAction(title:NSLocalizedString("Media Details", comment: "User action to change media details."),
style: .default,
handler: { [weak self] (action) in
self?.displayDetailsForAttachment(in: textView, imageAttachment, position: position)
})
alertController.addAction(detailsAction)
} else if let videoAttachment = attachment as? VideoAttachment, let videoURL = videoAttachment.mediaURL {
let detailsAction = UIAlertAction(title:NSLocalizedString("Play Video", comment: "User action to play video."),
style: .default,
handler: { [weak self] (action) in
self?.displayVideoPlayer(for: videoURL)
})
alertController.addAction(detailsAction)
}
alertController.title = title
alertController.message = message
alertController.popoverPresentationController?.sourceView = textView
alertController.popoverPresentationController?.sourceRect = CGRect(origin: position, size: CGSize(width: 1, height: 1))
alertController.popoverPresentationController?.permittedArrowDirections = .any
baseController.present(alertController, animated:true, completion: nil)
}
func displayDetailsForAttachment(in textView: TextView, _ attachment: ImageAttachment, position:CGPoint) {
let caption = textView.caption(for: attachment)
let detailsViewController = AttachmentDetailsViewController.controller(for: attachment, with: caption)
let linkInfo = textView.linkInfo(for: attachment)
let linkRange = linkInfo?.range
let linkUpdateRange = linkRange ?? textView.textStorage.ranges(forAttachment: attachment).first!
if let linkURL = linkInfo?.url {
detailsViewController.linkURL = linkURL
}
detailsViewController.onUpdate = { (alignment, size, srcURL, linkURL, alt, caption) in
let attachment = textView.edit(attachment) { attachment in
if let alt = alt {
attachment.extraAttributes["alt"] = .string(alt)
}
attachment.alignment = alignment
attachment.size = size
attachment.updateURL(srcURL)
}
if let caption = caption, caption.length > 0 {
textView.replaceCaption(for: attachment, with: caption)
} else {
textView.removeCaption(for: attachment)
}
if let newLinkURL = linkURL {
textView.setLink(newLinkURL, inRange: linkUpdateRange)
} else if linkURL != nil {
textView.removeLink(inRange: linkUpdateRange)
}
}
let selectedRange = textView.selectedRange
detailsViewController.onDismiss = {
textView.becomeFirstResponder()
textView.selectedRange = selectedRange
}
let navigationController = UINavigationController(rootViewController: detailsViewController)
baseController.present(navigationController, animated: true, completion: nil)
}
}
// MARK: - Unknown HTML
//
private extension TextViewAttachmentDelegateProvider {
func displayUnknownHtmlEditor(for attachment: HTMLAttachment, in textView: TextView) {
let targetVC = UnknownEditorViewController(attachment: attachment)
targetVC.onDidSave = { [weak self] html in
textView.edit(attachment) { updated in
updated.rawHTML = html
}
self?.baseController.dismiss(animated: true, completion: nil)
}
targetVC.onDidCancel = { [weak self] in
self?.baseController.dismiss(animated: true, completion: nil)
}
let navigationController = UINavigationController(rootViewController: targetVC)
displayAsPopover(viewController: navigationController)
}
func displayAsPopover(viewController: UIViewController) {
viewController.preferredContentSize = baseController.view.frame.size
let presentationController = viewController.popoverPresentationController
presentationController?.sourceView = baseController.view
presentationController?.delegate = self
baseController.present(viewController, animated: true, completion: nil)
}
}
// MARK: - UIPopoverPresentationControllerDelegate
//
extension TextViewAttachmentDelegateProvider: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
}
}
| mpl-2.0 | df678fc648335eb7d85347dba0fe5d22 | 42.549383 | 178 | 0.610914 | 6.240602 | false | false | false | false |
practicalswift/swift | test/stmt/errors.swift | 8 | 3590 | // RUN: %target-typecheck-verify-swift
enum MSV : Error {
case Foo, Bar, Baz
var _domain: String { return "" }
var _code: Int { return 0 }
}
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func thrower() throws {}
func opaque_error() -> Error { return MSV.Foo }
func one() {
throw MSV.Foo // expected-error {{error is not handled because the enclosing function is not declared 'throws'}}
}
func two() {
throw opaque_error() // expected-error {{error is not handled because the enclosing function is not declared 'throws'}}
}
func three() {
do {
throw opaque_error() // expected-error {{error is not handled because the enclosing catch is not exhaustive}}
} catch let e as MSV {
_ = e
}
}
func four() {
do {
throw opaque_error()
} catch let e {
_ = e
}
}
func five() {
do {
throw opaque_error()
} catch let e as MSV {
_ = e
} catch _ {
}
}
func six() {
do {
do {
throw opaque_error()
} catch let e as MSV {
_ = e
}
} catch _ {
}
}
func seven_helper() throws -> Int { throw MSV.Baz }
struct seven {
var x: Int {
do {
return try seven_helper()
} catch {
return 0
}
}
var y: Int {
return try! seven_helper()
}
var z: Int {
return (try? seven_helper()) ?? 0
}
}
class eight {
lazy var x: Int = {
do {
return try seven_helper()
} catch {
return 0
}
}()
lazy var y: Int = {
return try! seven_helper()
}()
lazy var z: Int = {
return (try? seven_helper()) ?? 0
}()
}
protocol ThrowingProto {
func foo() throws
static func bar() throws
}
func testExistential(_ p : ThrowingProto) throws {
try p.foo()
try type(of: p).bar()
}
func testGeneric<P : ThrowingProto>(p : P) throws {
try p.foo()
try P.bar()
}
// Don't warn about the "useless" try in these cases.
func nine_helper(_ x: Int, y: Int) throws {} // expected-note {{'nine_helper(_:y:)' declared here}}
func nine() throws {
try nine_helper(y: 0) // expected-error {{missing argument for parameter #1 in call}}
}
func ten_helper(_ x: Int) {}
func ten_helper(_ x: Int, y: Int) throws {}
func ten() throws {
try ten_helper(y: 0) // expected-error {{extraneous argument label 'y:' in call}} {{18-21=}}
}
// rdar://21074857
func eleven_helper(_ fn: () -> ()) {}
func eleven_one() {
eleven_helper {
do {
try thrower()
// FIXME: suppress the double-emission of the 'always true' warning
} catch let e as Error { // expected-warning {{immutable value 'e' was never used}} {{17-18=_}} expected-warning 2 {{'as' test is always true}}
}
}
}
func eleven_two() {
eleven_helper { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> ()'}}
do {
try thrower()
} catch let e as MSV {
}
}
}
enum Twelve { case Payload(Int) }
func twelve_helper(_ fn: (Int, Int) -> ()) {}
func twelve() {
twelve_helper { (a, b) in // expected-error {{invalid conversion from throwing function of type '(_, _) throws -> ()' to non-throwing function type '(Int, Int) -> ()'}}
do {
try thrower()
} catch Twelve.Payload(a...b) {
}
}
}
struct Thirteen : Error, Equatable {}
func ==(a: Thirteen, b: Thirteen) -> Bool { return true }
func thirteen_helper(_ fn: (Thirteen) -> ()) {}
func thirteen() {
thirteen_helper { (a) in // expected-error {{invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(Thirteen) -> ()'}}
do {
try thrower()
} catch a {
}
}
}
| apache-2.0 | d4b997eeae842ac01adc68cee915b7f7 | 20.497006 | 170 | 0.585794 | 3.402844 | false | false | false | false |
a178960320/MyDouyu | Douyu/Douyu/Classes/Main/Model/AnchorGroupModel.swift | 1 | 961 | //
// AnchorGroupModel.swift
// Douyu
//
// Created by 住梦iOS on 2017/2/28.
// Copyright © 2017年 qiongjiwuxian. All rights reserved.
//
import UIKit
class AnchorGroupModel: NSObject{
//该组中对应的房间信息
var room_list:[roomListModel] = [roomListModel]()
var tag_name:String = ""
var icon_url:String = "home_header_normal"
var icon_name = "home_header_normal"
var tag_id = ""
class func modelContainerPropertyGenericClass() -> [String : Any]? {
return ["room_list":roomListModel.self]
}
}
class roomListModel:NSObject{
var anchor_city = ""
var avatar_mid = ""
var avatar_small = ""
var cate_id = ""
var child_id = ""
var game_name = ""
var nickname = ""
var online = ""
var room_id = ""
var room_name = ""
var room_src = ""
var show_status = ""
var show_time = ""
var specific_catalog = ""
var vertical_src = ""
}
| mit | c18c01c28859d76c4a604a2762ce08ec | 20.227273 | 72 | 0.585653 | 3.498127 | false | false | false | false |
chenchangqing/CQTextField | Pod/Classes/CQTextField.swift | 1 | 4762 | //
// CQTextField.swift
// Pods
//
// Created by green on 15/12/17.
//
//
import UIKit
func scaleImage(_ image: UIImage, toScale scaleSize: CGFloat) -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: image.size.width * scaleSize, height: image.size.height * scaleSize))
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width * scaleSize, height: image.size.height * scaleSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
let CQTextFieldFrameworkSrcName = "Frameworks/CQTextField.framework/CQTextField.bundle/"
@IBDesignable public class CQTextField: UIView {
@IBInspectable dynamic var iconWidth: CGFloat = 16 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable dynamic var iconImage: UIImage? {
didSet {
iconLayer.contents = iconImage?.cgImage
}
}
@IBInspectable dynamic var placeholder: String = "" {
didSet {
textField.placeholder = placeholder
}
}
internal let iconLayer = CALayer()
public let textField = UITextField()
// 边界
@IBInspectable dynamic var borderColor: UIColor = UIColor.gray {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable dynamic var focusBorderColor: UIColor = UIColor.magenta
internal let borderWidth: CGFloat = 1
internal let cornerRadius : CGFloat = 4
// 文本框
internal let paddingIconAndText: CGFloat = 8
internal let textFieldHeight: CGFloat = 21
internal let textFieldMargin: CGFloat = 4
internal let textFieldFont: CGFloat = 14
override public func draw(_ rect: CGRect) {
super.draw(rect)
// 边界
self.layer.borderColor = borderColor.cgColor
self.layer.borderWidth = borderWidth
self.layer.cornerRadius = cornerRadius
// 图片
let minLength = min(self.bounds.width, self.bounds.height)
let iconMargin = (minLength - iconWidth)/2
let iconLayerOrigin = CGPoint(x: iconMargin, y: iconMargin)
let iconLayerSize = CGSize(width: iconWidth, height: iconWidth)
iconLayer.frame = CGRect(origin: iconLayerOrigin, size: iconLayerSize)
iconLayer.contents = iconImage?.cgImage
//iconLayer.backgroundColor = UIColor.grayColor().CGColor
self.layer.addSublayer(iconLayer)
// 文本框
let textFieldOriginX = iconLayer.frame.maxX + paddingIconAndText
let textFieldOrigin = CGPoint(x: textFieldOriginX, y: textFieldMargin)
let textFieldSizeWidth = rect.width - textFieldOrigin.x - iconMargin
let textFieldSize = CGSize(width: textFieldSizeWidth, height: textFieldHeight)
textField.frame = CGRect(origin: textFieldOrigin, size: textFieldSize)
textField.center.y = rect.height/2
textField.placeholder = placeholder
textField.font = UIFont.systemFont(ofSize: textFieldFont)
textField.clearButtonMode = .whileEditing
//textField.backgroundColor = UIColor.magentaColor()
self.addSubview(textField)
}
// MARK: - UITextField Observing
override public func willMove(toSuperview newSuperview: UIView?) {
if newSuperview != nil {
NotificationCenter.default.addObserver(self, selector: #selector(CQTextField.textFieldDidEndEditing), name:NSNotification.Name.UITextFieldTextDidEndEditing, object: self.textField)
NotificationCenter.default.addObserver(self, selector: #selector(CQTextField.textFieldDidBeginEditing), name:NSNotification.Name.UITextFieldTextDidBeginEditing, object: self.textField)
} else {
NotificationCenter.default.removeObserver(self)
}
}
/**
The textfield has started an editing session.
*/
func textFieldDidBeginEditing() {
animateViewsForTextEntry()
}
/**
The textfield has ended an editing session.
*/
func textFieldDidEndEditing() {
animateViewsForTextDisplay()
}
/**
Creates all the animations that are used to leave the textfield in the "entering text" state.
*/
func animateViewsForTextEntry() {
self.layer.borderColor = focusBorderColor.cgColor
}
/**
Creates all the animations that are used to leave the textfield in the "display input text" state.
*/
func animateViewsForTextDisplay() {
self.layer.borderColor = borderColor.cgColor
}
}
| mit | 9a7d60cfc8801fab6598997fddd9d5c4 | 32.602837 | 196 | 0.645631 | 5.200878 | false | false | false | false |
gowansg/firefox-ios | Storage/SQL/FaviconsTable.swift | 3 | 3325 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
private let TableNameFavicons = "favicons"
// NOTE: If you add a new Table, make sure you update the version number in BrowserDB.swift!
// This is our default favicons store.
class FaviconsTable<T>: GenericTable<Favicon> {
override var name: String { return TableNameFavicons }
override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" }
override func getInsertAndArgs(inout item: Favicon) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
args.append(item.url)
args.append(item.width)
args.append(item.height)
args.append(item.date)
args.append(item.type.rawValue)
return ("INSERT INTO \(TableNameFavicons) (url, width, height, date, type) VALUES (?,?,?,?,?)", args)
}
override func getUpdateAndArgs(inout item: Favicon) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
args.append(item.width)
args.append(item.height)
args.append(item.date)
args.append(item.type.rawValue)
args.append(item.url)
return ("UPDATE \(TableNameFavicons) SET width = ?, height = ?, date = ?, type = ? WHERE url = ?", args)
}
override func getDeleteAndArgs(inout item: Favicon?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let icon = item {
args.append(icon.url)
return ("DELETE FROM \(TableNameFavicons) WHERE url = ?", args)
}
return ("DELETE FROM \(TableNameFavicons)", args)
}
override var factory: ((row: SDRow) -> Favicon)? {
return { row -> Favicon in
let icon = Favicon(url: row["url"] as! String, date: NSDate(timeIntervalSince1970: row["date"] as! Double), type: IconType(rawValue: row["type"] as! Int)!)
icon.id = row["id"] as? Int
return icon
}
}
override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let filter: AnyObject = options?.filter {
args.append("%\(filter)%")
return ("SELECT id, url, date, type FROM \(TableNameFavicons) WHERE url LIKE ?", args)
}
return ("SELECT id, url, date, type FROM \(TableNameFavicons)", args)
}
func getIDFor(db: SQLiteDBConnection, obj: Favicon) -> Int? {
let opts = QueryOptions()
opts.filter = obj.url
let cursor = query(db, options: opts)
if (cursor.count != 1) {
return nil
}
return (cursor[0] as? Favicon)?.id
}
func insertOrUpdate(db: SQLiteDBConnection, obj: Favicon) {
var err: NSError? = nil
let id = self.insert(db, item: obj, err: &err)
if id >= 0 {
obj.id = id
return
}
if obj.id == nil {
obj.id = getIDFor(db, obj: obj)
}
}
}
| mpl-2.0 | cfeb8ee77a57ca85a7e0ebba23deee12 | 35.944444 | 167 | 0.571429 | 4.219543 | false | false | false | false |
AccessLite/BYT-Golden | BYT/Models/ColorScheme.swift | 1 | 4492 | //
// ColorScheme.swift
// BYT
//
// Created by Tom Seymour on 1/29/17.
// Copyright © 2017 AccessLite. All rights reserved.
//
import Foundation
import Foundation
import UIKit
class ColorScheme {
var record_url: String
var color_scheme_name: String
var _50: UIColor
var _100: UIColor
var _200: UIColor
var _300: UIColor
var _400: UIColor
var _500: UIColor
var _600: UIColor
var _700: UIColor
var _800: UIColor
var _900: UIColor
var a200: UIColor
var premium: String
var jsonDict: [String: Any]
var colorArray: [UIColor] {
return [_300, _400, _500, _600, _700, _800, _900, _800, _700, _600, _500, _400, _300, _200]
}
var primary: UIColor {
return _500
}
var primaryDark: UIColor {
return _700
}
var primaryLight: UIColor {
return _100
}
var accent: UIColor {
return a200
}
init(record_url: String,
color_scheme_name: String,
_50: String,
_100: String,
_200: String,
_300: String,
_400: String,
_500: String,
_600: String,
_700: String,
_800: String,
_900: String,
a200: String,
premium: String,
jsonDict: [String: Any]) {
self.record_url = record_url
self.color_scheme_name = color_scheme_name
self._50 = UIColor(hexString: _50 )
self._100 = UIColor(hexString: _100)
self._200 = UIColor(hexString: _200)
self._300 = UIColor(hexString: _300)
self._400 = UIColor(hexString: _400)
self._500 = UIColor(hexString: _500)
self._600 = UIColor(hexString: _600)
self._700 = UIColor(hexString: _700)
self._800 = UIColor(hexString: _800)
self._900 = UIColor(hexString: _900)
self.a200 = UIColor(hexString: a200)
self.premium = premium
self.jsonDict = jsonDict
}
convenience init?(from dict:[String:Any]) {
if let record_url = dict["record_url"] as? String,
let color_scheme_name = dict["color_scheme_name"] as? String,
let _50 = dict["_50"] as? String,
let _100 = dict["_100"] as? String,
let _200 = dict["_200"] as? String,
let _300 = dict["_300"] as? String,
let _400 = dict["_400"] as? String,
let _500 = dict["_500"] as? String,
let _600 = dict["_600"] as? String,
let _700 = dict["_700"] as? String,
let _800 = dict["_800"] as? String,
let _900 = dict["_900"] as? String,
let a200 = dict["a200"] as? String,
let premium = dict["premium"] as? String {
self.init(record_url:record_url,
color_scheme_name: color_scheme_name,
_50: _50,
_100: _100,
_200: _200,
_300: _300,
_400: _400,
_500: _500,
_600: _600,
_700: _700,
_800: _800,
_900: _900,
a200: a200,
premium: premium,
jsonDict: dict)
} else {
return nil
}
}
static func parseColorSchemes(from data: Data) -> [ColorScheme]? {
var colorSchemes = [ColorScheme]()
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let validArr = json as? [[String: Any]] else { return nil }
for scheme in validArr {
if let scheme = ColorScheme(from: scheme) {
colorSchemes.append(scheme)
}
}
}
catch {
print(error)
}
return colorSchemes
}
convenience required init?(data: Data) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
if let validJson = json {
self.init(from: validJson)
} else {
return nil
}
}
catch {
print("Problem recreating currentColorScheme from data: \(error)")
return nil
}
}
func toData() throws -> Data {
return try JSONSerialization.data(withJSONObject: self.jsonDict, options: [])
}
}
| mit | 398da4bb9f6b491407b9a163b9608bb7 | 28.94 | 104 | 0.492986 | 4.131555 | false | false | false | false |
chrislavender/Thumbafon | Thumbafon/AppDelegate.swift | 1 | 5188 | //
// AppDelegate.swift
// Thumbafon
//
// Created by Chris Lavender on 9/12/15.
// Copyright (c) 2015 Gnarly Dog Music. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.christopherlavender.Thumbafon" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Thumbafon", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("Thumbafon.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
if moc.hasChanges == false {return}
do {
try moc.save()
} catch {
print(error)
}
}
}
}
| cc0-1.0 | daca37447f08abcf2e08c855e0b62a74 | 48.409524 | 290 | 0.716847 | 5.732597 | false | false | false | false |
duliodenis/v | V/V/Controllers/SignUpViewController.swift | 1 | 4938 | //
// SignUpViewController.swift
// V
//
// Created by Dulio Denis on 8/16/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController {
private let phoneNumberField = UITextField()
private let emailField = UITextField()
private let passwordField = UITextField()
var remoteStore: RemoteStore?
var contactImporter: ContactImporter?
var rootViewController: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.flatBlue()
let label = UILabel()
label.text = STRING_SIGNUP_TEXT
label.font = UIFont(name: "AdventPro-Regular", size: 24)
label.textColor = UIColor.flatWhite()
view.addSubview(label)
let continueButton = CustomButton()
continueButton.setTitle("Continue", forState: .Normal)
continueButton.setTitleColor(BUTTON_TITLE_COLOR, forState: .Normal)
continueButton.titleLabel?.font = UIFont(name: "AdventPro-Regular", size: 24)
continueButton.addTarget(self, action: "tappedContinue:", forControlEvents: .TouchUpInside)
continueButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(continueButton)
phoneNumberField.keyboardType = .PhonePad
phoneNumberField.textColor = UIColor.flatWhite()
emailField.textColor = UIColor.flatWhite()
passwordField.textColor = UIColor.flatWhite()
label.translatesAutoresizingMaskIntoConstraints = false
let fields = [(phoneNumberField, "Phone Number"), (emailField, "Email"), (passwordField, "Password")]
fields.forEach{
$0.0.placeholder = $0.1
}
passwordField.secureTextEntry = true
let stackView = UIStackView(arrangedSubviews: fields.map{$0.0})
stackView.axis = .Vertical
stackView.alignment = .Fill
stackView.spacing = 20
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
let constraints: [NSLayoutConstraint] = [
label.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor, constant: 20),
label.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor),
stackView.topAnchor.constraintEqualToAnchor(label.bottomAnchor, constant: 20),
stackView.leadingAnchor.constraintEqualToAnchor(view.layoutMarginsGuide.leadingAnchor),
stackView.trailingAnchor.constraintEqualToAnchor(view.layoutMarginsGuide.trailingAnchor),
continueButton.topAnchor.constraintEqualToAnchor(stackView.bottomAnchor, constant: 20),
continueButton.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor),
continueButton.widthAnchor.constraintEqualToAnchor(view.widthAnchor, constant: -75)
]
NSLayoutConstraint.activateConstraints(constraints)
phoneNumberField.becomeFirstResponder()
}
func tappedContinue(sender: UIButton) {
sender.enabled = false
guard let phoneNumber = phoneNumberField.text where phoneNumber.characters.count > 0 else {
alertForError(STRING_PHONE_NUMBER_ERROR)
sender.enabled = true
return
}
guard let email = emailField.text where email.characters.count > 0 else {
alertForError(STRING_EMAIL_ERROR)
sender.enabled = true
return
}
guard let password = passwordField.text where password.characters.count >= 6 else {
alertForError(STRING_PASSWORD_ERROR)
sender.enabled = true
return
}
remoteStore?.signUp(phoneNumber: phoneNumber, email: email, password: password, success: {
guard let rootVC = self.rootViewController,
remoteStore = self.remoteStore,
contactImporter = self.contactImporter else {return}
remoteStore.startSyncing()
contactImporter.fetch()
contactImporter.listenForChanges()
self.presentViewController(rootVC, animated: true, completion: nil)
}, error: {
errorString in
self.alertForError(errorString)
sender.enabled = true
})
}
private func alertForError(error: String) {
let alertController = UIAlertController(title: "Error", message: error, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | 4b53928202a3451ab686217959744afc | 36.401515 | 109 | 0.639862 | 5.787808 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos | Data Structures & Algorithms/LinkedList.playground/Contents.swift | 1 | 5472 | //: Playground - noun: a place where people can play
import UIKit
import Foundation
public class Node<Value> {
public var value: Value
public var next: Node?
public init(value: Value, next: Node? = nil) {
self.value = value
self.next = next
}
}
extension Node: CustomStringConvertible {
public var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value) -> " + String(describing: next) + " "
}
}
let node1 = Node(value: 1)
let node2 = Node(value: 2)
let node3 = Node(value: 3)
node1.next = node2
node2.next = node3
//print(node1)
public class LinkedList<Value> {
public var head: Node<Value>?
public var tail: Node<Value>?
public init() {}
public var isEmpty: Bool {
return head == nil
}
public func push(_ value: Value) {
head = Node(value: value, next: head)
if tail == nil {
tail = head
}
}
public func append(_ value: Value) {
guard !isEmpty else {
push(value)
return
}
tail!.next = Node(value: value)
tail = tail!.next
}
public func node(at index: Int) -> Node<Value>? {
var currentNode = head
var currentIndex = 0
while currentNode != nil && currentIndex < index {
currentNode = currentNode!.next
currentIndex += 1
}
return currentNode
}
@discardableResult
public func insert(_ value: Value, after node: Node<Value>) -> Node<Value> {
guard tail !== node else {
append(value)
return tail!
}
node.next = Node(value: value, next: node.next)
return node.next!
}
@discardableResult
public func pop() -> Value? {
defer {
head = head?.next
if isEmpty {
tail = nil
}
}
return head?.value
}
@discardableResult
public func removeLast() -> Value? {
guard let head = head else {
return nil
}
guard head.next != nil else {
return pop()
}
var prev = head
var current = head
while let next = current.next {
prev = current
current = next
}
prev.next = nil
tail = prev
return current.value
}
@discardableResult
public func remove(after node: Node<Value>) -> Value? {
defer {
if node.next === tail {
tail = node
}
node.next = node.next?.next
}
return node.next?.value
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
guard let head = head else {
return "Empty List"
}
return String(describing: head)
}
}
//var list = LinkedList<Int>()
//list.push(3)
//list.append(1)
//list.push(2)
//list.append(2)
//list.push(1)
//list.append(3)
//print("Before inserting: \(list)")
//var middleNode = list.node(at: 1)!
//
//for _ in 1...4 {
// middleNode = list.insert(-1, after: middleNode)
//}
//print("After inserting: \(list)")
//print("Before popping list: \(list)")
//
//let poppedValue = list.pop()
//
//print("After popping list: \(list)")
//print("Popped value: " + String(describing: poppedValue))
//print("Before removing last node: \(list)")
//let removedValue = list.removeLast()
//print("After removing last node: \(list)")
//print("Removed value: " + String(describing: removedValue))
//print("Before removing at particular index: \(list)")
//let index = 1
//let node = list.node(at: index - 1)!
//let removedValue = list.remove(after: node)
//print("After removing at index \(index): \(list)")
//print("Removed value: " + String(describing: removedValue))
extension LinkedList: Collection {
public struct Index: Comparable {
public var node: Node<Value>?
static public func ==(lhs: Index, rhs: Index) -> Bool {
switch (lhs.node, rhs.node) {
case let (left?, right?):
return left.next === right.next
case (nil, nil):
return true
default:
return false
}
}
static public func <(lhs: Index, rhs: Index) -> Bool {
guard lhs != rhs else {
return false
}
let nodes = sequence(first: lhs.node) { $0?.next }
return nodes.contains{ $0 === rhs.node }
}
}
public var startIndex: Index {
return Index(node: head)
}
public var endIndex: Index {
return Index(node: tail?.next)
}
public func index(after i: Index) -> Index {
return Index(node: i.node?.next)
}
public subscript(position: Index) -> Value {
return position.node!.value
}
}
// Verifying Collection Adherence
//var list = LinkedList<Int>()
//for i in 0...9 {
// list.append(i)
//}
//print("List: \(list)")
//print("First element: \(list[list.startIndex])")
//print("Array containing first 3 elements: \(Array(list.prefix(3)))")
//print("Array continaing last 3 elements: \(Array(list.suffix(3)))")
//let sum = list.reduce(0, +)
//print("Sum of all values: \(sum)")
| gpl-2.0 | da18d17ef616793234bf1cbe270ba767 | 22.285106 | 80 | 0.536367 | 4.120482 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Effects.playground/Pages/Reverb.xcplaygroundpage/Contents.swift | 1 | 2575 | //: ## Simple Reverb
//: ### This is an implementation of Apple's simplest reverb which only allows you to set presets
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var reverb = AKReverb(player)
reverb.dryWetMix = 0.5
AudioKit.output = reverb
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Reverb")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: processingPlaygroundFiles))
addSubview(AKPropertySlider(
property: "Mix",
value: reverb.dryWetMix,
color: AKColor.greenColor()
) { sliderValue in
reverb.dryWetMix = sliderValue
})
let presets = ["Cathedral","Large Hall", "Large Hall 2",
"Large Room", "Large Room 2", "Medium Chamber",
"Medium Hall", "Medium Hall 2", "Medium Hall 3",
"Medium Room", "Plate", "Small Room"]
addSubview(AKPresetLoaderView(presets: presets) { preset in
switch preset {
case "Cathedral":
reverb.loadFactoryPreset(.Cathedral)
case "Large Hall":
reverb.loadFactoryPreset(.LargeHall)
case "Large Hall 2":
reverb.loadFactoryPreset(.LargeHall2)
case "Large Room":
reverb.loadFactoryPreset(.LargeRoom)
case "Large Room 2":
reverb.loadFactoryPreset(.LargeRoom2)
case "Medium Chamber":
reverb.loadFactoryPreset(.MediumChamber)
case "Medium Hall":
reverb.loadFactoryPreset(.MediumHall)
case "Medium Hall 2":
reverb.loadFactoryPreset(.MediumHall2)
case "Medium Hall 3":
reverb.loadFactoryPreset(.MediumHall3)
case "Medium Room":
reverb.loadFactoryPreset(.MediumRoom)
case "Plate":
reverb.loadFactoryPreset(.Plate)
case "Small Room":
reverb.loadFactoryPreset(.SmallRoom)
default: break
}}
)
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit | 06e6f61b6632b6a281e50f151a414a6c | 30.402439 | 97 | 0.593786 | 5.421053 | false | false | false | false |
g38015/checkit | Checkit-iOS/Checkit-iOS/LandingViewController.swift | 1 | 2126 | //
// LandingViewController.swift
// Checkit-iOS
//
// Created by Peter Hitchcock on 3/13/16.
// Copyright © 2016 Peter Hitchcock. All rights reserved.
//
import UIKit
import ExpandingMenu
class LandingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureExpandingMenuButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func configureExpandingMenuButton() {
let menuButtonSize: CGSize = CGSize(width: 70.0, height: 70.0)
let menuButton = ExpandingMenuButton(frame: CGRect(origin: CGPointZero, size: menuButtonSize), centerImage: UIImage(named: "chooser-button-tab")!, centerHighlightedImage: UIImage(named: "chooser-button-tab-highlighted")!)
menuButton.center = CGPointMake(self.view.bounds.width - 32.0, self.view.bounds.height - 72.0)
self.view.addSubview(menuButton)
let item1 = ExpandingMenuItem(size: menuButtonSize, title: "Search Checks", image: UIImage(named: "chooser-moment-icon-music")!, highlightedImage: UIImage(named: "chooser-moment-icon-place-highlighted")!, backgroundImage: UIImage(named: "chooser-moment-button"), backgroundHighlightedImage: UIImage(named: "chooser-moment-button-highlighted")) { () -> Void in
self.performSegueWithIdentifier("checksSegue", sender: self)
}
let item2 = ExpandingMenuItem(size: menuButtonSize, title: "Info", image: UIImage(named: "chooser-moment-icon-place")!, highlightedImage: UIImage(named: "chooser-moment-icon-place-highlighted")!, backgroundImage: UIImage(named: "chooser-moment-button"), backgroundHighlightedImage: UIImage(named: "chooser-moment-button-highlighted")) { () -> Void in
self.performSegueWithIdentifier("infoSegue", sender: self)
}
menuButton.addMenuItems([item1, item2])
menuButton.willPresentMenuItems = { (menu) -> Void in
print("MenuItems will present.")
}
menuButton.didDismissMenuItems = { (menu) -> Void in
print("MenuItems dismissed.")
}
}
}
| mit | 8e527572c3b613bc9e1f87f31956716b | 41.5 | 367 | 0.699294 | 4.4926 | false | false | false | false |
MartinOSix/DemoKit | dSwift/SwiftProjiect/SwiftProjiect/ChannelTitleView.swift | 1 | 4286 | //
// ChannelTitleView.swift
// SwiftProjiect
//
// Created by runo on 17/6/13.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
import Foundation
public protocol ChannelTitleViewDelegate: NSObjectProtocol {
func channelTitleView(DidSelect Index:Int)
}
class ChannelTitleView: UIScrollView {
var titles: [String]?
var currentIndex: Int = 0
var buttonArr = [UIButton]()
var titleNormalColor = UIColor.black
var titleSelecColor = UIColor.red
var titleFont : CGFloat = 14.0
var indicateView = UIView()
weak open var clickDelegate: ChannelTitleViewDelegate?
init(frame: CGRect,titles :[String]) {
super.init(frame: frame)
if titles.count == 0 {
return
}
setUpTitleView(titles: titles)
setUpIndicateView()
}
func setUpIndicateView() {
indicateView.backgroundColor = UIColor.red
let btn = self.buttonArr[self.currentIndex]
indicateView.frame = CGRect(x: btn.cq_x, y: frame.height-3, width: btn.cq_width, height: 3)
self.addSubview(indicateView)
}
func setUpTitleView(titles: [String]) {
//移除原始数据
buttonArr.removeAll()
for (_,value) in self.subviews.enumerated() {
value.removeFromSuperview()
}
var upBtnFrameMaxY: CGFloat = 0
for title in titles {
let btn = UIButton(type: UIButtonType.custom)
let nsTitle = NSString.init(string: title)
let btnSize = nsTitle.boundingRect(with: CGSize.init(width: 0, height: frame.size.height), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: self.titleFont)], context: nil)
btn.setTitle(title, for: .normal)
btn.setTitleColor(self.titleNormalColor, for: .normal)
btn.setTitleColor(self.titleSelecColor, for: .selected)
btn.setTitleColor(self.titleNormalColor, for: .focused)
btn.titleLabel?.font = UIFont.systemFont(ofSize: self.titleFont)
btn.frame = CGRect.init(x: upBtnFrameMaxY, y: 0.0, width: btnSize.width+10, height: frame.size.height)
btn.addTarget(self, action: #selector(btnClick(btn:)), for: .touchUpInside)
upBtnFrameMaxY = btn.frame.maxX
self.addSubview(btn)
buttonArr.append(btn)
self.contentSize = CGSize(width: btn.frame.maxX, height: frame.size.height)
self.showsHorizontalScrollIndicator = false
self.bounces = false
}
let btn = self.buttonArr[self.currentIndex]
btn.isSelected = true
//如果没有超过一页则平铺
if upBtnFrameMaxY < kScreenWidth {
resetBntFrame(totalWidth: upBtnFrameMaxY)
}
}
//按比例平铺Btn
func resetBntFrame(totalWidth: CGFloat) {
var upBtnFrameMaxX: CGFloat = 0
for btn in self.buttonArr {
let newWidth = btn.frame.width/totalWidth * kScreenWidth
btn.cq_width = newWidth
btn.cq_x = upBtnFrameMaxX;
upBtnFrameMaxX = btn.frame.maxX
}
}
//btn点击事件
func btnClick(btn :UIButton) {
if let index = self.buttonArr.index(of: btn),index != self.currentIndex {
let previousBtn = self.buttonArr[self.currentIndex]
previousBtn.isSelected = false
btn.isSelected = true
self.currentIndex = index
let frame = CGRect(x: btn.cq_x, y: self.frame.height-3, width: btn.cq_width, height: 3)
UIView.animate(withDuration: 0.2, animations: {
self.indicateView.frame = frame
})
self.clickDelegate?.channelTitleView(DidSelect: index)
}
}
func rsetCurrentIndex(At index:Int) {
let btn = self.buttonArr[index]
btn.sendActions(for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | ff30f3a56ba4dca35107f8ee4057ab27 | 30.81203 | 250 | 0.595604 | 4.559267 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Model/ReqModel/SLVLikedFilterdInfo.swift | 1 | 4953 | //
// SLVLikedFilterdInfo.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 28..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import ObjectMapper
/*
좋아요 상품 필터
POST
/api/filter/likes
userId String 사용자 ID
sort Number 브랜드 진열 유형
1: 추천순(포토샵 적용, 업데이트 날짜)
2: 신상품순(기본 정렬)
3: 인기순(좋아요 갯수 + 잇템 갯수)
4: 가격이 낮은순
5: 가격이 높은순
category1Id String 카테고리 ID
category2Id String 카테고리 ID
category3Id String 카테고리 ID
category4Id String 카테고리 ID
brands Array[String] 브랜드 ID 배열 기본값: 빈 배열
startPrice Number 가격 범위: 시작 * 기본값: 0
endtPrice Number 가격 범위: 종료 * 기본값: 0
colors Array[String] 색상 배열 * 기본값: 빈 배열
sizes Array[String] 사이즈 배열 * 기본값: 빈 배열
isSale Boolean 세일 여부 * 기본값: false
isSoldOut Boolean 재고(매진) 여부 * 기본값: false
isStyle Boolean 스타일 여부 * 기본값: false
skip Number 이전 아이템 갯수(offset) * 검색 공통(기본값: 0)
limit Number 페이지 단위 아이템 갯수 * 검색 공통(기본값: 10)
*/
class SLVLikedFilterdInfo: Mappable {
var userId:String = BBAuthToken.shared.name()
var sort: Int? {
didSet {
if sort != oldValue {
isSame = false
}
}
}
var category1Id: String? {
didSet {
if category1Id != oldValue {
isSame = false
}
}
}
var category2Id: String? {
didSet {
if category2Id != oldValue {
isSame = false
}
}
}
var category3Id: String? {
didSet {
if category3Id != oldValue {
isSame = false
}
}
}
var category4Id: String? {
didSet {
if category4Id != oldValue {
isSame = false
}
}
}
var brands: [String] = [] {
didSet {
if brands != oldValue {
isSame = false
}
}
}
var startPrice: Double = 0 {
didSet {
if startPrice != oldValue {
isSame = false
}
}
}
var endPrice: Double = 0 {
didSet {
if endPrice != oldValue {
isSame = false
}
}
}
var colors: [String] = [] {
didSet {
if colors != oldValue {
isSame = false
}
}
}
var sizes: [String] = [] {
didSet {
if sizes != oldValue {
isSame = false
}
}
}
var isSale: Bool = false {
didSet {
if isSale != oldValue {
isSame = false
}
}
}
var isSoldOut: Bool = false {
didSet {
if isSoldOut != oldValue {
isSame = false
}
}
}
var isStyle: Bool = false {
didSet {
if isStyle != oldValue {
isSame = false
}
}
}
var isSame: Bool = true
var skip: String = "0"
var limit: String = "10"
init?() {
}
required init?(map: Map) {
}
func mapping(map: Map) {
// userId <- map["userId"]
sort <- map["sort"]
category1Id <- map["category1Id"]
category2Id <- map["category2Id"]
category3Id <- map["category3Id"]
category4Id <- map["category4Id"]
brands <- map["brands"]
startPrice <- map["startPrice"]
endPrice <- map["endPrice"]
colors <- map["colors"]
sizes <- map["sizes"]
isSale <- map["isSale"]
isSoldOut <- map["isSoldOut"]
isStyle <- map["isStyle"]
}
func setupPage() {
let pageKey = "likedFilteredProducts"
if self.isSame == false {
skip = "0"
limit = "10"
PageMappingType(rawValue: pageKey)?.clearSkipValue()
} else {
skip = (PageMappingType(rawValue: pageKey)?.skipValue)!
limit = (PageMappingType(rawValue: pageKey)?.limitValue)!
}
}
//TODO: 정상동작 여부 필수 테스트 필요함.
func toJSON() -> [String : Any] {
self.setupPage()
return Mapper().toJSON(self)
}
}
| mit | 2deb543a3c57557e018d63ac6557c7fb | 22.086294 | 75 | 0.438434 | 3.982487 | false | false | false | false |
eh1255/RedBallTracking | RedBallTrackingiOS/RedBallTrackingiOS/CommHandler.swift | 1 | 1467 | //
// File.swift
// RedBallTrackingiOS
//
// Created by Erik Hornberger on 2016/06/21.
// Copyright © 2016年 EExT. All rights reserved.
//
import Foundation
class CommHanlder:NSObject, TargetUpdateDelegate {
// Setup the singleton as the delegate for the shared instance of the OpenVCWrapper
static let sharedInstance = CommHanlder()
// Initialize the client on port 9000
let client:F53OSCClient = {
let client = F53OSCClient.init()
client.port = 9000
return client
}()
// The server address is retrieved from and stored in NSUserDefaults
// so that it is persisted between sessions
var serverAddress:String {
get { return NSUserDefaults.standardUserDefaults().stringForKey("serverAddress") ?? "" }
set { NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "serverAddress")}
}
// This function will get called whenever an object is detected by the camera
func targetCoordinatesChanged(xCoord: Int, screenCoordinates yCoord: Int) {
sendCoordinates(x: xCoord, y: yCoord)
}
// Send the coordinates out to the server using the Open Sound Control protocol
func sendCoordinates(x x:Int, y:Int) {
client.host = serverAddress
let message = F53OSCMessage(addressPattern: "/redCoordinates", arguments: [x,y])
client.sendPacket(message)
print(x)
print(y)
print()
}
} | mit | bc77e5865a8c81028775b61b34ca85ee | 31.555556 | 97 | 0.670765 | 4.532508 | false | false | false | false |
Nickelfox/FLUtilities | Source/Classes/UIColor+Utility.swift | 2 | 1007 | //
// UIColor+Utility.swift
// FLUtilities
//
// Created by Ravindra Soni on 18/12/16.
// Copyright © 2016 Nickelfox. All rights reserved.
//
import Foundation
import UIKit
public extension UIColor {
convenience init(red: Int, green: Int, blue: Int, opacity: CGFloat = 1.0) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: opacity)
}
convenience init(hex: Int, alpha: CGFloat = 1.0) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff, opacity:alpha)
}
convenience init(hexString: String) {
var hexValue: CUnsignedInt = 0
let scanner = Scanner(string: hexString)
scanner.scanHexInt32(&hexValue)
let value = Int(hexValue)
self.init(red:(value >> 16) & 0xff, green:(value >> 8) & 0xff, blue:value & 0xff)
}
}
| mit | 391ce5298a8a57e0adddd628dfbfe8a4 | 29.484848 | 114 | 0.659046 | 3.067073 | false | false | false | false |
dfuerle/kuroo | kuroo/ProfileViewController.swift | 1 | 4520 | //
// ProfileViewController.swift
// kuroo
//
// Copyright (c) 2015 Dmitri Fuerle. All rights reserved.
//
import UIKit
protocol ProfileDelegate {
func donePressed(profileViewController: ProfileViewController)
func changeSafeContactPressed(profileViewController: ProfileViewController)
}
class ProfileViewController: UIViewController, SettingsDelegate, SupportsContext {
struct Constants {
static let historyStoryboard = "History"
static let settingsStoryboard = "Settings"
static let scrollerXMargin: CGFloat = 8
}
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var selectedBackground: UIView!
@IBOutlet weak var leftButton: UIButton!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var overlayXposition: NSLayoutConstraint!
var delegate: ProfileDelegate?
var historyViewController: HistoryTableViewController!
var settingsViewController: SettingsTableViewController!
var context: Context!
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
debugPrint("viewDidLoad \(self)")
guard self.context != nil else {
fatalError("Unresolved error context is nil")
}
self.navigationController?.navigationBar.barTintColor = context.kuGreen
self.selectedBackground.backgroundColor = context.kuGreen
scrollView.backgroundColor = UIColor.white
historyViewController = UIStoryboard.init(name: Constants.historyStoryboard, bundle: nil).instantiateInitialViewController() as! HistoryTableViewController
historyViewController.context = context
self.addChildViewController(historyViewController)
self.scrollView.addSubview(historyViewController.view)
historyViewController.view.translatesAutoresizingMaskIntoConstraints = false
settingsViewController = UIStoryboard.init(name: Constants.settingsStoryboard, bundle: nil).instantiateInitialViewController() as! SettingsTableViewController
settingsViewController.context = context
self.addChildViewController(settingsViewController)
self.scrollView.addSubview(settingsViewController.view)
settingsViewController.view.translatesAutoresizingMaskIntoConstraints = false
settingsViewController.settingsDelegate = self
let views = ["history" : historyViewController.view!,
"settings" : settingsViewController.view!]
let formatStrings = ["H:|-0-[settings]-0-[history]-0-|",
"V:|-0-[history]-0-|",
"V:|-0-[settings]-0-|"]
var constraints = self.scrollView.wld_constrainsts(withVisualFormats: formatStrings, metrics: nil, views: views)
constraints.append(self.scrollView.wld_constrainstForEqualWidth(v1: self.scrollView, v2: historyViewController.view!))
constraints.append(self.scrollView.wld_constrainstForEqualHeight(v1: self.scrollView, v2: historyViewController.view!))
constraints.append(self.scrollView.wld_constrainstForEqualWidth(v1: self.scrollView, v2: settingsViewController.view!))
constraints.append(self.scrollView.wld_constrainstForEqualHeight(v1: self.scrollView, v2: settingsViewController.view!))
NSLayoutConstraint.activate(constraints)
}
// MARK: - Actions
@IBAction func doneButtonTouched(_ sender: UIBarButtonItem) {
debugPrint("doneButtonTouched \(self)")
if let delegate = delegate {
delegate.donePressed(profileViewController: self)
}
}
@IBAction func leftButtonTouched(_ sender: UIButton) {
debugPrint("leftButtonTouched \(self)")
scrollView.setContentOffset(CGPoint(x:0, y:0), animated: true)
}
@IBAction func rightButtonTouched(_ sender: UIButton) {
debugPrint("rightButtonTouched \(self)")
scrollView.setContentOffset(CGPoint(x:scrollView.contentSize.width/2, y:0), animated: true)
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x / 2
overlayXposition.constant = offsetX + Constants.scrollerXMargin
}
// MARK: - SettingsDelegate
func changeSafeContactPressed(settingsTableViewController: SettingsTableViewController) {
if let delegate = delegate {
delegate.changeSafeContactPressed(profileViewController: self)
}
}
}
| gpl-2.0 | 8d8d07e4f812639ac91586d1d7298c93 | 42.047619 | 166 | 0.710398 | 5.492102 | false | false | false | false |
keyacid/keyacid-iOS | keyacid/ScanQRCodeViewController.swift | 1 | 4485 | //
// ScanQRCodeViewController.swift
// keyacid
//
// Created by Yuan Zhou on 6/24/17.
// Copyright © 2017 yvbbrjdr. All rights reserved.
//
import UIKit
import AVFoundation
class ScanQRCodeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet weak var scanPlaceHolder: UIImageView!
var captureSession: AVCaptureSession? = nil
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
do {
let captureDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
let captureInput: AVCaptureDeviceInput = try AVCaptureDeviceInput.init(device: captureDevice)
captureSession = AVCaptureSession.init()
captureSession?.addInput(captureInput)
let captureMetadataOutput: AVCaptureMetadataOutput = AVCaptureMetadataOutput.init()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
let videoPreviewLayer: AVCaptureVideoPreviewLayer? = AVCaptureVideoPreviewLayer.init(session: captureSession)
videoPreviewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer!.frame = scanPlaceHolder.bounds
scanPlaceHolder.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
} catch {
let notValid: UIAlertController = UIAlertController.init(title: "Error", message: "Camera access denied!", preferredStyle: .alert)
let OKButton: UIAlertAction = UIAlertAction.init(title: "OK", style: UIAlertActionStyle.default, handler: nil)
notValid.addAction(OKButton)
self.present(notValid, animated: true, completion: nil)
return
}
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if metadataObjects == nil || metadataObjects.count == 0 {
return
}
for metadataObject in metadataObjects {
if (metadataObject as AnyObject).type == AVMetadataObjectTypeQRCode {
RemoteProfileTableViewController.scannedString = (metadataObject as! AVMetadataMachineReadableCodeObject).stringValue
captureSession?.stopRunning()
self.navigationController?.popViewController(animated: true)
return
}
}
}
@IBAction func loadClicked() {
let picker: UIImagePickerController = UIImagePickerController.init()
picker.sourceType = .photoLibrary
picker.allowsEditing = false
picker.delegate = self
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var ok:Bool = false
let chosenImage: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let detector: CIDetector? = CIDetector.init(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
let features: [CIFeature]? = detector?.features(in: CIImage.init(image: chosenImage)!)
if features!.count > 0 {
for feature in features! {
if feature.type == CIFeatureTypeQRCode {
RemoteProfileTableViewController.scannedString = (feature as! CIQRCodeFeature).messageString
ok = true
break
}
}
}
dismiss(animated: true) {
if ok {
self.navigationController?.popViewController(animated: true)
} else {
let qrFailed: UIAlertController = UIAlertController.init(title: "Error", message: "No QR Code is detected!", preferredStyle: .alert)
let OKButton: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
qrFailed.addAction(OKButton)
self.present(qrFailed, animated: true, completion: nil)
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
| bsd-3-clause | ac442db94f599beec03c9b78fd6188ac | 47.215054 | 155 | 0.676182 | 6.043127 | false | false | false | false |
divljiboy/IOSChatApp | Quick-Chat/Pods/BulletinBoard/Sources/Appearance/BLTNItemAppearance.swift | 1 | 5870 | /**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* An object that defines the appearance of bulletin items.
*/
@objc public class BLTNItemAppearance: NSObject {
// MARK: - Color Customization
/// The tint color to apply to the action button (default blue).
@objc public var actionButtonColor: UIColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1)
/// The title color to apply to action button (default white).
@objc public var actionButtonTitleColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
/// The border color to apply to action button.
@objc public var actionButtonBorderColor: UIColor? = nil
/// The border width to apply to action button.
@objc public var actionButtonBorderWidth: CGFloat = 1.0
/// The title color to apply to the alternative button (default blue).
@objc public var alternativeButtonTitleColor: UIColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1)
/// The border color to apply to the alternative button.
@objc public var alternativeButtonBorderColor: UIColor? = nil
/// The border width to apply to the alternative button.
@objc public var alternativeButtonBorderWidth: CGFloat = 1.0
/// The tint color to apply to the imageView (if image rendered in template mode, default blue).
@objc public var imageViewTintColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1)
/// The color of title text labels (default light gray).
@objc public var titleTextColor = #colorLiteral(red: 0.568627451, green: 0.5647058824, blue: 0.5725490196, alpha: 1)
/// The color of description text labels (default black).
@objc public var descriptionTextColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
// MARK: - Corner Radius Customization
/// The corner radius of the action button (default 12).
@objc public var actionButtonCornerRadius: CGFloat = 12
/// The corner radius of the alternative button (default 12).
@objc public var alternativeButtonCornerRadius: CGFloat = 12
// MARK: - Font Customization
/// An optional custom font to use for the title label. Set this to nil to use the system font.
@objc public var titleFontDescriptor: UIFontDescriptor?
/// An optional custom font to use for the description label. Set this to nil to use the system font.
@objc public var descriptionFontDescriptor: UIFontDescriptor?
/// An optional custom font to use for the buttons. Set this to nil to use the system font.
@objc public var buttonFontDescriptor: UIFontDescriptor?
/**
* Whether the description text should be displayed with a smaller font.
*
* You should set this to `true` if your text is long (more that two sentences).
*/
@objc public var shouldUseCompactDescriptionText: Bool = false
// MARK: - Font Constants
/// The font size of title elements (default 30).
@objc public var titleFontSize: CGFloat = 30
/// The font size of description labels (default 20).
@objc public var descriptionFontSize: CGFloat = 20
/// The font size of compact description labels (default 15).
@objc public var compactDescriptionFontSize: CGFloat = 15
/// The font size of action buttons (default 17).
@objc public var actionButtonFontSize: CGFloat = 17
/// The font size of alternative buttons (default 15).
@objc public var alternativeButtonFontSize: CGFloat = 15
}
// MARK: - Font Factories
extension BLTNItemAppearance {
/**
* Creates the font for title labels.
*/
@objc public func makeTitleFont() -> UIFont {
if let titleFontDescriptor = self.titleFontDescriptor {
return UIFont(descriptor: titleFontDescriptor, size: titleFontSize)
} else {
return UIFont.systemFont(ofSize: titleFontSize, weight: UIFontWeightMedium)
}
}
/**
* Creates the font for description labels.
*/
@objc public func makeDescriptionFont() -> UIFont {
let size = shouldUseCompactDescriptionText ? compactDescriptionFontSize : descriptionFontSize
if let descriptionFontDescriptor = self.descriptionFontDescriptor {
return UIFont(descriptor: descriptionFontDescriptor, size: size)
} else {
return UIFont.systemFont(ofSize: size)
}
}
/**
* Creates the font for action buttons.
*/
@objc public func makeActionButtonFont() -> UIFont {
if let buttonFontDescriptor = self.buttonFontDescriptor {
return UIFont(descriptor: buttonFontDescriptor, size: actionButtonFontSize)
} else {
return UIFont.systemFont(ofSize: actionButtonFontSize, weight: UIFontWeightSemibold)
}
}
/**
* Creates the font for alternative buttons.
*/
@objc public func makeAlternativeButtonFont() -> UIFont {
if let buttonFontDescriptor = self.buttonFontDescriptor {
return UIFont(descriptor: buttonFontDescriptor, size: alternativeButtonFontSize)
} else {
return UIFont.systemFont(ofSize: alternativeButtonFontSize, weight: UIFontWeightSemibold)
}
}
}
// MARK: - Status Bar
/**
* Styles of status bar to use with bulletin items.
*/
@objc public enum BLTNStatusBarAppearance: Int {
/// The status bar is hidden.
case hidden
/// The color of the status bar is determined automatically. This is the default style.
case automatic
/// Style to use with dark backgrounds.
case lightContent
/// Style to use with light backgrounds.
case darkContent
}
// MARK: - Swift Compatibility
#if swift(>=4.0)
let UIFontWeightMedium = UIFont.Weight.medium
let UIFontWeightSemibold = UIFont.Weight.semibold
#endif
| mit | 5e46c51cfcdb47abf856907d9f6164b2 | 30.902174 | 121 | 0.689438 | 4.791837 | false | false | false | false |
MikeCorpus/Part-Timr_Employer | Part-Timr/EmployerVC.swift | 1 | 4940 | //
// EmployerVC.swift
// Part-Timr for Hirer
//
// Created by Michael V. Corpus on 11/02/2017.
// Copyright © 2017 Michael V. Corpus. All rights reserved.
//
import UIKit
import MapKit
class EmployerVC: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, ParttimrController {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var callParttimrBtn: UIButton!
private var locationManager = CLLocationManager()
private var userLocation: CLLocationCoordinate2D?
private var parttimrLocation: CLLocationCoordinate2D?
private var timer = Timer();
private var canCallParttimr = true
private var hirerCanceledRequest = false
private var appStartedForTheFirstTime = true;
override func viewDidLoad() {
super.viewDidLoad()
initializeLocationManager()
HireHandler.Instance.observeMessagesForHirer()
HireHandler.Instance.delegate = self
}
private func initializeLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locationManager.location?.coordinate {
userLocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
let region = MKCoordinateRegion(center: userLocation!, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView.setRegion(region, animated: true)
mapView.removeAnnotations(mapView.annotations)
if parttimrLocation != nil {
if !canCallParttimr {
let parttimrAnnotation = MKPointAnnotation();
parttimrAnnotation.coordinate = parttimrLocation!;
parttimrAnnotation.title = "Driver Location";
mapView.addAnnotation(parttimrAnnotation);
}
}
let annotation = MKPointAnnotation()
annotation.coordinate = userLocation!
annotation.title = "Hirer's Location"
mapView.addAnnotation(annotation)
}
}
func updateHirerLocation() {
HireHandler.Instance.updateParttimrsLocation(lat: userLocation!.longitude, long: userLocation!.latitude)
}
func canCallParttimr(delegateCalled: Bool) {
if delegateCalled {
callParttimrBtn.setTitle("Cancel", for: UIControlState.normal)
canCallParttimr = false
} else {
callParttimrBtn.setTitle("Hire!", for: UIControlState.normal)
canCallParttimr = true
}
}
func parttimrAcceptedRequest(requestAccepted: Bool, parttimrName: String) {
if !hirerCanceledRequest {
if requestAccepted {
alertTheUser(title: "Part-Timr Accepted", message: "\(parttimrName) Accepted Your Request")
} else {
HireHandler.Instance.cancelParttimr()
alertTheUser(title: "Part-Timr Canceled", message: "\(parttimrName ) Canceled Your Request")
}
}
hirerCanceledRequest = false;
}
func updateParttimrsLocation(lat: Double, long: Double) {
parttimrLocation = CLLocationCoordinate2D(latitude: lat, longitude: long)
}
@IBAction func Hire(_ sender: AnyObject ) {
if userLocation != nil {
if canCallParttimr {
HireHandler.Instance.requestParttimr(latitude: Double (userLocation!.latitude), longitude: Double (userLocation!.longitude))
timer = Timer.scheduledTimer(timeInterval: TimeInterval(10), target: self, selector: #selector(EmployerVC.updateParttimrsLocation), userInfo: nil, repeats: true);
} else {
hirerCanceledRequest = true
HireHandler.Instance.cancelParttimr()
timer.invalidate()
}
}
}
@IBAction func logOut(_ sender: Any) {
if AuthProvider.Instance.logOut() {
dismiss(animated: true, completion: nil)
print("LOGOUT SUCCESSFUL")
} else {
self.alertTheUser(title: "Problem logging out", message: "Please try again later.")
}
}
func alertTheUser(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction (UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated:true, completion: nil)
}
}
| mit | 3605b7e12f4a60df4d9aed213c837b94 | 33.062069 | 182 | 0.619559 | 5.481687 | false | false | false | false |
ypopovych/Future | Sources/Future/Future.swift | 1 | 5741 | //===--- Future.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Result
import Boilerplate
import ExecutionContext
public protocol FutureProtocol : ExecutionContextTenantProtocol {
associatedtype Value
init(value:Value)
init(error:Error)
init<E : Error>(result:Result<Value, E>)
@discardableResult
func onComplete<E: Error>(_ callback: @escaping (Result<Value, E>) -> Void) -> Self
var isCompleted:Bool {get}
}
public class Future<V> : FutureProtocol {
public typealias Value = V
private var _chain:TaskChain?
private var _resolver:ExecutionContextProtocol?
internal var result:Result<Value, AnyError>? = nil {
didSet {
if nil != result {
self.isCompleted = true
/// some performance optimization is done here, so don't touch the ifs. ExecutionContext.current is not the fastest func
let context = selectContext()
_chain!.append { next in
return { context in
admin.execute {
self._resolver = context
self._chain = nil
context.execute {
next.content?(context)
}
}
}
}
_chain!.perform(in: context)
}
}
}
public let context: ExecutionContextProtocol
//make it atomic later
private (set) public var isCompleted:Bool = false
internal init(context:ExecutionContextProtocol) {
self._chain = TaskChain()
self.context = context
}
public required convenience init(value:Value) {
self.init(result: Result<Value, AnyError>(value: value))
}
public required convenience init(error:Error) {
self.init(result: Result(error: AnyError(error)))
}
public required convenience init<E : Error>(result:Result<Value, E>) {
self.init(context: immediate)
self.result = result.asAnyError()
self.isCompleted = true
self._resolver = selectContext()
self._chain = nil
}
private func selectContext() -> ExecutionContextProtocol {
return self.context.isEqual(to: immediate) ? ExecutionContext.current : self.context
}
@discardableResult
public func onComplete<E: Error>(_ callback: @escaping (Result<Value, E>) -> Void) -> Self {
return self.onCompleteInternal(callback: callback)
}
//to avoid endless recursion
internal func onCompleteInternal<E: Error>(callback: @escaping (Result<Value, E>) -> Void) -> Self {
admin.execute {
if let resolver = self._resolver {
let mapped:Result<Value, E>? = self.result!.tryAsError()
if let result = mapped {
resolver.execute {
callback(result)
}
}
} else {
self._chain!.append { next in
return { context in
let mapped:Result<Value, E>? = self.result!.tryAsError()
if let result = mapped {
callback(result)
next.content?(context)
} else {
next.content?(context)
}
}
}
}
}
return self
}
}
extension Future : MovableExecutionContextTenantProtocol {
public typealias SettledTenant = Future<Value>
public func settle(in context: ExecutionContextProtocol) -> SettledTenant {
let future = MutableFuture<Value>(context: context)
future.completeWith(future: self)
return future
}
}
public func future<T>(context:ExecutionContextProtocol = contextSelector(), _ task:@escaping () throws ->T) -> Future<T> {
let future = MutableFuture<T>(context: context)
context.execute {
do {
let value = try task()
try! future.success(value: value)
} catch let e {
try! future.fail(error: e)
}
}
return future
}
public func future<T, E : Error>(context:ExecutionContextProtocol = contextSelector(), _ task:@escaping () -> Result<T, E>) -> Future<T> {
let future = MutableFuture<T>(context: context)
context.execute {
let result = task()
try! future.complete(result: result)
}
return future
}
public func future<T, F : FutureProtocol>(context:ExecutionContextProtocol = contextSelector(), _ task:@escaping () -> F) -> Future<T> where F.Value == T {
let future = MutableFuture<T>(context: context)
context.execute {
future.completeWith(future: task())
}
return future
}
| apache-2.0 | 19f859af9532412f90322b1bad1322ca | 31.619318 | 155 | 0.551994 | 5.116756 | false | false | false | false |
apple/swift | test/decl/protocol/special/coding/immutable_property.swift | 14 | 2071 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
struct Foo : Codable {
let x1: String = ""
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'x1' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{3-6=var}}
public let x2: String = ""
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'x2' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{10-13=var}}
internal let x3: String = ""
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'x3' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{12-15=var}}
fileprivate let x4: String = ""
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'x4' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{15-18=var}}
private let x5: String = ""
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'x5' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{11-14=var}}
}
| apache-2.0 | 291c559b4d9baab9ad78657927d16226 | 72.964286 | 152 | 0.738291 | 4.397028 | false | false | false | false |
1170197998/Swift-DEMO | FoldTableView/FoldTableView/Models/SectionModel.swift | 1 | 1001 | //
// SectionModel.swift
// FoldTableView
//
// Created by ShaoFeng on 16/7/29.
// Copyright © 2016年 Cocav. All rights reserved.
//
import UIKit
class SectionModel: NSObject {
var sectionTitle: String? = nil
var isExpanded: Bool? = false
var cellModels: [CellModel] = []
class func loadData(finish: ([SectionModel]) -> ()) {
var array = [SectionModel]()
for i in 0..<20 {
let sectionModel = SectionModel()
sectionModel.isExpanded = false
sectionModel.sectionTitle = "第" + String(i + 1) + "组"
var cellModels = [CellModel]()
for j in 0..<10 {
let cellModel = CellModel()
cellModel.cellTitle = "第" + String(i + 1) + "组,第" + String(j + 1) + "行"
cellModels.append(cellModel)
}
sectionModel.cellModels = cellModels
array.append(sectionModel)
}
finish(array)
}
}
| apache-2.0 | 36f2d27f1c13eadf5e0d14b87823d55b | 26.388889 | 87 | 0.534483 | 4.286957 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Maps/Map reference scale/MapReferenceScaleViewController.swift | 1 | 2708 | //
// Copyright © 2019 Esri.
//
// 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
import ArcGIS
/// A view controller that manages the interface of the Map Reference Scale
/// sample.
class MapReferenceScaleViewController: UIViewController {
/// The map view managed by the view controller.
@IBOutlet weak var mapView: AGSMapView! {
didSet {
mapView.map = makeMap()
}
}
/// Creates a map.
///
/// - Returns: A new `AGSMap` object.
func makeMap() -> AGSMap {
let portal = AGSPortal(url: URL(string: "https://runtime.maps.arcgis.com")!, loginRequired: false)
let portalItem = AGSPortalItem(portal: portal, itemID: "3953413f3bd34e53a42bf70f2937a408")
return AGSMap(item: portalItem)
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [
"MapReferenceScaleViewController",
"MapReferenceScaleSettingsViewController",
"MapReferenceScaleLayerSelectionViewController"
]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let navigationController = segue.destination as? UINavigationController,
let settingsViewController = navigationController.topViewController as? MapReferenceScaleSettingsViewController {
settingsViewController.map = mapView.map
settingsViewController.mapScale = mapView.mapScale
settingsViewController.delegate = self
}
}
}
extension MapReferenceScaleViewController: MapReferenceScaleSettingsViewControllerDelegate {
func mapReferenceScaleSettingsViewControllerDidChangeMapScale(_ controller: MapReferenceScaleSettingsViewController) {
mapView.setViewpointScale(controller.mapScale)
}
func mapReferenceScaleSettingsViewControllerDidFinish(_ controller: MapReferenceScaleSettingsViewController) {
dismiss(animated: true)
}
}
| apache-2.0 | 4dc0496cca7fa975304d5b41a0b0ed66 | 37.126761 | 125 | 0.705948 | 5.126894 | false | false | false | false |
TeamProxima/predictive-fault-tracker | mobile/SieHack/SieHack/WeeklyTemperatureViewController.swift | 1 | 4810 | //
// WeeklyTemperatureViewController.swift
// Siemens Hackathon2
//
// Created by Emre Yigit Alparslan on 10/23/16.
// Copyright © 2016 Proxima. All rights reserved.
//
import UIKit
import Charts
class WeeklyTemperatureViewController: UIViewController {
@IBOutlet weak var tempLineChart: LineChartView!
@IBOutlet weak var humiLineChart: LineChartView!
@IBOutlet weak var activityIndi: UIActivityIndicatorView!
var rasIP = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tempLineChart.noDataText = ""
humiLineChart.noDataText = ""
if let ri = UserDefaults.standard.value(forKey: "rasPi IP") as? String{
rasIP = ri
}
getDataFromDatabase()
}
func setLineChart(element: String, values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<values.count {
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
if element == "Humidity"{
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Humidity")
lineChartDataSet.circleRadius = 0.0
lineChartDataSet.setColor(NSUIColor.green)
let lineChartData = LineChartData(dataSet: lineChartDataSet)
lineChartData.setDrawValues(false)
humiLineChart.data = lineChartData
humiLineChart.setScaleEnabled(true)
}else if element == "Temperature"{
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Temperature")
lineChartDataSet.circleRadius = 0.0
lineChartDataSet.setColor(NSUIColor.red)
let lineChartData = LineChartData(dataSet: lineChartDataSet)
lineChartData.setDrawValues(false)
tempLineChart.data = lineChartData
tempLineChart.setScaleEnabled(true)
}
}
func getDataFromDatabase(){
tempLineChart.isUserInteractionEnabled = false
humiLineChart.isUserInteractionEnabled = false
activityIndi.isHidden = false
activityIndi.startAnimating()
let url = URL(string: "http://\(rasIP)/weekly")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error == nil{
if let urlContent = data{
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
var datasetTemp = [Double]()
var datasetHumi = [Double]()
if let elements = (jsonResult["scores"])! as? NSArray{
var i = 0
while i < elements.count{
if let element = elements[i] as? AnyObject{
datasetTemp.append(element["temperature"] as! Double)
datasetHumi.append(element["humidity"] as! Double)
i+=1
}
}
}
DispatchQueue.main.sync(execute: {
self.setLineChart(element: "Temperature", values: datasetTemp)
self.setLineChart(element: "Humidity", values: datasetHumi)
self.tempLineChart.isUserInteractionEnabled = true
self.humiLineChart.isUserInteractionEnabled = true
self.activityIndi.isHidden = true
self.activityIndi.stopAnimating()
})
}catch{
print("Json Process Failling")
}
}
}else{
print(error)
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f0588db1323477651f70507c3f1897d3 | 35.709924 | 165 | 0.539405 | 5.937037 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/plus-one.swift | 2 | 1558 | /**
* https://leetcode.com/problems/plus-one/
*
*
*/
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
let n = digits.count
var flag = 1
var resDigits = digits
for i in 0..<resDigits.count {
resDigits[n-i-1] += flag
flag = 0
if resDigits[n-i-1] >= 10 {
flag = 1
resDigits[n-i-1] %= 10
}
}
if flag > 0 {
resDigits = [1] + resDigits
}
return resDigits
}
}
/**
* https://leetcode.com/problems/plus-one/
*
*
*/
// Date: Sun May 3 09:58:42 PDT 2020
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var flag = 1
var index = digits.count - 1
var ret: [Int] = []
while flag > 0 || index >= 0 {
if index >= 0 {
flag += digits[index]
}
ret.insert(flag % 10, at: 0)
flag = flag / 10
index -= 1
}
return ret
}
}
/**
* https://leetcode.com/problems/plus-one/
*
*
*/
// Date: Mon Jul 6 08:34:17 PDT 2020
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var offset = 1
var result = digits
for index in stride(from: digits.count - 1, through: 0, by: -1) {
result[index] += offset
offset = result[index] / 10
result[index] %= 10
}
if offset > 0 {
result.insert(offset, at: 0)
}
return result
}
}
| mit | 8b71bf8ca15b5bd8735e2009194be60e | 21.57971 | 73 | 0.440308 | 3.745192 | false | false | false | false |
luoziyong/firefox-ios | Client/Helpers/FxALoginHelper.swift | 1 | 12645 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Account
import Deferred
import Foundation
import Shared
import SwiftyJSON
import Sync
import UserNotifications
import XCGLogger
private let applicationDidRequestUserNotificationPermissionPrefKey = "applicationDidRequestUserNotificationPermissionPrefKey"
private let log = Logger.browserLogger
private let verificationPollingInterval = DispatchTimeInterval.seconds(3)
private let verificationMaxRetries = 100 // Poll every 3 seconds for 5 minutes.
protocol FxAPushLoginDelegate : class {
func accountLoginDidFail()
func accountLoginDidSucceed(withFlags flags: FxALoginFlags)
}
/// Small struct to keep together the immediately actionable flags that the UI is likely to immediately
/// following a successful login. This is not supposed to be a long lived object.
struct FxALoginFlags {
let pushEnabled: Bool
let verified: Bool
}
/// This class manages the from successful login for FxAccounts to
/// asking the user for notification permissions, registering for
/// remote push notifications (APNS), then creating an account and
/// storing it in the profile.
class FxALoginHelper {
static var sharedInstance: FxALoginHelper = {
return FxALoginHelper()
}()
weak var delegate: FxAPushLoginDelegate?
fileprivate weak var profile: Profile?
fileprivate var account: FirefoxAccount!
fileprivate var accountVerified: Bool!
// This should be called when the application has started.
// This configures the helper for logging into Firefox Accounts, and
// if already logged in, checking if anything needs to be done in response
// to changing of user settings and push notifications.
func application(_ application: UIApplication, didLoadProfile profile: Profile) {
self.profile = profile
guard let account = profile.getAccount() else {
// There's no account, no further action.
return loginDidFail()
}
// accountVerified is needed by delegates.
accountVerified = account.actionNeeded != .needsVerification
guard AppConstants.MOZ_FXA_PUSH else {
return loginDidSucceed()
}
if let _ = account.pushRegistration {
// We have an account, and it's already registered for push notifications.
return loginDidSucceed()
}
// Now: we have an account that does not have push notifications set up.
// however, we need to deal with cases of asking for permissions too frequently.
let asked = profile.prefs.boolForKey(applicationDidRequestUserNotificationPermissionPrefKey) ?? true
let permitted = application.currentUserNotificationSettings!.types != .none
// If we've never asked(*), then we should probably ask.
// If we've asked already, then we should not ask again.
// TODO: add UI to tell the user to go flip the Setting app.
// (*) if we asked in a prior release, and the user was ok with it, then there is no harm asking again.
// If the user denied permission, or flipped permissions in the Settings app, then
// we'll bug them once, but this is probably unavoidable.
if asked && !permitted {
return loginDidSucceed()
}
// By the time we reach here, we haven't registered for APNS
// Either we've never asked the user, or the user declined, then re-enabled
// the notification in the Settings app.
self.account = account
requestUserNotifications(application)
}
// This is called when the user logs into a new FxA account.
// It manages the asking for user permission for notification and registration
// for APNS and WebPush notifications.
func application(_ application: UIApplication, didReceiveAccountJSON data: JSON) {
if data["keyFetchToken"].stringValue() == nil || data["unwrapBKey"].stringValue() == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
log.error("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return self.loginDidFail()
}
assert(profile != nil, "Profile should still exist and be loaded into this FxAPushLoginStateMachine")
guard let profile = profile,
let account = FirefoxAccount.from(profile.accountConfiguration, andJSON: data) else {
return self.loginDidFail()
}
accountVerified = data["verified"].bool ?? false
self.account = account
requestUserNotifications(application)
}
fileprivate func requestUserNotifications(_ application: UIApplication) {
DispatchQueue.main.async {
self.requestUserNotificationsMainThreadOnly(application)
}
}
fileprivate func requestUserNotificationsMainThreadOnly(_ application: UIApplication) {
assert(Thread.isMainThread, "requestAuthorization should be run on the main thread")
if #available(iOS 10, *) {
let center = UNUserNotificationCenter.current()
return center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else {
return self.application(application, canDisplayUserNotifications: false)
}
self.application(application, canDisplayUserNotifications: granted)
}
}
// This is for iOS 9 and below.
// We'll still be using local notifications, i.e. the old behavior,
// so we need to keep doing it like this.
let viewAction = UIMutableUserNotificationAction()
viewAction.identifier = SentTabAction.view.rawValue
viewAction.title = Strings.SentTabViewActionTitle
viewAction.activationMode = .foreground
viewAction.isDestructive = false
viewAction.isAuthenticationRequired = false
let bookmarkAction = UIMutableUserNotificationAction()
bookmarkAction.identifier = SentTabAction.bookmark.rawValue
bookmarkAction.title = Strings.SentTabBookmarkActionTitle
bookmarkAction.activationMode = .foreground
bookmarkAction.isDestructive = false
bookmarkAction.isAuthenticationRequired = false
let readingListAction = UIMutableUserNotificationAction()
readingListAction.identifier = SentTabAction.readingList.rawValue
readingListAction.title = Strings.SentTabAddToReadingListActionTitle
readingListAction.activationMode = .foreground
readingListAction.isDestructive = false
readingListAction.isAuthenticationRequired = false
let sentTabsCategory = UIMutableUserNotificationCategory()
sentTabsCategory.identifier = TabSendCategory
sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], for: .default)
sentTabsCategory.setActions([bookmarkAction, viewAction], for: .minimal)
let settings = UIUserNotificationSettings(types: .alert, categories: [sentTabsCategory])
application.registerUserNotificationSettings(settings)
}
// This is necessarily called from the AppDelegate.
// Once we have permission from the user to display notifications, we should
// try and register for APNS. If not, then start syncing.
func application(_ application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
let types = notificationSettings.types
let allowed = types != .none && types.rawValue != 0
self.application(application, canDisplayUserNotifications: allowed)
}
func application(_ application: UIApplication, canDisplayUserNotifications allowed: Bool) {
guard allowed else {
return readyForSyncing()
}
// Record that we have asked the user, and they have given an answer.
profile?.prefs.setBool(true, forKey: applicationDidRequestUserNotificationPermissionPrefKey)
guard #available(iOS 10, *) else {
return readyForSyncing()
}
if AppConstants.MOZ_FXA_PUSH {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
} else {
readyForSyncing()
}
}
func getPushConfiguration() -> PushConfiguration? {
let label = PushConfigurationLabel(rawValue: AppConstants.scheme)
return label?.toConfiguration()
}
func apnsRegisterDidSucceed(_ deviceToken: Data) {
let apnsToken = deviceToken.hexEncodedString
guard let pushConfiguration = getPushConfiguration() ?? self.profile?.accountConfiguration.pushConfiguration,
let accountConfiguration = profile?.accountConfiguration else {
log.error("Push server endpoint could not be found")
return pushRegistrationDidFail()
}
// Experimental mode needs: a) the scheme to be Fennec, and b) the accountConfiguration to be flipped in debug mode.
let experimentalMode = (pushConfiguration.label == .fennec && accountConfiguration.label == .latestDev)
let client = PushClient(endpointURL: pushConfiguration.endpointURL, experimentalMode: experimentalMode)
client.register(apnsToken).upon { res in
guard let pushRegistration = res.successValue else {
return self.pushRegistrationDidFail()
}
return self.pushRegistrationDidSucceed(apnsToken: apnsToken, pushRegistration: pushRegistration)
}
}
func apnsRegisterDidFail() {
readyForSyncing()
}
fileprivate func pushRegistrationDidSucceed(apnsToken: String, pushRegistration: PushRegistration) {
account.pushRegistration = pushRegistration
readyForSyncing()
}
fileprivate func pushRegistrationDidFail() {
readyForSyncing()
}
fileprivate func readyForSyncing() {
guard let profile = self.profile, let account = self.account else {
return loginDidSucceed()
}
profile.setAccount(account)
awaitVerification()
loginDidSucceed()
}
fileprivate func awaitVerification(_ attemptsLeft: Int = verificationMaxRetries) {
guard let account = account,
let profile = profile else {
return
}
if attemptsLeft == 0 {
return
}
// The only way we can tell if the account has been verified is to
// start a sync. If it works, then yay,
account.advance().upon { state in
if attemptsLeft == verificationMaxRetries {
// We need to associate the fxaDeviceId with sync;
// We can do this anything after the first time we account.advance()
// but before the first time we sync.
let scratchpadPrefs = profile.prefs.branch("sync.scratchpad")
if let deviceRegistration = account.deviceRegistration {
scratchpadPrefs.setString(deviceRegistration.toJSON().stringValue()!, forKey: PrefDeviceRegistration)
}
}
guard state.actionNeeded == .needsVerification else {
// Verification has occurred remotely, and we can proceed.
// The state machine will have told any listening UIs that
// we're done.
return self.performVerifiedSync(profile, account: account)
}
if account.pushRegistration != nil {
// Verification hasn't occurred yet, but we've registered for push
// so we can wait for a push notification in FxAPushMessageHandler.
return
}
let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass)
queue.asyncAfter(deadline: DispatchTime.now() + verificationPollingInterval) {
self.awaitVerification(attemptsLeft - 1)
}
}
}
fileprivate func loginDidSucceed() {
let flags = FxALoginFlags(pushEnabled: account?.pushRegistration != nil, verified: accountVerified)
delegate?.accountLoginDidSucceed(withFlags: flags)
}
fileprivate func loginDidFail() {
delegate?.accountLoginDidFail()
}
func performVerifiedSync(_ profile: Profile, account: FirefoxAccount) {
profile.syncManager.syncEverything(why: .didLogin)
}
}
| mpl-2.0 | 1ba962d54b3ae6c437e3e5613e7dc761 | 40.323529 | 138 | 0.678055 | 5.640054 | false | true | false | false |
szpnygo/firefox-ios | Sync/KeyBundle.swift | 18 | 10190 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import FxA
import Account
private let KeyLength = 32
public class KeyBundle: Equatable {
let encKey: NSData
let hmacKey: NSData
public class func fromKB(kB: NSData) -> KeyBundle {
let salt = NSData()
let contextInfo = FxAClient10.KW("oldsync")
let len: UInt = 64 // KeyLength + KeyLength, without type nonsense.
let derived = kB.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: len)
return KeyBundle(encKey: derived.subdataWithRange(NSRange(location: 0, length: KeyLength)),
hmacKey: derived.subdataWithRange(NSRange(location: KeyLength, length: KeyLength)))
}
public class func random() -> KeyBundle {
// Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which
// on iOS is populated by the OS from kernel-level sources of entropy.
// That should mean that we don't need to seed or initialize anything before calling
// this. That is probably not true on (some versions of) OS X.
return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32))
}
public class var invalid: KeyBundle {
return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")
}
public init(encKeyB64: String, hmacKeyB64: String) {
self.encKey = Bytes.decodeBase64(encKeyB64)
self.hmacKey = Bytes.decodeBase64(hmacKeyB64)
}
public init(encKey: NSData, hmacKey: NSData) {
self.encKey = encKey
self.hmacKey = hmacKey
}
private func _hmac(ciphertext: NSData) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) {
let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CCHmac(hmacAlgorithm, hmacKey.bytes, hmacKey.length, ciphertext.bytes, ciphertext.length, result)
return (result, digestLen)
}
public func hmac(ciphertext: NSData) -> NSData {
let (result, digestLen) = _hmac(ciphertext)
var data = NSMutableData(bytes: result, length: digestLen)
result.destroy()
return data
}
/**
* Returns a hex string for the HMAC.
*/
public func hmacString(ciphertext: NSData) -> String {
let (result, digestLen) = _hmac(ciphertext)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(hash)
}
public func encrypt(cleartext: NSData, iv: NSData?=nil) -> (ciphertext: NSData, iv: NSData)? {
let iv = iv ?? Bytes.generateRandomBytes(16)
let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt))
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = NSData(bytes: b, length: Int(copied))
b.destroy()
return (d, iv)
}
b.destroy()
return nil
}
// You *must* verify HMAC before calling this.
public func decrypt(ciphertext: NSData, iv: NSData) -> String? {
let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt))
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = NSData(bytesNoCopy: b, length: Int(copied))
let s = NSString(data: d, encoding: NSUTF8StringEncoding)
b.destroy()
return s as String?
}
b.destroy()
return nil
}
private func crypt(input: NSData, iv: NSData, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutablePointer<Void>, count: Int) {
let resultSize = input.length + kCCBlockSizeAES128
let result = UnsafeMutablePointer<Void>.alloc(resultSize)
var copied: Int = 0
let success: CCCryptorStatus =
CCCrypt(op,
CCHmacAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
encKey.bytes,
kCCKeySizeAES256,
iv.bytes,
input.bytes,
input.length,
result,
resultSize,
&copied
);
return (success, result, copied)
}
public func verify(#hmac: NSData, ciphertextB64: NSData) -> Bool {
let expectedHMAC = hmac
let computedHMAC = self.hmac(ciphertextB64)
return expectedHMAC.isEqualToData(computedHMAC)
}
/**
* Swift can't do functional factories. I would like to have one of the following
* approaches be viable:
*
* 1. Derive the constructor from the consumer of the factory.
* 2. Accept a type as input.
*
* Neither of these are viable, so we instead pass an explicit constructor closure.
*
* Most of these approaches produce either odd compiler errors, or -- worse --
* compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159).
*
* For this reason, be careful trying to simplify or improve this code.
*/
public func factory<T: CleartextPayloadJSON>(f: JSON -> T) -> String -> T? {
return { (payload: String) -> T? in
let potential = EncryptedJSON(json: payload, keyBundle: self)
if !(potential.isValid()) {
return nil
}
let cleartext = potential.cleartext
if (cleartext == nil) {
return nil
}
return f(cleartext!)
}
}
// TODO: how much do we want to move this into EncryptedJSON?
public func serializer<T: CleartextPayloadJSON>(f: T -> JSON) -> Record<T> -> JSON? {
return { (record: Record<T>) -> JSON? in
let json = f(record.payload)
if let data = json.toString(pretty: false).utf8EncodedData,
// We pass a null IV, which means "generate me a new one".
// We then include the generated IV in the resulting record.
let (ciphertext, iv) = self.encrypt(data, iv: nil) {
// So we have the encrypted payload. Now let's build the envelope around it.
let ciphertext = ciphertext.base64EncodedString
// The HMAC is computed over the base64 string. As bytes. Yes, I know.
if let encodedCiphertextBytes = ciphertext.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false) {
let hmac = self.hmacString(encodedCiphertextBytes)
let iv = iv.base64EncodedString
// The payload is stringified JSON. Yes, I know.
let payload = JSON([
"ciphertext": ciphertext,
"IV": iv,
"hmac": hmac,
]).toString(pretty: false)
return JSON([
"id": record.id,
"sortindex": record.sortindex,
"ttl": record.ttl ?? JSON.null,
"payload": payload,
])
}
}
return nil
}
}
public func asPair() -> [String] {
return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString]
}
}
public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool {
return lhs.encKey.isEqualToData(rhs.encKey) &&
lhs.hmacKey.isEqualToData(rhs.hmacKey)
}
public class Keys: Equatable {
let valid: Bool
let defaultBundle: KeyBundle
var collectionKeys: [String: KeyBundle] = [String: KeyBundle]()
public init(defaultBundle: KeyBundle) {
self.defaultBundle = defaultBundle
self.valid = true
}
public init(payload: KeysPayload?) {
if let payload = payload {
if payload.isValid() {
if let keys = payload.defaultKeys {
self.defaultBundle = keys
self.valid = true
return
}
self.collectionKeys = payload.collectionKeys
}
}
self.defaultBundle = KeyBundle.invalid
self.valid = false
}
public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) {
let f: (JSON) -> KeysPayload = { KeysPayload($0) }
let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f))
self.init(payload: keysRecord?.payload)
}
public func forCollection(collection: String) -> KeyBundle {
if let bundle = collectionKeys[collection] {
return bundle
}
return defaultBundle
}
public func encrypter<T: CleartextPayloadJSON>(collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> {
return RecordEncrypter(bundle: forCollection(collection), encoder: encoder)
}
public func asPayload() -> KeysPayload {
let json: JSON = JSON([
"collection": "crypto",
"default": self.defaultBundle.asPair(),
"collections": mapValues(self.collectionKeys, { $0.asPair() })
])
return KeysPayload(json)
}
}
/**
* Yup, these are basically typed tuples.
*/
public struct RecordEncoder<T: CleartextPayloadJSON> {
let decode: JSON -> T
let encode: T -> JSON
}
public struct RecordEncrypter<T: CleartextPayloadJSON> {
let serializer: Record<T> -> JSON?
let factory: String -> T?
init(bundle: KeyBundle, encoder: RecordEncoder<T>) {
self.serializer = bundle.serializer(encoder.encode)
self.factory = bundle.factory(encoder.decode)
}
}
public func ==(lhs: Keys, rhs: Keys) -> Bool {
return lhs.valid == rhs.valid &&
lhs.defaultBundle == rhs.defaultBundle &&
lhs.collectionKeys == rhs.collectionKeys
}
| mpl-2.0 | 9e8972b7bfa8b7773de22a5ed2022e39 | 34.629371 | 145 | 0.597743 | 4.711049 | false | false | false | false |
BaiduCloudTeam/PaperInSwift | PaperInSwift/CHTransitionViewController.swift | 1 | 6861 | //
// CHTransitionViewController.swift
// PaperInSwift
//
// Created by HX_Wang on 15/10/10.
// Copyright © 2015年 Team_ChineseHamburger. All rights reserved.
//
import UIKit
public protocol CHControllerTransitionDelegate : class {
func interactionBeganAtPoint(origin : CGPoint);
}
public class CHTranstionController: NSObject, UIViewControllerAnimatedTransitioning,UIViewControllerInteractiveTransitioning, UIGestureRecognizerDelegate {
// MARK: - Public Properties
public var delegate : CHControllerTransitionDelegate?
public var hasActiveInteraction : Bool = false
public var navigationOperation : UINavigationControllerOperation?
public var collectionView : UICollectionView!
// MARK: - Private Properties
private var transitionLayout : CHTransitionLayout?
private weak var context : UIViewControllerContextTransitioning?
private var initialPinchDistance : CGFloat?
private var initialPinchPoint : CGPoint?
private var initialScale : CGFloat?
// MARK: - Initializer
public init(collectionView : UICollectionView) {
super.init()
let pinchGesture = UIPinchGestureRecognizer(target: self, action: Selector("handlePinch:"))
collectionView.addGestureRecognizer(pinchGesture)
}
// MARK: - UIViewControllerAnimatedTransitioning Delegate Method
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return NSTimeInterval(1)
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
}
// MARK: - UIViewControllerInteractiveTransitioning Delegate Method
public func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
context = transitionContext;
let fromCollectionViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? UICollectionViewController
let toCollectionViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as? UICollectionViewController
let containerView = transitionContext.containerView()
containerView?.addSubview((toCollectionViewController?.view)!)
fromCollectionViewController?.collectionView?.startInteractiveTransitionToCollectionViewLayout((toCollectionViewController?.collectionViewLayout)!, completion: {didFinish,didComplete in
self.context?.completeTransition(didComplete)
self.transitionLayout = nil
self.context = nil
self.hasActiveInteraction = false
})
}
func updateWithProgress(progress:CGFloat, andOffset offset:UIOffset) {
if let _ = self.context {
if (((progress != self.transitionLayout!.transitionProgress) || !UIOffsetEqualToOffset(offset, self.transitionLayout!.offset!))) {
self.transitionLayout?.offset = offset
self.transitionLayout?.transitionProgress = progress
self.transitionLayout?.invalidateLayout()
self.context?.updateInteractiveTransition(progress)
}
}
}
func updateWithProgress(progress:CGFloat) {
if let _ = self.context {
if(((progress != self.transitionLayout!.transitionProgress))) {
self.transitionLayout?.transitionProgress = progress
self.transitionLayout?.invalidateLayout()
self.context?.updateInteractiveTransition(progress)
}
}
}
func endInteractionWithSuccess(success:Bool) {
guard let _ = self.context else {
self.hasActiveInteraction = false;
return
}
if ((self.transitionLayout!.transitionProgress > 0.1) && success) {
self.collectionView.finishInteractiveTransition()
self.context?.finishInteractiveTransition()
} else {
self.collectionView.cancelInteractiveTransition()
self.context?.cancelInteractiveTransition()
}
}
// MARK: - CHControllerTransitionDelegate Method
func interactionBeganAtPoint(origin : CGPoint) {
}
func handlePinch(sender : UIPinchGestureRecognizer) {
if (sender.state == UIGestureRecognizerState.Ended) {
self.endInteractionWithSuccess(true)
} else if (sender.state == UIGestureRecognizerState.Cancelled) {
self.endInteractionWithSuccess(false)
} else if (sender.numberOfTouches() == 2) {
var point:CGPoint = CGPointZero
var point1:CGPoint = CGPointZero
var point2:CGPoint = CGPointZero
var distance:CGFloat = 0
point1 = sender.locationOfTouch(0, inView: sender
.view)
point2 = sender.locationOfTouch(1, inView: sender
.view)
distance = sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y))
point = sender.locationInView(sender.view)
if(sender.state == UIGestureRecognizerState.Began) {
if(!self.hasActiveInteraction) {
self.initialPinchDistance = distance
self.initialPinchPoint = point
self.hasActiveInteraction = true
self.delegate?.interactionBeganAtPoint(point)
}
}
if(self.hasActiveInteraction) {
if(sender.state == UIGestureRecognizerState.Changed) {
let delta :CGFloat = distance - self.initialPinchDistance!
let offsetX :CGFloat = point.x - (self.initialPinchPoint?.x)!
let offsetY:CGFloat = (point.y - self.initialPinchPoint!.y) + delta/CGFloat(M_PI);
let offsetToUse:UIOffset = UIOffsetMake(offsetX, offsetY)
var distanceDelta:CGFloat = distance - self.initialPinchDistance!
if (self.navigationOperation == UINavigationControllerOperation.Pop) {
distanceDelta = -distanceDelta
}
let progress:CGFloat = max(min(((distanceDelta + sender.velocity * CGFloat(M_PI)) / 250), 1.0), 0.0)
self.updateWithProgress(progress, andOffset: offsetToUse)
}
}
}
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| mit | c84bd72c7031ec94860af0ed6921bc40 | 42.681529 | 193 | 0.656168 | 6.058304 | false | false | false | false |
lvogelzang/Blocky | Blocky/Levels/Level48.swift | 1 | 877 | //
// Level48.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level48: Level {
let levelNumber = 48
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| mit | d591a630a76e360ddcfa9c2113b35e10 | 24.794118 | 89 | 0.573546 | 2.649547 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClientTests/FW/Logic/Request/TrackAutocompleteSelectRequestBuilderTests.swift | 1 | 3971 | //
// TrackAutocompleteSelectRequestBuilderTests.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import XCTest
@testable import ConstructorAutocomplete
class TrackAutocompleteSelectRequestBuilderTests: XCTestCase {
fileprivate let testACKey = "asdf1213123"
fileprivate let searchTerm = "😃test ink[]"
fileprivate let originalQuery = "testing#@#??!!asd"
fileprivate let sectionName = "product"
fileprivate let group = CIOGroup(displayName: "groupName1", groupID: "groupID2", path: "path/to/group")
fileprivate var encodedSearchTerm: String = ""
fileprivate var encodedOriginalQuery: String = ""
fileprivate var encodedSectionName: String = ""
fileprivate var builder: RequestBuilder!
override func setUp() {
super.setUp()
self.encodedSearchTerm = searchTerm.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
self.encodedOriginalQuery = originalQuery.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.encodedSectionName = sectionName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.builder = RequestBuilder(apiKey: testACKey, baseURL: Constants.Query.baseURLString)
}
func testTrackAutocompleteSelectBuilder() {
let tracker = CIOTrackAutocompleteSelectData(searchTerm: searchTerm, originalQuery: originalQuery, sectionName: sectionName)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertTrue(url.hasPrefix("https://ac.cnstrc.com/autocomplete/\(encodedSearchTerm)/select?"))
XCTAssertTrue(url.contains("original_query=\(encodedOriginalQuery)"), "URL should contain the original query")
XCTAssertTrue(url.contains("section=\(encodedSectionName)"), "URL should contain the autocomplete section")
XCTAssertTrue(url.contains("c=\(Constants.versionString())"), "URL should contain the version string")
XCTAssertTrue(url.contains("key=\(testACKey)"), "URL should contain the api key")
}
func testTrackAutocompleteSelectBuilder_WithCustomBaseURL() {
let customBaseURL = "https://custom-base-url.com"
self.builder = RequestBuilder(apiKey: testACKey, baseURL: customBaseURL)
let tracker = CIOTrackAutocompleteSelectData(searchTerm: searchTerm, originalQuery: originalQuery, sectionName: sectionName)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertTrue(url.hasPrefix(customBaseURL))
}
func testTrackAutocompleteSelectBuilder_WithGroup() {
let tracker = CIOTrackAutocompleteSelectData(searchTerm: searchTerm, originalQuery: originalQuery, sectionName: sectionName, group: group)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertTrue(url.contains("group%5Bgroup_name%5D=groupName1"), "URL should contain a URL query item with group name if item in group")
XCTAssertTrue(url.contains("group%5Bgroup_id%5D=groupID2"), "URL should contain a URL query item with group id if item in group")
}
func testTrackAutocompleteSelectBuilder_WithoutGroup() {
let tracker = CIOTrackAutocompleteSelectData(searchTerm: searchTerm, originalQuery: originalQuery, sectionName: sectionName, group: nil)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertFalse(url.contains("group%5Bgroup_name%5D"), "URL shouldn't contain a URL query item with group id if item outside a group")
XCTAssertFalse(url.contains("group%5Bgroup_id%5D"), "URL shouldn't contain a URL query item with group name if item outside a group")
}
}
| mit | fdf4a43c95c428c00d065aba10f15c02 | 50.519481 | 146 | 0.734308 | 4.921836 | false | true | false | false |
cacawai/Tap2Read | tap2read/tap2read/TTSMgr.swift | 1 | 2387 | //
// TTSMgr.swift
// tap2read
//
// Created by 徐新元 on 21/08/2016.
// Copyright © 2016 Last4 Team. All rights reserved.
//
import UIKit
import AVFoundation
/// Text to speach
class TTSMgr: NSObject {
var avSpeechUtterance = AVSpeechUtterance.init()
var avSpeechSynthesizer = AVSpeechSynthesizer.init()
var postUtteranceDelay:TimeInterval = 0.0
var speechRate:Float = 0.28
var pitchMultiplier:Float = 1.0
var language = ConfigMgr.sharedInstance.currentLanguage()
class var sharedInstance : TTSMgr {
struct Static {
static let instance : TTSMgr = TTSMgr()
}
return Static.instance
}
func configSpeech(_ text:String!, postUtteranceDelay: TimeInterval, speechRate:Float, pitchMultiplier: Float, language: String!) {
self.postUtteranceDelay = postUtteranceDelay
self.speechRate = speechRate
self.pitchMultiplier = pitchMultiplier
self.language = language
self.configSpeech(text, language: language)
}
func configSpeech(_ text:String!, language: String?) {
avSpeechUtterance = AVSpeechUtterance.init(string: text)
avSpeechUtterance.postUtteranceDelay = self.postUtteranceDelay //播放下一语句前暂停时长
avSpeechUtterance.rate = speechRate;//0.0~1.0
avSpeechUtterance.pitchMultiplier = pitchMultiplier; //设置语调 (0.5-2.0)
avSpeechUtterance.voice = AVSpeechSynthesisVoice.init(language:language) //发音语言
}
func readText(_ text: String?, language: String?) {
if text == nil {
return
}
if language == nil {
self.readText(text)
return
}
avSpeechSynthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
self.configSpeech(text, language: language)
avSpeechSynthesizer.speak(avSpeechUtterance)
}
func readText(_ text: String?) {
if text == nil {
return
}
// let speechVoices : [AVSpeechSynthesisVoice] = AVSpeechSynthesisVoice.speechVoices()
// print("Total SpeechVoices \(speechVoices)")
avSpeechSynthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
self.configSpeech(text, language: self.language)
avSpeechSynthesizer.speak(avSpeechUtterance)
}
}
| mit | d26ed50e837efcbf52d49a5c868d7031 | 32.942029 | 135 | 0.649018 | 4.712274 | false | true | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/DefaultBrowserOnboarding/DefaultBrowserOnboardingViewController.swift | 1 | 12851 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import UIKit
import Shared
/*
|----------------|
| X |
|Title Multiline |
| | (Top View)
|Description |
|Multiline |
| |
| |
| |
|----------------|
| [Button] | (Bottom View)
|----------------|
*/
class DefaultBrowserOnboardingViewController: UIViewController, OnViewDismissable {
struct UX {
static let textOffset: CGFloat = 20
static let textOffsetSmall: CGFloat = 13
static let titleSize: CGFloat = 28
static let titleSizeSmall: CGFloat = 24
static let titleSizeLarge: CGFloat = 34
static let ctaButtonCornerRadius: CGFloat = 10
static let ctaButtonColor = UIColor.Photon.Blue50
static let ctaButtonWidth: CGFloat = 350
static let ctaButtonWidthSmall: CGFloat = 300
static let ctaButtonBottomSpace: CGFloat = 60
static let ctaButtonBottomSpaceSmall: CGFloat = 5
static let closeButtonSize = CGRect(width: 44, height: 44)
}
// MARK: - Properties
var onViewDismissed: (() -> Void)?
// Public constants
let viewModel = DefaultBrowserOnboardingViewModel()
let theme = LegacyThemeManager.instance
// Private vars
private var titleFontSize: CGFloat {
return screenSize.height > 1000 ? UX.titleSizeLarge :
screenSize.height > 640 ? UX.titleSize : UX.titleSizeSmall
}
// Orientation independent screen size
private let screenSize = DeviceInfo.screenSizeOrientationIndependent()
// UI
private lazy var scrollView: UIScrollView = .build { view in
view.backgroundColor = .clear
}
private lazy var containerView: UIView = .build { _ in }
private lazy var closeButton: UIButton = .build { button in
button.setImage(UIImage(named: ImageIdentifiers.closeLargeButton), for: .normal)
button.accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.HomeTabBanner.closeButton
}
private lazy var titleLabel: UILabel = .build { [weak self] label in
label.font = DynamicFontHelper.defaultHelper.preferredBoldFont(withTextStyle: .title1,
size: self?.titleFontSize ?? UX.titleSize)
label.textAlignment = .center
label.numberOfLines = 0
label.accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.HomeTabBanner.titleLabel
}
private lazy var descriptionText: UILabel = .build { label in
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, size: 17)
label.numberOfLines = 0
label.accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.HomeTabBanner.descriptionLabel
}
private lazy var descriptionLabel1: UILabel = .build { label in
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, size: 17)
label.numberOfLines = 0
label.accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.HomeTabBanner.descriptionLabel1
}
private lazy var descriptionLabel2: UILabel = .build { label in
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, size: 17)
label.numberOfLines = 0
label.accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.HomeTabBanner.descriptionLabel2
}
private lazy var descriptionLabel3: UILabel = .build { label in
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, size: 17)
label.numberOfLines = 0
label.accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.HomeTabBanner.descriptionLabel3
}
private lazy var goToSettingsButton: ResizableButton = .build { button in
button.layer.cornerRadius = UX.ctaButtonCornerRadius
button.accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.HomeTabBanner.ctaButton
button.titleLabel?.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .title3, size: 20)
button.contentEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
button.titleLabel?.textAlignment = .center
}
// MARK: - Inits
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycles
override func viewDidLoad() {
super.viewDidLoad()
initialViewSetup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Portrait orientation: lock enable
OrientationLockUtility.lockOrientation(UIInterfaceOrientationMask.portrait,
andRotateTo: UIInterfaceOrientation.portrait)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Portrait orientation: lock disable
OrientationLockUtility.lockOrientation(UIInterfaceOrientationMask.all)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
onViewDismissed?()
onViewDismissed = nil
}
func initialViewSetup() {
titleLabel.text = viewModel.model?.titleText
descriptionText.text = viewModel.model?.descriptionText[0]
descriptionLabel1.text = viewModel.model?.descriptionText[1]
descriptionLabel2.text = viewModel.model?.descriptionText[2]
descriptionLabel3.text = viewModel.model?.descriptionText[3]
goToSettingsButton.setTitle(.DefaultBrowserOnboardingButton, for: .normal)
closeButton.addTarget(self, action: #selector(dismissAnimated), for: .touchUpInside)
goToSettingsButton.addTarget(self, action: #selector(goToSettings), for: .touchUpInside)
updateTheme()
setupLayout()
// Theme change notification
NotificationCenter.default.addObserver(self,
selector: #selector(updateTheme),
name: .DisplayThemeChanged,
object: nil)
}
private func setupLayout() {
let textOffset: CGFloat = screenSize.height > 668 ? UX.textOffset : UX.textOffsetSmall
let containerHeightConstraint = containerView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
containerHeightConstraint.priority = .defaultLow
view.addSubview(closeButton)
containerView.addSubview(titleLabel)
containerView.addSubview(descriptionText)
containerView.addSubview(descriptionLabel1)
containerView.addSubview(descriptionLabel2)
containerView.addSubview(descriptionLabel3)
containerView.addSubview(goToSettingsButton)
scrollView.addSubviews(containerView)
view.addSubviews(scrollView)
NSLayoutConstraint.activate([
closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
closeButton.heightAnchor.constraint(equalToConstant: UX.closeButtonSize.height),
closeButton.widthAnchor.constraint(equalToConstant: UX.closeButtonSize.width),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.topAnchor.constraint(equalTo: closeButton.bottomAnchor, constant: 10),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
scrollView.frameLayoutGuide.widthAnchor.constraint(equalTo: containerView.widthAnchor),
scrollView.contentLayoutGuide.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
scrollView.contentLayoutGuide.topAnchor.constraint(equalTo: containerView.topAnchor),
scrollView.contentLayoutGuide.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
scrollView.contentLayoutGuide.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
containerHeightConstraint,
titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor),
titleLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: textOffset),
titleLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -textOffset),
descriptionText.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: textOffset),
descriptionText.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: textOffset),
descriptionText.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -textOffset),
descriptionLabel1.topAnchor.constraint(equalTo: descriptionText.bottomAnchor, constant: textOffset),
descriptionLabel1.leadingAnchor.constraint(equalTo: descriptionText.leadingAnchor),
descriptionLabel1.trailingAnchor.constraint(equalTo: descriptionText.trailingAnchor),
descriptionLabel2.topAnchor.constraint(equalTo: descriptionLabel1.bottomAnchor, constant: textOffset),
descriptionLabel2.leadingAnchor.constraint(equalTo: descriptionLabel1.leadingAnchor),
descriptionLabel2.trailingAnchor.constraint(equalTo: descriptionLabel1.trailingAnchor),
descriptionLabel3.topAnchor.constraint(equalTo: descriptionLabel2.bottomAnchor, constant: textOffset),
descriptionLabel3.leadingAnchor.constraint(equalTo: descriptionLabel2.leadingAnchor),
descriptionLabel3.trailingAnchor.constraint(equalTo: descriptionLabel2.trailingAnchor),
goToSettingsButton.topAnchor.constraint(greaterThanOrEqualTo: descriptionLabel3.bottomAnchor, constant: 24)
])
if screenSize.height > 1000 {
NSLayoutConstraint.activate([
goToSettingsButton.bottomAnchor.constraint(equalTo: containerView.bottomAnchor,
constant: -UX.ctaButtonBottomSpace),
goToSettingsButton.widthAnchor.constraint(equalToConstant: UX.ctaButtonWidth)
])
} else if screenSize.height > 640 {
NSLayoutConstraint.activate([
goToSettingsButton.bottomAnchor.constraint(equalTo: containerView.bottomAnchor,
constant: -UX.ctaButtonBottomSpaceSmall),
goToSettingsButton.widthAnchor.constraint(equalToConstant: UX.ctaButtonWidth)
])
goToSettingsButton.contentEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
} else {
NSLayoutConstraint.activate([
goToSettingsButton.bottomAnchor.constraint(equalTo: containerView.bottomAnchor,
constant: -UX.ctaButtonBottomSpaceSmall),
goToSettingsButton.widthAnchor.constraint(equalToConstant: UX.ctaButtonWidthSmall)
])
}
goToSettingsButton.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
}
// Button Actions
@objc private func dismissAnimated() {
self.dismiss(animated: true, completion: nil)
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .dismissDefaultBrowserOnboarding)
}
@objc private func goToSettings() {
viewModel.goToSettings?()
UserDefaults.standard.set(true, forKey: PrefsKeys.DidDismissDefaultBrowserMessage) // Don't show default browser card if this button is clicked
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .goToSettingsDefaultBrowserOnboarding)
}
// Theme
@objc func updateTheme() {
let textColor: UIColor = theme.currentName == .dark ? .white : .black
view.backgroundColor = .systemBackground
titleLabel.textColor = textColor
descriptionText.textColor = textColor
descriptionLabel1.textColor = textColor
descriptionLabel2.textColor = textColor
descriptionLabel3.textColor = textColor
goToSettingsButton.backgroundColor = UX.ctaButtonColor
goToSettingsButton.setTitleColor(.white, for: .normal)
closeButton.tintColor = .secondaryLabel
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mpl-2.0 | 9d0a2884e7be69c6e8ccc9fda4748485 | 44.733096 | 151 | 0.689207 | 5.857338 | false | false | false | false |
ankit4oct/CreditCardInfo | Pods/CreditCardForm/CreditCardForm/Classes/AKMaskFieldUtility.swift | 1 | 3379 | //
// AKMaskFieldUtility.swift
// AKMaskField
// GitHub: https://github.com/artemkrachulov/AKMaskField
//
// Created by Artem Krachulov
// Copyright (c) 2016 Artem Krachulov. All rights reserved.
// Website: http://www.artemkrachulov.com/
//
import UIKit
class AKMaskFieldUtility {
/// [Source](http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index)
class func rangeFromString(_ string: String, nsRange: NSRange) -> Range<String.Index>! {
guard
let from16 = string.utf16.index(string.utf16.startIndex, offsetBy: nsRange.location, limitedBy: string.utf16.endIndex),
let to16 = string.utf16.index(from16, offsetBy: nsRange.length, limitedBy: string.utf16.endIndex),
let from = String.Index(from16, within: string),
let to = String.Index(to16, within: string)
else { return nil }
return from ..< to
/*
let from16 = string.utf16.startIndex.advancedBy(nsRange.location, limit: string.utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: string.utf16.endIndex)
if let from = String.Index(from16, within: string),
let to = String.Index(to16, within: string) {
return from ..< to
}
return nil*/
}
class func substring(_ sourceString: String?, withNSRange range: NSRange) -> String {
guard let sourceString = sourceString else {
return ""
}
return sourceString.substring(with: rangeFromString(sourceString, nsRange: range))
}
class func replace(_ sourceString: inout String!, withString string: String, inRange range: NSRange) {
sourceString = sourceString.replacingCharacters(in: rangeFromString(sourceString, nsRange: range), with: string)
}
class func replacingOccurrencesOfString(_ string: inout String!, target: String, withString replacement: String) {
string = string.replacingOccurrences(of: target, with: replacement, options: .regularExpression, range: nil)
}
class func maskField(_ maskField: UITextField, moveCaretToPosition position: Int) {
guard let caretPosition = maskField.position(from: maskField.beginningOfDocument, offset: position) else {
return
}
maskField.selectedTextRange = maskField.textRange(from: caretPosition, to: caretPosition)
}
class func matchesInString(_ string: String, pattern: String) -> [NSTextCheckingResult] {
return try!
NSRegularExpression(pattern: pattern, options: .caseInsensitive)
.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, string.characters.count))
}
class func findIntersection(_ ranges: [NSRange], withRange range: NSRange) -> [NSRange?] {
var intersectRanges = [NSRange?]()
for r in ranges {
var intersectRange: NSRange!
let delta = r.location - range.location
var location, length, tail: Int
if delta <= 0 {
location = range.location
length = range.length
tail = r.length - abs(delta)
} else {
location = r.location
length = r.length
tail = range.length - abs(delta)
}
if tail > 0 && length > 0 {
intersectRange = NSMakeRange(location, min(tail, length))
}
intersectRanges.append(intersectRange)
}
return intersectRanges
}
}
| mit | 6d848321ce2ae6ba57cf6ba5a4bc6ed3 | 34.197917 | 135 | 0.672684 | 4.39974 | false | false | false | false |
themonki/onebusaway-iphone | OneBusAway/ui/listkit/ButtonSectionController.swift | 1 | 3740 | //
// ButtonSectionController.swift
// OneBusAway
//
// Created by Aaron Brethorst on 9/15/18.
// Copyright © 2018 OneBusAway. All rights reserved.
//
import UIKit
import IGListKit
import SnapKit
import OBAKit
class ButtonSectionCell: SelfSizingCollectionCell {
private let kDebugColors = false
fileprivate let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.setContentHuggingPriority(.required, for: .horizontal)
imageView.tintColor = OBATheme.obaDarkGreen
return imageView
}()
fileprivate let label: UILabel = {
let label = UILabel()
label.setContentHuggingPriority(.required, for: .vertical)
label.font = OBATheme.boldFootnoteFont
label.textColor = OBATheme.obaDarkGreen
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
let stack = UIStackView.oba_horizontalStack(withArrangedSubviews: [imageView, label])
stack.spacing = OBATheme.compactPadding
let stackWrapper = stack.oba_embedInWrapper()
contentView.addSubview(stackWrapper)
imageView.snp.makeConstraints { (make) in
make.height.equalTo(label)
make.width.equalTo(imageView.snp.height)
}
stackWrapper.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.bottom.equalToSuperview().inset(UIEdgeInsets(top: OBATheme.defaultMargin, left: 0, bottom: 0, right: 0))
}
if kDebugColors {
imageView.backgroundColor = .red
stackWrapper.backgroundColor = .magenta
label.backgroundColor = .green
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
label.text = nil
imageView.image = nil
}
}
class ButtonSection: NSObject, ListDiffable {
fileprivate let title: String
fileprivate let image: UIImage?
fileprivate let action: (_ cell: UICollectionViewCell) -> Void
init(title: String, image: UIImage?, action: @escaping (_ cell: UICollectionViewCell) -> Void) {
self.title = title
self.image = image
self.action = action
}
func diffIdentifier() -> NSObjectProtocol {
return self
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
guard let object = object as? ButtonSection else {
return false
}
return self == object
}
}
class ButtonSectionController: ListSectionController {
var data: ButtonSection?
override init() {
super.init()
inset = .zero
}
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 55)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard
let ctx = collectionContext,
let cell = ctx.dequeueReusableCell(of: ButtonSectionCell.self, for: self, at: index) as? ButtonSectionCell
else {
fatalError()
}
cell.label.text = data?.title
cell.imageView.image = data?.image
return cell
}
override func didSelectItem(at index: Int) {
guard let cell = collectionContext?.cellForItem(at: index, sectionController: self),
let data = data else {
return
}
data.action(cell)
}
override func didUpdate(to object: Any) {
precondition(object is ButtonSection)
data = object as? ButtonSection
}
}
| apache-2.0 | 46b83f696a303d9304a71871300a57e7 | 26.492647 | 125 | 0.635999 | 4.952318 | false | false | false | false |
davefoxy/SwiftBomb | SwiftBomb/Classes/Resources/LocationResource.swift | 1 | 3108 | //
// LocationResource.swift
// SwiftBomb
//
// Created by David Fox on 25/04/2016.
// Copyright © 2016 David Fox. All rights reserved.
//
import Foundation
/**
A class representing a *Location* on the Giant Bomb wiki. Examples include *The Moon* and *Underwater*.
To retrieve extended info for a location, call `fetchExtendedInfo(_:)` upon it.
*/
final public class LocationResource: ResourceUpdating {
/// The resource type.
public let resourceType = ResourceType.location
/// An array of aliases the location is known by.
public fileprivate(set) var aliases: [String]?
/// URL pointing to the location detail resource.
public fileprivate(set) var api_detail_url: URL?
/// Date the location was added to Giant Bomb.
public fileprivate(set) var date_added: Date?
/// Date the location was last updated on Giant Bomb.
public fileprivate(set) var date_last_updated: Date?
/// Brief summary of the location.
public fileprivate(set) var deck: String?
/// Description of the location.
public fileprivate(set) var description: String?
/// Game where the location made its first appearance.
public fileprivate(set) var first_appeared_in_game: GameResource?
/// Unique ID of the location.
public let id: Int?
/// Main image of the location.
public fileprivate(set) var image: ImageURLs?
/// Name of the location.
public fileprivate(set) var name: String?
/// URL pointing to the location on Giant Bomb.
public fileprivate(set) var site_detail_url: URL?
/// Extended info. Unused for this resource type.
public var extendedInfo: UnusedExtendedInfo?
/// Used to create a `LocationResource` from JSON.
public init(json: [String : AnyObject]) {
id = json["id"] as? Int
update(json: json)
}
func update(json: [String : AnyObject]) {
aliases = (json["aliases"] as? String)?.newlineSeparatedStrings() ?? aliases
api_detail_url = (json["api_detail_url"] as? String)?.url() as URL?? ?? api_detail_url
date_added = (json["date_added"] as? String)?.dateRepresentation() as Date?? ?? date_added
date_last_updated = (json["date_last_updated"] as? String)?.dateRepresentation() as Date?? ?? date_last_updated
deck = json["deck"] as? String ?? deck
description = json["description"] as? String ?? description
if let firstAppearedInGameJSON = json["first_appeared_in_game"] as? [String: AnyObject] {
first_appeared_in_game = GameResource(json: firstAppearedInGameJSON)
}
if let imageJSON = json["image"] as? [String: AnyObject] {
image = ImageURLs(json: imageJSON)
}
name = json["name"] as? String ?? name
site_detail_url = (json["site_detail_url"] as? String)?.url() as URL?? ?? site_detail_url
}
/// Pretty description of the location.
public var prettyDescription: String {
return name ?? "Location \(id)"
}
}
| mit | ec7d56eadccf1a2cc8108518f7f3b14c | 33.522222 | 119 | 0.635018 | 4.267857 | false | false | false | false |
JGiola/swift | test/SILGen/dynamic.swift | 1 | 29456 |
// RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift | %FileCheck %s
// RUN: %target-swift-emit-sil(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -verify
// REQUIRES: objc_interop
import Foundation
import gizmo
class Foo: Proto {
// Not objc or dynamic, so only a vtable entry
init(native: Int) {}
func nativeMethod() {}
var nativeProp: Int = 0
subscript(native native: Int) -> Int {
get { return native }
set {}
}
class subscript(nativeType nativeType: Int) -> Int {
get { return nativeType }
set {}
}
// @objc, so it has an ObjC entry point but can also be dispatched
// by vtable
@objc init(objc: Int) {}
@objc func objcMethod() {}
@objc var objcProp: Int = 0
@objc subscript(objc objc: AnyObject) -> Int {
get { return 0 }
set {}
}
// dynamic, so it has only an ObjC entry point
@objc dynamic init(dynamic: Int) {}
@objc dynamic func dynamicMethod() {}
@objc dynamic var dynamicProp: Int = 0
@objc dynamic subscript(dynamic dynamic: Int) -> Int {
get { return dynamic }
set {}
}
func overriddenByDynamic() {}
@NSManaged var managedProp: Int
}
protocol Proto {
func nativeMethod()
var nativeProp: Int { get set }
subscript(native native: Int) -> Int { get set }
static subscript(nativeType nativeType: Int) -> Int { get set }
func objcMethod()
var objcProp: Int { get set }
subscript(objc objc: AnyObject) -> Int { get set }
func dynamicMethod()
var dynamicProp: Int { get set }
subscript(dynamic dynamic: Int) -> Int { get set }
}
// ObjC entry points for @objc and dynamic entry points
// normal and @objc initializing ctors can be statically dispatched
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s7dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @$s7dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s7dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @$s7dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3FooC10objcMethod{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooC8objcPropSivgTo
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooC8objcPropSivsTo
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3FooC4objcSiyXl_tcigTo
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3FooC4objcSiyXl_tcisTo
// TODO: dynamic initializing ctor must be objc dispatched
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.init!initializer.foreign :
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooC0A4PropSivgTo
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooC0A4PropSivsTo
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3FooCAAS2i_tcigTo
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic3FooCAAS2i_tcisTo
// Protocol witnesses use best appropriate dispatch
// Native witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP12nativeMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP10nativePropSivgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP10nativePropSivsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcigTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcisTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP10nativeTypeS2i_tcigZTW
// CHECK: class_method {{%.*}} : $@thick Foo.Type, #Foo.subscript!getter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP10nativeTypeS2i_tcisZTW
// CHECK: class_method {{%.*}} : $@thick Foo.Type, #Foo.subscript!setter :
// @objc witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP10objcMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP8objcPropSivgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP8objcPropSivsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcigTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcisTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter :
// Dynamic witnesses use objc dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP0A6Method{{[_0-9a-zA-Z]*}}FTW
// CHECK: function_ref @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicMethod!foreign :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP0A4PropSivgTW
// CHECK: function_ref @$s7dynamic3FooC0A4PropSivgTD
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s7dynamic3FooC0A4PropSivgTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!getter.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDP0A4PropSivsTW
// CHECK: function_ref @$s7dynamic3FooC0A4PropSivsTD
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s7dynamic3FooC0A4PropSivsTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!setter.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDPAAS2i_tcigTW
// CHECK: function_ref @$s7dynamic3FooCAAS2i_tcigTD
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s7dynamic3FooCAAS2i_tcigTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!getter.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s7dynamic3FooCAA5ProtoA2aDPAAS2i_tcisTW
// CHECK: function_ref @$s7dynamic3FooCAAS2i_tcisTD
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s7dynamic3FooCAAS2i_tcisTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!setter.foreign :
// Superclass dispatch
class Subclass: Foo {
// Native and objc methods can directly reference super members
override init(native: Int) {
super.init(native: native)
}
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
override func nativeMethod() {
super.nativeMethod()
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC12nativeMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s7dynamic3FooC12nativeMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var nativeProp: Int {
get { return super.nativeProp }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC10nativePropSivg
// CHECK: function_ref @$s7dynamic3FooC10nativePropSivg : $@convention(method) (@guaranteed Foo) -> Int
set { super.nativeProp = newValue }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC10nativePropSivs
// CHECK: function_ref @$s7dynamic3FooC10nativePropSivs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(native native: Int) -> Int {
get { return super[native: native] }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC6nativeS2i_tcig
// CHECK: function_ref @$s7dynamic3FooC6nativeS2i_tcig : $@convention(method) (Int, @guaranteed Foo) -> Int
set { super[native: native] = newValue }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC6nativeS2i_tcis
// CHECK: function_ref @$s7dynamic3FooC6nativeS2i_tcis : $@convention(method) (Int, Int, @guaranteed Foo) -> ()
}
override class subscript(nativeType nativeType: Int) -> Int {
get { return super[nativeType: nativeType] }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC10nativeTypeS2i_tcigZ
// CHECK: function_ref @$s7dynamic3FooC10nativeTypeS2i_tcigZ : $@convention(method) (Int, @thick Foo.Type) -> Int
set { super[nativeType: nativeType] = newValue }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC10nativeTypeS2i_tcisZ
// CHECK: function_ref @$s7dynamic3FooC10nativeTypeS2i_tcisZ : $@convention(method) (Int, Int, @thick Foo.Type) -> ()
}
override init(objc: Int) {
super.init(objc: objc)
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC4objcACSi_tcfc
// CHECK: function_ref @$s7dynamic3FooC4objcACSi_tcfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
override func objcMethod() {
super.objcMethod()
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC10objcMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s7dynamic3FooC10objcMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var objcProp: Int {
get { return super.objcProp }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC8objcPropSivg
// CHECK: function_ref @$s7dynamic3FooC8objcPropSivg : $@convention(method) (@guaranteed Foo) -> Int
set { super.objcProp = newValue }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC8objcPropSivs
// CHECK: function_ref @$s7dynamic3FooC8objcPropSivs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(objc objc: AnyObject) -> Int {
get { return super[objc: objc] }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC4objcSiyXl_tcig
// CHECK: function_ref @$s7dynamic3FooC4objcSiyXl_tcig : $@convention(method) (@guaranteed AnyObject, @guaranteed Foo) -> Int
set { super[objc: objc] = newValue }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC4objcSiyXl_tcis
// CHECK: function_ref @$s7dynamic3FooC4objcSiyXl_tcis : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> ()
}
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.init!initializer.foreign :
override func dynamicMethod() {
super.dynamicMethod()
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC0A6Method{{[_0-9a-zA-Z]*}}F
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicMethod!foreign :
override var dynamicProp: Int {
get { return super.dynamicProp }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC0A4PropSivg
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicProp!getter.foreign :
set { super.dynamicProp = newValue }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassC0A4PropSivs
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicProp!setter.foreign :
}
override subscript(dynamic dynamic: Int) -> Int {
get { return super[dynamic: dynamic] }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassCAAS2i_tcig
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.subscript!getter.foreign :
set { super[dynamic: dynamic] = newValue }
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic8SubclassCAAS2i_tcis
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.subscript!setter.foreign :
}
@objc dynamic override func overriddenByDynamic() {}
}
class SubclassWithInheritedInits: Foo {
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic26SubclassWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $SubclassWithInheritedInits, #Foo.init!initializer.foreign :
}
class GrandchildWithInheritedInits: SubclassWithInheritedInits {
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic28GrandchildWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $GrandchildWithInheritedInits, #SubclassWithInheritedInits.init!initializer.foreign :
}
class GrandchildOfInheritedInits: SubclassWithInheritedInits {
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic26GrandchildOfInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $GrandchildOfInheritedInits, #SubclassWithInheritedInits.init!initializer.foreign :
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic20nativeMethodDispatchyyF : $@convention(thin) () -> ()
func nativeMethodDispatch() {
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(native: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter :
c[native: 0] = y
// CHECK: class_method {{%.*}} : $@thick Foo.Type, #Foo.subscript!getter :
let z = type(of: c)[nativeType: 0]
// CHECK: class_method {{%.*}} : $@thick Foo.Type, #Foo.subscript!setter :
type(of: c)[nativeType: 0] = z
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic18objcMethodDispatchyyF : $@convention(thin) () -> ()
func objcMethodDispatch() {
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(objc: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod :
c.objcMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter :
c.objcProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter :
let y = c[objc: 0 as NSNumber]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter :
c[objc: 0 as NSNumber] = y
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic0A14MethodDispatchyyF : $@convention(thin) () -> ()
func dynamicMethodDispatch() {
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(dynamic: 0)
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicMethod!foreign
c.dynamicMethod()
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!getter.foreign
let x = c.dynamicProp
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!setter.foreign
c.dynamicProp = x
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!getter.foreign
let y = c[dynamic: 0]
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!setter.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic15managedDispatchyyAA3FooCF
func managedDispatch(_ c: Foo) {
// CHECK: objc_method {{%.*}} : $Foo, #Foo.managedProp!getter.foreign
let x = c.managedProp
// CHECK: objc_method {{%.*}} : $Foo, #Foo.managedProp!setter.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic21foreignMethodDispatchyyF
func foreignMethodDispatch() {
// CHECK: function_ref @$sSo9GuisemeauC{{[_0-9a-zA-Z]*}}fC
let g = Guisemeau()!
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.frob!foreign
g.frob()
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.count!getter.foreign
let x = g.count
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.count!setter.foreign
g.count = x
// CHECK: objc_method {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.foreign
let y: Any! = g[0]
// CHECK: objc_method {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.foreign
g[0] = y
// CHECK: objc_method {{%.*}} : $NSObject, #NSObject.description!getter.foreign
_ = g.description
}
extension Gizmo {
// CHECK-LABEL: sil hidden [ossa] @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.init!initializer.foreign
convenience init(convenienceInExtension: Int) {
self.init(bellsOn: convenienceInExtension)
}
// CHECK-LABEL: sil hidden [ossa] @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: objc_method {{%.*}} : $@objc_metatype Gizmo.Type, #Gizmo.init!allocator.foreign
convenience init(foreignClassFactory x: Int) {
self.init(stuff: x)
}
// CHECK-LABEL: sil hidden [ossa] @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: objc_method {{%.*}} : $@objc_metatype Gizmo.Type, #Gizmo.init!allocator.foreign
convenience init(foreignClassExactFactory x: Int) {
self.init(exactlyStuff: x)
}
@objc func foreignObjCExtension() { }
@objc dynamic func foreignDynamicExtension() { }
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic24foreignExtensionDispatchyySo5GizmoCF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Gizmo):
func foreignExtensionDispatch(_ g: Gizmo) {
// CHECK: objc_method [[ARG]] : $Gizmo, #Gizmo.foreignObjCExtension!foreign : (Gizmo)
g.foreignObjCExtension()
// CHECK: objc_method [[ARG]] : $Gizmo, #Gizmo.foreignDynamicExtension!foreign
g.foreignDynamicExtension()
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic33nativeMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func nativeMethodDispatchFromOtherFile() {
// CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(native: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic31objcMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func objcMethodDispatchFromOtherFile() {
// CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(objc: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod :
c.objcMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter :
c.objcProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter :
let y = c[objc: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter :
c[objc: 0] = y
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic0A27MethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func dynamicMethodDispatchFromOtherFile() {
// CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(dynamic: 0)
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!foreign
c.dynamicMethod()
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.foreign
let x = c.dynamicProp
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.foreign
c.dynamicProp = x
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.foreign
let y = c[dynamic: 0]
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic28managedDispatchFromOtherFileyyAA0deF0CF
func managedDispatchFromOtherFile(_ c: FromOtherFile) {
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.foreign
let x = c.managedProp
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic0A16ExtensionMethodsyyAA13ObjCOtherFileCF
func dynamicExtensionMethods(_ obj: ObjCOtherFile) {
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!foreign
obj.extensionMethod()
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.foreign
_ = obj.extensionProp
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
// CHECK-NEXT: objc_method {{%.*}} : $@objc_metatype ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.foreign
_ = type(of: obj).extensionClassProp
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!foreign
obj.dynExtensionMethod()
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.foreign
_ = obj.dynExtensionProp
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
// CHECK-NEXT: objc_method {{%.*}} : $@objc_metatype ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.foreign
_ = type(of: obj).dynExtensionClassProp
}
public class Base {
@objc dynamic var x: Bool { return false }
}
public class Sub : Base {
// CHECK-LABEL: sil hidden [ossa] @$s7dynamic3SubC1xSbvg : $@convention(method) (@guaranteed Sub) -> Bool {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $Sub):
// CHECK: [[AUTOCLOSURE:%.*]] = function_ref @$s7dynamic3SubC1xSbvgSbyKXEfu_ : $@convention(thin) (@guaranteed Sub) -> (Bool, @error Error)
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: = partial_apply [callee_guaranteed] [[AUTOCLOSURE]]([[SELF_COPY]])
// CHECK: return {{%.*}} : $Bool
// CHECK: } // end sil function '$s7dynamic3SubC1xSbvg'
// CHECK-LABEL: sil private [transparent] [ossa] @$s7dynamic3SubC1xSbvgSbyKXEfu_ : $@convention(thin) (@guaranteed Sub) -> (Bool, @error Error) {
// CHECK: bb0([[VALUE:%.*]] : @guaranteed $Sub):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK: [[CAST_VALUE_COPY:%.*]] = upcast [[VALUE_COPY]]
// CHECK: [[BORROWED_CAST_VALUE_COPY:%.*]] = begin_borrow [[CAST_VALUE_COPY]]
// CHECK: [[DOWNCAST_FOR_SUPERMETHOD:%.*]] = unchecked_ref_cast [[BORROWED_CAST_VALUE_COPY]]
// CHECK: [[SUPER:%.*]] = objc_super_method [[DOWNCAST_FOR_SUPERMETHOD]] : $Sub, #Base.x!getter.foreign : (Base) -> () -> Bool, $@convention(objc_method) (Base) -> ObjCBool
// CHECK: = apply [[SUPER]]([[BORROWED_CAST_VALUE_COPY]])
// CHECK: end_borrow [[BORROWED_CAST_VALUE_COPY]]
// CHECK: destroy_value [[CAST_VALUE_COPY]]
// CHECK: } // end sil function '$s7dynamic3SubC1xSbvgSbyKXEfu_'
override var x: Bool { return false || super.x }
}
public class BaseExt : NSObject {}
extension BaseExt {
@objc public var count: Int {
return 0
}
}
public class SubExt : BaseExt {
public override var count: Int {
return 1
}
}
public class GenericBase<T> {
public func method(_: T) {}
}
public class ConcreteDerived : GenericBase<Int> {
@objc public override dynamic func method(_: Int) {}
}
// The dynamic override has a different calling convention than the base,
// so after re-abstracting the signature we must dispatch to the dynamic
// thunk.
// CHECK-LABEL: sil private [thunk] [ossa] @$s7dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV :
// CHECK: bb0(%0 : $*Int, %1 : @guaranteed $ConcreteDerived):
// CHECK-NEXT: [[VALUE:%.*]] = load [trivial] %0 : $*Int
// CHECK: [[DYNAMIC_THUNK:%.*]] = function_ref @$s7dynamic15ConcreteDerivedC6methodyySiFTD : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK-NEXT: apply [[DYNAMIC_THUNK]]([[VALUE]], %1) : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK: return
// Vtable contains entries for native and @objc methods, but not dynamic ones
// CHECK-LABEL: sil_vtable Foo {
// CHECK-NEXT: #Foo.init!allocator: {{.*}} : @$s7dynamic3FooC6nativeACSi_tcfC
// CHECK-NEXT: #Foo.nativeMethod: {{.*}} : @$s7dynamic3FooC12nativeMethodyyF
// CHECK-NEXT: #Foo.nativeProp!getter: {{.*}} : @$s7dynamic3FooC10nativePropSivg // dynamic.Foo.nativeProp.getter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!setter: {{.*}} : @$s7dynamic3FooC10nativePropSivs // dynamic.Foo.nativeProp.setter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!modify:
// CHECK-NEXT: #Foo.subscript!getter: {{.*}} : @$s7dynamic3FooC6nativeS2i_tcig // dynamic.Foo.subscript.getter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter: {{.*}} : @$s7dynamic3FooC6nativeS2i_tcis // dynamic.Foo.subscript.setter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!modify:
// CHECK-NEXT: #Foo.subscript!getter: {{.*}} : @$s7dynamic3FooC10nativeTypeS2i_tcigZ // static dynamic.Foo.subscript.getter : (nativeType: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter: {{.*}} : @$s7dynamic3FooC10nativeTypeS2i_tcisZ // static dynamic.Foo.subscript.setter : (nativeType: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!modify:
// CHECK-NEXT: #Foo.init!allocator: {{.*}} : @$s7dynamic3FooC4objcACSi_tcfC
// CHECK-NEXT: #Foo.objcMethod: {{.*}} : @$s7dynamic3FooC10objcMethodyyF
// CHECK-NEXT: #Foo.objcProp!getter: {{.*}} : @$s7dynamic3FooC8objcPropSivg // dynamic.Foo.objcProp.getter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!setter: {{.*}} : @$s7dynamic3FooC8objcPropSivs // dynamic.Foo.objcProp.setter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!modify:
// CHECK-NEXT: #Foo.subscript!getter: {{.*}} : @$s7dynamic3FooC4objcSiyXl_tcig // dynamic.Foo.subscript.getter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter: {{.*}} : @$s7dynamic3FooC4objcSiyXl_tcis // dynamic.Foo.subscript.setter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!modify:
// CHECK-NEXT: #Foo.overriddenByDynamic: {{.*}} : @$s7dynamic3FooC19overriddenByDynamic{{[_0-9a-zA-Z]*}}
// CHECK-NEXT: #Foo.deinit!deallocator: {{.*}}
// CHECK-NEXT: }
// Vtable uses a dynamic thunk for dynamic overrides
// CHECK-LABEL: sil_vtable Subclass {
// CHECK: #Foo.overriddenByDynamic: {{.*}} : @$s7dynamic8SubclassC19overriddenByDynamic{{[_0-9a-zA-Z]*}}FTD
// CHECK: }
// Check vtables for implicitly-inherited initializers
// CHECK-LABEL: sil_vtable SubclassWithInheritedInits {
// CHECK: #Foo.init!allocator: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26SubclassWithInheritedInitsC6nativeACSi_tcfC
// CHECK: #Foo.init!allocator: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26SubclassWithInheritedInitsC4objcACSi_tcfC
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildWithInheritedInits {
// CHECK: #Foo.init!allocator: (Foo.Type) -> (Int) -> Foo : @$s7dynamic28GrandchildWithInheritedInitsC6nativeACSi_tcfC
// CHECK: #Foo.init!allocator: (Foo.Type) -> (Int) -> Foo : @$s7dynamic28GrandchildWithInheritedInitsC4objcACSi_tcfC
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildOfInheritedInits {
// CHECK: #Foo.init!allocator: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26GrandchildOfInheritedInitsC6nativeACSi_tcfC
// CHECK: #Foo.init!allocator: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26GrandchildOfInheritedInitsC4objcACSi_tcfC
// CHECK-NOT: .init!
// CHECK: }
// No vtable entry for override of @objc extension property
// CHECK-LABEL: sil_vtable [serialized] SubExt {
// CHECK-NEXT: #SubExt.deinit!deallocator: @$s7dynamic6SubExtCfD // dynamic.SubExt.__deallocating_deinit
// CHECK-NEXT: }
// Dynamic thunk + vtable re-abstraction
// CHECK-LABEL: sil_vtable [serialized] ConcreteDerived {
// CHECK-NEXT: #GenericBase.method: <T> (GenericBase<T>) -> (T) -> () : @$s7dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV [override] // vtable thunk for dynamic.GenericBase.method(A) -> () dispatching to dynamic.ConcreteDerived.method(Swift.Int) -> ()
// CHECK-NEXT: #GenericBase.init!allocator: <T> (GenericBase<T>.Type) -> () -> GenericBase<T> : @$s7dynamic15ConcreteDerivedCACycfC [override]
// CHECK-NEXT: #ConcreteDerived.deinit!deallocator: @$s7dynamic15ConcreteDerivedCfD // dynamic.ConcreteDerived.__deallocating_deinit
// CHECK-NEXT: }
| apache-2.0 | 143dbc178820fa6da595cb06f6b7ddac | 49.698795 | 271 | 0.678809 | 3.51001 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/InactiveChannelsController.swift | 1 | 9849 | //
// InactiveChannelsController.swift
// Telegram
//
// Created by Mikhail Filimonov on 13/12/2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import Postbox
import TelegramCore
private func localizedInactiveDate(_ timestamp: Int32) -> String {
let nowTimestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970)
var t: time_t = time_t(TimeInterval(timestamp))
var timeinfo: tm = tm()
localtime_r(&t, &timeinfo)
var now: time_t = time_t(nowTimestamp)
var timeinfoNow: tm = tm()
localtime_r(&now, &timeinfoNow)
let string: String
if timeinfoNow.tm_year == timeinfo.tm_year && timeinfoNow.tm_mon == timeinfo.tm_mon {
//weeks
let dif = Int(roundf(Float(timeinfoNow.tm_mday - timeinfo.tm_mday) / 7))
string = strings().inactiveChannelsInactiveWeekCountable(dif)
} else if timeinfoNow.tm_year == timeinfo.tm_year {
//month
let dif = Int(timeinfoNow.tm_mon - timeinfo.tm_mon)
string = strings().inactiveChannelsInactiveMonthCountable(dif)
} else {
//year
var dif = Int(timeinfoNow.tm_year - timeinfo.tm_year)
if Int(timeinfoNow.tm_mon - timeinfo.tm_mon) > 6 {
dif += 1
}
string = strings().inactiveChannelsInactiveYearCountable(dif)
}
return string
}
private final class InactiveChannelsArguments {
let context: AccountContext
let select: SelectPeerInteraction
let premium:()->Void
init(context: AccountContext, select: SelectPeerInteraction, premium:@escaping()->Void) {
self.context = context
self.select = select
self.premium = premium
}
}
private struct InactiveChannelsState : Equatable {
let channels:[InactiveChannel]?
init(channels: [InactiveChannel]?) {
self.channels = channels
}
func withUpdatedChannels(_ channels: [InactiveChannel]) -> InactiveChannelsState {
return InactiveChannelsState(channels: channels)
}
}
private func inactiveEntries(state: InactiveChannelsState, arguments: InactiveChannelsArguments, source: InactiveSource) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId: Int32 = 0
var index: Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
if arguments.context.isPremium && !arguments.context.premiumIsBlocked {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("_id_text"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return GeneralBlockTextRowItem(initialSize, stableId: stableId, viewType: .singleItem, text: source.localizedString, font: .normal(.text), header: GeneralBlockTextHeader(text: source.header, icon: theme.icons.sentFailed))
}))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
if !arguments.context.isPremium && !arguments.context.premiumIsBlocked {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("_id_premium"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return PremiumIncreaseLimitItem.init(initialSize, stableId: stableId, context: arguments.context, type: .channels, counts: nil, viewType: .singleItem, callback: arguments.premium)
}))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
//
if let channels = state.channels {
if !channels.isEmpty {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().inactiveChannelsHeader), data: .init(color: theme.colors.grayText, viewType: .textTopItem)))
index += 1
}
for channel in channels {
let viewType = bestGeneralViewType(channels, for: channel)
struct _Equatable : Equatable {
let channel: InactiveChannel
let viewType: GeneralViewType
}
let equatable = _Equatable(channel: channel, viewType: viewType)
entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("_id_peer_\(channel.peer.id.toInt64())"), equatable: InputDataEquatable(equatable), comparable: nil, item: { initialSize, stableId in
return ShortPeerRowItem(initialSize, peer: channel.peer, account: arguments.context.account, context: arguments.context, stableId: stableId, enabled: true, height: 50, photoSize: NSMakeSize(36, 36), status: localizedInactiveDate(channel.lastActivityDate), inset: NSEdgeInsets(left: 30, right: 30), interactionType: .selectable(arguments.select), viewType: viewType)
}))
index += 1
}
if !channels.isEmpty {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
} else {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().inactiveChannelsHeader), data: .init(color: theme.colors.grayText, viewType: .textTopItem)))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("_id_loading"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return LoadingTableItem(initialSize, height: 42, stableId: stableId, viewType: .singleItem)
}))
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
return entries
}
func InactiveChannelsController(context: AccountContext, source: InactiveSource) -> InputDataModalController {
let initialState = InactiveChannelsState(channels: nil)
let statePromise = ValuePromise<InactiveChannelsState>(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((InactiveChannelsState) -> InactiveChannelsState) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let disposable = MetaDisposable()
disposable.set((context.engine.peers.inactiveChannelList() |> delay(0.5, queue: .mainQueue())).start(next: { channels in
updateState {
$0.withUpdatedChannels(channels)
}
}))
let arguments = InactiveChannelsArguments(context: context, select: SelectPeerInteraction(), premium: {
})
let signal = statePromise.get() |> map { state in
return InputDataSignalValue(entries: inactiveEntries(state: state, arguments: arguments, source: source))
}
let controller = InputDataController(dataSignal: signal, title: strings().inactiveChannelsTitle)
var close: (()->Void)? = nil
let modalInteractions = ModalInteractions(acceptTitle: strings().inactiveChannelsOK, accept: {
close?()
if !arguments.select.presentation.selected.isEmpty {
let removeSignal = combineLatest(arguments.select.presentation.selected.map { context.engine.peers.removePeerChat(peerId: $0, reportChatSpam: false)})
let peers = arguments.select.presentation.peers.map { $0.value }
let signal = context.account.postbox.transaction { transaction in
updatePeers(transaction: transaction, peers: peers, update: { _, updated in
return updated
})
} |> mapToSignal { _ in
return removeSignal
}
_ = showModalProgress(signal: signal, for: context.window).start()
}
}, drawBorder: true, height: 50, singleButton: true)
arguments.select.singleUpdater = { [weak modalInteractions] presentation in
modalInteractions?.updateDone { button in
button.isEnabled = !presentation.selected.isEmpty
}
}
controller.afterTransaction = { [weak modalInteractions] _ in
modalInteractions?.updateDone { button in
let state = stateValue.with { $0 }
if let channels = state.channels {
button.isEnabled = channels.isEmpty || !arguments.select.presentation.selected.isEmpty
button.set(text: channels.isEmpty ? strings().modalOK : strings().inactiveChannelsOK, for: .Normal)
} else {
button.isEnabled = false
}
}
}
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: {
close?()
})
controller.updateDatas = { data in
return .none
}
controller.onDeinit = {
disposable.dispose()
}
let modalController = InputDataModalController(controller, modalInteractions: modalInteractions, closeHandler: { f in f() }, size: NSMakeSize(400, 300))
close = { [weak modalController] in
modalController?.close()
}
return modalController
}
enum InactiveSource {
case join
case create
case upgrade
case invite
var localizedString: String {
switch self {
case .join:
return strings().joinChannelsTooMuch
case .create:
return strings().createChannelsTooMuch
case .upgrade:
return strings().upgradeChannelsTooMuch
case .invite:
return strings().inviteChannelsTooMuch
}
}
var header: String {
return strings().inactiveChannelsBlockHeader
}
}
func showInactiveChannels(context: AccountContext, source: InactiveSource) {
showModal(with: InactiveChannelsController(context: context, source: source), for: context.window)
}
| gpl-2.0 | 115448a2cfb8a8b6adaf0513bdf9fcde | 37.619608 | 381 | 0.652417 | 4.818004 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChannelInfoEntries.swift | 1 | 60284 | //
// ChannelInfoEntries.swift
// Telegram-Mac
//
// Created by keepcoder on 12/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import Postbox
import TelegramCore
import TGUIKit
import SwiftSignalKit
struct ChannelInfoEditingState: Equatable {
let editingName: String?
let editingDescriptionText: String
init(editingName:String? = nil, editingDescriptionText:String = "") {
self.editingName = editingName
self.editingDescriptionText = editingDescriptionText
}
func withUpdatedEditingDescriptionText(_ editingDescriptionText: String) -> ChannelInfoEditingState {
return ChannelInfoEditingState(editingName: self.editingName, editingDescriptionText: editingDescriptionText)
}
static func ==(lhs: ChannelInfoEditingState, rhs: ChannelInfoEditingState) -> Bool {
if lhs.editingName != rhs.editingName {
return false
}
if lhs.editingDescriptionText != rhs.editingDescriptionText {
return false
}
return true
}
}
class ChannelInfoState: PeerInfoState {
let editingState: ChannelInfoEditingState?
let savingData: Bool
let updatingPhotoState:PeerInfoUpdatingPhotoState?
init(editingState: ChannelInfoEditingState?, savingData: Bool, updatingPhotoState: PeerInfoUpdatingPhotoState?) {
self.editingState = editingState
self.savingData = savingData
self.updatingPhotoState = updatingPhotoState
}
override init() {
self.editingState = nil
self.savingData = false
self.updatingPhotoState = nil
}
func isEqual(to: PeerInfoState) -> Bool {
if let to = to as? ChannelInfoState {
return self == to
}
return false
}
static func ==(lhs: ChannelInfoState, rhs: ChannelInfoState) -> Bool {
if lhs.editingState != rhs.editingState {
return false
}
if lhs.savingData != rhs.savingData {
return false
}
return lhs.updatingPhotoState == rhs.updatingPhotoState
}
func withUpdatedEditingState(_ editingState: ChannelInfoEditingState?) -> ChannelInfoState {
return ChannelInfoState(editingState: editingState, savingData: self.savingData, updatingPhotoState: self.updatingPhotoState)
}
func withUpdatedSavingData(_ savingData: Bool) -> ChannelInfoState {
return ChannelInfoState(editingState: self.editingState, savingData: savingData, updatingPhotoState: self.updatingPhotoState)
}
func withUpdatedUpdatingPhotoState(_ f: (PeerInfoUpdatingPhotoState?) -> PeerInfoUpdatingPhotoState?) -> ChannelInfoState {
return ChannelInfoState(editingState: self.editingState, savingData: self.savingData, updatingPhotoState: f(self.updatingPhotoState))
}
func withoutUpdatingPhotoState() -> ChannelInfoState {
return ChannelInfoState(editingState: self.editingState, savingData: self.savingData, updatingPhotoState: nil)
}
}
private func valuesRequiringUpdate(state: ChannelInfoState, view: PeerView) -> (title: String?, description: String?) {
if let peer = view.peers[view.peerId] as? TelegramChannel {
var titleValue: String?
var descriptionValue: String?
if let editingState = state.editingState {
if let title = editingState.editingName, title != peer.title {
titleValue = title
}
if let cachedData = view.cachedData as? CachedChannelData {
if let about = cachedData.about {
if about != editingState.editingDescriptionText {
descriptionValue = editingState.editingDescriptionText
}
} else if !editingState.editingDescriptionText.isEmpty {
descriptionValue = editingState.editingDescriptionText
}
}
}
return (titleValue, descriptionValue)
} else {
return (nil, nil)
}
}
class ChannelInfoArguments : PeerInfoArguments {
private var _linksManager:InviteLinkPeerManager?
var linksManager: InviteLinkPeerManager {
if let _linksManager = _linksManager {
return _linksManager
} else {
_linksManager = InviteLinkPeerManager(context: context, peerId: peerId)
_linksManager!.loadNext()
return _linksManager!
}
}
private var _requestManager:PeerInvitationImportersContext?
var requestManager: PeerInvitationImportersContext {
if let _requestManager = _requestManager {
return _requestManager
} else {
let importersContext = context.engine.peers.peerInvitationImporters(peerId: peerId, subject: .requests(query: nil))
_requestManager = importersContext
_requestManager!.loadMore()
return _requestManager!
}
}
private let reportPeerDisposable = MetaDisposable()
private let updatePeerNameDisposable = MetaDisposable()
private let toggleSignaturesDisposable = MetaDisposable()
private let updatePhotoDisposable = MetaDisposable()
func updateState(_ f: (ChannelInfoState) -> ChannelInfoState) -> Void {
updateInfoState { state -> PeerInfoState in
return f(state as! ChannelInfoState)
}
}
override func dismissEdition() {
updateState { state in
return state.withUpdatedSavingData(false).withUpdatedEditingState(nil)
}
}
override func updateEditable(_ editable:Bool, peerView:PeerView, controller: PeerInfoController) -> Bool {
let context = self.context
let peerId = self.peerId
let updateState:((ChannelInfoState)->ChannelInfoState)->Void = { [weak self] f in
self?.updateState(f)
}
if editable {
if let peer = peerViewMainPeer(peerView), let cachedData = peerView.cachedData as? CachedChannelData {
updateState { state -> ChannelInfoState in
return state.withUpdatedEditingState(ChannelInfoEditingState(editingName: peer.displayTitle, editingDescriptionText: cachedData.about ?? ""))
}
}
} else {
var updateValues: (title: String?, description: String?) = (nil, nil)
updateState { state in
updateValues = valuesRequiringUpdate(state: state, view: peerView)
return state
}
if let titleValue = updateValues.title, titleValue.isEmpty {
controller.genericView.tableView.item(stableId: IntPeerInfoEntryStableId(value: 1).hashValue)?.view?.shakeView()
return false
}
updateState { state in
if updateValues.0 != nil || updateValues.1 != nil {
return state.withUpdatedSavingData(true)
} else {
return state.withUpdatedEditingState(nil)
}
}
let updateTitle: Signal<Void, NoError>
if let titleValue = updateValues.title {
updateTitle = context.engine.peers.updatePeerTitle(peerId: peerId, title: titleValue)
|> `catch` { _ in return .complete() }
} else {
updateTitle = .complete()
}
let updateDescription: Signal<Void, NoError>
if let descriptionValue = updateValues.description {
updateDescription = context.engine.peers.updatePeerDescription(peerId: peerId, description: descriptionValue.isEmpty ? nil : descriptionValue)
|> `catch` { _ in return .complete() }
} else {
updateDescription = .complete()
}
let signal = combineLatest(updateTitle, updateDescription)
updatePeerNameDisposable.set(showModalProgress(signal: (signal |> deliverOnMainQueue), for: context.window).start(error: { _ in
updateState { state in
return state.withUpdatedSavingData(false)
}
}, completed: {
updateState { state in
return state.withUpdatedSavingData(false).withUpdatedEditingState(nil)
}
}))
}
return true
}
func visibilitySetup() {
let setup = ChannelVisibilityController(context, peerId: peerId, isChannel: true)
_ = (setup.onComplete.get() |> deliverOnMainQueue).start(next: { [weak self] _ in
self?.pullNavigation()?.back()
})
pushViewController(setup)
}
func openInviteLinks() {
pushViewController(InviteLinksController(context: context, peerId: peerId, manager: linksManager))
}
func openRequests() {
pushViewController(RequestJoinMemberListController(context: context, peerId: peerId, manager: requestManager, openInviteLinks: { [weak self] in
self?.openInviteLinks()
}))
}
func openReactions(allowedReactions: PeerAllowedReactions?, availableReactions: AvailableReactions?) {
pushViewController(ReactionsSettingsController(context: context, peerId: peerId, allowedReactions: allowedReactions, availableReactions: availableReactions, mode: .chat(isGroup: false)))
}
func setupDiscussion() {
_ = (self.context.account.postbox.loadedPeerWithId(self.peerId) |> deliverOnMainQueue).start(next: { [weak self] peer in
if let `self` = self {
self.pushViewController(ChannelDiscussionSetupController(context: self.context, peer: peer))
}
})
}
func toggleSignatures( _ enabled: Bool) -> Void {
toggleSignaturesDisposable.set(context.engine.peers.toggleShouldChannelMessagesSignatures(peerId: peerId, enabled: enabled).start())
}
func members() -> Void {
pushViewController(ChannelMembersViewController(context, peerId: peerId))
}
func admins() -> Void {
pushViewController(ChannelAdminsViewController(context, peerId: peerId))
}
func makeVoiceChat(_ current: CachedChannelData.ActiveCall?, callJoinPeerId: PeerId?) {
let context = self.context
let peerId = self.peerId
if let activeCall = current {
let join:(PeerId, Date?, Bool)->Void = { joinAs, _, _ in
_ = showModalProgress(signal: requestOrJoinGroupCall(context: context, peerId: peerId, joinAs: joinAs, initialCall: activeCall, initialInfo: nil, joinHash: nil), for: context.window).start(next: { result in
switch result {
case let .samePeer(callContext):
applyGroupCallResult(context.sharedContext, callContext)
case let .success(callContext):
applyGroupCallResult(context.sharedContext, callContext)
default:
alert(for: context.window, info: strings().errorAnError)
}
})
}
if let callJoinPeerId = callJoinPeerId {
join(callJoinPeerId, nil, false)
} else {
selectGroupCallJoiner(context: context, peerId: peerId, completion: join)
}
} else {
createVoiceChat(context: context, peerId: peerId, canBeScheduled: true)
}
}
func blocked() -> Void {
pushViewController(ChannelBlacklistViewController(context, peerId: peerId))
}
func updateChannelPhoto(_ custom: NSImage?, control: Control?) {
let context = self.context
let updatePhoto:(Signal<NSImage, NoError>) -> Void = { image in
let signal = image |> mapToSignal { image in
return putToTemp(image: image, compress: true)
} |> deliverOnMainQueue
_ = signal.start(next: { path in
let controller = EditImageModalController(URL(fileURLWithPath: path), settings: .disableSizes(dimensions: .square))
showModal(with: controller, for: context.window, animationType: .scaleCenter)
_ = controller.result.start(next: { [weak self] url, _ in
self?.updatePhoto(url.path)
})
controller.onClose = {
removeFile(at: path)
}
})
}
if let image = custom {
updatePhoto(.single(image))
} else {
let context = self.context
let updateVideo = self.updateVideo
let makeVideo:(MediaObjectToAvatar)->Void = { object in
switch object.object.foreground.type {
case .emoji:
updatePhoto(object.start() |> mapToSignal { value in
if let result = value.result {
switch result {
case let .image(image):
return .single(image)
default:
return .never()
}
} else {
return .never()
}
})
default:
let signal:Signal<VideoAvatarGeneratorState, NoError> = object.start() |> map { value in
if let result = value.result {
switch result {
case let .video(path, thumb):
return .complete(thumb: thumb, video: path, keyFrame: nil)
default:
return .error
}
} else if let status = value.status {
switch status {
case let .initializing(thumb):
return .start(thumb: thumb)
case let .converting(progress):
return .progress(progress)
default:
return .error
}
} else {
return .error
}
}
updateVideo(signal)
}
}
var items:[ContextMenuItem] = []
items.append(.init(strings().editAvatarPhotoOrVideo, handler: {
filePanel(with: photoExts + videoExts, allowMultiple: false, canChooseDirectories: false, for: context.window, completion: { paths in
if let path = paths?.first, let image = NSImage(contentsOfFile: path) {
updatePhoto(.single(image))
} else if let path = paths?.first {
selectVideoAvatar(context: context, path: path, localize: strings().videoAvatarChooseDescChannel, signal: { signal in
updateVideo(signal)
})
}
})
}, itemImage: MenuAnimation.menu_shared_media.value))
items.append(.init(strings().editAvatarCustomize, handler: {
showModal(with: AvatarConstructorController(context, target: .avatar, videoSignal: makeVideo), for: context.window)
}, itemImage: MenuAnimation.menu_view_sticker_set.value))
if let control = control, let event = NSApp.currentEvent {
let menu = ContextMenu()
for item in items {
menu.addItem(item)
}
let value = AppMenu(menu: menu)
value.show(event: event, view: control)
} else {
filePanel(with: photoExts + videoExts, allowMultiple: false, canChooseDirectories: false, for: context.window, completion: { paths in
if let path = paths?.first, let image = NSImage(contentsOfFile: path) {
updatePhoto(.single(image))
} else if let path = paths?.first {
selectVideoAvatar(context: context, path: path, localize: strings().videoAvatarChooseDescChannel, signal: { signal in
updateVideo(signal)
})
}
})
}
}
}
func updateVideo(_ signal:Signal<VideoAvatarGeneratorState, NoError>) -> Void {
let updateState:((ChannelInfoState)->ChannelInfoState)->Void = { [weak self] f in
self?.updateState(f)
}
let cancel = { [weak self] in
self?.updatePhotoDisposable.set(nil)
updateState { state -> ChannelInfoState in
return state.withoutUpdatingPhotoState()
}
}
let context = self.context
let peerId = self.peerId
let updateSignal: Signal<UpdatePeerPhotoStatus, UploadPeerPhotoError> = signal
|> castError(UploadPeerPhotoError.self)
|> mapToSignal { state in
switch state {
case .error:
return .fail(.generic)
case let .start(path):
updateState { (state) -> ChannelInfoState in
return state.withUpdatedUpdatingPhotoState { previous -> PeerInfoUpdatingPhotoState? in
return PeerInfoUpdatingPhotoState(progress: 0, image: NSImage(contentsOfFile: path)?._cgImage, cancel: cancel)
}
}
return .next(.progress(0))
case let .progress(value):
return .next(.progress(value * 0.2))
case let .complete(thumb, video, keyFrame):
let (thumbResource, videoResource) = (LocalFileReferenceMediaResource(localFilePath: thumb, randomId: arc4random64(), isUniquelyReferencedTemporaryFile: true),
LocalFileReferenceMediaResource(localFilePath: video, randomId: arc4random64(), isUniquelyReferencedTemporaryFile: true))
return context.engine.peers.updatePeerPhoto(peerId: peerId, photo: context.engine.peers.uploadedPeerPhoto(resource: thumbResource), video: context.engine.peers.uploadedPeerVideo(resource: videoResource) |> map(Optional.init), videoStartTimestamp: keyFrame, mapResourceToAvatarSizes: { resource, representations in
return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations)
}) |> map { result in
switch result {
case let .progress(current):
return .progress(0.2 + (current * 0.8))
default:
return result
}
}
}
}
updatePhotoDisposable.set((updateSignal |> deliverOnMainQueue).start(next: { status in
updateState { state -> ChannelInfoState in
switch status {
case .complete:
return state.withoutUpdatingPhotoState()
case let .progress(progress):
return state.withUpdatedUpdatingPhotoState { previous -> PeerInfoUpdatingPhotoState? in
return previous?.withUpdatedProgress(progress)
}
}
}
}, error: { error in
updateState { (state) -> ChannelInfoState in
return state.withoutUpdatingPhotoState()
}
}, completed: {
updateState { (state) -> ChannelInfoState in
return state.withoutUpdatingPhotoState()
}
}))
}
func updatePhoto(_ path:String) -> Void {
let updateState:((ChannelInfoState)->ChannelInfoState)->Void = { [weak self] f in
self?.updateState(f)
}
let cancel = { [weak self] in
self?.updatePhotoDisposable.set(nil)
updateState { state -> ChannelInfoState in
return state.withoutUpdatingPhotoState()
}
}
let context = self.context
let peerId = self.peerId
let updateSignal = Signal<String, NoError>.single(path) |> map { path -> TelegramMediaResource in
return LocalFileReferenceMediaResource(localFilePath: path, randomId: arc4random64())
} |> beforeNext { resource in
updateState { (state) -> ChannelInfoState in
return state.withUpdatedUpdatingPhotoState { previous -> PeerInfoUpdatingPhotoState? in
return PeerInfoUpdatingPhotoState(progress: 0, image: NSImage(contentsOfFile: path)?.cgImage(forProposedRect: nil, context: nil, hints: nil), cancel: cancel)
}
}
} |> castError(UploadPeerPhotoError.self) |> mapToSignal { resource -> Signal<UpdatePeerPhotoStatus, UploadPeerPhotoError> in
return context.engine.peers.updatePeerPhoto(peerId: peerId, photo: context.engine.peers.uploadedPeerPhoto(resource: resource), mapResourceToAvatarSizes: { resource, representations in
return mapResourceToAvatarSizes(postbox: context.account.postbox, resource: resource, representations: representations)
})
}
updatePhotoDisposable.set((updateSignal |> deliverOnMainQueue).start(next: { status in
updateState { state -> ChannelInfoState in
switch status {
case .complete:
return state
case let .progress(progress):
return state.withUpdatedUpdatingPhotoState { previous -> PeerInfoUpdatingPhotoState? in
return previous?.withUpdatedProgress(progress)
}
}
}
}, error: { error in
updateState { (state) -> ChannelInfoState in
return state.withoutUpdatingPhotoState()
}
}, completed: {
updateState { (state) -> ChannelInfoState in
return state.withoutUpdatingPhotoState()
}
}))
}
func stats(_ datacenterId: Int32) {
self.pushViewController(ChannelStatsViewController(context, peerId: peerId, datacenterId: datacenterId))
}
func share() {
let peer = context.account.postbox.peerView(id: peerId) |> take(1) |> deliverOnMainQueue
let context = self.context
_ = peer.start(next: { peerView in
if let peer = peerViewMainPeer(peerView) {
var link: String = "https://t.me/c/\(peer.id.id)"
if let address = peer.addressName, !address.isEmpty {
link = "https://t.me/\(address)"
} else if let cachedData = peerView.cachedData as? CachedChannelData, let invitation = cachedData.exportedInvitation?._invitation {
link = invitation.link
}
showModal(with: ShareModalController(ShareLinkObject(context, link: link)), for: context.window)
}
})
}
func report() -> Void {
let context = self.context
let peerId = self.peerId
let report = reportReasonSelector(context: context) |> map { value -> (ChatController?, ReportReasonValue) in
switch value.reason {
case .fake:
return (nil, value)
default:
return (ChatController(context: context, chatLocation: .peer(peerId), initialAction: .selectToReport(reason: value)), value)
}
} |> deliverOnMainQueue
reportPeerDisposable.set(report.start(next: { [weak self] controller, value in
if let controller = controller {
self?.pullNavigation()?.push(controller)
} else {
showModal(with: ReportDetailsController(context: context, reason: value, updated: { value in
_ = showModalProgress(signal: context.engine.peers.reportPeer(peerId: peerId, reason: value.reason, message: value.comment), for: context.window).start(completed: {
showModalText(for: context.window, text: strings().peerInfoChannelReported)
})
}), for: context.window)
}
}))
}
func updateEditingDescriptionText(_ text:String) -> Void {
updateState { state in
if let editingState = state.editingState {
return state.withUpdatedEditingState(editingState.withUpdatedEditingDescriptionText(text))
}
return state
}
}
func updateEditingName(_ name:String) -> Void {
updateState { state in
if let editingState = state.editingState {
return state.withUpdatedEditingState(ChannelInfoEditingState(editingName: name, editingDescriptionText: editingState.editingDescriptionText))
} else {
return state
}
}
}
deinit {
reportPeerDisposable.dispose()
updatePeerNameDisposable.dispose()
toggleSignaturesDisposable.dispose()
updatePhotoDisposable.dispose()
}
}
enum ChannelInfoEntry: PeerInfoEntry {
case info(sectionId: ChannelInfoSection, peerView: PeerView, editable:Bool, updatingPhotoState:PeerInfoUpdatingPhotoState?, viewType: GeneralViewType)
case scam(sectionId: ChannelInfoSection, title: String, text: String, viewType: GeneralViewType)
case about(sectionId: ChannelInfoSection, text: String, viewType: GeneralViewType)
case userName(sectionId: ChannelInfoSection, value: [String], viewType: GeneralViewType)
case setTitle(sectionId: ChannelInfoSection, text: String, viewType: GeneralViewType)
case admins(sectionId: ChannelInfoSection, count:Int32?, viewType: GeneralViewType)
case blocked(sectionId: ChannelInfoSection, count:Int32?, viewType: GeneralViewType)
case members(sectionId: ChannelInfoSection, count:Int32?, viewType: GeneralViewType)
case link(sectionId: ChannelInfoSection, addressName:String, viewType: GeneralViewType)
case inviteLinks(section: ChannelInfoSection, count: Int32, viewType: GeneralViewType)
case requests(section: ChannelInfoSection, count: Int32, viewType: GeneralViewType)
case reactions(section: ChannelInfoSection, text: String, allowedReactions: PeerAllowedReactions?, availableReactions: AvailableReactions?, viewType: GeneralViewType)
case discussion(sectionId: ChannelInfoSection, group: Peer?, participantsCount: Int32?, viewType: GeneralViewType)
case discussionDesc(sectionId: ChannelInfoSection, viewType: GeneralViewType)
case aboutInput(sectionId: ChannelInfoSection, description:String, viewType: GeneralViewType)
case aboutDesc(sectionId: ChannelInfoSection, viewType: GeneralViewType)
case signMessages(sectionId: ChannelInfoSection, sign:Bool, viewType: GeneralViewType)
case signDesc(sectionId: ChannelInfoSection, viewType: GeneralViewType)
case report(sectionId: ChannelInfoSection, viewType: GeneralViewType)
case leave(sectionId: ChannelInfoSection, isCreator: Bool, viewType: GeneralViewType)
case media(sectionId: ChannelInfoSection, controller: PeerMediaController, isVisible: Bool, viewType: GeneralViewType)
case section(Int)
func withUpdatedViewType(_ viewType: GeneralViewType) -> ChannelInfoEntry {
switch self {
case let .info(sectionId, peerView, editable, updatingPhotoState, _): return .info(sectionId: sectionId, peerView: peerView, editable: editable, updatingPhotoState: updatingPhotoState, viewType: viewType)
case let .scam(sectionId, title, text, _): return .scam(sectionId: sectionId, title: title, text: text, viewType: viewType)
case let .about(sectionId, text, _): return .about(sectionId: sectionId, text: text, viewType: viewType)
case let .userName(sectionId, value, _): return .userName(sectionId: sectionId, value: value, viewType: viewType)
case let .setTitle(sectionId, text, _): return .setTitle(sectionId: sectionId, text: text, viewType: viewType)
case let .admins(sectionId, count, _): return .admins(sectionId: sectionId, count: count, viewType: viewType)
case let .blocked(sectionId, count, _): return .blocked(sectionId: sectionId, count: count, viewType: viewType)
case let .members(sectionId, count, _): return .members(sectionId: sectionId, count: count, viewType: viewType)
case let .link(sectionId, addressName, _): return .link(sectionId: sectionId, addressName: addressName, viewType: viewType)
case let .inviteLinks(section, count, _): return .inviteLinks(section: section, count: count, viewType: viewType)
case let .requests(section, count, _): return .requests(section: section, count: count, viewType: viewType)
case let .discussion(sectionId, group, participantsCount, _): return .discussion(sectionId: sectionId, group: group, participantsCount: participantsCount, viewType: viewType)
case let .reactions(section, text, allowedReactions, availableReactions, _): return .reactions(section: section, text: text, allowedReactions: allowedReactions, availableReactions: availableReactions, viewType: viewType)
case let .discussionDesc(sectionId, _): return .discussionDesc(sectionId: sectionId, viewType: viewType)
case let .aboutInput(sectionId, description, _): return .aboutInput(sectionId: sectionId, description: description, viewType: viewType)
case let .aboutDesc(sectionId, _): return .aboutDesc(sectionId: sectionId, viewType: viewType)
case let .signMessages(sectionId, sign, _): return .signMessages(sectionId: sectionId, sign: sign, viewType: viewType)
case let .signDesc(sectionId, _): return .signDesc(sectionId: sectionId, viewType: viewType)
case let .report(sectionId, _): return .report(sectionId: sectionId, viewType: viewType)
case let .leave(sectionId, isCreator, _): return .leave(sectionId: sectionId, isCreator: isCreator, viewType: viewType)
case let .media(sectionId, controller, isVisible, _): return .media(sectionId: sectionId, controller: controller, isVisible: isVisible, viewType: viewType)
case .section: return self
}
}
var stableId: PeerInfoEntryStableId {
return IntPeerInfoEntryStableId(value: self.stableIndex)
}
func isEqual(to: PeerInfoEntry) -> Bool {
guard let entry = to as? ChannelInfoEntry else {
return false
}
switch self {
case let .info(sectionId, lhsPeerView, editable, updatingPhotoState, viewType):
switch entry {
case .info(sectionId, let rhsPeerView, editable, updatingPhotoState, viewType):
let lhsPeer = peerViewMainPeer(lhsPeerView)
let lhsCachedData = lhsPeerView.cachedData
let lhsNotificationSettings = lhsPeerView.notificationSettings
let rhsPeer = peerViewMainPeer(rhsPeerView)
let rhsCachedData = rhsPeerView.cachedData
let rhsNotificationSettings = rhsPeerView.notificationSettings
if let lhsPeer = lhsPeer, let rhsPeer = rhsPeer {
if !lhsPeer.isEqual(rhsPeer) {
return false
}
} else if (lhsPeer != nil) != (rhsPeer != nil) {
return false
}
if let lhsNotificationSettings = lhsNotificationSettings, let rhsNotificationSettings = rhsNotificationSettings {
if !lhsNotificationSettings.isEqual(to: rhsNotificationSettings) {
return false
}
} else if (lhsNotificationSettings != nil) != (rhsNotificationSettings != nil) {
return false
}
if let lhsCachedData = lhsCachedData, let rhsCachedData = rhsCachedData {
if !lhsCachedData.isEqual(to: rhsCachedData) {
return false
}
} else if (lhsCachedData != nil) != (rhsCachedData != nil) {
return false
}
return true
default:
return false
}
case let .scam(sectionId, title, text, viewType):
switch entry {
case .scam(sectionId, title, text, viewType):
return true
default:
return false
}
case let .about(sectionId, text, viewType):
switch entry {
case .about(sectionId, text, viewType):
return true
default:
return false
}
case let .userName(sectionId, value, viewType):
switch entry {
case .userName(sectionId, value, viewType):
return true
default:
return false
}
case let .setTitle(sectionId, text, viewType):
switch entry {
case .setTitle(sectionId, text, viewType):
return true
default:
return false
}
case let .report(sectionId, viewType):
switch entry {
case .report(sectionId, viewType):
return true
default:
return false
}
case let .admins(sectionId, count, viewType):
if case .admins(sectionId, count, viewType) = entry {
return true
} else {
return false
}
case let .blocked(sectionId, count, viewType):
if case .blocked(sectionId, count, viewType) = entry {
return true
} else {
return false
}
case let .members(sectionId, count, viewType):
if case .members(sectionId, count, viewType) = entry {
return true
} else {
return false
}
case let .link(sectionId, addressName, viewType):
if case .link(sectionId, addressName, viewType) = entry {
return true
} else {
return false
}
case let .inviteLinks(sectionId, count, viewType):
if case .inviteLinks(sectionId, count, viewType) = entry {
return true
} else {
return false
}
case let .requests(sectionId, count, viewType):
if case .requests(sectionId, count, viewType) = entry {
return true
} else {
return false
}
case let .discussion(sectionId, lhsGroup, participantsCount, viewType):
if case .discussion(sectionId, let rhsGroup, participantsCount, viewType) = entry {
if let lhsGroup = lhsGroup, let rhsGroup = rhsGroup {
return lhsGroup.isEqual(rhsGroup)
} else if (lhsGroup != nil) != (rhsGroup != nil) {
return false
}
return true
} else {
return false
}
case let .reactions(sectionId, text, allowedReactions, availableReactions, viewType):
if case .reactions(sectionId, text, allowedReactions, availableReactions, viewType) = entry {
return true
} else {
return false
}
case let .discussionDesc(sectionId, viewType):
if case .discussionDesc(sectionId, viewType) = entry {
return true
} else {
return false
}
case let .aboutInput(sectionId, text, viewType):
if case .aboutInput(sectionId, text, viewType) = entry {
return true
} else {
return false
}
case let .aboutDesc(sectionId, viewType):
if case .aboutDesc(sectionId, viewType) = entry {
return true
} else {
return false
}
case let .signMessages(sectionId, sign, viewType):
if case .signMessages(sectionId, sign, viewType) = entry {
return true
} else {
return false
}
case let .signDesc(sectionId, viewType):
if case .signDesc(sectionId, viewType) = entry {
return true
} else {
return false
}
case let .leave(sectionId, isCreator, viewType):
switch entry {
case .leave(sectionId, isCreator, viewType):
return true
default:
return false
}
case let .section(lhsId):
switch entry {
case let .section(rhsId):
return lhsId == rhsId
default:
return false
}
case let .media(sectionId, _, isVisible, viewType):
switch entry {
case .media(sectionId, _, isVisible, viewType):
return true
default:
return false
}
}
}
private var stableIndex: Int {
switch self {
case .info:
return 0
case .setTitle:
return 1
case .scam:
return 2
case .about:
return 3
case .userName:
return 4
case .admins:
return 8
case .members:
return 9
case .blocked:
return 10
case .link:
return 11
case .inviteLinks:
return 12
case .requests:
return 13
case .reactions:
return 14
case .discussion:
return 15
case .discussionDesc:
return 16
case .aboutInput:
return 17
case .aboutDesc:
return 18
case .signMessages:
return 19
case .signDesc:
return 20
case .report:
return 21
case .leave:
return 22
case .media:
return 23
case let .section(id):
return (id + 1) * 1000 - id
}
}
fileprivate var sectionId: Int {
switch self {
case let .info(sectionId, _, _, _, _):
return sectionId.rawValue
case let .setTitle(sectionId, _, _):
return sectionId.rawValue
case let .scam(sectionId, _, _, _):
return sectionId.rawValue
case let .about(sectionId, _, _):
return sectionId.rawValue
case let .userName(sectionId, _, _):
return sectionId.rawValue
case let .admins(sectionId, _, _):
return sectionId.rawValue
case let .blocked(sectionId, _, _):
return sectionId.rawValue
case let .members(sectionId, _, _):
return sectionId.rawValue
case let .link(sectionId, _, _):
return sectionId.rawValue
case let .inviteLinks(sectionId, _, _):
return sectionId.rawValue
case let .requests(sectionId, _, _):
return sectionId.rawValue
case let .discussion(sectionId, _, _, _):
return sectionId.rawValue
case let .reactions(sectionId, _, _, _, _):
return sectionId.rawValue
case let .discussionDesc(sectionId, _):
return sectionId.rawValue
case let .aboutInput(sectionId, _, _):
return sectionId.rawValue
case let .aboutDesc(sectionId, _):
return sectionId.rawValue
case let .signMessages(sectionId, _, _):
return sectionId.rawValue
case let .signDesc(sectionId, _):
return sectionId.rawValue
case let .report(sectionId, _):
return sectionId.rawValue
case let .leave(sectionId, _, _):
return sectionId.rawValue
case let .media(sectionId, _, _, _):
return sectionId.rawValue
case let .section(sectionId):
return sectionId
}
}
private var sortIndex: Int {
switch self {
case let .info(sectionId, _, _, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .setTitle(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .scam(sectionId, _, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .about(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .userName(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .admins(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .blocked(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .members(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .link(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .inviteLinks(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .requests(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .discussion(sectionId, _, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .reactions(sectionId, _, _, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .discussionDesc(sectionId, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .aboutInput(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .aboutDesc(sectionId, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .signMessages(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .signDesc(sectionId, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .report(sectionId, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .leave(sectionId, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .media(sectionId, _, _, _):
return (sectionId.rawValue * 1000) + stableIndex
case let .section(sectionId):
return (sectionId + 1) * 1000 - sectionId
}
}
func isOrderedBefore(_ entry: PeerInfoEntry) -> Bool {
guard let entry = entry as? ChannelInfoEntry else {
return false
}
return self.sortIndex < entry.sortIndex
}
func item(initialSize:NSSize, arguments:PeerInfoArguments) -> TableRowItem {
let arguments = arguments as! ChannelInfoArguments
switch self {
case let .info(_, peerView, editable, updatingPhotoState, viewType):
return PeerInfoHeadItem(initialSize, stableId: stableId.hashValue, context: arguments.context, arguments: arguments, peerView: peerView, threadData: nil, viewType: viewType, editing: editable, updatingPhotoState: updatingPhotoState, updatePhoto: arguments.updateChannelPhoto)
case let .scam(_, title, text, viewType):
return TextAndLabelItem(initialSize, stableId:stableId.hashValue, label: title, copyMenuText: strings().textCopy, labelColor: theme.colors.redUI, text: text, context: arguments.context, viewType: viewType, detectLinks:false)
case let .about(_, text, viewType):
return TextAndLabelItem(initialSize, stableId: stableId.hashValue, label: strings().peerInfoInfo, copyMenuText: strings().textCopyLabelAbout, text:text, context: arguments.context, viewType: viewType, detectLinks:true, openInfo: { peerId, toChat, postId, _ in
if toChat {
arguments.peerChat(peerId, postId: postId)
} else {
arguments.peerInfo(peerId)
}
}, hashtag: arguments.context.bindings.globalSearch)
case let .userName(_, value, viewType):
let link = "https://t.me/\(value[0])"
let text: String
if value.count > 1 {
text = strings().peerInfoUsernamesList("https://t.me/\(value[0])", value.suffix(value.count - 1).map { "@\($0)" }.joined(separator: ", "))
} else {
text = "@\(value[0])"
}
let interactions = TextViewInteractions()
interactions.processURL = { value in
if let value = value as? inAppLink {
arguments.copy(value.link)
}
}
interactions.localizeLinkCopy = globalLinkExecutor.localizeLinkCopy
return TextAndLabelItem(initialSize, stableId: stableId.hashValue, label: strings().peerInfoSharelink, copyMenuText: strings().textCopyLabelShareLink, labelColor: theme.colors.text, text: text, context: arguments.context, viewType: viewType, detectLinks: true, isTextSelectable: value.count > 1, callback: arguments.share, selectFullWord: true, _copyToClipboard: {
arguments.copy(link)
}, linkInteractions: interactions)
case let .report(_, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoReport, type: .none, viewType: viewType, action: { () in
arguments.report()
})
case let .members(_, count, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoSubscribers, icon: theme.icons.peerInfoMembers, type: .nextContext(count != nil && count! > 0 ? "\(count!)" : ""), viewType: viewType, action: arguments.members)
case let .admins(_, count, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoAdministrators, icon: theme.icons.peerInfoAdmins, type: .nextContext(count != nil && count! > 0 ? "\(count!)" : ""), viewType: viewType, action: arguments.admins)
case let .blocked(_, count, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoRemovedUsers, icon: theme.icons.profile_removed, type: .nextContext(count != nil && count! > 0 ? "\(count!)" : ""), viewType: viewType, action: arguments.blocked)
case let .link(_, addressName: addressName, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoChannelType, icon: theme.icons.profile_channel_type, type: .context(addressName.isEmpty ? strings().channelPrivate : strings().channelPublic), viewType: viewType, action: arguments.visibilitySetup)
case let .inviteLinks(_, count, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoInviteLinks, icon: theme.icons.profile_links, type: .nextContext(count > 0 ? "\(count)" : ""), viewType: viewType, action: arguments.openInviteLinks)
case let .requests(_, count, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoMembersRequest, icon: theme.icons.profile_requests, type: .badge(count > 0 ? "\(count)" : "", theme.colors.redUI), viewType: viewType, action: arguments.openRequests)
case let .discussion(_, group, _, viewType):
let title: String
if let group = group {
if let address = group.addressName {
title = "@\(address)"
} else {
title = group.displayTitle
}
} else {
title = strings().peerInfoDiscussionAdd
}
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoDiscussion, icon: theme.icons.profile_group_discussion, type: .nextContext(title), viewType: viewType, action: arguments.setupDiscussion)
case let .discussionDesc(_, viewType):
return GeneralTextRowItem(initialSize, stableId: stableId.hashValue, text: strings().peerInfoDiscussionDesc, viewType: viewType)
case let .reactions(_, text, allowedReactions, availableReactions, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoReactions, icon: theme.icons.profile_reactions, type: .nextContext(text), viewType: viewType, action: {
arguments.openReactions(allowedReactions: allowedReactions, availableReactions: availableReactions)
})
case let .setTitle(_, text, viewType):
return InputDataRowItem(initialSize, stableId: stableId.hashValue, mode: .plain, error: nil, viewType: viewType, currentText: text, placeholder: nil, inputPlaceholder: strings().peerInfoChannelTitlePleceholder, filter: { $0 }, updated: arguments.updateEditingName, limit: 255)
case let .aboutInput(_, text, viewType):
return InputDataRowItem(initialSize, stableId: stableId.hashValue, mode: .plain, error: nil, viewType: viewType, currentText: text, placeholder: nil, inputPlaceholder: strings().peerInfoAboutPlaceholder, filter: { $0 }, updated: arguments.updateEditingDescriptionText, limit: 255)
case let .aboutDesc(_, viewType):
return GeneralTextRowItem(initialSize, stableId: stableId.hashValue, text: strings().channelDescriptionHolderDescrpiton, viewType: viewType)
case let .signMessages(_, sign, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: strings().peerInfoSignMessages, icon: theme.icons.profile_channel_sign, type: .switchable(sign), viewType: viewType, action: { [weak arguments] in
arguments?.toggleSignatures(!sign)
})
case let .signDesc(_, viewType):
return GeneralTextRowItem(initialSize, stableId: stableId.hashValue, text: strings().peerInfoSignMessagesDesc, viewType: viewType)
case let .leave(_, isCreator, viewType):
return GeneralInteractedRowItem(initialSize, stableId: stableId.hashValue, name: isCreator ? strings().peerInfoDeleteChannel : strings().peerInfoLeaveChannel, nameStyle:redActionButton, type: .none, viewType: viewType, action: arguments.delete)
case let .media(_, controller, isVisible, viewType):
return PeerMediaBlockRowItem(initialSize, stableId: stableId.hashValue, controller: controller, isVisible: isVisible, viewType: viewType)
case .section(_):
return GeneralRowItem(initialSize, height:30, stableId: stableId.hashValue, viewType: .separator)
}
}
}
enum ChannelInfoSection : Int {
case header = 1
case desc = 2
case info = 3
case type = 4
case sign = 5
case manage = 6
case addition = 7
case destruct = 8
case media = 9
}
func channelInfoEntries(view: PeerView, arguments:PeerInfoArguments, mediaTabsData: PeerMediaTabsData, inviteLinksCount: Int32, joinRequestsCount: Int32, availableReactions: AvailableReactions?) -> [PeerInfoEntry] {
let arguments = arguments as! ChannelInfoArguments
var state:ChannelInfoState {
return arguments.state as! ChannelInfoState
}
var entries: [ChannelInfoEntry] = []
var infoBlock:[ChannelInfoEntry] = []
func applyBlock(_ block:[ChannelInfoEntry]) {
var block = block
for (i, item) in block.enumerated() {
block[i] = item.withUpdatedViewType(bestGeneralViewType(block, for: i))
}
entries.append(contentsOf: block)
}
infoBlock.append(.info(sectionId: .header, peerView: view, editable: state.editingState != nil, updatingPhotoState: state.updatingPhotoState, viewType: .singleItem))
if let channel = peerViewMainPeer(view) as? TelegramChannel {
if let editingState = state.editingState {
if channel.hasPermission(.changeInfo) {
infoBlock.append(.setTitle(sectionId: .header, text: editingState.editingName ?? "", viewType: .singleItem))
}
if channel.hasPermission(.changeInfo) && !channel.isScam && !channel.isFake {
infoBlock.append(.aboutInput(sectionId: .header, description: editingState.editingDescriptionText, viewType: .singleItem))
}
applyBlock(infoBlock)
entries.append(.aboutDesc(sectionId: .header, viewType: .textBottomItem))
if channel.adminRights != nil || channel.flags.contains(.isCreator) {
var block: [ChannelInfoEntry] = []
if channel.flags.contains(.isCreator) {
block.append(.link(sectionId: .type, addressName: channel.username ?? "", viewType: .singleItem))
}
let group: Peer?
if let cachedData = view.cachedData as? CachedChannelData, let linkedDiscussionPeerId = cachedData.linkedDiscussionPeerId.peerId {
group = view.peers[linkedDiscussionPeerId]
} else {
group = nil
}
if channel.canInviteUsers {
block.append(.inviteLinks(section: .type, count: inviteLinksCount, viewType: .singleItem))
if joinRequestsCount > 0 {
block.append(.requests(section: .type, count: joinRequestsCount, viewType: .singleItem))
}
}
if channel.groupAccess.canEditGroupInfo {
let cachedData = view.cachedData as? CachedChannelData
let text: String
if let allowed = cachedData?.allowedReactions.knownValue, let availableReactions = availableReactions {
switch allowed {
case .all:
text = strings().peerInfoReactionsAll
case let .limited(count):
if count.count != availableReactions.enabled.count {
text = strings().peerInfoReactionsPart("\(count.count)", "\(availableReactions.enabled.count)")
} else {
text = strings().peerInfoReactionsAll
}
case .empty:
text = strings().peerInfoReactionsDisabled
}
} else {
text = strings().peerInfoReactionsAll
}
block.append(.reactions(section: .type, text: text, allowedReactions: cachedData?.allowedReactions.knownValue, availableReactions: availableReactions, viewType: .singleItem))
block.append(.discussion(sectionId: .type, group: group, participantsCount: nil, viewType: .singleItem))
}
applyBlock(block)
if channel.adminRights?.rights.contains(.canChangeInfo) == true {
entries.append(.discussionDesc(sectionId: .type, viewType: .textBottomItem))
}
}
let messagesShouldHaveSignatures:Bool
switch channel.info {
case let .broadcast(info):
messagesShouldHaveSignatures = info.flags.contains(.messagesShouldHaveSignatures)
default:
messagesShouldHaveSignatures = false
}
if channel.hasPermission(.changeInfo) {
entries.append(.signMessages(sectionId: .sign, sign: messagesShouldHaveSignatures, viewType: .singleItem))
entries.append(.signDesc(sectionId: .sign, viewType: .textBottomItem))
}
if channel.flags.contains(.isCreator) {
entries.append(.leave(sectionId: .destruct, isCreator: channel.flags.contains(.isCreator), viewType: .singleItem))
}
} else {
applyBlock(infoBlock)
var aboutBlock:[ChannelInfoEntry] = []
if channel.isScam {
aboutBlock.append(.scam(sectionId: .desc, title: strings().peerInfoScam, text: strings().channelInfoScamWarning, viewType: .singleItem))
} else if channel.isFake {
aboutBlock.append(.scam(sectionId: .desc, title: strings().peerInfoFake, text: strings().channelInfoFakeWarning, viewType: .singleItem))
}
if let cachedData = view.cachedData as? CachedChannelData {
if let about = cachedData.about, !about.isEmpty, !channel.isScam && !channel.isFake {
aboutBlock.append(.about(sectionId: .desc, text: about, viewType: .singleItem))
}
}
var usernames = channel.usernames.filter { $0.isActive }.map {
$0.username
}
if usernames.isEmpty, let address = channel.addressName {
usernames.append(address)
}
if !usernames.isEmpty {
aboutBlock.append(.userName(sectionId: .desc, value: usernames, viewType: .singleItem))
}
applyBlock(aboutBlock)
}
if channel.flags.contains(.isCreator) || channel.adminRights != nil {
var membersCount:Int32? = nil
var adminsCount:Int32? = nil
var blockedCount:Int32? = nil
if let cachedData = view.cachedData as? CachedChannelData {
membersCount = cachedData.participantsSummary.memberCount
adminsCount = cachedData.participantsSummary.adminCount
blockedCount = cachedData.participantsSummary.kickedCount
}
entries.append(.admins(sectionId: .manage, count: adminsCount, viewType: .firstItem))
entries.append(.members(sectionId: .manage, count: membersCount, viewType: .innerItem))
entries.append(.blocked(sectionId: .manage, count: blockedCount, viewType: .lastItem))
}
}
if mediaTabsData.loaded && !mediaTabsData.collections.isEmpty, let controller = arguments.mediaController() {
entries.append(.media(sectionId: ChannelInfoSection.media, controller: controller, isVisible: state.editingState == nil, viewType: .singleItem))
}
var items:[ChannelInfoEntry] = []
var sectionId:Int = 0
let sorted = entries.sorted(by: { (p1, p2) -> Bool in
return p1.isOrderedBefore(p2)
})
for entry in sorted {
if entry.sectionId != sectionId {
if entry.sectionId == ChannelInfoSection.media.rawValue {
sectionId = entry.sectionId
} else {
items.append(.section(sectionId))
sectionId = entry.sectionId
}
}
items.append(entry)
}
sectionId += 1
items.append(.section(sectionId))
return items
}
| gpl-2.0 | ad593564f77ab9cc2a248e9618830153 | 45.949377 | 377 | 0.59 | 5.550921 | false | false | false | false |
ymedialabs/Swift-Notes | Swift-Notes.playground/Pages/19. Protocols.xcplaygroundpage/Contents.swift | 1 | 8623 | //: # Swift Foundation
//: ----
//: ## Protocols
//: A ***protocol*** defines a blueprint of methods, properties and other functionalities, which can be adopted by a class, structure or enumerations to provide an actual implementation of the requirements.
//: ## Syntax
/*:
protocol SomeProtocol {
//protocol definition
}
//Adopting a protocol.
struct SomeStruct: SomeProtocol {
}
//List superclass name before protocols.
class SomeClass: SuperClass, SomeProtocol, AnotherProtocol {
}
*/
protocol Fuel {
var fuelType: String {get set} //Read-write property
func addFuel() //some method
}
protocol Name {
var name: String {get} //read-only property
var manufacturer: String {get} //read-only property
}
struct Car: Name, Fuel {
let name: String
var manufacturer: String
var fuelType: String
func addFuel() {
//some code.
}
}
//Note that it is mandatory to fulfill all of protocol's requirements.
var swiftCar = Car(name: "Swift", manufacturer: "Maruti Suzuki", fuelType: "Diesel")
struct Rocket: Name, Fuel {
let name: String
var manufacturer: String
var fuelType: String
func addFuel() {
//some code.
}
}
var falcon = Rocket(name: "Falcon", manufacturer: "SpaceX", fuelType: "Rocket Fuel")
//: ## 📖
/*:
* Property requirements are always declared as variable properties, prefixed with the var keyword.
* If a protocol requires a property to be gettable and settable, that property requirement cannot be fulfilled by a constant stored property or a read-only computed property.
* If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it is valid for the property to be also settable if this is useful for your own code.
*/
falcon.manufacturer = "Telsa"
falcon.manufacturer
//Type property requirements
protocol SomeProtocol {
static var someProperty: Int {get}
}
//: ## 📖
//: Always prefix type property requirements with `static` keyword inside a protocol.
//: ### Mutating method requirements
//: If you define a protocol instance method requirement that is intended to mutate instances of any type that adopts the protocol, mark the method with the mutating keyword as part of the protocol’s definition.
protocol ChangeDirection {
mutating func change()
}
enum Direction: ChangeDirection {
case Forward, Reverse
mutating func change() {
switch self {
case .Forward:
self = .Reverse
case .Reverse :
self = .Forward
}
}
}
var carDirection = Direction.Forward
carDirection.change()
//: ### Initializer requirements
//: You can implement a protocol initializer requirement on a conforming class as either a designated initializer or a convenience initializer. In both cases, you must mark the initializer implementation with the `required` modifier.
protocol AnotherProtocol {
init(name: String)
}
struct SomeStruct: AnotherProtocol {
init(name: String){
}
}
class SomeClass: AnotherProtocol {
required init(name: String) {
}
}
let foo = SomeStruct(name: "Foo")
let bar = SomeClass(name: "Bar")
//: ## 📖
/*:
* `required` ensures that on all subclasses of `SomeClass`, you provide an implementation of the initializer requirement, so the the protocol requirement is fulfilled.
* Therefore, you do not need to mark protocol initializer implementations with the `required` modifier on classes that are marked with the `final` modifier, since `final` classes cannot be subclassed.
*/
//In case the initializer from the superclass matches the initializer from protocol, mark it with both override and required modifiers.
protocol YetAnotherProtocol {
init()
}
class SomeSuperClass {
init() {
// initializer implementation goes here
}
}
class SomeSubClass: SomeSuperClass, YetAnotherProtocol {
// "required" from SomeProtocol conformance; "override" from SomeSuperClass
required override init() {
// initializer implementation goes here
}
}
//: ### Protocols as Types
//: Any protocol is a full-fledged type.
protocol MyProtocol {
func quote() -> String
}
class MyClass {
var protocolVariable: MyProtocol
init(fooBar: MyProtocol){
protocolVariable = fooBar
}
func anotherMethod() -> String{
return protocolVariable.quote()
}
}
class SomeOtherClass: MyProtocol {
func quote() -> String {
return "You know nothing"
}
}
let classA = SomeOtherClass()
let classB = MyClass(fooBar: classA)
classB.anotherMethod()
//: ### Delegation
//: ***Delegation*** is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type.
//: Delegation can be used to respond to a particular action, or to retrieve data from an external source without needing to know the underlying type of that source.
protocol TableViewDataSource {
func numberOfRows() -> Int
}
class TableView {
var dataSource: TableViewDataSource?
func renderTableView(){
let rowCount = dataSource?.numberOfRows()
print("Rows : \(rowCount)")
}
}
struct MyDataSource: TableViewDataSource {
func numberOfRows() -> Int {
return 6
}
}
let data = MyDataSource()
let table = TableView()
table.dataSource = data
table.renderTableView()
//: ### Protocol Extensions
// Existing types can be extendede to adopt and conform to a protocol.
protocol DescriptionProtocol {
func printDescription() -> String
}
extension TableView: DescriptionProtocol {
func printDescription() -> String {
return "Table View Class"
}
}
extension Int: DescriptionProtocol{
func printDescription() -> String {
return "Int Type"
}
}
let someInt = 3
someInt.printDescription()
//: ## 📖
//: Types do not automatically adopt a protocol just by satisfying its requirements. They must always explicitly declare their adoption of the protocol.
//: So if a type already conforms to all of a protocol requirements, but has not declared that it adopts that protocol, you can make it adopt the protocl with an empty extension.
struct AnotherStruct {
func printDescription() -> String {
return "AnotherStruct Type"
}
}
extension AnotherStruct: DescriptionProtocol { } //Compiler doesn't complain as the struct has already adopted to the protocol.
//: ### Collections of Protocol Types
//: Protocols can be stored in collection such as Array or Dictionary just like any other types.
let fooBar = AnotherStruct()
let conformedTypes: [DescriptionProtocol] = [someInt, table, fooBar]
for type in conformedTypes {
type.printDescription()
}
//: ## Protocol Inheritance
//: Protocols can inherit from one or more other protocols and can add further requirements in top of the requirements it inherits.
//: Syntax
/*:
protocol ProtocolC: ProtocolA, ProtocolB {
}
*/
protocol PrettyDescription: DescriptionProtocol {
func printPrettyDescription() -> String
}
extension AnotherStruct: PrettyDescription {
func printPrettyDescription() -> String {
return "This is AnotherStruct. Oh yeah!"
}
}
fooBar.printPrettyDescription()
extension Double: PrettyDescription {
func printPrettyDescription() -> String {
return "This is Double. Oh yeah!"
}
func printDescription() -> String {
return "Double Type"
}
}
//: ## 📖
//: It is required to implement `printDescription()` method to satisfy the `PrettyDescription` protocol since it inherits from `DescriptionProtocol`.
//: ### Class-Only Protocols
//: Protocols can limit iteself to be conformed only by Class types and not by Structures or Enumerations. It can be done by adding the `class` keyword to the protocol's inheritance list. The `class` keyword must appear first in inheritance list.
protocol ClassyProtocol: class {
}
class MyAnotherClass: ClassyProtocol {
}
//struct MyAnotherStruct: ClassyProtocol { } //❌ Compile time ERROR !!
//: ## Protocol Composition
//: Multiple protocols can be combined into a singe requirement. Protocol compositions have the form `protocol<Protocol1, Protocol
protocol ProtocolA { }
protocol ProtocolB { }
struct StructA: ProtocolA, ProtocolB {
}
func someMethod(prettyTypes:protocol<ProtocolA, ProtocolB>) {
}
let jarjar = StructA()
someMethod(jarjar)
let anakin = MyAnotherClass()
//someMethod(anakin)
//: ----
//: [Next](@next)
| mit | 87b87d33eda2e32e56b746521d8903e7 | 24.231672 | 246 | 0.702464 | 4.528421 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.