repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
koba-uy/chivia-app-ios | refs/heads/master | src/Pods/MapboxCoreNavigation/MapboxCoreNavigation/SpokenDistanceFormatter.swift | lgpl-3.0 | 1 | import CoreLocation
/// Provides appropriately formatted, localized descriptions of linear distances for voice use.
@objc(MBSpokenDistanceFormatter)
public class SpokenDistanceFormatter: DistanceFormatter {
/**
Returns a more human readable `String` from a given `CLLocationDistance`.
The user’s `Locale` is used here to set the units.
*/
public override func string(from distance: CLLocationDistance) -> String {
// British roads are measured in miles, yards, and feet. Simulate this idiosyncrasy using the U.S. locale.
let localeIdentifier = numberFormatter.locale.identifier
if localeIdentifier == "en-GB" || localeIdentifier == "en_GB" {
numberFormatter.locale = Locale(identifier: "en-US")
}
var unit: LengthFormatter.Unit = .millimeter
unitString(fromMeters: distance, usedUnit: &unit)
let replacesYardsWithMiles = unit == .yard && distance.miles > 0.2
let showsMixedFraction = (unit == .mile && distance.miles < 10) || replacesYardsWithMiles
// An elaborate hack to use vulgar fractions with miles regardless of
// language.
if showsMixedFraction {
numberFormatter.positivePrefix = "|"
numberFormatter.positiveSuffix = "|"
numberFormatter.decimalSeparator = "!"
numberFormatter.alwaysShowsDecimalSeparator = true
} else {
numberFormatter.positivePrefix = ""
numberFormatter.positiveSuffix = ""
numberFormatter.decimalSeparator = nonFractionalLengthFormatter.numberFormatter.decimalSeparator
numberFormatter.alwaysShowsDecimalSeparator = nonFractionalLengthFormatter.numberFormatter.alwaysShowsDecimalSeparator
}
numberFormatter.usesSignificantDigits = false
numberFormatter.maximumFractionDigits = maximumFractionDigits(for: distance)
numberFormatter.roundingIncrement = roundingIncrement(for: distance, unit: unit) as NSNumber
var distanceString = formattedDistance(distance, modify: &unit)
// Elaborate hack continued.
if showsMixedFraction {
var parts = distanceString.components(separatedBy: "|")
assert(parts.count == 3, "Positive format should’ve inserted two pipe characters.")
var numberParts = parts[1].components(separatedBy: "!")
assert(numberParts.count == 2, "Decimal separator should be present.")
let decimal = Int(numberParts[0])
if let fraction = Double(".\(numberParts[1])0") {
let fourths = Int(round(fraction * 4))
if fourths == fourths % 4 {
if decimal == 0 && fourths != 0 {
numberParts[0] = ""
}
var vulgarFractions = ["", "¼", "½", "¾"]
if Locale.current.languageCode == "en" {
vulgarFractions = ["", "a quarter", "a half", "3 quarters"]
if numberParts[0].isEmpty {
parts[2] = " \(unitString(fromValue: 1, unit: unit)) "
if fourths == 3 {
parts[2] = " of a\(parts[2])"
}
}
}
numberParts[1] = vulgarFractions[fourths]
if !numberParts[0].isEmpty && !numberParts[1].isEmpty {
numberParts[0] += " & "
}
parts[1] = numberParts.joined(separator: "")
} else {
parts[1] = numberParts.joined(separator: nonFractionalLengthFormatter.numberFormatter.decimalSeparator)
}
} else {
parts[1] = numberParts.joined(separator: nonFractionalLengthFormatter.numberFormatter.decimalSeparator)
}
distanceString = parts.joined(separator: "")
}
return distanceString
}
}
| f2a376ba8edfd60415c5f91fe60573ea | 46.511628 | 130 | 0.578561 | false | false | false | false |
danielgindi/Charts | refs/heads/master | ChartsDemo-iOS/Swift/Demos/StackedBarChartViewController.swift | apache-2.0 | 2 | //
// StackedBarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
class StackedBarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: BarChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
lazy var formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.negativeSuffix = " $"
formatter.positiveSuffix = " $"
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Stacked Bar Chart"
self.options = [.toggleValues,
.toggleIcons,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData,
.toggleBarBorders]
chartView.delegate = self
chartView.chartDescription.enabled = false
chartView.maxVisibleCount = 40
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = false
chartView.highlightFullBarEnabled = false
let leftAxis = chartView.leftAxis
leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: formatter)
leftAxis.axisMinimum = 0
chartView.rightAxis.enabled = false
let xAxis = chartView.xAxis
xAxis.labelPosition = .top
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.drawInside = false
l.form = .square
l.formToTextSpace = 4
l.xEntrySpace = 6
// chartView.legend = l
sliderX.value = 12
sliderY.value = 100
slidersValueChanged(nil)
self.updateChartData()
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setChartData(count: Int(sliderX.value + 1), range: UInt32(sliderY.value))
}
func setChartData(count: Int, range: UInt32) {
let yVals = (0..<count).map { (i) -> BarChartDataEntry in
let mult = range + 1
let val1 = Double(arc4random_uniform(mult) + mult / 3)
let val2 = Double(arc4random_uniform(mult) + mult / 3)
let val3 = Double(arc4random_uniform(mult) + mult / 3)
return BarChartDataEntry(x: Double(i), yValues: [val1, val2, val3], icon: #imageLiteral(resourceName: "icon"))
}
let set = BarChartDataSet(entries: yVals, label: "Statistics Vienna 2014")
set.drawIconsEnabled = false
set.colors = [ChartColorTemplates.material()[0], ChartColorTemplates.material()[1], ChartColorTemplates.material()[2]]
set.stackLabels = ["Births", "Divorces", "Marriages"]
let data = BarChartData(dataSet: set)
data.setValueFont(.systemFont(ofSize: 7, weight: .light))
data.setValueFormatter(DefaultValueFormatter(formatter: formatter))
data.setValueTextColor(.white)
chartView.fitBars = true
chartView.data = data
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
updateChartData()
}
}
| 150441e00c33233f4a237a929b144fd3 | 31.228346 | 126 | 0.583924 | false | false | false | false |
mattwelborn/HSTracker | refs/heads/master | HSTracker/Statistics/LadderGrid.swift | mit | 1 | //
// LadderGrid.swift
// HSTracker
//
// Created by Matthew Welborn on 6/25/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import SQLite
import CleanroomLogger
// Reads precomputed Monte Carlo data from grid.db
// TODO: run long simulation on cluster for better grid
struct LadderGrid {
var db: Connection?
let grid = Table("grid")
let colTargetRank = Expression<Int64>("target_rank")
let colStars = Expression<Int64>("stars")
let colBonus = Expression<Int64>("bonus")
let colWinp = Expression<Double>("winp")
let colGames = Expression<Double>("games")
init() {
do {
// TODO: put the db in the bundle
let path = NSBundle.mainBundle().resourcePath! + "/Resources/grid.db"
Log.verbose?.message("Loading grid at \(path)")
db = try Connection(path, readonly: true)
} catch {
db = nil
// swiftlint:disable line_length
Log.warning?.message("Failed to load grid db! Will result in Ladder stats tab not working.")
// swiftlint:enable line_length
}
}
func getGamesToRank(targetRank: Int, stars: Int, bonus: Int, winp: Double) -> Double? {
guard let dbgood = db
else { return nil }
let query = grid.select(colGames)
.filter(colTargetRank == Int64(targetRank))
.filter(colStars == Int64(stars))
.filter(colBonus == Int64(bonus))
// Round to nearest hundredth
let lowerWinp = Double(floor(winp*100)/100)
let upperWinp = Double(ceil(winp*100)/100)
let lower = query.filter(colWinp == lowerWinp)
let upper = query.filter(colWinp == upperWinp)
guard let lowerResult = dbgood.pluck(lower), upperResult = dbgood.pluck(upper)
else { return nil }
let l = lowerResult[colGames]
let u = upperResult[colGames]
// Linear interpolation
if lowerWinp == upperWinp {
return l
} else {
return l * ( 1 - ( winp - lowerWinp) / 0.01) + u * (winp - lowerWinp)/0.01
}
}
}
| 68f98609427f3f9e995eb36a3bf92b06 | 31.086957 | 104 | 0.583559 | false | false | false | false |
cafbuddy/cafbuddy-iOS | refs/heads/master | Caf Buddy/MySignupViewController.swift | mit | 1 | //
// MySignupViewController.swift
// CafMate
//
// Created by Jacob Forster on 11/9/14.
// Copyright (c) 2014 St. Olaf ACM. All rights reserved.
//
import Foundation
import UIKit
class MySignUpViewController : PFSignUpViewController
{
let screenSize: CGRect = UIScreen.mainScreen().bounds
var label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = colorWithHexString(COLOR_MAIN_BACKGROUND_OFFWHITE)
//change the logo
/*label.text = "Caf Buddy"
label.font = UIFont(name: "HoeflerText-BlackItalic", size: 60)
label.sizeToFit()
label.textAlignment = NSTextAlignment.Center*/
var hamburger = UIImageView(image: UIImage(named: "cafbuddylogo"))
self.signUpView.logo = hamburger
}
override func viewDidAppear(animated: Bool) {
//self.logInView.logInButton.layer.cornerRadius = 3.0
//self.logInView.signUpButton.backgroundColor = UIColor.blueColor()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let screenSize: CGRect = UIScreen.mainScreen().bounds
//redo the log-in fields
self.signUpView.signUpButton.frame = CGRectMake((screenSize.width - CGFloat(BUTTON_WIDTH))/2, self.signUpView.signUpButton.frame.origin.y + 35, CGFloat(BUTTON_WIDTH), self.signUpView.signUpButton.frame.height)
self.signUpView.usernameField.frame = CGRectMake((screenSize.width - CGFloat(BUTTON_WIDTH))/2, self.signUpView.usernameField.frame.origin.y - 10, CGFloat(BUTTON_WIDTH), self.signUpView.usernameField.frame.height + 10)
self.signUpView.usernameField.layer.cornerRadius = 4.0
self.signUpView.passwordField.frame = CGRectMake((screenSize.width - CGFloat(BUTTON_WIDTH))/2, self.signUpView.passwordField.frame.origin.y + 10, CGFloat(BUTTON_WIDTH), self.signUpView.passwordField.frame.height + 10)
self.signUpView.passwordField.layer.cornerRadius = 4.0
self.signUpView.emailField.frame = CGRectMake((screenSize.width - CGFloat(BUTTON_WIDTH))/2, self.signUpView.emailField.frame.origin.y + 30, CGFloat(BUTTON_WIDTH), self.signUpView.emailField.frame.height + 10)
self.signUpView.emailField.layer.cornerRadius = 4.0
self.signUpView.logo.frame = CGRectMake((CGFloat(screenSize.width) - 200)/2,screenSize.height/120, 200, 200)
self.signUpView.signUpButton.setBackgroundImage(nil, forState: UIControlState.Normal)
self.signUpView.signUpButton.backgroundColor = colorWithHexString(COLOR_ACCENT_BLUE)
self.signUpView.signUpButton.layer.cornerRadius = 4.0
//get rid of dismiss button
/*self.logInView.logo.frame = CGRectMake(0, 75, screenSize.width, 100)
self.logInView.logInButton.layer.cornerRadius = 5.0*/
}
}
| 739c755c08a2d523b396b14412bdc331 | 42.279412 | 225 | 0.687734 | false | false | false | false |
smoope/swift-client-conversation | refs/heads/master | Framework/Source/ConversationView.swift | apache-2.0 | 1 | //
// Copyright 2017 smoope GmbH
//
// 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
internal enum ConversationViewElementKind: String {
case headLoading = "head-loading"
case headText = "head-text"
case avatar = "avatar"
case detail = "detail"
case unknown = "unknown"
init(_ rawValue: RawValue) {
let value = ConversationViewElementKind(rawValue: rawValue)
self = value ?? .unknown
}
}
extension ConversationViewElementKind: ExpressibleByStringLiteral {
init(stringLiteral value: String) {
self.init(value)
}
init(unicodeScalarLiteral value: String) {
self.init(value)
}
init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
}
public class ConversationView: UICollectionView {
public dynamic var nativeBackgroundColor: UIColor? {
didSet {
nativeTextColor = nativeBackgroundColor?.legibleTextColor ?? .darkText
}
}
public dynamic var foreignBackgroundColor: UIColor? {
didSet {
foreignTextColor = foreignBackgroundColor?.legibleTextColor ?? .darkText
}
}
public dynamic var actionColor: UIColor? {
didSet {
tintColor = actionColor
actionTextColor = actionColor?.legibleTextColor ?? .white
}
}
public dynamic var isCalendarEventDetectorDisabled: Bool = false
internal var nativeTextColor: UIColor = .darkText
internal var foreignTextColor: UIColor = .darkText
internal var actionTextColor: UIColor = .white
internal var messageBackgroundImage: UIImage? = UIImage(named: "filled-background-16", in: Bundle(for: ConversationView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
internal var messageBackgroundInset: UIEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
internal var isLoadingNew: Bool = false
internal var triggeredLoadNewCount: Int = 0
internal var isLoadingMore: Bool = false
internal var wasLoadingMore: Bool = false
// MARK: ui variables
internal var canLoadMore: Bool = true {
didSet {
guard canLoadMore != oldValue else { return }
collectionViewLayout.invalidateLayout()
}
}
internal var wasErrorOnLoadMore: Bool = false {
didSet {
guard wasErrorOnLoadMore != oldValue else { return }
collectionViewLayout.invalidateLayout()
}
}
internal var dataDetectorTypes: UIDataDetectorTypes = [.address, .calendarEvent, .link, .phoneNumber]
// MARK: -
internal override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
internal func commonInit() {
nativeBackgroundColor = ConversationView.appearance().nativeBackgroundColor
?? UIColor(colorLiteralRed: 0, green: 150/255, blue: 136/255, alpha: 1)
foreignBackgroundColor = ConversationView.appearance().foreignBackgroundColor
?? UIColor(white: 0.86, alpha: 1)
actionColor = ConversationView.appearance().actionColor
?? actionColor
?? tintColor
isCalendarEventDetectorDisabled = ConversationView.appearance().isCalendarEventDetectorDisabled
registerCellTypes()
reassingDataDetectorTypes()
}
internal func registerCellTypes() {
register(TextCell.self, forCellWithReuseIdentifier: "text")
register(PreviewCell.self, forCellWithReuseIdentifier: "preview")
register(FileCell.self, forCellWithReuseIdentifier: "file")
register(SingleChoiceCell.self, forCellWithReuseIdentifier: "smoope.choice.single")
register(URLButtonsCell.self, forCellWithReuseIdentifier: "smoope.url.buttons")
register(TextSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.headText.rawValue,
withReuseIdentifier: ConversationViewElementKind.headText.rawValue)
register(LoadingSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.headLoading.rawValue,
withReuseIdentifier: ConversationViewElementKind.headLoading.rawValue)
register(RoundAvatarSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.avatar.rawValue,
withReuseIdentifier: ConversationViewElementKind.avatar.rawValue)
register(_MsgAuthorTimeSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.detail.rawValue,
withReuseIdentifier: ConversationViewElementKind.detail.rawValue)
}
internal func reassingDataDetectorTypes() {
var types: UIDataDetectorTypes = [.address, .calendarEvent, .link, .phoneNumber]
isCalendarEventDetectorDisabled ? types.subtract(.calendarEvent) : types.formUnion(.calendarEvent)
dataDetectorTypes = types
}
internal func reloadDataWithoutMoving() {
reloadData()
layoutIfNeeded()
contentOffset = collectionViewLayout.targetContentOffset(forProposedContentOffset: contentOffset)
}
internal func scrollTo(indexPath: IndexPath, animated: Bool) {
guard let frame = layoutAttributesForSupplementaryElement(ofKind: "detail", at: indexPath)?.frame else { return }
scrollRectToVisible(frame, animated: animated)
}
internal func updateDetailLabels(_ indexPaths: [IndexPath]) {
for indexPath in indexPaths {
if let sup = supplementaryView(forElementKind: ConversationViewElementKind.detail.rawValue, at: indexPath) {
delegate?.collectionView?(self,
willDisplaySupplementaryView: sup,
forElementKind: ConversationViewElementKind.detail.rawValue,
at: indexPath)
}
}
}
}
internal protocol ConversationTrait {
var nativeBackgroundColor: UIColor? { get }
var foreignBackgroundColor: UIColor? { get }
var nativeTextColor: UIColor { get }
var foreignTextColor: UIColor { get }
var actionColor: UIColor? { get }
}
extension ConversationView: ConversationTrait { }
| e5750f47bba7e6d73a22abb77a12b260 | 34.404878 | 187 | 0.662166 | false | false | false | false |
lucasleelz/LemoniOS | refs/heads/master | LemoniOS/Classes/profile/ViewControllers/ProfileViewController.swift | mit | 2 | //
// ProfileViewController.swift
// lemon-oa-ios
//
// Created by lucas on 15/3/25.
// Copyright (c) 2015年 三只小猪. All rights reserved.
//
import UIKit
class ProfileViewController: UITableViewController {
private static let cellIdentifier = "ProfileCell"
lazy var profileItems: [ProfileItem] = {
var results = [ProfileItem]()
results.append(ProfileItem(withAvatarURLString: "avatar_default", name: "lucaslee"))
results.append(ProfileItem(withAvatarURLString: "", name: "设置"))
results.append(ProfileItem(withAvatarURLString: "", name: "意见反馈"))
results.append(ProfileItem(withAvatarURLString: "", name: "关于 Lemon"))
return results
}()
override func viewDidLoad() {
super.viewDidLoad()
}
}
// MARK: - UITableViewDataSource
extension ProfileViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.profileItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: ProfileViewController.cellIdentifier, for: indexPath)
}
}
// MARK: - UITableViewDelegate
extension ProfileViewController {
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let profile = self.profileItems[indexPath.row]
cell.imageView?.image = UIImage(named: profile.avatarURLString)
cell.textLabel?.text = profile.name
}
override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.imageView?.image = nil;
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
defer {
tableView .deselectRow(at: indexPath, animated: true)
}
guard let navigationController = navigationController
where navigationController.topViewController == self else {
return
}
// dosomething.
}
}
| d7df5611252cc437fb7d4c11867f693d | 30.608696 | 126 | 0.679505 | false | false | false | false |
SeptAi/Cooperate | refs/heads/master | Cooperate/Cooperate/Class/ViewModel/ProjectViewModel.swift | mit | 1 | //
// HomeViewModel.swift
// Cooperate
//
// Created by J on 2017/1/4.
// Copyright © 2017年 J. All rights reserved.
//
import Foundation
/*
1.与Model直接交互,并封装单条数据的所有业务逻辑
2.将数据包装到List中
*/
/*
表格性能优化
1.减少计算,素材提前计算好
2.控件不要设置圆角半径
3.不要动态创建控件。提前创建-判断是够显示
4.cell中控件的层次、数量减少
5.进行测量(速度、内存、CPU)
*/
// 协议:CustomStringConvertible--实现var description:String{}
class ProjectViewModel: CustomStringConvertible {
// 项目模型
var project:Project
// 用户图标 - 存储型属性(内存换取cpu)
var userIcon:String?
// 会员图标 - 预留
var memberIcon:UIImage?
// 标题
var title:String?
// 时间提示
var timeAt:Date?{
didSet{
guard let time = timeAt?.description.components(separatedBy: " ") else {
return
}
if time.count >= 2 {
timeDay = time[0]
timeNow = time[1]
}
}
}
var timeDay:String = " "
var timeNow:String = " "
// 用户名
var name:String?
// 正文的属性文本
var normalAttrText:NSAttributedString?
// 转发、点赞、评论 文字
var retweetedStr:String?
var commentStr:String?
var likeStr:String?
// 配图视图的大小
var pictureViewSize = CGSize()
// 配图
var picUrls:[ProjectPicture]?{
return project.pic_urls
}
// 行高
var rowHeight:CGFloat = 0
init(model:Project) {
self.project = model
userIcon = model.user?.avatar_hd
title = model.title
// 在初始化的时候赋值,是不调用didSet方法的。
timeAt = model.time
name = model.user?.screen_name
// 设置底部计数
retweetedStr = countString(count: model.reposts_count, defaultStr: " 转发")
commentStr = countString(count: model.comments_count, defaultStr: " 评论")
likeStr = countString(count: model.attitudes_count, defaultStr: " 赞")
// 计算配图的大小(有原创就计算原创的。转发计算转发的)
pictureViewSize = calcPictureViewSize(count: (picUrls?.count) ?? 0)
// 字体
let normalFont = UIFont.systemFont(ofSize:15)
// FIXME: - 表情
normalAttrText = NSAttributedString(string: model.content ?? " ", attributes: [NSFontAttributeName:normalFont,NSForegroundColorAttributeName:UIColor.darkGray])
// 计算行高
updateRowHeight()
}
// 根据当前模型内容计算行高
func updateRowHeight(){
// 使用位置:构造函数末尾、更新单图
let margin:CGFloat = 12
let iconHeight:CGFloat = 34
let toolbarHeight:CGFloat = 35
let viewSize = CGSize(width: UIScreen.cz_screenWidth() - 2 * margin, height: CGFloat(MAXFLOAT))
var height:CGFloat = 0
// 1.计算顶部位置
height = 2 * margin + iconHeight + margin
// 2.正文高度 -- 属性文本
if let text = normalAttrText {
// 属性文本默认包含字体属性
// size 宽度固定,高度自动填满(高度尽量大) usesLineFragmentOrigin换行文本
height += text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height
//height += (text as NSString).boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName:originalFont], context: nil).height
}
// 4.配图视图
height += pictureViewSize.height
height += margin
// 5.底部工具栏
height += toolbarHeight
// 使用属性记录 “1”表示视图压缩后占据的高度
rowHeight = height + 1
}
// 使用单个图像时,更新配图视图的大小
func updateSingleImageSize(image:UIImage){
var size = image.size
// 过宽图像处理
let maxWidth:CGFloat = 200
let minWidth:CGFloat = 40
if size.width > maxWidth {
size.width = maxWidth
// 等比例调整高度
size.height = size.width * image.size.height / image.size.width
}
// 过窄图像处理
if size.width < minWidth {
size.width = minWidth
// 高度特殊处理 - 否则过长
size.height = size.width * image.size.height / image.size.width / 4
}
// 过高图片处理,高度减小,会自动裁切
if size.height > 200{
size.height = 200
}
// 特类:存在本身过长、过窄的图像(定义minHeight)
size.height += StatusPictureViewOutterMargin
// 重新设置视图配图大小
pictureViewSize = size
updateRowHeight()
}
var description: String{
return project.description
}
// 根据配数量判断大小
private func calcPictureViewSize(count:Int?) -> CGSize{
if count == 0 || count == nil{
return CGSize()
}
// 1. 配图视图的宽度
// 2. 计算高度
// 根据count知道行数
let row = (count! - 1) / 3 + 1
// 行数计算高度
var height = StatusPictureViewOutterMargin
height += CGFloat(row) * StatusPictureItemWidth
height += CGFloat(row + 1) * StatusPictureViewINnnerMargin
return CGSize(width: StatusPictureViewWidth, height: height)
}
// 给定数字进行描述
private func countString(count:Int,defaultStr:String) -> String{
if count == 0 {
return defaultStr
}
if count < 10000 {
return count.description
}
return String(format: "%.02f 万", Double(count / 10000))
}
}
| e2909614a33e58f41f006cabb37fcaf5 | 25.75 | 176 | 0.559603 | false | false | false | false |
apple/swift-format | refs/heads/main | Sources/SwiftFormatCore/SyntaxLintRule.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 Foundation
import SwiftSyntax
/// A rule that lints a given file.
open class SyntaxLintRule: SyntaxVisitor, Rule {
/// Whether this rule is opt-in, meaning it's disabled by default. Rules are opt-out unless they
/// override this property.
open class var isOptIn: Bool {
return false
}
/// The context in which the rule is executed.
public let context: Context
/// Creates a new rule in a given context.
public required init(context: Context) {
self.context = context
super.init(viewMode: .sourceAccurate)
}
}
| 8454591aca3d4dce58cfcc5938c9cfb1 | 32.4375 | 98 | 0.614953 | false | false | false | false |
js/WaddaColor | refs/heads/master | WaddaColor/ColorModels.swift | mit | 1 | //
// Colorspaces.swift
// WaddaColor
//
// Created by Johan Sørensen on 23/02/16.
// Copyright © 2016 Johan Sørensen. All rights reserved.
//
import Foundation
public typealias ColorDistance = Double
private func clampedPrecondition(val: Double) {
precondition(val >= 0.0 && val <= 1.0, "value (\(val) must be betweem 0.0 and 1.0)")
}
public struct RGBA: Equatable, CustomStringConvertible {
public let r: Double // 0.0-1.0
public let g: Double
public let b: Double
public let a: Double // 0.0-1.0
// Initialize structure respresenting RGBA, where r, g, b, a should be between 0.0 and 1.0
public init(_ r: Double, _ g: Double, _ b: Double, _ a: Double) {
clampedPrecondition(r)
clampedPrecondition(g)
clampedPrecondition(b)
clampedPrecondition(a)
self.r = r
self.g = g
self.b = b
self.a = a
}
public var color: UIColor {
return UIColor(red: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: CGFloat(a))
}
// Returns a value between 0.0 and 100.0, where 100.0 is a perfect match
public func distanceTo(other: RGBA) -> ColorDistance {
let xyz1 = XYZ(rgb: self)
let xyz2 = XYZ(rgb: other)
let lab1 = LAB(xyz: xyz1)
let lab2 = LAB(xyz: xyz2)
return lab1.distance(lab2)
}
public var description: String {
return "<RGBA(r: \(r), g: \(g), b: \(b), a: \(a))>"
}
}
public func ==(lhs: RGBA, rhs: RGBA) -> Bool {
return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a
}
public struct HSL: CustomStringConvertible {
public let hue: Double //0-360
public let saturation: Double // 0-100
public let lightness: Double // 0-100
public init(rgb: RGBA) {
let maximum = max(rgb.r, max(rgb.g, rgb.b))
let minimum = min(rgb.r, min(rgb.g, rgb.b))
var h = 0.0
var s = 0.0
let l = (maximum + minimum) / 2.0;
let delta = maximum - minimum
if delta != 0 {
if l > 0.5 {
s = delta / (2.0 - maximum - minimum)
} else {
s = delta / (maximum + minimum)
}
if maximum == rgb.r {
h = (rgb.g - rgb.b) / delta + (rgb.g < rgb.b ? 6.0 : 0)
} else if maximum == rgb.g {
h = (rgb.b - rgb.r) / delta + 2.0
} else if maximum == rgb.b {
h = (rgb.r - rgb.g) / delta + 4.0
}
h /= 6.0;
h *= 3.6;
}
self.hue = h * 100.0
self.saturation = s * 100.0
self.lightness = l * 100.0
}
public func isLight(cutoff: Double = 50) -> Bool {
return lightness >= cutoff
}
public func isDark(cutoff: Double = 50) -> Bool {
return lightness <= cutoff
}
public var description: String {
return "<HSL(hue: \(hue), saturation: \(saturation), lightness: \(lightness))>"
}
}
public struct XYZ: CustomStringConvertible {
public let x: Double
public let y: Double
public let z: Double
public init(rgb: RGBA) {
var red = rgb.r
var green = rgb.g
var blue = rgb.b
if red > 0.04045 {
red = (red + 0.055) / 1.055
red = pow(red, 2.4)
} else {
red = red / 12.92
}
if green > 0.04045 {
green = (green + 0.055) / 1.055;
green = pow(green, 2.4);
} else {
green = green / 12.92;
}
if blue > 0.04045 {
blue = (blue + 0.055) / 1.055;
blue = pow(blue, 2.4);
} else {
blue = blue / 12.92;
}
red *= 100.0
green *= 100.0
blue *= 100.0
self.x = red * 0.4124 + green * 0.3576 + blue * 0.1805
self.y = red * 0.2126 + green * 0.7152 + blue * 0.0722
self.z = red * 0.0193 + green * 0.1192 + blue * 0.9505
}
public var description: String {
return "<XYZ(x: \(x), y: \(y), z: \(z))>"
}
}
public struct LAB: CustomStringConvertible {
public let l: Double
public let a: Double
public let b: Double
// init(l: Double, a: Double, b: Double) {
// self.l = l
// self.a = a
// self.b = b
// }
public init(xyz: XYZ) {
var x = xyz.x / 95.047
var y = xyz.y / 100.0
var z = xyz.z / 108.883
if x > 0.008856 {
x = pow(x, 1.0/3.0)
} else {
x = 7.787 * x + 16.0 / 116.0
}
if y > 0.008856 {
y = pow(y, 1.0/3.0)
} else {
y = (7.787 * y) + (16.0 / 116.0)
}
if z > 0.008856 {
z = pow(z, 1.0/3.0)
} else {
z = 7.787 * z + 16.0 / 116.0
}
self.l = 116.0 * y - 16.0
self.a = 500.0 * (x - y)
self.b = 200.0 * (y - z)
}
// CIE1994 distance
public func distance(other: LAB) -> Double {
let k1 = 0.045
let k2 = 0.015
let C1 = sqrt(a * a + b * b)
let C2 = sqrt(other.a * other.a + other.b * other.b)
let deltaA = a - other.a
let deltaB = b - other.b
let deltaC = C1 - C2
let deltaH2 = deltaA * deltaA + deltaB * deltaB - deltaC * deltaC
let deltaH = (deltaH2 > 0.0) ? sqrt(deltaH2) : 0.0;
let deltaL = l - other.l;
let sC = 1.0 + k1 * C1
let sH = 1.0 + k2 * C1
let vL = deltaL / 1.0
let vC = deltaC / (1.0 * sC)
let vH = deltaH / (1.0 * sH)
let deltaE = sqrt(vL * vL + vC * vC + vH * vH)
return deltaE
}
public var description: String {
return "<LAB(l: \(l), a: \(a), b: \(b))>"
}
}
| 148e80f0bafc58d4a2aea622f52b9220 | 25.369863 | 95 | 0.482251 | false | false | false | false |
czerenkow/LublinWeather | refs/heads/master | App/LastUsedStationInteractor.swift | mit | 1 | //
// LastUsedStationInteractor.swift
// LublinWeather
//
// Copyright (c) 2016 Damian Rzeszot
//
// 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.
//
class LastUsedStationInteractor: LastUsedStationProvider {
var listStationsProvider: ListStationsProvider
var lastUsedStationStore: LastUsedStationStore
var weatherStationList: [WeatherStation] {
return listStationsProvider.getStations()
}
// MARK: - Initialization
init(listStationsProvider: ListStationsProvider, lastUsedStationStore: LastUsedStationStore) {
self.listStationsProvider = listStationsProvider
self.lastUsedStationStore = lastUsedStationStore
}
// MARK: - Provider
func getLastUsedStation() -> WeatherStation? {
guard let identifier = lastUsedStationStore.loadLastUsedStation() else {
return nil
}
return weatherStationList
.filter { $0.identifier == identifier }
.first
}
func clearLastUsedStation() {
lastUsedStationStore.forgotLastUsedStation()
}
func setLastUsedStation(station: WeatherStation) {
lastUsedStationStore.storeLastUsedStation(identifier: station.identifier)
}
}
| 757e87c77f0b4af3796d015320774c80 | 33.242424 | 98 | 0.728319 | false | false | false | false |
ibari/StationToStation | refs/heads/master | Pods/p2.OAuth2/OAuth2/OAuth2ImplicitGrant.swift | gpl-2.0 | 1 | //
// OAuth2ImplicitGrant.swift
// OAuth2
//
// Created by Pascal Pfiffner on 6/9/14.
// Copyright 2014 Pascal Pfiffner
//
// 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
/**
Class to handle OAuth2 requests for public clients, such as distributed Mac/iOS Apps.
*/
public class OAuth2ImplicitGrant: OAuth2
{
public override func authorizeURLWithRedirect(redirect: String?, scope: String?, params: [String: String]?) -> NSURL {
return authorizeURLWithBase(authURL, redirect: redirect, scope: scope, responseType: "token", params: params)
}
public override func handleRedirectURL(redirect: NSURL) {
logIfVerbose("Handling redirect URL \(redirect.description)")
var error: NSError?
var comp = NSURLComponents(URL: redirect, resolvingAgainstBaseURL: true)
// token should be in the URL fragment
if let fragment = comp?.percentEncodedFragment where count(fragment) > 0 {
let params = OAuth2ImplicitGrant.paramsFromQuery(fragment)
if let token = params["access_token"] where !token.isEmpty {
if let tokType = params["token_type"] {
if "bearer" == tokType.lowercaseString {
// got a "bearer" token, use it if state checks out
if let tokState = params["state"] {
if tokState == state {
accessToken = token
accessTokenExpiry = nil
if let expires = params["expires_in"]?.toInt() {
accessTokenExpiry = NSDate(timeIntervalSinceNow: NSTimeInterval(expires))
}
logIfVerbose("Successfully extracted access token")
didAuthorize(params)
return
}
error = genOAuth2Error("Invalid state \(tokState), will not use the token", .InvalidState)
}
else {
error = genOAuth2Error("No state returned, will not use the token", .InvalidState)
}
}
else {
error = genOAuth2Error("Only \"bearer\" token is supported, but received \"\(tokType)\"", .Unsupported)
}
}
else {
error = genOAuth2Error("No token type received, will not use the token", .PrerequisiteFailed)
}
}
else {
error = errorForErrorResponse(params)
}
}
else {
error = genOAuth2Error("Invalid redirect URL: \(redirect)", .PrerequisiteFailed)
}
didFail(error)
}
}
| 8d536e1597dcdb5db9789371ed18e90c | 32.130952 | 119 | 0.681639 | false | false | false | false |
HarwordLiu/Ing. | refs/heads/master | Ing/Ing/Operations/CKSubscriptionOperations/FetchAllSubscriptionsOperation.swift | mit | 1 | //
// FetchAllSubscriptionsOperation.swift
// CloudKitSyncPOC
//
// Created by Nick Harris on 1/18/16.
// Copyright © 2016 Nick Harris. All rights reserved.
//
import CloudKit
class FetchAllSubscriptionsOperation: CKFetchSubscriptionsOperation {
var fetchedSubscriptions: [String : CKSubscription]
override init() {
fetchedSubscriptions = [:]
super.init()
}
override func main() {
print("FetchAllSubscriptionsOperation.main()")
setOperationBlocks()
super.main()
}
func setOperationBlocks() {
fetchSubscriptionCompletionBlock = {
[unowned self]
(subscriptions: [String : CKSubscription]?, error: NSError?) -> Void in
print("FetchAllSubscriptionsOperation.fetchRecordZonesCompletionBlock")
if let error = error {
print("FetchAllRecordZonesOperation error: \(error)")
}
if let subscriptions = subscriptions {
self.fetchedSubscriptions = subscriptions
for subscriptionID in subscriptions.keys {
print("Fetched CKSubscription: \(subscriptionID)")
}
}
} as? ([String : CKSubscription]?, Error?) -> Void
}
}
| 8aedb42a2b5e09c0958503282c884c73 | 26.653061 | 83 | 0.571956 | false | false | false | false |
freshOS/ws | refs/heads/master | Sources/ws/WSHTTPVerb.swift | mit | 2 | //
// WSHTTPVerb.swift
// ws
//
// Created by Sacha Durand Saint Omer on 06/04/16.
// Copyright © 2016 s4cha. All rights reserved.
//
import Foundation
public enum WSHTTPVerb: String {
case get = "GET"
case put = "PUT"
case post = "POST"
case patch = "PATCH"
case delete = "DELETE"
}
| 23c06b820f1126dfb484a64d6d227516 | 17.235294 | 51 | 0.622581 | false | false | false | false |
AndreyPanov/ApplicationCoordinator | refs/heads/master | ApplicationCoordinator/Flows/Create flow/ItemCreateCoordinator.swift | mit | 1 | final class ItemCreateCoordinator: BaseCoordinator, ItemCreateCoordinatorOutput {
var finishFlow: ((ItemList?)->())?
private let factory: ItemCreateModuleFactory
private let router: Router
init(router: Router, factory: ItemCreateModuleFactory) {
self.factory = factory
self.router = router
}
override func start() {
showCreate()
}
//MARK: - Run current flow's controllers
private func showCreate() {
let createItemOutput = factory.makeItemAddOutput()
createItemOutput.onCompleteCreateItem = { [weak self] item in
self?.finishFlow?(item)
}
createItemOutput.onHideButtonTap = { [weak self] in
self?.finishFlow?(nil)
}
router.setRootModule(createItemOutput)
}
}
| c94ae0e44dd0a99233862715468bdc9e | 24.689655 | 81 | 0.695302 | false | false | false | false |
wenghengcong/Coderpursue | refs/heads/master | BeeFun/Pods/SwiftyStoreKit/SwiftyStoreKit/InAppProductQueryRequest.swift | mit | 1 | //
// InAppPurchaseProductRequest.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import StoreKit
typealias InAppProductRequestCallback = (RetrieveResults) -> Void
protocol InAppProductRequest: class {
func start()
func cancel()
}
class InAppProductQueryRequest: NSObject, InAppProductRequest, SKProductsRequestDelegate {
private let callback: InAppProductRequestCallback
private let request: SKProductsRequest
deinit {
request.delegate = nil
}
init(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) {
self.callback = callback
request = SKProductsRequest(productIdentifiers: productIds)
super.init()
request.delegate = self
}
func start() {
request.start()
}
func cancel() {
request.cancel()
}
// MARK: SKProductsRequestDelegate
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let retrievedProducts = Set<SKProduct>(response.products)
let invalidProductIDs = Set<String>(response.invalidProductIdentifiers)
performCallback(RetrieveResults(retrievedProducts: retrievedProducts,
invalidProductIDs: invalidProductIDs, error: nil))
}
func requestDidFinish(_ request: SKRequest) {
}
func request(_ request: SKRequest, didFailWithError error: Error) {
performCallback(RetrieveResults(retrievedProducts: Set<SKProduct>(), invalidProductIDs: Set<String>(), error: error))
}
private func performCallback(_ results: RetrieveResults) {
DispatchQueue.main.async {
self.callback(results)
}
}
}
| 4b9fbb1c920b6081826d6b9153f7937b | 34.341772 | 125 | 0.725287 | false | false | false | false |
otakisan/SmartToDo | refs/heads/master | SmartToDo/Views/ListOfTaskListsTableViewController.swift | mit | 1 | //
// ListOfTaskListsTableViewController.swift
// SmartToDo
//
// Created by takashi on 2014/09/15.
// Copyright (c) 2014年 ti. All rights reserved.
//
import UIKit
class ListOfTaskListsTableViewController: UITableViewController {
lazy var listOfDays : [NSDate] = self.createDayList()
var daysBeforeAndAfter = 7
var taskStoreService : TaskStoreService = TaskStoreService()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.registerNib(UINib(nibName: "ListOfTaskListsTableViewCell", bundle: nil), forCellReuseIdentifier: "ListOfTaskListsTableViewCell")
self.setTitle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.reloadTaskList()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.listOfDays.count
}
private func createDayList() -> [NSDate] {
var dateList : [NSDate] = []
let today = NSDate()
for dayDiff in -1 * self.daysBeforeAndAfter ... self.daysBeforeAndAfter {
let timeInterval = NSTimeInterval(dayDiff * 24 * 3600)
dateList.append(today.dateByAddingTimeInterval(timeInterval))
}
return dateList
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ListOfTaskListsTableViewCell", forIndexPath: indexPath) as! ListOfTaskListsTableViewCell
// セルを構成する
let taskDate = self.listOfDays[indexPath.row]
cell.taskCount = self.taskStoreService.countByDueDate(taskDate)
cell.taskLeftCount = self.taskStoreService.countUnfinishedByDueDate(taskDate, toDueDate: taskDate)
cell.refreshDisplay(taskDate)
// 当日を出す場合、初期表示で当日を先頭にするが、
// それよりも前にも日がある。
// この関数は非表示->表示で呼ばれるような感じだから難しいかも。
// if self.isEqualDate(taskDate, date2: NSDate()) {
// self.displayTodayCell()
// }
return cell
}
private func displayTodayCell(){
let todayIndexPath = NSIndexPath(forRow: self.listOfDays.count / 2, inSection: 0)
self.tableView.scrollToRowAtIndexPath(todayIndexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}
private func setTitle(){
// 表示期間をタイトル表示する ちょっと日付の値を出力するだけで、このような実装量が必要になる?
let dayInterval = 60 * 60 * 24
let fromDate = NSDate(timeIntervalSinceNow: (NSTimeInterval)(dayInterval * self.daysBeforeAndAfter * -1))
let fromComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.NSMonthCalendarUnit, NSCalendarUnit.NSDayCalendarUnit], fromDate: fromDate)
let from = String(format: "%02d/%02d", fromComponents.month, fromComponents.day)
let toDate = NSDate(timeIntervalSinceNow: (NSTimeInterval)(dayInterval * self.daysBeforeAndAfter))
let toComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.NSMonthCalendarUnit, NSCalendarUnit.NSDayCalendarUnit], fromDate: toDate)
let to = String(format: "%02d/%02d", toComponents.month, toComponents.day)
self.navigationItem.title = "\(from) - \(to)"
// self.navigationItem.title = "\(fromComponents.month)/\(fromComponents.day) - \(toComponents.month)/\(toComponents.day)"
// self.navigationItem.title = String(format: NSLocalizedString("ListOfTaskListsTitle", comment: "comment"), self.daysBeforeAndAfter)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showTaskListSegue", sender: self.tableView.cellForRowAtIndexPath(indexPath))
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if let vc = segue.destinationViewController as? TaskListTableViewController {
if let cell = sender as? ListOfTaskListsTableViewCell {
vc.dayOfTask = cell.dateOfTaskList!
}
self.configureDstLeftButton(vc)
}
}
func configureDstLeftButton(vc : UIViewController){
// 遷移先のレフトボタンを構成する(自分に制御を移すため)
if var nvc = self.navigationController {
let bckItem = UIBarButtonItem(title: NSLocalizedString("BackToListOfLists", comment: ""), style: UIBarButtonItemStyle.Bordered, target: self, action: "didBack:")
vc.navigationItem.leftBarButtonItem = bckItem
}
}
@IBAction private func didBack(sender : AnyObject){
self.navigationController?.popViewControllerAnimated(true)
}
func reloadTaskList(){
self.listOfDays = self.createDayList()
self.tableView.reloadData()
}
/**
Quick Look に表示する値を返却する
*/
func debugQuickLookObject() -> AnyObject? {
return "List Of Days : \(self.listOfDays.count)"
}
}
| 48e4aae42b7f6813e4b3c9b7af222b60 | 38.380952 | 173 | 0.675131 | false | false | false | false |
Nick-The-Uncharted/TagListView | refs/heads/master | TagListView/CloseButton.swift | mit | 2 | //
// CloseButton.swift
// TagListViewDemo
//
// Created by Benjamin Wu on 2/11/16.
// Copyright © 2016 Ela. All rights reserved.
//
import UIKit
internal class CloseButton: UIButton {
var iconSize: CGFloat = 10
var lineWidth: CGFloat = 1
var lineColor: UIColor = UIColor.whiteColor().colorWithAlphaComponent(0.54)
weak var tagView: TagView?
override func drawRect(rect: CGRect) {
let path = UIBezierPath()
path.lineWidth = lineWidth
path.lineCapStyle = .Round
let iconFrame = CGRect(
x: (rect.width - iconSize) / 2.0,
y: (rect.height - iconSize) / 2.0,
width: iconSize,
height: iconSize
)
path.moveToPoint(iconFrame.origin)
path.addLineToPoint(CGPoint(x: iconFrame.maxX, y: iconFrame.maxY))
path.moveToPoint(CGPoint(x: iconFrame.maxX, y: iconFrame.minY))
path.addLineToPoint(CGPoint(x: iconFrame.minX, y: iconFrame.maxY))
lineColor.setStroke()
path.stroke()
}
}
| f16e8e35b40eff2459c5ec30d189d67d | 23.714286 | 79 | 0.624277 | false | false | false | false |
zwaldowski/Lustre | refs/heads/swift-2_0 | Lustre/Result.swift | mit | 1 | //
// Result.swift
// Lustre
//
// Created by Zachary Waldowski on 2/7/15.
// Copyright © 2014-2015. Some rights reserved.
//
public enum Result<T> {
case Failure(ErrorType)
case Success(T)
public init(error: ErrorType) {
self = .Failure(error)
}
public init(value: T) {
self = .Success(value)
}
}
extension Result: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
switch self {
case .Failure(let error): return String(error)
case .Success(let value): return String(value)
}
}
public var debugDescription: String {
switch self {
case .Failure(let error): return "Failure(\(String(reflecting: error)))"
case .Success(let value): return "Success(\(String(reflecting: value)))"
}
}
}
extension Result: EitherType {
public init(left error: ErrorType) {
self.init(error: error)
}
public init(right value: T) {
self.init(value: value)
}
public func analysis<Result>(@noescape ifLeft ifLeft: ErrorType -> Result, @noescape ifRight: T -> Result) -> Result {
switch self {
case .Failure(let error): return ifLeft(error)
case .Success(let value): return ifRight(value)
}
}
}
extension EitherType where LeftType == ErrorType {
public func flatMap<Value>(@noescape transform: RightType -> Result<Value>) -> Result<Value> {
return analysis(ifLeft: Result.Failure, ifRight: transform)
}
public func map<Value>(@noescape transform: RightType -> Value) -> Result<Value> {
return flatMap { .Success(transform($0)) }
}
public func recoverWith(@autoclosure fallbackResult: () -> Result<RightType>) -> Result<RightType> {
return analysis(ifLeft: { _ in fallbackResult() }, ifRight: Result.Success)
}
}
public func ??<Either: EitherType where Either.LeftType == ErrorType>(lhs: Either, @autoclosure rhs: () -> Result<Either.RightType>) -> Result<Either.RightType> {
return lhs.recoverWith(rhs())
}
| 768e78411d751c3f498bb8a3bdcbf8a3 | 26.727273 | 162 | 0.622482 | false | false | false | false |
ReactiveSprint/ReactiveSprint-Swift | refs/heads/master | Pod/Classes/FetchedArrayViewModel.swift | mit | 1 | //
// FetchedArrayViewModel.Swift
// Pods
//
// Created by Ahmad Baraka on 3/2/16.
// Copyright © 2016 ReactiveSprint. All rights reserved.
//
import ReactiveCocoa
import Result
/// Non-generic FetchedArrayViewModelType used with Cocoa.
public protocol CocoaFetchedArrayViewModelType: CocoaArrayViewModelType
{
/// Whether the ViewModel is refreshing.
var refreshing: AnyProperty<Bool> { get }
/// Whether the ViewModel is fetching next page and is not refreshing.
var fetchingNextPage: AnyProperty<Bool> { get }
/// Whether the ViewModel has next page.
var hasNextPage: AnyProperty<Bool> { get }
var refreshCocoaAction: CocoaAction { get }
var fetchCocoaAction: CocoaAction { get }
var fetchIfNeededCocoaAction: CocoaAction { get }
}
/// ArrayViewModel which its array is lazily fetched, or even paginated.
public protocol FetchedArrayViewModelType: ArrayViewModelType, CocoaFetchedArrayViewModelType
{
associatedtype FetchInput
associatedtype FetchOutput
associatedtype PaginationType
associatedtype FetchError: ViewModelErrorType
/// Next Page
var nextPage: PaginationType? { get }
/// Action which refreshes ViewModels.
var refreshAction: Action<FetchInput, FetchOutput, FetchError> { get }
/// Action which fetches ViewModels.
///
/// If `nextPage` is nil, then this action will refresh, else this action should fetch next page.
var fetchAction: Action<FetchInput, FetchOutput, FetchError> { get }
/// Applies `fetchAction` only if next page is availabe or returns `SignalProducer.empty`
var fetchIfNeededAction: Action<FetchInput, FetchOutput, ActionError<FetchError>> { get }
}
public extension FetchedArrayViewModelType
{
private var willFetchNextPage: Bool {
return nextPage != nil
}
public func fetchIfNeeded(input: FetchInput) -> SignalProducer<FetchOutput, ActionError<FetchError>>
{
if willFetchNextPage && hasNextPage.value
{
return fetchAction.apply(input)
}
return SignalProducer.empty
}
}
public extension FetchedArrayViewModelType
{
public var fetchCocoaAction: CocoaAction { return fetchAction.unsafeCocoaAction }
public var refreshCocoaAction: CocoaAction { return refreshAction.unsafeCocoaAction }
public var fetchIfNeededCocoaAction: CocoaAction { return fetchIfNeededAction.unsafeCocoaAction }
}
/// An implementation of FetchedArrayViewModelType that fetches ViewModels by calling `fetchClosure.`
public class FetchedArrayViewModel<Element: ViewModelType, PaginationType, FetchError: ViewModelErrorType>: ViewModel, FetchedArrayViewModelType
{
private let _viewModels: MutableProperty<[Element]> = MutableProperty([])
public var viewModels: [Element] {
return _viewModels.value
}
private(set) public lazy var count: AnyProperty<Int> = AnyProperty(initialValue: 0, producer: self._viewModels.producer.map { $0.count })
public let localizedEmptyMessage = MutableProperty<String?>(nil)
private let _refreshing = MutableProperty(false)
private(set) public lazy var refreshing: AnyProperty<Bool> = AnyProperty(self._refreshing)
private let _fetchingNextPage = MutableProperty(false)
private(set) public lazy var fetchingNextPage: AnyProperty<Bool> = AnyProperty(self._fetchingNextPage)
private let _hasNextPage = MutableProperty(true)
private(set) public lazy var hasNextPage: AnyProperty<Bool> = AnyProperty(self._hasNextPage)
private(set) public var nextPage: PaginationType? = nil
public let fetchClosure: PaginationType? -> SignalProducer<(PaginationType?, [Element]), FetchError>
private(set) public lazy var refreshAction: Action<(), [Element], FetchError> = self.initRefreshAction()
private(set) public lazy var fetchAction: Action<(), [Element], FetchError> = self.initFetchAction()
private(set) public lazy var fetchIfNeededAction: Action<(), [Element], ActionError<FetchError>> = { _ in
let action = Action<(), [Element], ActionError<FetchError>>(enabledIf: self.enabled) { [unowned self] _ in
return self.fetchIfNeeded()
}
action.unsafeCocoaAction = CocoaAction(action, input: ())
return action
}()
/// Initializes an instance with `fetchClosure`
///
/// - Parameter fetchClosure: A closure which is called each time `refreshAction` or `fetchAction`
/// are called passing latest PaginationType
/// and returns a `SignalProducer` which sends PaginationType and an array of `Element`.
/// If the returned SignalProducer sends nil PaginationType, then no pagination will be handled.
public init(_ fetchClosure: PaginationType? -> SignalProducer<(PaginationType?, [Element]), FetchError>)
{
self.fetchClosure = fetchClosure
super.init()
}
public subscript(index: Int) -> Element {
return _viewModels.value[index]
}
/// Initializes refresh action.
///
/// Default implementation initializes an Action that is enabled when the receiver is,
/// and executes `fetchClosure` with nil page.
///
/// `CocoaAction.unsafeCocoaAction` is set with a safe one ignoring any input.
///
/// The returned action is also bound to the receiver using `bindAction`
public func initRefreshAction() -> Action<(), [Element], FetchError>
{
let action: Action<(), [Element], FetchError> = Action(enabledIf: self.enabled) { [unowned self] _ in
self._refreshing.value = true
return self._fetch(nil)
}
bindAction(action)
action.unsafeCocoaAction = CocoaAction(action, input: ())
return action
}
/// Initializes Fetch action.
///
/// Default implementation initializes an Action that is enabled when the receiver is,
/// and executes `fetchClosure` with `nextPage`.
///
/// `CocoaAction.unsafeCocoaAction` is set with a safe one ignoring any input.
///
/// The returned action is also bound to the receiver using `bindAction`
public func initFetchAction() -> Action<(), [Element], FetchError>
{
let action: Action<(), [Element], FetchError> = Action(enabledIf: self.enabled) { [unowned self] _ in
if self.willFetchNextPage
{
self._fetchingNextPage.value = true
}
else
{
self._refreshing.value = true
}
return self._fetch(self.nextPage)
}
bindAction(action)
action.unsafeCocoaAction = CocoaAction(action, input: ())
return action
}
private func _fetch(page: PaginationType?) -> SignalProducer<[Element], FetchError>
{
return self.fetchClosure(page)
.on(next: { [unowned self] page, viewModels in
if self.refreshing.value
{
self._viewModels.value.removeAll()
}
self._viewModels.value.appendContentsOf(viewModels)
self._hasNextPage.value = viewModels.count > 0
self.nextPage = page
},
terminated: { [unowned self] in
self._refreshing.value = false
self._fetchingNextPage.value = false
})
.map { $0.1 }
}
public func indexOf(predicate: Element -> Bool) -> Int?
{
return viewModels.indexOf(predicate)
}
}
| 0f39ae6eb769c703e693086a7d5d1adb | 35.732057 | 144 | 0.657418 | false | false | false | false |
arvedviehweger/swift | refs/heads/master | benchmark/single-source/DictTest3.swift | apache-2.0 | 3 | //===--- DictTest3.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
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_Dictionary3(_ N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
var hash1 = [String: Int]()
var hash2 = [String: Int]()
var res = ""
for _ in 1...N {
hash1 = [:]
for i in 0..<size1 {
hash1["foo_" + String(i)] = i
}
hash2 = hash1
for _ in 1..<reps {
for (k, v) in hash1 {
hash2[k] = hash2[k]! + v
}
}
res = (String(hash1["foo_1"]!) + " " + String(hash1["foo_99"]!) + " " +
String(hash2["foo_1"]!) + " " + String(hash2["foo_99"]!))
if res != ref_result {
break
}
}
CheckResults(res == ref_result, "Incorrect results in Dictionary3: \(res) != \(ref_result)")
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_Dictionary3OfObjects(_ N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
var hash1 : [ Box<String> : Box<Int> ] = [:]
var hash2 : [ Box<String> : Box<Int> ] = [:]
var res = ""
for _ in 1...N {
hash1 = [:]
for i in 0..<size1 {
hash1[Box("foo_" + String(i))] = Box(i)
}
hash2 = hash1
for _ in 1..<reps {
for (k, v) in hash1 {
hash2[k] = Box(hash2[k]!.value + v.value)
}
}
res = (String(hash1[Box("foo_1")]!.value) + " " + String(hash1[Box("foo_99")]!.value) + " " +
String(hash2[Box("foo_1")]!.value) + " " + String(hash2[Box("foo_99")]!.value))
if res != ref_result {
break
}
}
CheckResults(res == ref_result, "Incorrect results in Dictionary3OfObject: \(res) != \(ref_result)")
}
| 57003952cb679274fa1eef717870eb1e | 23.946237 | 102 | 0.522845 | false | false | false | false |
kumabook/MusicFav | refs/heads/master | MusicFav/SelectPlaylistTableViewController.swift | mit | 1 | //
// SelectPlaylistTableViewController.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 2/9/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import UIKit
import MusicFeeder
class SelectPlaylistTableViewController: UITableViewController {
let tableCellReuseIdentifier = "selectPlaylistTableViewCell"
let cellHeight: CGFloat = 80
var playlists: [Playlist] = []
var callback: ((Playlist?) -> Void)?
var appDelegate: AppDelegate { get { return UIApplication.shared.delegate as! AppDelegate }}
override func viewDidLoad() {
super.viewDidLoad()
clearsSelectionOnViewWillAppear = true
let nib = UINib(nibName: "SelectPlaylistTableViewCell", bundle: nil)
tableView?.register(nib, forCellReuseIdentifier:self.tableCellReuseIdentifier)
observePlaylists()
}
override func viewWillAppear(_ animated: Bool) {
Logger.sendScreenView(self)
updateNavbar()
}
func updateNavbar() {
let closeButton = UIBarButtonItem(title: "Cancel".localize(),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(SelectPlaylistTableViewController.close))
let newPlaylistButton = UIBarButtonItem(image: UIImage(named: "add_stream"),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(SelectPlaylistTableViewController.newPlaylist))
navigationItem.rightBarButtonItems = [newPlaylistButton]
navigationItem.leftBarButtonItems = [closeButton]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func observePlaylists() {
playlists = Playlist.shared.current
tableView.reloadData()
Playlist.shared.signal.observeResult({ result in
guard let event = result.value else { return }
let section = 0
switch event {
case .created(let playlist):
let indexPath = IndexPath(item: self.playlists.count, section: section)
self.playlists.append(playlist)
self.tableView.insertRows(at: [indexPath], with: .fade)
case .updated(let playlist):
self.updatePlaylist(playlist)
case .removed(let playlist):
if let index = self.playlists.index(of: playlist) {
self.playlists.remove(at: index)
let indexPath = IndexPath(item: index, section: section)
self.tableView.deleteRows(at: [indexPath], with: .fade)
}
case .tracksAdded(let playlist, _):
self.updatePlaylist(playlist)
case .trackRemoved(let playlist, _, _):
self.updatePlaylist(playlist)
case .trackUpdated(let playlist, _):
self.updatePlaylist(playlist)
case .sharedListUpdated:
self.playlists = Playlist.shared.current
self.tableView.reloadData()
}
})
}
func updatePlaylist(_ playlist: Playlist) {
let section = 0
if let index = self.playlists.index(of: playlist) {
let indexPath = IndexPath(item: index, section: section)
self.playlists[index] = playlist
self.tableView.reloadRows(at: [indexPath], with: .fade)
}
}
@objc func newPlaylist() {
appDelegate.miniPlayerViewController?.playlistTableViewController.newPlaylist()
}
func editPlaylist(_ index: Int) {
appDelegate.miniPlayerViewController?.playlistTableViewController.showTitleEditAlertViewAtIndex(index)
}
@objc func close() {
navigationController?.dismiss(animated: true, completion: {
if let callback = self.callback {
callback(nil)
}
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playlists.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.cellHeight
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.tableCellReuseIdentifier, for: indexPath) as! SelectPlaylistTableViewCell
let playlist = playlists[indexPath.item]
cell.titleLabel.text = playlist.title
cell.trackNumLabel.text = "\(playlist.tracks.count) tracks"
cell.thumbImageView.sd_setImage(with: playlist.thumbnailUrl)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
navigationController?.dismiss(animated: true, completion: { () -> Void in
if let callback = self.callback {
callback(self.playlists[indexPath.item])
}
})
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let edit = UITableViewRowAction(style: .default, title: "Edit title".localize()) {
(action, indexPath) in
self.editPlaylist(indexPath.item)
}
edit.backgroundColor = UIColor.green
let remove = UITableViewRowAction(style: .default, title: "Remove".localize()) {
(action, indexPath) in
self.playlists[indexPath.item].remove()
}
remove.backgroundColor = UIColor.red
return [edit, remove]
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
}
| 63594914f3cc61879ca8c608760a5573 | 37.903846 | 143 | 0.618224 | false | false | false | false |
Pacific3/PUIKit | refs/heads/master | PUIKit/Operations/Observers/NetworkActivityObserver.swift | mit | 1 |
public struct NetworkActivityObserver: OperationObserver {
public init() { }
public func operationDidStart(operation: Operation) {
executeOnMainThread {
NetworkIndicatorManager.sharedManager.networkActivityDidStart()
}
}
public func operationDidFinish(operation: Operation, errors: [NSError]) {
executeOnMainThread {
NetworkIndicatorManager.sharedManager.networkActivityDidEnd()
}
}
public func operation(operation: Operation, didProduceOperation newOperation: NSOperation) { }
public func operationDidCancel(operation: Operation) {
executeOnMainThread {
NetworkIndicatorManager.sharedManager.networkActivityDidEnd()
}
}
}
private class NetworkIndicatorManager {
static let sharedManager = NetworkIndicatorManager()
private var activiyCount = 0
private var visibilityTimer: Timer?
func networkActivityDidStart() {
assert(NSThread.isMainThread(), "Only on main thread!")
activiyCount += 1
updateNetworkActivityIndicatorVisibility()
}
func networkActivityDidEnd() {
assert(NSThread.isMainThread(), "Only on main thread!")
activiyCount -= 1
updateNetworkActivityIndicatorVisibility()
}
private func updateNetworkActivityIndicatorVisibility() {
if activiyCount > 0 {
showIndicator()
} else {
visibilityTimer = Timer(interval: 1.0) {
self.hideIndicator()
}
}
}
private func showIndicator() {
visibilityTimer?.cancel()
visibilityTimer = nil
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
private func hideIndicator() {
visibilityTimer?.cancel()
visibilityTimer = nil
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
private class Timer {
var isCancelled = false
init(interval: NSTimeInterval, handler: dispatch_block_t) {
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue()) { [weak self] in
if self?.isCancelled == false {
handler()
}
}
}
func cancel() {
isCancelled = true
}
}
| 1a76399b384be6517bed5bb9b76492f7 | 26.886364 | 98 | 0.623472 | false | false | false | false |
Yummypets/YPImagePicker | refs/heads/master | Source/Pages/Gallery/YPLibraryVC+PanGesture.swift | mit | 1 | //
// YPLibraryVC+PanGesture.swift
// YPImagePicker
//
// Created by Sacha DSO on 26/01/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
public class PanGestureHelper: NSObject, UIGestureRecognizerDelegate {
var v: YPLibraryView!
private let assetViewContainerOriginalConstraintTop: CGFloat = 0
private var dragDirection = YPDragDirection.up
private var imaginaryCollectionViewOffsetStartPosY: CGFloat = 0.0
private var cropBottomY: CGFloat = 0.0
private var dragStartPos: CGPoint = .zero
private let dragDiff: CGFloat = 0
private var _isImageShown = true
// The height constraint of the view with main selected image
var topHeight: CGFloat {
get {
return v.assetViewContainerConstraintTop?.constant ?? 0
}
set {
if newValue >= v.assetZoomableViewMinimalVisibleHeight - v.assetViewContainer.frame.height {
v.assetViewContainerConstraintTop?.constant = newValue
}
}
}
// Is the main image shown
var isImageShown: Bool {
get { return self._isImageShown }
set {
if newValue != isImageShown {
self._isImageShown = newValue
v.assetViewContainer.isShown = newValue
// Update imageCropContainer
v.assetZoomableView.isScrollEnabled = isImageShown
}
}
}
func registerForPanGesture(on view: YPLibraryView) {
v = view
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panned(_:)))
panGesture.delegate = self
view.addGestureRecognizer(panGesture)
topHeight = 0
}
public func resetToOriginalState() {
topHeight = assetViewContainerOriginalConstraintTop
animateView()
dragDirection = .up
}
fileprivate func animateView() {
UIView.animate(withDuration: 0.2,
delay: 0.0,
options: [.curveEaseInOut, .beginFromCurrentState],
animations: {
self.v.refreshImageCurtainAlpha()
self.v.layoutIfNeeded()
}
,
completion: nil)
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith
otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let p = gestureRecognizer.location(ofTouch: 0, in: v)
// Desactivate pan on image when it is shown.
if isImageShown {
if p.y < v.assetZoomableView.frame.height {
return false
}
}
return true
}
@objc
func panned(_ sender: UIPanGestureRecognizer) {
let containerHeight = v.assetViewContainer.frame.height
let currentPos = sender.location(in: v)
let overYLimitToStartMovingUp = currentPos.y * 1.4 < cropBottomY - dragDiff
switch sender.state {
case .began:
let view = sender.view
let loc = sender.location(in: view)
let subview = view?.hitTest(loc, with: nil)
if subview == v.assetZoomableView
&& topHeight == assetViewContainerOriginalConstraintTop {
return
}
dragStartPos = sender.location(in: v)
cropBottomY = v.assetViewContainer.frame.origin.y + containerHeight
// Move
if dragDirection == .stop {
dragDirection = (topHeight == assetViewContainerOriginalConstraintTop)
? .up
: .down
}
// Scroll event of CollectionView is preferred.
if (dragDirection == .up && dragStartPos.y < cropBottomY + dragDiff) ||
(dragDirection == .down && dragStartPos.y > cropBottomY) {
dragDirection = .stop
}
case .changed:
switch dragDirection {
case .up:
if currentPos.y < cropBottomY - dragDiff {
topHeight =
max(v.assetZoomableViewMinimalVisibleHeight - containerHeight,
currentPos.y + dragDiff - containerHeight)
}
case .down:
if currentPos.y > cropBottomY {
topHeight =
min(assetViewContainerOriginalConstraintTop, currentPos.y - containerHeight)
}
case .scroll:
topHeight =
v.assetZoomableViewMinimalVisibleHeight - containerHeight
+ currentPos.y - imaginaryCollectionViewOffsetStartPosY
case .stop:
if v.collectionView.contentOffset.y < 0 {
dragDirection = .scroll
imaginaryCollectionViewOffsetStartPosY = currentPos.y
}
}
default:
imaginaryCollectionViewOffsetStartPosY = 0.0
if sender.state == UIGestureRecognizer.State.ended && dragDirection == .stop {
return
}
if overYLimitToStartMovingUp && isImageShown == false {
// The largest movement
topHeight =
v.assetZoomableViewMinimalVisibleHeight - containerHeight
animateView()
dragDirection = .down
} else {
// Get back to the original position
resetToOriginalState()
}
}
// Update isImageShown
isImageShown = topHeight == assetViewContainerOriginalConstraintTop
}
}
| b16ce12ea6fce636ac80e7b71fbf126c | 34.694611 | 109 | 0.55947 | false | false | false | false |
korgx9/QRCodeReader.swift | refs/heads/master | Sources/QRCodeReaderView.swift | mit | 1 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
final class QRCodeReaderView: UIView, QRCodeReaderDisplayable {
/// A label to display info message
public var informationLabel: UILabel? = {
let il = UILabel()
il.translatesAutoresizingMaskIntoConstraints = false
il.textColor = UIColor.white
il.numberOfLines = 0
il.textAlignment = .center
return il
}()
lazy var overlayView: UIView? = {
let ov = ReaderOverlayView()
ov.backgroundColor = .clear
ov.clipsToBounds = true
ov.translatesAutoresizingMaskIntoConstraints = false
return ov
}()
let cameraView: UIView = {
let cv = UIView()
cv.clipsToBounds = true
cv.translatesAutoresizingMaskIntoConstraints = false
return cv
}()
lazy var cancelButton: UIButton? = {
let cb = UIButton()
cb.translatesAutoresizingMaskIntoConstraints = false
cb.setTitleColor(.gray, for: .highlighted)
return cb
}()
lazy var switchCameraButton: UIButton? = {
let scb = SwitchCameraButton()
scb.translatesAutoresizingMaskIntoConstraints = false
return scb
}()
lazy var toggleTorchButton: UIButton? = {
let ttb = ToggleTorchButton()
ttb.translatesAutoresizingMaskIntoConstraints = false
return ttb
}()
func setupComponents(showCancelButton: Bool, showSwitchCameraButton: Bool, showTorchButton: Bool, showOverlayView: Bool, showInformationLabel: Bool) {
translatesAutoresizingMaskIntoConstraints = false
addComponents()
cancelButton?.isHidden = !showCancelButton
switchCameraButton?.isHidden = !showSwitchCameraButton
toggleTorchButton?.isHidden = !showTorchButton
overlayView?.isHidden = !showOverlayView
informationLabel?.isHidden = !showInformationLabel
guard let cb = cancelButton, let scb = switchCameraButton, let ttb = toggleTorchButton, let ov = overlayView, let il = informationLabel else { return }
let views = ["cv": cameraView, "ov": ov, "cb": cb, "scb": scb, "ttb": ttb, "il": informationLabel] as [String : Any]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: [], metrics: nil, views: views))
if showCancelButton {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv][cb(40)]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cb]-|", options: [], metrics: nil, views: views))
}
else {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv]|", options: [], metrics: nil, views: views))
}
if showSwitchCameraButton {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[scb(50)]", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[scb(70)]|", options: [], metrics: nil, views: views))
}
if showTorchButton {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[ttb(50)]", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[ttb(70)]", options: [], metrics: nil, views: views))
}
if showInformationLabel {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-120-[il]", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[il]-20-|", options: [], metrics: nil, views: views))
}
for attribute in Array<NSLayoutAttribute>([.left, .top, .right, .bottom]) {
addConstraint(NSLayoutConstraint(item: ov, attribute: attribute, relatedBy: .equal, toItem: cameraView, attribute: attribute, multiplier: 1, constant: 0))
}
}
// MARK: - Scan Result Indication
func startTimerForBorderReset() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
if let ovl = self.overlayView as? ReaderOverlayView {
ovl.overlayColor = .white
}
}
}
func addRedBorder() {
self.startTimerForBorderReset()
if let ovl = self.overlayView as? ReaderOverlayView {
ovl.overlayColor = .red
}
}
func addGreenBorder() {
self.startTimerForBorderReset()
if let ovl = self.overlayView as? ReaderOverlayView {
ovl.overlayColor = .green
}
}
// MARK: - Convenience Methods
private func addComponents() {
addSubview(cameraView)
if let ov = overlayView {
addSubview(ov)
}
if let scb = switchCameraButton {
addSubview(scb)
}
if let ttb = toggleTorchButton {
addSubview(ttb)
}
if let cb = cancelButton {
addSubview(cb)
}
if let il = informationLabel {
addSubview(il)
}
}
}
| 3e58808790d744e795944c7b0e569237 | 32.715084 | 160 | 0.683347 | false | false | false | false |
lyft/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/ReturnArrowWhitespaceRule.swift | mit | 1 | import Foundation
import SourceKittenFramework
public struct ReturnArrowWhitespaceRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "return_arrow_whitespace",
name: "Returning Whitespace",
description: "Return arrow and return type should be separated by a single space or on a " +
"separate line.",
kind: .style,
nonTriggeringExamples: [
"func abc() -> Int {}\n",
"func abc() -> [Int] {}\n",
"func abc() -> (Int, Int) {}\n",
"var abc = {(param: Int) -> Void in }\n",
"func abc() ->\n Int {}\n",
"func abc()\n -> Int {}\n"
],
triggeringExamples: [
"func abc()↓->Int {}\n",
"func abc()↓->[Int] {}\n",
"func abc()↓->(Int, Int) {}\n",
"func abc()↓-> Int {}\n",
"func abc()↓ ->Int {}\n",
"func abc()↓ -> Int {}\n",
"var abc = {(param: Int)↓ ->Bool in }\n",
"var abc = {(param: Int)↓->Bool in }\n"
],
corrections: [
"func abc()↓->Int {}\n": "func abc() -> Int {}\n",
"func abc()↓-> Int {}\n": "func abc() -> Int {}\n",
"func abc()↓ ->Int {}\n": "func abc() -> Int {}\n",
"func abc()↓ -> Int {}\n": "func abc() -> Int {}\n",
"func abc()↓\n -> Int {}\n": "func abc()\n -> Int {}\n",
"func abc()↓\n-> Int {}\n": "func abc()\n-> Int {}\n",
"func abc()↓ ->\n Int {}\n": "func abc() ->\n Int {}\n",
"func abc()↓ ->\nInt {}\n": "func abc() ->\nInt {}\n"
]
)
public func validate(file: File) -> [StyleViolation] {
return violationRanges(in: file, skipParentheses: true).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
let violationsRanges = violationRanges(in: file, skipParentheses: false)
let matches = file.ruleEnabled(violatingRanges: violationsRanges, for: self)
if matches.isEmpty { return [] }
let regularExpression = regex(pattern)
let description = type(of: self).description
var corrections = [Correction]()
var contents = file.contents
let results = matches.reversed().compactMap { range in
return regularExpression.firstMatch(in: contents, options: [], range: range)
}
let replacementsByIndex = [2: " -> ", 4: " -> ", 6: " ", 7: " "]
for result in results {
guard result.numberOfRanges > (replacementsByIndex.keys.max() ?? 0) else { break }
for (index, string) in replacementsByIndex {
if let range = contents.nsrangeToIndexRange(result.range(at: index)) {
contents.replaceSubrange(range, with: string)
break
}
}
// skip the parentheses when reporting correction
let location = Location(file: file, characterOffset: result.range.location + 1)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
// MARK: - Private
private let pattern: String = {
//just horizontal spacing so that "func abc()->\n" can pass validation
let space = "[ \\f\\r\\t]"
// Either 0 space characters or 2+
let incorrectSpace = "(\(space){0}|\(space){2,})"
// The possible combinations of whitespace around the arrow
let patterns = [
"(\(incorrectSpace)\\->\(space)*)",
"(\(space)\\->\(incorrectSpace))",
"\\n\(space)*\\->\(incorrectSpace)",
"\(incorrectSpace)\\->\\n\(space)*"
]
// ex: `func abc()-> Int {` & `func abc() ->Int {`
return "\\)(\(patterns.joined(separator: "|")))\\S+"
}()
private func violationRanges(in file: File, skipParentheses: Bool) -> [NSRange] {
let matches = file.match(pattern: pattern, with: [.typeidentifier])
guard skipParentheses else {
return matches
}
return matches.map {
// skip first (
NSRange(location: $0.location + 1, length: $0.length - 1)
}
}
}
| 90c29fce1f1bfd7e3084338b299329a6 | 37.625 | 100 | 0.518662 | false | false | false | false |
huangboju/QMUI.swift | refs/heads/master | QMUI.swift/Demo/Modules/Demos/UIKit/QDTableViewCellViewController.swift | mit | 1 | //
// QDTableViewCellViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/18.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
/// 展示 QMUITableViewCell 能力的 demo 列表
class QDTableViewCellViewController: QDCommonListViewController {
override func initDataSource() {
dataSource = ["通过 insets 系列属性调整间距",
"通过配置表修改 accessoryType 的样式",
"动态高度计算"]
}
override func didSelectCell(_ title: String) {
tableView.qmui_clearsSelection()
var viewController: UIViewController?
if title == "通过 insets 系列属性调整间距" {
viewController = QDTableViewCellInsetsViewController()
} else if title == "通过配置表修改 accessoryType 的样式" {
viewController = QDTableViewCellAccessoryTypeViewController()
} else if title == "动态高度计算" {
viewController = QDTableViewCellDynamicHeightViewController()
}
if let viewController = viewController {
viewController.title = title
navigationController?.pushViewController(viewController, animated: true)
}
}
}
| f286fd22af94774fb93c30b706cab7c6 | 30 | 84 | 0.639058 | false | false | false | false |
okerivy/AlgorithmLeetCode | refs/heads/master | AlgorithmLeetCode/AlgorithmLeetCode/E_35_SearchInsertPosition.swift | mit | 1 | //
// E_35_SearchInsertPosition.swift
// AlgorithmLeetCode
//
// Created by okerivy on 2017/3/9.
// Copyright © 2017年 okerivy. All rights reserved.
//
import Foundation
// MARK: - 题目名称: 35. Search Insert Position
/* MARK: - 所属类别:
标签: Array, Binary Search
相关题目:
(E) First Bad Version
*/
/* MARK: - 题目英文:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
*/
/* MARK: - 题目翻译:
给定排序的数组和目标值,如果找到目标,则返回索引。如果没有,返回索引,如果它被插入顺序。
您可以假定数组中没有重复。
这里有几个例子。
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
*/
/* MARK: - 解题思路:
这题要求在一个排好序的数组查找某值value,如果存在则返回对应index,不存在则返回能插入到数组中的index(保证数组有序)。
对于不存在的情况,我们只需要在数组里面找到最小的一个值大于value的index,这个index就是我们可以插入的位置。譬如[1, 3, 5, 6],查找2,我们知道3是最小的一个大于2的数值,而3的index为1,所以我们需要在1这个位置插入2。如果数组里面没有值大于value,则插入到数组末尾。
我们采用二分法解决
典型的二分查找算法。二分查找算法是在有序数组中用到的较为频繁的一种算法,
在未接触二分查找算法时,最通用的一种做法是,对数组进行遍历,跟每个元素进行比较,其时间为O(n)。
但二分查找算法则更优,可在最坏的情况下用 O(log n) 完成搜索任务。
譬如数组 {1,2,3,4,5,6,7,8,9},查找元素6,用二分查找的算法执行的话,其顺序为:
第一步查找中间元素,即5,由于 5 < 6 ,则6必然在5之后的数组元素中,那么就在{6,7,8,9}中查找,
寻找 {6, 7, 8, 9} 的中位数,为7,7 > 6,则6应该在7左边的数组元素中,那么只剩下6,即找到了。
二分查找算法就是不断将数组进行对半分割,每次拿中间元素和 target 进行比较。
*/
// FIXME: 没有完成
/* MARK: - 复杂度分析:
*/
// MARK: - 代码:
private class Solution {
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
var low = 0
var high = nums.count - 1
// 二分查找 查找第一个出现的元素
// low = high = nums.count - 1 的时候 证明没有找到
while low < high {
// 直接使用(high + low)/2 可能导致溢出
let mid = (high - low) / 2 + low
if nums[mid] < target {
low = mid + 1
} else {
high = mid
}
}
// 对边界进行判断
// 走出while 循环 row = high 需要的是让 target <= nums[row] 这样才能插入
// 但是 对于需要插入一个大于数组中最大的数 来说 这个时候 nums[row] 依然小于 target
// 需要插入到最后面
if nums[low] < target {
low += 1
}
// 如果 while low <= high { 那么上面这个if 判断就不需要了
return low
}
}
// MARK: - 测试代码:
func searchInsertPosition() {
let nums1 = [1,2,3,5,6,6,6,8]
print(Solution().searchInsert(nums1, 8)) // 7
print(Solution().searchInsert(nums1, 2)) // 1
print(Solution().searchInsert(nums1, 6)) // 4
print(Solution().searchInsert(nums1, 7)) // 7
print(Solution().searchInsert(nums1, 0)) // 0
}
| a909dfa8ee710034c5cbf535ba71f40b | 19.105263 | 155 | 0.577038 | false | false | false | false |
Harvey-CH/TEST | refs/heads/master | v2exProject 2/v2exProject/View/NodeCell.swift | apache-2.0 | 2 | //
// NodeCell.swift
// v2exProject
//
// Created by 郑建文 on 16/8/4.
// Copyright © 2016年 Zheng. All rights reserved.
//
import UIKit
import Kingfisher
import SwiftDate
import ObjectMapper
class NodeCell: UITableViewCell {
@IBOutlet weak var nodeImage: UIImageView!
@IBOutlet weak var nodeTitle: UILabel!
@IBOutlet weak var nodeStars: UILabel!
@IBOutlet weak var nodeIntro: UILabel!
@IBOutlet weak var nodeCreate: UILabel!
var node:Node?{
didSet{
if let url = node!.avatar_normal {
self.nodeImage.kf_setImageWithURL(NSURL(string: "https:\(url)")!)
}
self.nodeTitle.text = (node!.title) ?? "无"
self.nodeStars.text = "\((node?.stars) ?? 0)人点赞"
self.nodeIntro.text = node!.header
self.nodeCreate.text = node!.created?.toString()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| da1d556a04431d7d82317f2e77b30a89 | 24.652174 | 81 | 0.608475 | false | false | false | false |
zisko/swift | refs/heads/master | test/SILGen/partial_apply_generic.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
protocol Panda {
associatedtype Cuddles : Foo
}
protocol Foo {
static func staticFunc()
func instanceFunc()
func makesSelfNonCanonical<T : Panda>(_: T) where T.Cuddles == Self
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic14getStaticFunc1{{[_0-9a-zA-Z]*}}F
func getStaticFunc1<T: Foo>(t: T.Type) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK-NEXT: apply [[REF]]<T>(%0)
return t.staticFunc
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @$S21partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.staticFunc!1
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<Self>(%0)
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @$S21partial_apply_generic14getStaticFunc2{{[_0-9a-zA-Z]*}}F
func getStaticFunc2<T: Foo>(t: T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: apply [[REF]]<T>
return T.staticFunc
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic16getInstanceFunc1{{[_0-9a-zA-Z]*}}F
func getInstanceFunc1<T: Foo>(t: T) -> () -> () {
// CHECK: alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization]
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: apply [[REF]]<T>
return t.instanceFunc
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.instanceFunc!1
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<Self>(%0)
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @$S21partial_apply_generic16getInstanceFunc2{{[_0-9a-zA-Z]*}}F
func getInstanceFunc2<T: Foo>(t: T) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<T>(
return T.instanceFunc
// CHECK-NEXT: destroy_addr %0 : $*
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic16getInstanceFunc3{{[_0-9a-zA-Z]*}}F
func getInstanceFunc3<T: Foo>(t: T.Type) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<T>(
return t.instanceFunc
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic23getNonCanonicalSelfFunc1tyq_cxcxm_t7CuddlesQy_RszAA5PandaR_r0_lF : $@convention(thin) <T, U where T == U.Cuddles, U : Panda> (@thick T.Type) -> @owned @callee_guaranteed (@in T) -> @owned @callee_guaranteed (@in U) -> () {
func getNonCanonicalSelfFunc<T : Foo, U : Panda>(t: T.Type) -> (T) -> (U) -> () where U.Cuddles == T {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP21makesSelfNonCanonicalyyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <τ_0_0><τ_1_0 where τ_0_0 == τ_1_0.Cuddles, τ_1_0 : Panda> (@in τ_0_0) -> @owned @callee_guaranteed (@in τ_1_0) -> ()
// CHECK-NEXT: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[REF]]<T, U>()
return t.makesSelfNonCanonical
// CHECK-NEXT: return [[CLOSURE]]
}
// curry thunk of Foo.makesSelfNonCanonical<A where ...> (A1) -> ()
// CHECK-LABEL: sil shared [thunk] @$S21partial_apply_generic3FooP21makesSelfNonCanonicalyyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <Self><T where Self == T.Cuddles, T : Panda> (@in Self) -> @owned @callee_guaranteed (@in T) -> () {
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.makesSelfNonCanonical!1 : <Self><T where Self == T.Cuddles, T : Panda> (Self) -> (T) -> () : $@convention(witness_method: Foo) <τ_0_0><τ_1_0 where τ_0_0 == τ_1_0.Cuddles, τ_1_0 : Panda> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK-NEXT: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[REF]]<Self, T>(%0)
// CHECK-NEXT: return [[CLOSURE]]
| d69b60e54923ddb828558484e32cd461 | 50.109756 | 277 | 0.657838 | false | false | false | false |
grpc/grpc-swift | refs/heads/main | Sources/GRPC/ClientCalls/Call.swift | apache-2.0 | 1 | /*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Logging
import NIOCore
import NIOHPACK
import NIOHTTP2
import protocol SwiftProtobuf.Message
/// An object representing a single RPC from the perspective of a client. It allows the caller to
/// send request parts, request a cancellation, and receive response parts in a provided callback.
///
/// The call object sits atop an interceptor pipeline (see ``ClientInterceptor``) which allows for
/// request and response streams to be arbitrarily transformed or observed. Requests sent via this
/// call will traverse the pipeline before reaching the network, and responses received will
/// traverse the pipeline having been received from the network.
///
/// This object is a lower-level API than the equivalent wrapped calls (such as ``UnaryCall`` and
/// ``BidirectionalStreamingCall``). The caller is therefore required to do more in order to use this
/// object correctly. Callers must call ``invoke(onError:onResponsePart:)`` to start the call and ensure that the correct
/// number of request parts are sent in the correct order (exactly one `metadata`, followed
/// by at most one `message` for unary and server streaming calls, and any number of `message` parts
/// for client streaming and bidirectional streaming calls. All call types must terminate their
/// request stream by sending one `end` message.
///
/// Callers are not able to create ``Call`` objects directly, rather they must be created via an
/// object conforming to ``GRPCChannel`` such as ``ClientConnection``.
public final class Call<Request, Response> {
@usableFromInline
internal enum State {
/// Idle, waiting to be invoked.
case idle(ClientTransportFactory<Request, Response>)
/// Invoked, we have a transport on which to send requests. The transport may be closed if the
/// RPC has already completed.
case invoked(ClientTransport<Request, Response>)
}
/// The current state of the call.
@usableFromInline
internal var _state: State
/// User provided interceptors for the call.
@usableFromInline
internal let _interceptors: [ClientInterceptor<Request, Response>]
/// Whether compression is enabled on the call.
private var isCompressionEnabled: Bool {
return self.options.messageEncoding.enabledForRequests
}
/// The `EventLoop` the call is being invoked on.
public let eventLoop: EventLoop
/// The path of the RPC, usually generated from a service definition, e.g. "/echo.Echo/Get".
public let path: String
/// The type of the RPC, e.g. unary, bidirectional streaming.
public let type: GRPCCallType
/// Options used to invoke the call.
public let options: CallOptions
/// A promise for the underlying `Channel`. We only allocate this if the user asks for
/// the `Channel` and we haven't invoked the transport yet. It's a bit unfortunate.
private var channelPromise: EventLoopPromise<Channel>?
/// Returns a future for the underlying `Channel`.
internal var channel: EventLoopFuture<Channel> {
if self.eventLoop.inEventLoop {
return self._channel()
} else {
return self.eventLoop.flatSubmit {
return self._channel()
}
}
}
// Calls can't be constructed directly: users must make them using a `GRPCChannel`.
@inlinable
internal init(
path: String,
type: GRPCCallType,
eventLoop: EventLoop,
options: CallOptions,
interceptors: [ClientInterceptor<Request, Response>],
transportFactory: ClientTransportFactory<Request, Response>
) {
self.path = path
self.type = type
self.options = options
self._state = .idle(transportFactory)
self.eventLoop = eventLoop
self._interceptors = interceptors
}
/// Starts the call and provides a callback which is invoked on every response part received from
/// the server.
///
/// This must be called prior to ``send(_:)`` or ``cancel()``.
///
/// - Parameters:
/// - onError: A callback invoked when an error is received.
/// - onResponsePart: A callback which is invoked on every response part.
/// - Important: This function should only be called once. Subsequent calls will be ignored.
@inlinable
public func invoke(
onError: @escaping (Error) -> Void,
onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
) {
self.options.logger.debug("starting rpc", metadata: ["path": "\(self.path)"], source: "GRPC")
if self.eventLoop.inEventLoop {
self._invoke(onStart: {}, onError: onError, onResponsePart: onResponsePart)
} else {
self.eventLoop.execute {
self._invoke(onStart: {}, onError: onError, onResponsePart: onResponsePart)
}
}
}
/// Send a request part on the RPC.
/// - Parameters:
/// - part: The request part to send.
/// - promise: A promise which will be completed when the request part has been handled.
/// - Note: Sending will always fail if ``invoke(onError:onResponsePart:)`` has not been called.
@inlinable
public func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
if self.eventLoop.inEventLoop {
self._send(part, promise: promise)
} else {
self.eventLoop.execute {
self._send(part, promise: promise)
}
}
}
/// Attempt to cancel the RPC.
/// - Parameter promise: A promise which will be completed once the cancellation request has been
/// dealt with.
/// - Note: Cancellation will always fail if ``invoke(onError:onResponsePart:)`` has not been called.
public func cancel(promise: EventLoopPromise<Void>?) {
if self.eventLoop.inEventLoop {
self._cancel(promise: promise)
} else {
self.eventLoop.execute {
self._cancel(promise: promise)
}
}
}
}
extension Call {
/// Send a request part on the RPC.
/// - Parameter part: The request part to send.
/// - Returns: A future which will be resolved when the request has been handled.
/// - Note: Sending will always fail if ``invoke(onError:onResponsePart:)`` has not been called.
@inlinable
public func send(_ part: GRPCClientRequestPart<Request>) -> EventLoopFuture<Void> {
let promise = self.eventLoop.makePromise(of: Void.self)
self.send(part, promise: promise)
return promise.futureResult
}
/// Attempt to cancel the RPC.
/// - Note: Cancellation will always fail if ``invoke(onError:onResponsePart:)`` has not been called.
/// - Returns: A future which will be resolved when the cancellation request has been cancelled.
public func cancel() -> EventLoopFuture<Void> {
let promise = self.eventLoop.makePromise(of: Void.self)
self.cancel(promise: promise)
return promise.futureResult
}
}
extension Call {
internal func compress(_ compression: Compression) -> Bool {
return compression.isEnabled(callDefault: self.isCompressionEnabled)
}
internal func sendMessages<Messages>(
_ messages: Messages,
compression: Compression,
promise: EventLoopPromise<Void>?
) where Messages: Sequence, Messages.Element == Request {
if self.eventLoop.inEventLoop {
if let promise = promise {
self._sendMessages(messages, compression: compression, promise: promise)
} else {
self._sendMessages(messages, compression: compression)
}
} else {
self.eventLoop.execute {
if let promise = promise {
self._sendMessages(messages, compression: compression, promise: promise)
} else {
self._sendMessages(messages, compression: compression)
}
}
}
}
// Provide a few convenience methods we need from the wrapped call objects.
private func _sendMessages<Messages>(
_ messages: Messages,
compression: Compression
) where Messages: Sequence, Messages.Element == Request {
self.eventLoop.assertInEventLoop()
let compress = self.compress(compression)
var iterator = messages.makeIterator()
var maybeNext = iterator.next()
while let current = maybeNext {
let next = iterator.next()
// If there's no next message, then we'll flush.
let flush = next == nil
self._send(.message(current, .init(compress: compress, flush: flush)), promise: nil)
maybeNext = next
}
}
private func _sendMessages<Messages>(
_ messages: Messages,
compression: Compression,
promise: EventLoopPromise<Void>
) where Messages: Sequence, Messages.Element == Request {
self.eventLoop.assertInEventLoop()
let compress = self.compress(compression)
var iterator = messages.makeIterator()
var maybeNext = iterator.next()
while let current = maybeNext {
let next = iterator.next()
let isLast = next == nil
// We're already on the event loop, use the `_` send.
if isLast {
// Only flush and attach the promise to the last message.
self._send(.message(current, .init(compress: compress, flush: true)), promise: promise)
} else {
self._send(.message(current, .init(compress: compress, flush: false)), promise: nil)
}
maybeNext = next
}
}
}
extension Call {
/// Invoke the RPC with this response part handler.
/// - Important: This *must* to be called from the `eventLoop`.
@usableFromInline
internal func _invoke(
onStart: @escaping () -> Void,
onError: @escaping (Error) -> Void,
onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
) {
self.eventLoop.assertInEventLoop()
switch self._state {
case let .idle(factory):
let transport = factory.makeConfiguredTransport(
to: self.path,
for: self.type,
withOptions: self.options,
onEventLoop: self.eventLoop,
interceptedBy: self._interceptors,
onStart: onStart,
onError: onError,
onResponsePart: onResponsePart
)
self._state = .invoked(transport)
case .invoked:
// We can't be invoked twice. Just ignore this.
()
}
}
/// Send a request part on the transport.
/// - Important: This *must* to be called from the `eventLoop`.
@inlinable
internal func _send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
self.eventLoop.assertInEventLoop()
switch self._state {
case .idle:
promise?.fail(GRPCError.InvalidState("Call must be invoked before sending request parts"))
case let .invoked(transport):
transport.send(part, promise: promise)
}
}
/// Attempt to cancel the call.
/// - Important: This *must* to be called from the `eventLoop`.
private func _cancel(promise: EventLoopPromise<Void>?) {
self.eventLoop.assertInEventLoop()
switch self._state {
case .idle:
promise?.succeed(())
self.channelPromise?.fail(GRPCStatus(code: .cancelled))
case let .invoked(transport):
transport.cancel(promise: promise)
}
}
/// Get the underlying `Channel` for this call.
/// - Important: This *must* to be called from the `eventLoop`.
private func _channel() -> EventLoopFuture<Channel> {
self.eventLoop.assertInEventLoop()
switch (self.channelPromise, self._state) {
case let (.some(promise), .idle),
let (.some(promise), .invoked):
// We already have a promise, just use that.
return promise.futureResult
case (.none, .idle):
// We need to allocate a promise and ask the transport for the channel later.
let promise = self.eventLoop.makePromise(of: Channel.self)
self.channelPromise = promise
return promise.futureResult
case let (.none, .invoked(transport)):
// Just ask the transport.
return transport.getChannel()
}
}
}
extension Call {
// These helpers are for our wrapping call objects (`UnaryCall`, etc.).
/// Invokes the call and sends a single request. Sends the metadata, request and closes the
/// request stream.
/// - Parameters:
/// - request: The request to send.
/// - onError: A callback invoked when an error is received.
/// - onResponsePart: A callback invoked for each response part received.
@inlinable
internal func invokeUnaryRequest(
_ request: Request,
onStart: @escaping () -> Void,
onError: @escaping (Error) -> Void,
onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
) {
if self.eventLoop.inEventLoop {
self._invokeUnaryRequest(
request: request,
onStart: onStart,
onError: onError,
onResponsePart: onResponsePart
)
} else {
self.eventLoop.execute {
self._invokeUnaryRequest(
request: request,
onStart: onStart,
onError: onError,
onResponsePart: onResponsePart
)
}
}
}
/// Invokes the call for streaming requests and sends the initial call metadata. Callers can send
/// additional messages and end the stream by calling `send(_:promise:)`.
/// - Parameters:
/// - onError: A callback invoked when an error is received.
/// - onResponsePart: A callback invoked for each response part received.
@inlinable
internal func invokeStreamingRequests(
onStart: @escaping () -> Void,
onError: @escaping (Error) -> Void,
onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
) {
if self.eventLoop.inEventLoop {
self._invokeStreamingRequests(
onStart: onStart,
onError: onError,
onResponsePart: onResponsePart
)
} else {
self.eventLoop.execute {
self._invokeStreamingRequests(
onStart: onStart,
onError: onError,
onResponsePart: onResponsePart
)
}
}
}
/// On-`EventLoop` implementation of `invokeUnaryRequest(request:_:)`.
@usableFromInline
internal func _invokeUnaryRequest(
request: Request,
onStart: @escaping () -> Void,
onError: @escaping (Error) -> Void,
onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
) {
self.eventLoop.assertInEventLoop()
assert(self.type == .unary || self.type == .serverStreaming)
self._invoke(onStart: onStart, onError: onError, onResponsePart: onResponsePart)
self._send(.metadata(self.options.customMetadata), promise: nil)
self._send(
.message(request, .init(compress: self.isCompressionEnabled, flush: false)),
promise: nil
)
self._send(.end, promise: nil)
}
/// On-`EventLoop` implementation of `invokeStreamingRequests(_:)`.
@usableFromInline
internal func _invokeStreamingRequests(
onStart: @escaping () -> Void,
onError: @escaping (Error) -> Void,
onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
) {
self.eventLoop.assertInEventLoop()
assert(self.type == .clientStreaming || self.type == .bidirectionalStreaming)
self._invoke(onStart: onStart, onError: onError, onResponsePart: onResponsePart)
self._send(.metadata(self.options.customMetadata), promise: nil)
}
}
#if compiler(>=5.6)
// @unchecked is ok: all mutable state is accessed/modified from the appropriate event loop.
extension Call: @unchecked Sendable where Request: Sendable, Response: Sendable {}
#endif
| 774eccd2a2a8d640e35673a3017ebcaa | 34.257848 | 121 | 0.683052 | false | false | false | false |
onmyway133/Github.swift | refs/heads/master | GithubSwiftTests/Classes/ServerSpec.swift | mit | 1 | //
// ServerSpec.swift
// GithubSwift
//
// Created by Khoa Pham on 09/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import GithubSwift
import Quick
import Nimble
import Mockingjay
import RxSwift
import Sugar
class ServerSpec: QuickSpec {
override func spec() {
describe("+HTTPSEnterpriseServerWithServer") {
it("should convert a http URL to a HTTPS URL") {
let httpServer = Server(baseURL: NSURL(string: "http://github.enterprise")!)
expect(httpServer.baseURL?.scheme).to(equal("http"))
let httpsServer = Server.HTTPSEnterpriseServer(httpServer)
expect(httpsServer.baseURL?.scheme).to(equal("https"))
expect(httpsServer.baseURL?.host).to(equal(httpServer.baseURL?.host))
expect(httpsServer.baseURL?.path).to(equal("/"))
}
}
describe("server") {
it("should have a dotComServer") {
let dotComServer = Server.dotComServer
expect(dotComServer).notTo(beNil())
expect(dotComServer.baseURL).to(beNil())
expect(dotComServer.baseWebURL).to(equal(NSURL(string: Server.dotcomBaseWebURL)))
expect(dotComServer.APIEndpoint).to(equal(NSURL(string: Server.dotComAPIEndpoint)))
expect((dotComServer.isEnterprise)).to(beFalsy())
}
it("should be only one dotComServer") {
let dotComServer = Server([:])
expect(dotComServer).to(equal(Server.dotComServer))
}
it("can be an enterprise instance") {
let enterpriseServer = Server(baseURL: NSURL(string: "https://localhost/")!)
expect(enterpriseServer).notTo(beNil())
expect((enterpriseServer.isEnterprise)).to(beTruthy())
expect(enterpriseServer.baseURL).to(equal(NSURL(string: "https://localhost/")!))
expect(enterpriseServer.baseWebURL).to(equal(enterpriseServer.baseURL))
expect(enterpriseServer.APIEndpoint).to(equal(NSURL(string: "https://localhost/api/v3/")))
}
it("should use baseURL for equality") {
let dotComServer = Server.dotComServer
let enterpriseServer = Server(baseURL: NSURL(string:"https://localhost/")!)
let secondEnterpriseServer = Server(baseURL: NSURL(string:"https://localhost/")!)
let thirdEnterpriseServer = Server(baseURL: NSURL(string:"https://192.168.0.1")!)
expect(dotComServer).notTo(equal(enterpriseServer))
expect(dotComServer).notTo(equal(secondEnterpriseServer))
expect(dotComServer).notTo(equal(thirdEnterpriseServer))
expect(enterpriseServer).to(equal(secondEnterpriseServer))
expect(enterpriseServer).notTo(equal(thirdEnterpriseServer))
expect(secondEnterpriseServer).notTo(equal(thirdEnterpriseServer))
}
}
}
}
| fadcf56dd58fd5018a2dd1d3409578ff | 35.5 | 98 | 0.661749 | false | false | false | false |
zisko/swift | refs/heads/master | test/SILGen/access_marker_gen.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen -enable-sil-ownership %s | %FileCheck %s
func modify<T>(_ x: inout T) {}
public struct S {
var i: Int
var o: AnyObject?
}
// CHECK-LABEL: sil hidden [noinline] @$S17access_marker_gen5initSyAA1SVyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> @owned S {
// CHECK: bb0(%0 : @owned $Optional<AnyObject>):
// CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S }
// CHECK: [[ADDR:%.*]] = project_box [[MARKED_BOX]] : ${ var S }, 0
// CHECK: cond_br %{{.*}}, bb1, bb2
// CHECK: bb1:
// CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS1]] : $*S
// CHECK: end_access [[ACCESS1]] : $*S
// CHECK: bb2:
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS2]] : $*S
// CHECK: end_access [[ACCESS2]] : $*S
// CHECK: bb3:
// CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S
// CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S
// CHECK: end_access [[ACCESS3]] : $*S
// CHECK: return [[RET]] : $S
// CHECK-LABEL: } // end sil function '$S17access_marker_gen5initSyAA1SVyXlSgF'
@inline(never)
func initS(_ o: AnyObject?) -> S {
var s: S
if o == nil {
s = S(i: 0, o: nil)
} else {
s = S(i: 1, o: o)
}
return s
}
@inline(never)
func takeS(_ s: S) {}
// CHECK-LABEL: sil @$S17access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: %[[ADDRS:.*]] = project_box %[[BOX]] : ${ var S }, 0
// CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S
// CHECK: %[[ADDRI:.*]] = struct_element_addr %15 : $*S, #S.i
// CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int
// CHECK: end_access %[[ACCESS1]] : $*S
// CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S
// CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S
// CHECK: end_access %[[ACCESS2]] : $*S
// CHECK-LABEL: } // end sil function '$S17access_marker_gen14modifyAndReadSyyF'
public func modifyAndReadS() {
var s = initS(nil)
s.i = 42
takeS(s)
}
var global = S(i: 0, o: nil)
func readGlobal() -> AnyObject? {
return global.o
}
// CHECK-LABEL: sil hidden @$S17access_marker_gen10readGlobalyXlSgyF
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S17access_marker_gen6globalAA1SVvau :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]()
// CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S
// CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]]
// CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o
// CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]]
// CHECK-NEXT: end_access [[T2]]
// CHECK-NEXT: return [[T4]]
public struct HasTwoStoredProperties {
var f: Int = 7
var g: Int = 9
// CHECK-LABEL: sil hidden @$S17access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> ()
// CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g
// CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f
// CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties
mutating func noOverlapOnAssignFromPropToProp() {
f = g
}
}
class C {
final var x: Int = 0
}
func testClassInstanceProperties(c: C) {
let y = c.x
c.x = y
}
// CHECK-LABEL: sil hidden @$S17access_marker_gen27testClassInstanceProperties1cyAA1CC_tF :
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: assign [[Y]] to [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
class D {
var x: Int = 0
}
// materializeForSet callback
// CHECK-LABEL: sil private [transparent] @$S17access_marker_gen1DC1xSivmytfU_
// CHECK: end_unpaired_access [dynamic] %1 : $*Builtin.UnsafeValueBuffer
// materializeForSet
// CHECK-LABEL: sil hidden [transparent] @$S17access_marker_gen1DC1xSivm
// CHECK: [[T0:%.*]] = ref_element_addr %2 : $D, #D.x
// CHECK-NEXT: begin_unpaired_access [modify] [dynamic] [[T0]] : $*Int
func testDispatchedClassInstanceProperty(d: D) {
modify(&d.x)
}
// CHECK-LABEL: sil hidden @$S17access_marker_gen35testDispatchedClassInstanceProperty1dyAA1DC_tF
// CHECK: [[D:%.*]] = begin_borrow %0 : $D
// CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!materializeForSet.1
// CHECK: apply [[METHOD]]({{.*}}, [[D]])
// CHECK-NOT: begin_access
// CHECK: end_borrow [[D]] from %0 : $D
| b8df5c999baa602427cc7f608d7150cd | 39.751825 | 170 | 0.597349 | false | false | false | false |
CaiMiao/CGSSGuide | refs/heads/master | DereGuide/View/Option/StepperOption.swift | mit | 1 | //
// StepperOption.swift
// DereGuide
//
// Created by zzk on 2017/8/19.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
class StepperOption: UIControl {
var leftLabel: UILabel!
var stepper: ValueStepper!
override init(frame: CGRect) {
super.init(frame: frame)
stepper = ValueStepper()
stepper.tintColor = Color.parade
stepper.numberFormatter.maximumFractionDigits = 0
stepper.stepValue = 1
addSubview(stepper)
stepper.snp.makeConstraints { (make) in
make.width.equalTo(140)
make.top.equalToSuperview()
make.right.equalToSuperview()
make.bottom.equalToSuperview()
}
stepper.valueLabel.snp.remakeConstraints { (make) in
make.center.equalToSuperview()
}
leftLabel = UILabel()
addSubview(leftLabel)
leftLabel.numberOfLines = 2
leftLabel.adjustsFontSizeToFitWidth = true
leftLabel.baselineAdjustment = .alignCenters
leftLabel.font = UIFont.systemFont(ofSize: 14)
leftLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(stepper)
make.left.equalToSuperview()
make.right.lessThanOrEqualTo(stepper.snp.left)
}
stepper.descriptionLabel.removeFromSuperview()
}
func setup(title: String, minValue: Double, maxValue: Double, currentValue: Double) {
self.leftLabel.text = title
stepper.minimumValue = minValue
stepper.maximumValue = maxValue
stepper.value = currentValue
}
override func addTarget(_ target: Any?, action: Selector, for controllEvents: UIControlEvents) {
stepper.addTarget(target, action: action, for: controllEvents)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 7ea43d802dab9dcf4de024e0fcb4645b | 28.69697 | 100 | 0.622959 | false | false | false | false |
CallMeMrAlex/DYTV | refs/heads/master | DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Main(主框架)/Controller/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// DYTV-AlexanderZ-Swift
//
// Created by Alexander Zou on 16/9/23.
// Copyright © 2016年 Alexander Zou. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVCs()
}
}
extension MainViewController {
fileprivate func addChildVCs() {
tabBar.tintColor = UIColor.orange
addChildViewController(HomeViewController(), title: "首页", imageName: "btn_home_normal", selImg: "btn_home_selected")
addChildViewController(LiveViewController(), title: "直播", imageName: "btn_column_normal",selImg: "btn_column_selected")
addChildViewController(FollowViewController(), title: "关注", imageName: "btn_live_normal",selImg: "btn_live_selected")
addChildViewController(MineViewController(), title: "我的", imageName: "btn_user_normal", selImg: "btn_user_selected")
}
fileprivate func addChildViewController(_ vc: UIViewController, title: String, imageName: String, selImg:String) {
// 设置标题
vc.tabBarItem.title = title
// 设置图像
vc.tabBarItem.image = UIImage(named: imageName)
vc.tabBarItem.selectedImage = UIImage(named: selImg)
// 导航控制器
let nav = CustomNavViewController(rootViewController: vc)
addChildViewController(nav)
}
}
| 984b42022e69e854f74120c1a1666dc0 | 29.270833 | 127 | 0.650379 | false | false | false | false |
qiscus/qiscus-sdk-ios | refs/heads/master | Qiscus/Qiscus/View/QChatCell/QCellCardRight.swift | mit | 1 | //
// QCellCardRight.swift
// Example
//
// Created by Ahmad Athaullah on 8/1/17.
// Copyright © 2017 Ahmad Athaullah. All rights reserved.
//
import UIKit
import SwiftyJSON
class QCellCardRight: QChatCell {
@IBOutlet weak var buttonArea: UIStackView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var displayView: UIImageView!
@IBOutlet weak var cardTitle: UILabel!
@IBOutlet weak var cardDescription: UITextView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var cardHeight: NSLayoutConstraint!
@IBOutlet weak var buttonAreaHeight: NSLayoutConstraint!
@IBOutlet weak var topMargin: NSLayoutConstraint!
var buttons = [UIButton]()
override func awakeFromNib() {
super.awakeFromNib()
self.containerView.layer.cornerRadius = 10.0
self.containerView.layer.borderWidth = 0.5
self.containerView.layer.borderColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1).cgColor
self.containerView.clipsToBounds = true
self.displayView.contentMode = .scaleAspectFill
self.displayView.clipsToBounds = true
}
override func commentChanged() {
if let color = self.userNameColor {
self.userNameLabel.textColor = color
}
let data = self.comment!.data
let payload = JSON(parseJSON: data)
let title = payload["title"].stringValue
let description = payload["description"].stringValue
let imageURL = payload["image"].stringValue
self.cardTitle.text = title
self.displayView.loadAsync(imageURL, onLoaded: {(image, _) in
self.displayView.image = image
})
self.cardDescription.text = description
if self.showUserName{
userNameLabel.isHidden = false
topMargin.constant = 20
}else{
userNameLabel.isHidden = true
topMargin.constant = 0
}
let buttonsData = payload["buttons"].arrayValue
let buttonWidth = self.buttonArea.frame.size.width
for currentButton in self.buttons {
self.buttonArea.removeArrangedSubview(currentButton)
currentButton.removeFromSuperview()
}
self.buttons = [UIButton]()
var yPos = CGFloat(0)
let titleColor = UIColor(red: 101/255, green: 119/255, blue: 183/255, alpha: 1)
var i = 0
for buttonData in buttonsData{
let buttonFrame = CGRect(x: 0, y: yPos, width: buttonWidth, height: 45)
let button = UIButton(frame: buttonFrame)
button.setTitle(buttonData["label"].stringValue, for: .normal)
button.tag = i
let borderFrame = CGRect(x: 0, y: 0, width: buttonWidth, height: 0.5)
let buttonBorder = UIView(frame: borderFrame)
buttonBorder.backgroundColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
button.setTitleColor(titleColor, for: .normal)
button.addSubview(buttonBorder)
self.buttons.append(button)
self.buttonArea.addArrangedSubview(button)
button.addTarget(self, action: #selector(cardButtonTapped(_:)), for: .touchUpInside)
yPos += 45
i += 1
}
self.buttonAreaHeight.constant = yPos
self.cardHeight.constant = 90 + yPos
self.containerView.layoutIfNeeded()
}
@objc func cardButtonTapped(_ sender: UIButton) {
let data = self.comment!.data
let payload = JSON(parseJSON: data)
let buttonsData = payload["buttons"].arrayValue
if buttonsData.count > sender.tag {
self.delegate?.didTapCardButton(onComment: self.comment!, index: sender.tag)
}
}
public override func updateUserName() {
if let sender = self.comment?.sender {
self.userNameLabel.text = sender.fullname
}else{
self.userNameLabel.text = self.comment?.senderName
}
}
}
| 2e027b9e541386964dd25c43d1d0de16 | 36.518519 | 105 | 0.62463 | false | false | false | false |
psturm-swift/SwiftySignals | refs/heads/master | Sources/Property.swift | mit | 1 | // Copyright (c) 2017 Patrick Sturm <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE
import Foundation
public final class Property<T> {
private let _observable: ObservableSync<T>
private let _syncQueue: DispatchQueue
private var _value: T
public var value: T {
set {
self._syncQueue.async(flags: .barrier) {
self._value = newValue
self._observable.send(message: newValue)
}
}
get {
var syncedValue: T!
self._syncQueue.sync {
syncedValue = self._value
}
return syncedValue
}
}
public var didSet: EndPoint<ObservableSync<T>> {
return EndPoint<ObservableSync<T>>(
observable: _observable,
dispatchQueue: DispatchQueue.main)
}
public init(value: T) {
let syncQueue = DispatchQueue(label: "SwiftySignals.Property", attributes: .concurrent)
self._observable = ObservableSync<T>()
self._syncQueue = syncQueue
self._value = value
self._observable.send(message: value)
}
deinit {
_observable.unsubscribeAll()
}
}
| 77384bd7c9d681a3f08a5c7573418f9f | 35.918033 | 95 | 0.665187 | false | false | false | false |
ozgur/MovingCells | refs/heads/master | MovingCells/ImageDataSource.swift | mit | 1 | //
// ImageDataSource.swift
// MovingCells
//
// Created by Ozgur Vatansever on 4/24/16.
// Copyright © 2016 Techshed. All rights reserved.
//
import UIKit
class ImageDataSource {
fileprivate var images = [UIImage]()
init() {
self.loadImages()
}
fileprivate func loadImages() {
let filePath = Bundle.main.path(forResource: "Images", ofType: "plist")!
images.removeAll()
for loadedImage in NSArray(contentsOfFile: filePath) ?? [] {
if let imageDict = loadedImage as? [String: String] {
images.append(UIImage(named: imageDict["image"]!)!)
}
}
}
subscript(index: Int) -> UIImage? {
if index < 0 || index >= images.count {
return nil
}
return images[index]
}
var count: Int {
return images.count
}
func exchangeImageAtIndex(_ index: Int, withImageAtIndex otherIndex: Int) {
if index != otherIndex {
swap(&images[index], &images[otherIndex])
}
}
}
| 8d2fecfda38d532a9f1383dc39f2a57f | 20.086957 | 77 | 0.620619 | false | false | false | false |
ZeeQL/ZeeQL3 | refs/heads/develop | Sources/ZeeQL/Access/SQLExpression.swift | apache-2.0 | 1 | //
// SQLExpression.swift
// ZeeQL
//
// Created by Helge Heß on 18.02.17.
// Copyright © 2017-2019 ZeeZide GmbH. All rights reserved.
//
import struct Foundation.Date
/**
* This class is used to generate adaptor specific SQL. Usually for mapped
* qualifiers and records (but it also works for 'raw' values if the entity is
* missing).
*
* For example this class maps Qualifier's to their SQL representation. This
* requires proper quoting of values and mapping of attribute names to columns
* names.
*
* The final generation (prepare...) is triggered by the AdaptorChannel when
* it is asked to perform an adaptor operation. It turns the AdaptorOperation
* into a straight method call (eg selectAttributes) which in turn uses the
* SQLExpressionFactory to create and prepare an expression.
*
* ## Raw SQL Patterns
*
* If the 'CustomQueryExpressionHintKey' is set, the value of this key is
* processed as a keyvalue-format pattern to produce the SQL. SQLExpression
* will still prepare and provide the parts of the SQL (eg qualifiers, sorts)
* but the assembly will be done using the SQL pattern.
*
* Example:
*
* SELECT COUNT(*) FROM %(tables)s %(where)s %(limit)s
*
* Keys:
* | select | eg SELECT or SELECT DISTINCT
* | columns | eg BASE.lastname, BASE.firstname
* | tables | eg BASE.customer
* | basetable | eg customer
* | qualifier | eg lastname LIKE 'Duck%'
* | orderings | eg lastname ASC, firstname DESC
* | limit | eg OFFSET 0 LIMIT 1
* | lock | eg FOR UPDATE
* | joins |
*
* Compound:
*
* | where | eg WHERE lastname LIKE 'Duck%'
* | andQualifier | eg AND lastname LIKE 'Duck%' (nothing w/o qualifier)
* | orQualifier | eg OR lastname LIKE 'Duck%' (nothing w/o qualifier)
* | orderby | eg ORDER BY mod_date DESC (nothing w/o orderings)
* | andOrderBy | eg mod_date DESC (nothing w/o orderings)
*
* Note: parts which involve bind variables (eg andQualifier) can only be used
* ONCE! This is because the bindings are generated only once, but the
* '?' in the SQL are generated multiple times. Hence the
* PreparedStatement will report that not all '?' bindings are set!
* (TBD: fix me, make generation dynamic)
*
*
* ## How it works
*
* The main methods are the four prepare.. methods,
* prepareSelectExpressionWithAttributes(), prepareUpdateExpressionWith.. etc.
* Those methods are usually called by the SQLExpressionFactory, which first
* allocates the SQLExpression subclass (as provided by the specific database
* adaptor) and calls the prepare... method.
*/
open class SQLExpression: SmartDescription {
// TODO(Swift): Maybe mark stuff as throws and throw generation errors.
// This would avoid some nil-values.
// TODO(Swift): Naming.
public static let CustomQueryExpressionHintKey =
"CustomQueryExpressionHintKey"
public final let BaseEntityPath = ""
public final let BaseEntityAlias = "BASE"
open var log : ZeeQLLogger = globalZeeQLLogger
public var statement = "" // SQL result
public let entity : Entity?
public var listString = ""
public var valueList = ""
/**
* Contains the list of bindings which got created during SQL construction. A
* bind dictionary contains such keys:
*
* - BindVariableAttributeKey - the Attribute object
* - BindVariablePlaceHolderKey - the placeholder used in the SQL (eg '?')
* - BindVariableNameKey - the name which is bound
*
* @return a List of bind records.
*/
public struct BindVariable {
public var attribute : Attribute? = nil
public var placeholder : String = "?"
public var name : String = ""
public var value : Any? = nil
public init() {}
}
public var bindVariables = [ BindVariable ]()
public var useAliases = false // only true for selects
public var useBindVariables = false
var relationshipPathToAlias = [ String : String ]()
var relationshipPathToRelationship = [ String : Relationship ]()
var joinClauseString = ""
/* transient state */
var qualifier : Qualifier?
public init(entity: Entity? = nil) {
self.entity = entity
if entity != nil {
relationshipPathToAlias[BaseEntityPath] = BaseEntityAlias
}
}
/* preparation and assembly */
open func prepareDeleteExpressionFor(qualifier q: Qualifier) {
guard let entity = self.entity else { return } // required
useAliases = false
qualifier = q
/* where */
guard let whereClause = whereClauseString else {
log.error("got no whereClause despite qualifier?!", q)
return
}
/* table list */
let table = sqlStringFor(schemaObjectName: entity.externalName
?? entity.name)
/* assemble */
statement = assembleDeleteStatementWithQualifier(q, table, whereClause)
/* tear down */
qualifier = nil
}
open func assembleDeleteStatementWithQualifier(_ q : Qualifier,
_ tableList : String,
_ whereClause : String)
-> String
{
return "DELETE FROM \(tableList) WHERE \(whereClause)"
}
/**
* This method calls addInsertListAttribute() for each key/value in the given
* row. It then builds the table name using tableListWithRootEntity().
* And finally calls assembleInsertStatementWithRow() to setup the final
* SQL.
*
* The result is stored in the 'self.statement' ivar.
*
* @param _row - the keys/values to INSERT
*/
open func prepareInsertExpressionWithRow(_ row: [ String : Any? ]) {
// TODO: add method to insert multiple rows
// Note: we need the entity for the table name ...
guard let entity = entity else { return }
useAliases = false
/* fields and values */
for key in row.keys {
guard let attr = entity[attribute: key] ?? entity[columnName: key] else {
globalZeeQLLogger.log("did not find attribute", key, "of", row,
"in", entity)
continue
}
if let value = row[key] {
addInsertListAttribute(attr, value: value)
}
else {
addInsertListAttribute(attr, value: nil)
}
}
/* table list */
let tables = tableListWith(rootEntity: entity)
/* assemble */
statement =
assembleInsertStatementWithRow(row, tables, listString, valueList)
}
func assembleInsertStatementWithRow(_ row : AdaptorRow,
_ tableList : String,
_ columnList : String?,
_ valueList : String)
-> String
{
var sb = "INSERT INTO \(tableList)"
if let cl = columnList { sb += " ( \(cl) )" }
sb += " VALUES ( \(valueList) )"
return sb
}
/**
* Method to assemble multi-row inserts. Subclasses might onverride that to
* generate multiple INSERT statements separated by a semicolon.
*
* In PostgreSQL this is available with 8.2.x, the syntax is:
*
* INSERT INTO Log ( a, b ) VALUES (1,2), (3,4), (5,6);
*
* @param rows - list of rows to insert
* @param _tableList - SQL table reference (eg 'address')
* @param _columnList - SQL list of columns (eg 'firstname, lastname')
* @param _valueLists - SQL list of values
* @return assembles SQL, or null if there where no values
*/
open func assembleInsertStatementWithRows(_ rows : [ AdaptorRow ],
_ tableList : String,
_ columnList : String?,
_ valueLists : [ String ])
-> String?
{
guard !valueLists.isEmpty else { return nil }
// hm, PG also allows: INSERT INTO a DEFAULT VALUES;
var sb = "INSERT INTO \(tableList)"
if let cl = columnList { sb += " ( \(cl) )" }
sb += " VALUES "
var isFirst = true
for v in valueLists {
guard !v.isEmpty else { continue }
if isFirst { isFirst = false }
else { sb += ", " }
sb += "( \(v) )"
}
return sb
}
open func prepareUpdateExpressionWithRow(_ row : AdaptorRow,
_ q : Qualifier)
{
guard !row.isEmpty else {
log.error("missing row for update ...")
statement.removeAll()
return
}
guard let entity = entity else { return }
useAliases = false
qualifier = q
/* fields and values */
/* Note: needs to be done _before_ the whereClause, so that the ordering of
* the bindings is correct.
*/
for key in row.keys {
guard let attr = entity[attribute: key] else { continue }
if let value = row[key] {
addUpdateListAttribute(attr, value: value)
}
else {
addUpdateListAttribute(attr, value: nil)
}
}
/* where */
guard let whereClause = whereClauseString else {
log.error("got no where clause despite qualifier?!", q)
return
}
/* table list */
let tables = tableListWith(rootEntity: entity)
/* assemble */
statement = assembleUpdateStatementWithRow(row, q, tables, listString,
whereClause)
/* tear down */
qualifier = nil
}
open func assembleUpdateStatementWithRow(_ row : AdaptorRow,
_ q : Qualifier,
_ table : String,
_ vals : String,
_ _where : String) -> String
{
var sb = "UPDATE \(table) SET \(vals)"
if !_where.isEmpty { sb += " WHERE \(_where)" }
return sb
}
/**
* The primary entry point to create SQL SELECT expressions. Its usually
* called by the SQLExpressionFactory after it instantiated an adaptor
* specific SQLExpression class.
*
* What this method does:
*
* - checks for the CustomQueryExpressionHintKey
* - conjoins the restrictingQualifier of the Entity with the one of the
* FetchSpecification
* - builds the select prefix (SELECT, SELECT DISTINCT) depending on the
* `usesDistinct` setting of the FetchSpecification
* - builds the list of columns by calling addSelectListAttribute() with
* each attribute given, or uses '*' if none are specified
* - call `whereClauseString` to build the SQL WHERE expression, if
* relationships are used in the qualifiers, this will fill join related
* maps in the expression context (e.g. aliasesByRelationshipPath)
* - builds sort orderings by calling addOrderByAttributeOrdering() wtih
* each SortOrdering in the FetchSpecification
* - calls `joinClauseString` to create the SQL required for the JOINs
* to flatten relationships
* - builds the list of tables
* - builds lock and limit expressions
* - finally assembles the statements using either
* `assembleSelectStatementWithAttributes()`
* or
* `assembleCustomSelectStatementWithAttributes()`. The latter is used if
* a `CustomQueryExpressionHintKey` was set.
*
* The result of the method is stored in the `statement` ivar.
*
* - parameters:
* - attrs: the attributes to fetch, or null to fetch all (* SELECT)
* - lock: whether the rows/table should be locked in the database
* - fspec: the FetchSpecification containing the qualifier, etc
*/
open func prepareSelectExpressionWithAttributes(_ attrs : [ Attribute ],
_ lock : Bool,
_ fspec : FetchSpecification?)
{
/* check for custom statements */
let customSQL =
fspec?[hint: SQLExpression.CustomQueryExpressionHintKey] as? String
useAliases = true
qualifier = fspec?.qualifier
/* apply restricting qualifier */
let q = entity?.restrictingQualifier
if let q = q {
if let bq = qualifier {
qualifier = bq.and(q)
}
else {
qualifier = q
}
}
/* check for distinct */
let select = (fspec?.usesDistinct ?? false) ? "SELECT DISTINCT" : "SELECT"
/* prepare columns to select */
// TODO: Some database require that values used in the qualifiers and/or
// sort orderings are part of the SELECT. Support that.
let columns : String
if !attrs.isEmpty {
listString.removeAll()
for attr in attrs {
self.addSelectListAttribute(attr)
}
columns = listString
listString.removeAll()
}
else {
columns = "*"
}
/* prepare where clause (has side effects for joins etc) */
let whereClause = whereClauseString
/* prepare order bys */
let orderBy : String?
let fetchOrder = fspec?.sortOrderings
if let fetchOrder = fetchOrder, !fetchOrder.isEmpty {
listString.removeAll()
for so in fetchOrder {
addOrderByAttributeOrdering(so)
}
orderBy = listString
listString.removeAll()
}
else {
orderBy = nil
}
/* joins, must be done before the tablelist is generated! */
let inlineJoins = doesIncludeJoinsInFromClause
joinExpression()
let joinClause : String? = inlineJoins
? nil /* will be processed in tableListAndJoinsWithRootEntity() */
: joinClauseString
/* table list */
let tables : String?
if let entity = entity {
tables = inlineJoins
? tableListAndJoinsWith(rootEntity: entity)
: tableListWith(rootEntity: entity)
}
else {
tables = nil
}
/* lock */
let lockClause = lock ? self.lockClause : nil
/* limits */
let limitClause = self.limitClause(offset: fspec?.fetchOffset ?? -1,
limit: fspec?.fetchLimit ?? -1)
// TODO: GROUP BY expression [, ...]
// TODO: HAVING condition [, ...]
/* we are done, assemble */
if let customSQL = customSQL {
statement = assembleCustomSelectStatementWithAttributes(
attrs, lock, q, fetchOrder,
customSQL,
select, columns, tables, whereClause, joinClause, orderBy,
limitClause, lockClause) ?? ""
}
else {
statement = assembleSelectStatementWithAttributes(
attrs, lock, q, fetchOrder,
select, columns, tables, whereClause, joinClause, orderBy,
limitClause, lockClause)
}
}
open func assembleSelectStatementWithAttributes
(_ _attrs : [ Attribute ], _ _lock : Bool, _ _qualifier : Qualifier?,
_ _fetchOrder : [ SortOrdering ]?,
_ _select : String?,
_ _cols : String,
_ _tables : String?,
_ _where : String?,
_ _joinClause : String?,
_ _orderBy : String?,
_ _limit : String?,
_ _lockClause : String?) -> String
{
/* 128 was too small, SQL seems to be ~512 */
var sb = ""
sb.reserveCapacity(1024)
sb += _select ?? "SELECT"
sb += " "
sb += _cols
if let tables = _tables { sb += " FROM \(tables)" }
let hasWhere = !(_where ?? "").isEmpty
let hasJoinClause = !(_joinClause ?? "").isEmpty
if hasWhere || hasJoinClause {
sb += " WHERE "
if hasWhere { sb += _where ?? "" }
if hasWhere && hasJoinClause { sb += " AND " }
if hasJoinClause { sb += _joinClause ?? "" }
}
if let ob = _orderBy, !ob.isEmpty { sb += " ORDER BY \(ob)" }
if let limit = _limit { sb += " \(limit)" }
if let lockClause = _lockClause { sb += " \(lockClause)" }
return sb
}
/**
* Example:
*
* SELECT COUNT(*) FROM %(tables)s WHERE %(where)s %(limit)s
*
* Keys:
*
* select eg SELECT or SELECT DISTINCT
* columns eg BASE.lastname, BASE.firstname
* tables eg BASE.customer
* basetable eg customer
* qualifier eg lastname LIKE 'Duck%'
* orderings eg lastname ASC, firstname DESC
* limit eg OFFSET 0 LIMIT 1
* lock eg FOR UPDATE
* joins
*
* Compound:
*
* where eg WHERE lastname LIKE 'Duck%'
* andQualifier eg AND lastname LIKE 'Duck%' (nothing w/o qualifier)
* orQualifier eg OR lastname LIKE 'Duck%' (nothing w/o qualifier)
* orderby eg ORDER BY mod_date DESC (nothing w/o orderings)
* andOrderBy eg , mod_date DESC (nothing w/o orderings)
*
*/
open func assembleCustomSelectStatementWithAttributes
(_ _attrs : [ Attribute ], _ _lock : Bool, _ _qualifier: Qualifier?,
_ _fetchOrder: [ SortOrdering ]?,
_ _sqlPattern : String,
_ _select : String?,
_ _cols : String?,
_ _tables : String?,
_ _where : String?,
_ _joinClause : String?,
_ _orderBy : String?,
_ _limit : String?,
_ _lockClause : String?) -> String?
{
guard !_sqlPattern.isEmpty else { return nil }
guard _sqlPattern.contains("%") else { return _sqlPattern }
/* contains no placeholders */
/* prepare bindings */
/* Note: we need to put empty strings ("") into the bindings array for
* missing "optional" keys (eg limit), otherwise the format()
* function will render references as '<null>'.
* Eg:
* %(select)s * FROM abc %(limit)s
* If not limit is set, this will result in:
* SELECT * FROM abc <null>
*/
var bindings = [ String : Any? ]()
bindings["select"] = _select ?? ""
bindings["columns"] = _cols ?? ""
bindings["tables"] = _tables ?? ""
bindings["qualifier"] = _where ?? ""
bindings["joins"] = _joinClause ?? ""
bindings["limit"] = _limit ?? ""
bindings["lock"] = _lockClause ?? ""
bindings["orderings"] = _orderBy ?? ""
/* adding compounds */
if let w = _where, let jc = _joinClause {
bindings["where"] = " WHERE \(w) AND \(jc)"
}
else if let w = _where {
bindings["where"] = " WHERE \(w)"
}
else if let jc = _joinClause {
bindings["where"] = " WHERE \(jc)"
}
else {
bindings["where"] = ""
}
if let w = _where {
bindings["andQualifier"] = " AND \(w)"
bindings["orQualifier"] = " OR \(w)"
}
else {
bindings["andQualifier"] = ""
bindings["orQualifier"] = ""
}
if let ob = _orderBy {
bindings["orderby"] = " ORDER BY \(ob)"
bindings["andOrderBy"] = ", \(ob)"
}
else {
bindings["orderby"] = ""
bindings["andOrderBy"] = ""
}
/* some base entity information */
if let s = entity?.externalName, !s.isEmpty {
bindings["basetable"] = s
}
/* format */
return KeyValueStringFormatter.format(_sqlPattern, requiresAll: true,
object: bindings)
}
/* column lists */
/**
* This method calls sqlStringForAttribute() to get the column name of the
* attribute and then issues formatSQLString() with the configured
* `readFormat` (usually empty).
*
* The result of this is added the the 'self.listString' using
* appendItemToListString().
*
* The method is called by prepareSelectExpressionWithAttributes() to build
* the list of attributes used in the SELECT.
*/
open func addSelectListAttribute(_ attribute: Attribute) {
var s = sqlStringForAttribute(attribute)
s = formatSQLString(s, attribute.readFormat)
self.appendItem(s, to: &listString)
}
open func addUpdateListAttribute(_ attribute: Attribute, value: Any?) {
/* key */
let a = self.sqlStringForAttribute(attribute)
/* value */
// TODO: why not call sqlStringForValue()?
let useBind : Bool
if let value = value {
if value is QualifierVariable {
useBind = true
}
else if value is RawSQLValue {
useBind = false
}
else {
useBind = shouldUseBindVariable(for: attribute)
}
}
else {
useBind = self.shouldUseBindVariable(for: attribute)
}
let v : String
if useBind {
let bind = bindVariableDictionary(for: attribute, value: value)
v = bind.placeholder
addBindVariableDictionary(bind)
}
else if let value = value as? RawSQLValue {
v = value.value
}
else if let vv = formatValueForAttribute(value, attribute) {
v = vv
}
else {
log.error("could not format value:", value)
v = String(describing: value)
}
let fv : String
if let wf = attribute.writeFormat {
fv = formatSQLString(v, wf)
}
else {
fv = v
}
/* add to list */
self.appendItem(a + " = " + fv, to: &listString)
}
open func addInsertListAttribute(_ attribute: Attribute, value: Any?) {
/* key */
self.appendItem(self.sqlStringForAttribute(attribute), to: &listString)
/* value */
// TODO: why not call sqlStringForValue()?
let useBind : Bool
if let value = value {
if value is QualifierVariable {
useBind = true
}
else if value is RawSQLValue {
useBind = false
}
else {
useBind = self.shouldUseBindVariable(for: attribute)
}
}
else {
useBind = self.shouldUseBindVariable(for: attribute)
}
var v : String
if useBind {
let bind = bindVariableDictionary(for: attribute, value: value)
v = bind.placeholder
addBindVariableDictionary(bind)
}
else if let value = value as? RawSQLValue {
v = value.value
}
else if let vv = formatValueForAttribute(value, attribute) {
v = vv
}
else {
log.error("could not format value:", value)
v = String(describing: value)
}
if let wf = attribute.writeFormat {
v = formatSQLString(v, wf)
}
self.appendItem(v, to: &valueList)
}
/* limits */
open func limitClause(offset: Int = -1, limit: Int = -1) -> String? {
// TODO: offset = 0 is fine?
guard offset >= 0 || limit >= 0 else { return nil }
if offset > 0 && limit > 0 {
return "LIMIT \(limit) OFFSET \(offset)"
}
else if offset > 0 {
return "OFFSET \(offset)"
}
else {
return "LIMIT \(limit)"
}
}
/* orderings */
open func addOrderByAttributeOrdering(_ ordering: SortOrdering) {
let sel = ordering.selector
var s : String
if let attribute = entity?[attribute: ordering.key] {
s = sqlStringForAttribute(attribute)
}
else { /* raw fetch, just use the key as the SQL name */
s = ordering.key
}
if sel == SortOrdering.Selector.CompareCaseInsensitiveAscending ||
sel == SortOrdering.Selector.CompareCaseInsensitiveDescending
{
s = formatSQLString(s, "UPPER(%P)")
}
if (sel == SortOrdering.Selector.CompareCaseInsensitiveAscending ||
sel == SortOrdering.Selector.CompareAscending)
{
s += " ASC";
}
else if sel == SortOrdering.Selector.CompareCaseInsensitiveDescending ||
sel == SortOrdering.Selector.CompareDescending
{
s += " DESC";
}
/* add to list */
appendItem(s, to: &listString)
}
/* where clause */
var whereClauseString : String? {
return qualifier != nil ? sqlStringForQualifier(qualifier!) : nil
}
/* join clause */
var doesIncludeJoinsInFromClause : Bool { return true }
func sqlJoinTypeFor(relationshipPath _relPath: String,
relationship _relship: Relationship) -> String
{
// TODO: rel.joinSemantic() <= but do NOT add this because it seems easy!;-)
// consider the effects w/o proper JOIN ordering
return "LEFT JOIN" /* for now we always use LEFT JOIN */
}
/**
* Returns the list of tables to be used in the FROM of the SQL.
*
* @param _entity - root entity to use ("" alias)
* @return the list of tables, eg "person AS BASE, address T0"
*/
func tableListWith(rootEntity _entity: Entity) -> String {
var sb = ""
if useAliases, let alias = relationshipPathToAlias[""] {
// used by regular SELECTs
/* This variant just generates the table references, eg:
* person AS BASE, address AS T0, company AS T1
* the actual join is performed as part of the WHERE, and is built
* using the joinExpression() method.
*/
/* the base entity */
sb += sqlStringFor(schemaObjectName: _entity.externalName ?? _entity.name)
sb += " AS "
sb += alias
for relPath in relationshipPathToAlias.keys {
guard BaseEntityPath != relPath else { continue }
guard let rel = relationshipPathToRelationship[relPath],
let alias = relationshipPathToAlias[relPath],
let entity = rel.destinationEntity
else
{
continue
}
sb.append(", ");
let tableName = entity.externalName ?? entity.name
sb += sqlStringFor(schemaObjectName: tableName)
sb += " AS "
sb += alias
}
}
else { // use by UPDATE, DELETE, etc
// TODO: just add all table names ...
sb += sqlStringFor(schemaObjectName: _entity.externalName ?? _entity.name)
}
return sb
}
/**
* Returns the list of tables to be used in the FROM of the SQL,
* plus all necessary JOIN parts of the FROM.
*
* Builds the JOIN parts of the FROM statement, eg:
*
* person AS BASE
* LEFT JOIN address AS T0 ON ( T0.person_id = BASE.person_id )
* LEFT JOIN company AS T1 ON ( T1.owner_id = BASE.owner_id)
*
* It just adds the joins from left to right, since I don't know yet
* how to properly put the parenthesis around them :-)
*
* We currently ALWAYS build LEFT JOINs. Which is wrong, but unless we
* can order the JOINs, no option.
*
* @param _entity - root entity to use ("" alias)
* @return the list of tables, eg "person AS BASE INNER JOIN address AS T0"
*/
func tableListAndJoinsWith(rootEntity _entity: Entity) -> String {
var sb = ""
/* the base entity */
if let base = relationshipPathToAlias[""] {
sb += sqlStringFor(schemaObjectName: _entity.externalName ?? _entity.name)
sb += " AS "
sb += base
}
/* Sort the aliases by the number of components in their pathes. I
* think later we need to consider their prefixes and collect them
* in proper parenthesis
*/
let aliases = relationshipPathToAlias.keys.sorted { a, b in
return a.numberOfDots < b.numberOfDots
}
/* iterate over the aliases and build the JOIN fragments */
for relPath in aliases {
guard BaseEntityPath != relPath else { continue }
guard let rel = relationshipPathToRelationship[relPath],
let alias = relationshipPathToAlias[relPath],
let entity = rel.destinationEntity
else { continue }
let joins = rel.joins
guard !joins.isEmpty else {
log.error("found no Join's for relationship", rel)
continue /* nothing to do */
}
/* this does the 'LEFT JOIN' or 'INNER JOIN', etc */
sb += " "
sb += sqlJoinTypeFor(relationshipPath: relPath, relationship: rel)
sb += " "
/* table, eg: 'LEFT JOIN person AS T0' */
let tableName = entity.externalName ?? entity.name
sb += sqlStringFor(schemaObjectName: tableName)
sb += " AS "
sb += alias
sb += " ON ( "
let lastRelPath = relPath.lastRelPath
/* add joins */
var isFirstJoin = true
for join in joins {
guard let sa = join.source, let da = join.destination else {
log.error("join has no source or dest", join)
continue
}
//left = join.sourceAttribute().name();
//right = join.destinationAttribute().name();
let left = sqlStringForAttribute(sa, lastRelPath)
let right = sqlStringForAttribute(da, relPath)
if (isFirstJoin) { isFirstJoin = false }
else { sb += " AND " }
sb += left
sb += " = "
sb += right
}
sb += " )"
}
return sb
}
/**
* This is called by prepareSelectExpressionWithAttributes() to construct
* the SQL expression used to join the various Entity tables involved in
* the query.
*
* It constructs stuff like T1.person_id = T2.company_id. The actual joins
* are added using the addJoinClause method, which builds the expression
* (in the self.joinClauseString ivar).
*/
func joinExpression() {
guard relationshipPathToAlias.count > 1 else { return } /* only the base */
guard !doesIncludeJoinsInFromClause else { return }
/* joins are included in the FROM clause */
for relPath in relationshipPathToAlias.keys {
guard relPath != "" else { continue } /* root entity */
guard let rel = self.relationshipPathToRelationship[relPath]
else { continue }
let joins = rel.joins
guard !joins.isEmpty else { continue } /* nothing to do */
let lastRelPath = relPath.lastRelPath
/* calculate prefixes */
if self.useAliases {
#if false // noop
leftAlias = relationshipPathToAlias[lastRelPath]
rightAlias = relationshipPathToAlias[relPath]
#endif
}
else {
// TBD: presumably this has side-effects.
let ln = rel.entity.externalName ?? rel.entity.name
_ = sqlStringFor(schemaObjectName: ln) // left-alias
if let de = rel.destinationEntity {
let rn = de.externalName ?? de.name
_ = sqlStringFor(schemaObjectName: rn) // right-alias
}
}
/* add joins */
for join in joins {
guard let sa = join.source, let da = join.destination else { continue }
//left = join.source.name
//right = join.destination.name
let left = sqlStringForAttribute(sa, lastRelPath)
let right = sqlStringForAttribute(da, relPath)
addJoinClause(left, right, rel.joinSemantic)
}
}
}
/**
* Calls assembleJoinClause() to build the join expression (eg
* T1.person_id = T2.company_id). Then adds it to the 'joinClauseString'
* using AND.
*
* The semantics trigger the proper operation, eg '=', '*=', '=*' or '*=*'.
*
* @param _left - left side join expression
* @param _right - right side join expression
* @param _semantic - semantics, as passed on to assembleJoinClause()
*/
func addJoinClause(_ left: String, _ right: String,
_ semantic: Join.Semantic)
{
let jc = assembleJoinClause(left, right, semantic)
if joinClauseString.isEmpty {
joinClauseString = jc
}
else {
joinClauseString += " AND " + jc
}
}
func assembleJoinClause(_ left: String, _ right: String,
_ semantic: Join.Semantic) -> String
{
// TODO: semantic
let op : String
switch semantic {
case .innerJoin: op = " = "
case .leftOuterJoin: op = " *= "
case .rightOuterJoin: op = " =* "
case .fullOuterJoin: op = " *=* "
}
return left + op + right
}
/* basic construction */
/**
* Just adds the given _item String to the StringBuilder _sb. If the Builder
* is not empty, a ", " is added before the item.
*
* Used to assemble SELECT lists, eg:
*
* c_last_name, c_first_name
*
* @param _item - String to add
* @param _sb - StringBuilder containing the items
*/
func appendItem(_ item: String, to sb: inout String) {
if !sb.isEmpty { sb += ", " }
sb += item
}
/* formatting */
/**
* If the _format is null or contains no '%' character, the _sql is returned
* as-is.<br>
* Otherwise the '%P' String in the format is replaced with the _sql.
*
* @param _sql - SQL base expression (eg 'c_last_name')
* @param _format - pattern (eg 'UPPER(%P)')
* @return SQL string with the pattern applied
*/
func formatSQLString(_ sql: String, _ format: String?) -> String {
guard let format = format else { return sql }
guard format.contains("%") else { return format }
/* yes, the format replaces the value! */
// TODO: any other formats? what about %%P (escaped %)
return format.replacingOccurrences(of: "%P", with: sql)
}
/**
* Escapes the given String and embeds it into single quotes.
* Example:
*
* Hello World => 'Hello World'
*
* - parameter v: String to escape and quote (eg Hello World)
* - returns: the SQL escaped and quoted String (eg 'Hello World')
*/
public func formatStringValue(_ v: String?) -> String {
// TODO: whats the difference to sqlStringForString?
guard let v = v else { return "NULL" }
return "'" + escapeSQLString(v) + "'";
}
/**
* Escapes the given String and embeds it into single quotes.
* Example:
*
* Hello World => 'Hello World'
*
* - parameter v: String to escape and quote (eg Hello World)
* - returns: the SQL escaped and quoted String (eg 'Hello World')
*/
public func sqlStringFor(string v: String?) -> String {
// TBD: whats the difference to formatStringValue()? check docs
guard let v = v else { return "NULL" }
return "'" + escapeSQLString(v) + "'";
}
/**
* Returns the SQL representation of a Number. For INTs this is just the
* value, for float/doubles/bigdecs it might be database specific.
* The current implementation just calls the numbers toString() method.
*
* - parameter number: some Number object
* - returns the SQL representation of the given Number (or NULL for nil)
*/
public func sqlStringFor(number v: Int?) -> String {
guard let v = v else { return "NULL" }
return String(v)
}
// TBD: is this what we want?
public func sqlStringFor<T: BinaryInteger>(number v: T?) -> String {
guard let v = v else { return "NULL" }
return String(describing: v)
}
/**
* Returns the SQL representation of a Number. For INTs this is just the
* value, for float/doubles/bigdecs it might be database specific.
* The current implementation just calls the numbers toString() method.
*
* - parameter number: some Number object
* - returns the SQL representation of the given Number (or NULL for nil)
*/
public func sqlStringFor(number v: Double?) -> String {
guard let v = v else { return "NULL" }
return String(v)
}
/**
* Returns the SQL representation of a Number. For INTs this is just the
* value, for float/doubles/bigdecs it might be database specific.
* The current implementation just calls the numbers toString() method.
*
* - parameter number: some Number object
* - returns the SQL representation of the given Number (or NULL for nil)
*/
public func sqlStringFor(number v: Float?) -> String {
guard let v = v else { return "NULL" }
return String(v)
}
/**
* Returns the SQL representation of a Boolean. This returns TRUE and FALSE.
*
* - parameter bool: some boolean
* - returns the SQL representation of the given bool (or NULL for nil)
*/
public func sqlStringFor(bool v: Bool?) -> String {
guard let v = v else { return "NULL" }
return v ? "TRUE" : "FALSE"
}
/**
* The current implementation just returns the '\(d)' of the Date
* (which is rarely the correct thing to do).
* You should really use bindings for that.
*
* - parameters:
* - v: a Date object
* - attr: an Attribute containing formatting details
* - returns: the SQL representation of the given Date (or NULL for nil)
*/
public func formatDateValue(_ v: Date?, _ attr: Attribute? = nil) -> String? {
// TODO: FIXME. Use format specifications as denoted in the attribute
// TODO: is this called? Probably the formatting should be done using a
// binding in the JDBC adaptor
guard let v = v else { return nil }
return formatStringValue("\(v)") // TODO: FIXME
}
/**
* Returns the SQL String representation of the given value Object.
*
* - 'nil' will be rendered as the SQL 'NULL'
* - String values are rendered using formatStringValue()
* - Number values are rendered using sqlStringForNumber()
* - Date values are rendered using formatDateValue()
* - toString() is called on RawSQLValue values
* - arrays and Collections are rendered in "( )"
* - KeyGlobalID objects with one value are rendered as their value
*
* When an QualifierVariable is encountered an error is logged and null is
* returned.
* For unknown objects the string representation is rendered.
*
* - parameter v: some value to be formatted for inclusion in the SQL
* - returns: a String representing the value
*/
public func formatValue(_ v: Any?) -> String? {
// own method for basic stuff
guard let v = v else { return "NULL" }
if let v = v as? String { return self.formatStringValue(v) }
if let v = v as? Int { return self.sqlStringFor(number: v) }
if let v = v as? Int32 { return self.sqlStringFor(number: v) }
if let v = v as? Int64 { return self.sqlStringFor(number: v) }
// TBD: do we need to list all Integer types?
if let v = v as? Double { return self.sqlStringFor(number: v) }
if let v = v as? Float { return self.sqlStringFor(number: v) }
if let v = v as? Bool { return self.sqlStringFor(bool: v) }
if let v = v as? Date { return self.formatDateValue(v) }
if let v = v as? RawSQLValue { return v.value }
/* process lists */
if let list = v as? [ Int ] {
if list.isEmpty { return "( )" } // empty list
return "( " + list.map { String($0) }.joined(separator: ", ") + " )"
}
if let list = v as? [ Any? ] {
if list.isEmpty { return "( )" } // empty list
return "( " + list.map { formatValue($0) ?? "ERROR" }
.joined(separator: ", ") + " )"
}
if let key = v as? KeyGlobalID {
guard key.keyCount == 1 else {
log.error("cannot format KeyGlobalID with more than one value:", key)
return nil
}
return formatValue(key[0])
}
/* warn about qualifier variables */
if v is QualifierVariable {
log.error("detected unresolved qualifier variable:", v)
return nil
}
/* fallback to string representation */
log.error("unexpected SQL value, rendering as string:", v)
return formatStringValue("\(v)")
}
/**
* This method finally calls formatValue() but does some type coercion when
* an Attribute is provided.
*
* - parameters:
* - value: some value which should be formatted for a SQL string
* - attr: an optional Attribute containing formatting info
* - returns: String suitable for use in a SQL string (or null on error)
*/
func formatValueForAttribute(_ value: Any?, _ attr: Attribute?) -> String? {
guard let attr = attr else { return formatValue(value) }
if let value = value as? Bool {
/* convert Boolean values for integer columns */
// somewhat hackish
if attr.externalType?.hasPrefix("INT") ?? false {
return value ? formatValue(1) : formatValue(0)
}
}
else if let value = value as? Date {
/* catch this here because formatValue() does not have the attribute */
return formatDateValue(value, attr)
}
// TODO: do something with the attribute ...
// Note: read formats are applied later on
return formatValue(value)
}
/**
* This is called by sqlStringForKeyValueQualifier().
*
* - parameters:
* - _value: value to format
* - _keyPath: keypath leading to the related attribute
* - returns: SQL for the value
*/
func sqlStringForValue(_ _value: Any?, _ _keyPath: String) -> String? {
if let value = _value as? RawSQLValue { return value.value }
let attribute = entity?[keyPath: _keyPath]
let useBind : Bool
// TBD: check whether the value is an Expression?
if _value is QualifierVariable {
useBind = true;
}
else if let _ = _value as? [ Any? ] {
/* Not sure whether this should really override the attribute? Its for
* IN queries.
*/
useBind = false
}
else if let attribute = attribute {
useBind = self.shouldUseBindVariable(for: attribute)
}
else {
/* no model to base our decision on */
if _value != nil { /* we don't need a bind for NULL */
/* we dont bind bools and numbers, no risk of SQL attacks? */
useBind = !(_value is Int || _value is Double || _value is Bool)
}
else {
useBind = false
}
}
if useBind { // TBD: only if there is no attribute?
let bind = bindVariableDictionary(for: attribute, value: _value)
addBindVariableDictionary(bind)
return bind.placeholder
}
return formatValueForAttribute(_value, attribute)
}
/* bind variables */
/**
* Checks whether binds are required for the specified attribute. Eg this
* might be the case if its a BLOB attribute.
*
* The default implementation returns false.
*
* - parameter attr: Attribute whose value should be added
* - returns: whether or not binds ('?' patterns) should be used
*/
func mustUseBindVariable(for attribute: Attribute) -> Bool {
return false
}
/**
* Checks whether binds should be used for the specified attribute. Eg this
* might be the case if its a BLOB attribute. Currently we use binds for
* almost all attributes except INTs and BOOLs.
*
* - parameter attribute: Attribute whose value should be added
* - returns: whether or not binds ('?' patterns) should be used
*/
func shouldUseBindVariable(for attribute: Attribute) -> Bool {
if mustUseBindVariable(for: attribute) { return true }
/* Hm, any reasons NOT to use binds? Actually yes, prepared statements are
* slower if the query is used just once. However, its quite likely that
* model based fetches reuse the same kind of query a LOT. So using binds
* and caching the prepared statements makes quite some sense.
*
* Further, for JDBC this ensures that our basetypes are properly escaped,
* we don't need to take care of that (eg handling the various Date types).
*
* Hm, lets avoid binding numbers and booleans.
*/
if let exttype = attribute.externalType {
if exttype.hasPrefix("INT") { return false }
if exttype.hasPrefix("BOOL") { return false }
}
else if let vType = attribute.valueType {
return vType.shouldUseBindVariable(for: attribute)
}
return true
}
open func bindVariableDictionary(for attribute: Attribute?, value: Any?)
-> BindVariable
{
var bind = BindVariable()
bind.attribute = attribute
bind.value = value
// This depends on the database, e.g. APR DBD uses %s, %i etc
bind.placeholder = "?"
/* generate and add a variable name */
var name : String
if let value = value as? QualifierVariable {
name = value.key
}
else if let attribute = attribute {
name = attribute.columnName ?? attribute.name
name += "\(bindVariables.count)"
}
else {
name = "NOATTR\(bindVariables.count)"
}
bind.name = name
return bind
}
func addBindVariableDictionary(_ dict: BindVariable) {
bindVariables.append(dict)
}
/* attributes */
/**
* Returns the SQL expression for the attribute with the given name. The name
* can be a keypath, eg "customer.address.street".
*
* The method calls sqlStringForAttributePath() for key pathes,
* or sqlStringForAttribute() for direct matches.
*
* - parameters:
* - keyPath: the name of the attribute (eg 'name' or 'address.city')
* - returns: the SQL (eg 'BASE.c_name' or 'T3.c_city')
*/
func sqlStringForAttributeNamed(_ keyPath: String) -> String? {
guard !keyPath.isEmpty else { return nil }
/* Note: this implies that attribute names may not contain dots, which
* might be an issue with user generated tables.
*/
if keyPath.contains(".") {
/* its a keypath */
return sqlStringForAttributePath(keyPath.components(separatedBy: "."))
}
if entity == nil {
return keyPath /* just reuse the name for model-less operation */
}
if let attribute = entity?[attribute: keyPath] {
/* Note: this already adds the table alias */
return sqlStringForAttribute(attribute)
}
if let relship = entity?[relationship: keyPath] {
// TODO: what about relationships?
globalZeeQLLogger.error("unsupported, generating relationship match:\n",
" path:", keyPath, "\n",
" rs: ", relship, "\n",
" expr:", self)
return keyPath
}
globalZeeQLLogger.trace("generating raw value for unknown attribute:",
keyPath, self)
return keyPath
}
/**
* Returns the SQL expression for the given attribute in the given
* relationship path. Usually the path is empty (""), leading to a
* BASE.column reference.
*
* Example:
*
* attr = lastName/c_last_name, relPath = ""
* => BASE.c_last_name
*
* attr = address.city, relPath = "address"
* => T3.c_city
*
* - parameters:
* - attr: the Attribute
* - relPath: the relationship path, eg "" for the base entity
* - returns: a SQL string, like: "BASE.c_last_name"
*/
func sqlStringForAttribute(_ attr: Attribute, _ relPath: String)
-> String
{
// TODO: not sure how its supposed to work,
// maybe we should also maintain an _attr=>relPath map? (probably
// doesn't work because it can be used in many pathes)
// TODO: We need to support aliases. In this case the one for the
// root entity?
let s = attr.valueFor(SQLExpression: self)
if self.useAliases, let rp = relationshipPathToAlias[relPath] {
return rp + "." + s
}
return s
}
/**
* Returns the SQL string for a BASE attribute (using the "" relationship
* path).
*
* - parameter attr: the Attribute in the base entity
* - returns: a SQL string, like: "BASE.c_last_name"
*/
func sqlStringForAttribute(_ attr: Attribute) -> String {
return self.sqlStringForAttribute(attr, "" /* relship path, BASE */);
}
/**
* This method generates the SQL column reference for a given attribute path.
* For example employments.person.address.city might resolve to T3.city,
* while a plain street would resolve to BASE.street.
*
* It is called by sqlStringForAttributeNamed() if it detects a dot ('.') in
* the attribute name (eg customer.address.street).
*
* - paramater path: the attribute path to resolve (eg customer.address.city)
* - returns: a SQL expression for the qualifier (eg T0.c_city)
*/
func sqlStringForAttributePath(_ path: [ String ]) -> String? {
guard !path.isEmpty else { return nil }
guard path.count > 1 else { return sqlStringForAttributeNamed(path[0]) }
guard let entity = entity else {/* can't process relationships w/o entity */
log.error("cannot process attribute pathes w/o an entity:", path)
return nil
}
/* sideeffect: fill aliasesByRelationshipPath */
var relPath : String? = nil
var rel = entity[relationship: path[0]]
guard rel != nil else {
log.error("did not find relationship '\(path[0])' in entity:", entity)
return nil
}
for i in 0..<(path.count - 1) {
let key = path[i]
guard !key.isEmpty else { /* invalid path segment */
log.error("pathes contains an invalid path segment (..):", path)
continue
}
if let p = relPath {
relPath = p + "." + key
}
else {
relPath = key
}
/* find Relationship */
var nextRel = relationshipPathToRelationship[relPath!]
if nextRel != nil {
rel = nextRel
}
else {
/* not yet cached */
guard let de = i == 0 ? entity : rel?.destinationEntity else {
log.error("did not find entity of relationship " +
"\(relPath as Optional):", rel)
rel = nil
nextRel = nil
break
}
rel = de[relationship: key]
nextRel = rel
if rel == nil {
log.error("did not find relationship '\(key)' in:", de)
// TODO: break?
}
relationshipPathToRelationship[relPath!] = rel
}
/* find alias */
let alias = aliasForRelationshipPath(relPath!, key, rel)
relationshipPathToAlias[relPath!] = alias
}
/* lookup attribute in last relationship */
let ae = rel?.destinationEntity
guard let attribute = ae?[attribute: path.last!] else {
log.error("did not find attribute \(path.last!)" +
" in relationship \(rel as Optional)" +
" entity:", ae)
return nil
}
/* OK, we should now have an alias */
return sqlStringForAttribute(attribute, relPath ?? "ERROR")
}
@discardableResult
func aliasForRelationshipPath(_ relPath: String, _ key: String,
_ rel: Relationship?) -> String
{
// Alias registration is a MUST to ensure consistency
if let alias = relationshipPathToAlias[relPath] { // cached already
return alias
}
var alias : String
if useAliases {
let pc = key
let keyLen = key.count
/* produce an alias */
if pc.hasPrefix("to") && keyLen > 2 {
/* eg: toCustomer => Customer" */
let idx = key.index(key.startIndex, offsetBy: 2)
alias = String(key[idx..<key.endIndex])
}
else {
let pc0 = pc.first!
let pcLen = pc.count
alias = String(pc0).uppercased()
if relationshipPathToAlias.values.contains(alias) && pcLen > 1 {
let idx = pc.index(pc.startIndex, offsetBy: 2)
alias = pc[pc.startIndex..<idx].uppercased()
}
}
if relationshipPathToAlias.values.contains(alias) {
/* search for next ID */
let balias = alias
for i in 1..<100 { /* limit */
alias = "\(balias)\(i)"
if !relationshipPathToAlias.values.contains(alias) { break }
alias = balias
}
}
}
else if let de = rel?.destinationEntity { // not using aliases
// TODO: check whether its correct
alias = sqlStringFor(schemaObjectName: de.externalName ?? de.name)
}
else {
log.error("Missing relationship or entity to calculate alias for path:",
relPath, "key:", key, "relationship:", rel)
return "ERROR" // TODO
}
relationshipPathToAlias[relPath] = alias
return alias
}
// MARK: - Database SQL
var externalNameQuoteCharacter : String? {
/* char used to quote identifiers, eg backtick for MySQL! */
return "\""
}
open func sqlStringFor(schemaObjectName name: String) -> String {
if name == "*" { return "*" } /* maye not be quoted, not an ID */
guard let q = externalNameQuoteCharacter else { return name }
if name.contains(q) { /* quote by itself, eg ' => '' */
let nn = name.replacingOccurrences(of: q, with: q + q)
return q + nn + q
}
return q + name + q;
}
open var lockClause : String? {
return "FOR UPDATE" /* this is PostgreSQL 8.1 */
}
// MARK: - qualifiers
/**
* Returns the SQL operator for the given ComparisonOperation.
*
* - parameters:
* - op: the ComparisonOperation, eg .EqualTo or .Like
* - value: the value to be compared (only tested for null)
* - allowNull: whether to use "IS NULL" like special ops
* - returns: the String representing the operation, or null if none was found
*/
open func sqlStringForSelector(_ op : ComparisonOperation,
_ value: Any?, _ allowNull: Bool) -> String
{
/* Note: when used with key-comparison, the value is null! */
// TODO: fix equal to for that case!
let useNullVariant = value == nil && allowNull
switch op {
case .EqualTo: return !useNullVariant ? "=" : "IS"
case .NotEqualTo: return !useNullVariant ? "<>" : "IS NOT"
case .GreaterThan: return ">"
case .GreaterThanOrEqual: return ">="
case .LessThan: return "<"
case .LessThanOrEqual: return "<="
case .Contains: return "IN"
case .Like, .SQLLike: return "LIKE"
case .CaseInsensitiveLike, .SQLCaseInsensitiveLike:
if let ilike = sqlStringForCaseInsensitiveLike { return ilike }
return "LIKE"
case .Unknown(let op):
log.error("could not determine SQL operation for operator:", op)
return op
}
}
open var sqlStringForCaseInsensitiveLike : String? { return nil }
/**
* Converts the given Qualifier into a SQL expression suitable for the
* WHERE part of the SQL statement.
*
* If the qualifier implements QualifierSQLGeneration, its directly asked
* for the SQL representation.
* Otherwise we call the appropriate methods for known types of qualifiers.
*
* - parameters:
* - q: the qualifier to be converted
* - returns: a String representing the qualifier, or nil on error
*/
public func sqlStringForQualifier(_ q : Qualifier) -> String? {
/* first support custom SQL qualifiers */
if let q = q as? QualifierSQLGeneration {
return q.sqlStringForSQLExpression(self)
}
/* next check builtin qualifiers */
if let q = q as? NotQualifier {
return sqlStringForNegatedQualifier(q.qualifier)
}
if let q = q as? KeyValueQualifier {
return sqlStringForKeyValueQualifier(q)
}
if let q = q as? KeyComparisonQualifier {
return sqlStringForKeyComparisonQualifier(q)
}
if let q = q as? CompoundQualifier {
switch q.op {
case .And: return sqlStringForConjoinedQualifiers(q.qualifiers)
case .Or: return sqlStringForDisjoinedQualifiers(q.qualifiers)
}
}
if let q = q as? SQLQualifier { return sqlStringForRawQualifier(q) }
if let q = q as? BooleanQualifier { return sqlStringForBooleanQualifier(q) }
#if false // TODO
if let q = q as? CSVKeyValueQualifier {
return self.sqlStringForCSVKeyValueQualifier(q)
}
if let q = q as? OverlapsQualifier {
return self.sqlStringForOverlapsQualifier(q)
}
#endif
log.error("could not convert qualifier to SQL:", q)
return nil
}
public func sqlStringForBooleanQualifier(_ q: BooleanQualifier) -> String {
// TBD: we could return an empty qualifier for true?
return !q.value ? "1 = 2" : "1 = 1";
}
/**
* This returns the SQL for a raw qualifier (SQLQualifier). The SQL still
* needs to be generated because a SQL qualifier is composed of plain strings
* as well as 'dynamic' parts.
*
* QualifierVariables must be evaluated before this method is called.
*
* - parameter q: the SQLQualifier to be converted
* - returns: the SQL for the qualifier, or null on error
*/
public func sqlStringForRawQualifier(_ q: SQLQualifier) -> String {
// TODO: Do something inside the parts? Pattern replacement?
let parts = q.parts
guard !parts.isEmpty else { return "" }
var sb = ""
for part in parts {
switch part {
case .RawSQLValue(let value):
let rv = RawSQLValue(value: value)
// TBD: Whats correct here? Should we escape parts or not? For now we
// assume that values are just that and need to be escaped. Which
// implies that bindings cannot contain dynamic SQL.
// Note that 'raw' sections of the qualifier will be RawSQLValue
// objects.
if let s = formatValue(rv) {
sb += s
}
case .QualifierVariable(let name):
log.error("SQL qualifier contains a variable: \(part) \(name)")
}
}
return sb
}
/**
* This method generates the SQL for the given qualifier and then negates it,
* but embedded it in a "NOT ( Q )". Should work across all databases.
*
* - parameter q: base qualifier, to be negated
* - returns: the SQL string or null if no SQL was generated for the qualifier
*/
public func sqlStringForNegatedQualifier(_ q: Qualifier) -> String? {
guard let qs = sqlStringForQualifier(q), !qs.isEmpty else { return nil }
return "NOT ( " + qs + " )"
}
open var sqlTrueExpression : String { return "1 = 1" }
open var sqlFalseExpression : String { return "1 = 0" }
open func shouldCoalesceEmptyString(_ q: KeyValueQualifier) -> Bool {
// TBD: Do we have attribute info? (i.e. is the column nullable in the
// first place)
return q.operation == .Like || q.operation == .CaseInsensitiveLike
}
/**
* Generates the SQL for an KeyValueQualifier. This qualifier compares a
* column against some constant value using some operator.
*
* - parameter q: the KeyValueQualifier
* - returns: the SQL or nil if the SQL could not be generated
*/
public func sqlStringForKeyValueQualifier(_ q: KeyValueQualifier) -> String? {
/* generate lhs */
// TBD: use sqlStringForExpression with Key?
// What if the LHS is a relationship? (like addresses.street). It will
// yield the proper alias, e.g. "A.street"!
guard let sqlCol = self.sqlStringForExpression(q.leftExpression) else {
log.error("got no SQL string for attribute of LHS \(q.key):", q)
return nil
}
// TODO: unless the DB supports a specific case-search LIKE, we need
// to perform an upper
var v = q.value
let k = q.key
/* generate operator */
// TODO: do something about caseInsensitiveLike (TO_UPPER?), though in
// PostgreSQL and MySQL this is already covered by special operators
let opsel = q.operation
let op = self.sqlStringForSelector(opsel, v, true)
let needsCoalesce = shouldCoalesceEmptyString(q)
var sb = ""
if needsCoalesce { sb += "COALESCE(" } // undo NULL values for LIKE
sb += sqlCol
if needsCoalesce {
sb += ", "
sb += formatStringValue("")
sb += ")"
}
/* generate operator and value */
if op.hasPrefix("IS") && v == nil {
/* IS NULL or IS NOT NULL */
sb += " "
sb += op
sb += " NULL"
}
else if op == "IN" {
if let v = v as? QualifierVariable {
log.error("detected unresolved qualifier variable in IN qualifier:\n" +
" \(q)\n variable: \(v)")
return nil
}
// we might need to add casting support, eg:
// varcharcolumn IN ( 1, 2, 3, 4 )
// does NOT work with PostgreSQL. We need to do:
// varcharcolumn::int IN ( 1, 2, 3, 4 )
// which is also suboptimal if the varcharcolumn does contain strings,
// or:
// varcharcolumn IN ( 1::varchar, 2::varchar, 3::varchar, 4::varchar )
// which might be counter productive since it might get longer than:
// varcharcolumn = 1 OR varcharcolumn = 2 etc
if let c = v as? [ Any ] {
// TBD: can't we move all this to sqlStringForValue? This has similiar
// stuff already
let len = c.count
if len == 0 {
/* An 'IN ()' does NOT work in PostgreSQL, weird. We treat such a
* qualifier as always false. */
sb.removeAll()
sb += sqlFalseExpression
}
else {
sb += " IN ("
var isFirst = true
for subvalue in c {
guard let fv = sqlStringForValue(subvalue, k) else { continue }
if isFirst { isFirst = false }
else { sb += ", " }
sb += fv
}
sb += ")"
}
}
else if let range = v as? TimeRange {
// TBD: range query ..
// eg: birthday IN 2008-09-10 00:00 - 2008-09-11 00:00
// => birthday >= $start AND birthDay < $end
// TBD: DATE, TIME vs DATETIME ...
if range.isEmpty {
sb.removeAll()
sb += sqlFalseExpression
}
else {
let date : Date?
if let fromDate = range.fromDate {
sb += " "
sb += self.sqlStringForSelector(.GreaterThanOrEqual,
fromDate, false /* no null */)
sb += " "
sb += sqlStringForValue(fromDate, k) ?? "ERROR"
if let toDate = range.toDate {
sb += " AND "
sb += sqlCol
date = toDate
}
else {
date = fromDate
}
}
else {
date = range.toDate
}
if let date = date {
sb += " "
sb += sqlStringForSelector(.LessThan, date, false /* nonull */)
sb += " "
sb += sqlStringForValue(date, k) ?? "ERROR"
}
}
}
else {
/* Note: 'IN ( NULL )' at least works in PostgreSQL */
log.error("value of IN qualifier was no list:", v)
sb += " IN ("
sb += sqlStringForValue(v, k) ?? "ERROR"
sb += ")"
}
}
else if let range = v as? TimeRange {
if opsel == .GreaterThan {
if range.isEmpty { /* empty range, always greater */
sb.removeAll()
sb += sqlTrueExpression
}
else if let date = range.toDate {
/* to dates are exclusive, hence check for >= */
sb += " "
sb += self.sqlStringForSelector(.GreaterThanOrEqual,
date, false /* no null */)
sb += " "
sb += self.sqlStringForValue(date, k) ?? "ERROR"
}
else { /* open end, can't be greater */
sb.removeAll()
sb += self.sqlFalseExpression
}
}
else if opsel == .LessThan {
if range.isEmpty { /* empty range, always smaller */
sb.removeAll()
sb += self.sqlTrueExpression
}
else if let date = range.fromDate {
/* from dates are inclusive, hence check for < */
sb += " "
sb += op
sb += " "
sb += sqlStringForValue(date, k) ?? "ERROR"
}
else { /* open start, can't be smaller */
sb.removeAll()
sb += self.sqlFalseExpression
}
}
else {
log.error("TimeRange not yet supported as a value for op: ", op)
return nil
}
}
else {
sb += " "
sb += op
sb += " "
/* a regular value */
if let vv = v {
if opsel == .Like || opsel == .CaseInsensitiveLike {
// TODO: unless the DB supports a specific case-search LIKE, we need
// to perform an upper
v = self.sqlPatternFromShellPattern(String(describing: vv))
}
}
// this does bind stuff if enabled
sb += sqlStringForValue(v, k) ?? "ERROR"
}
return sb
}
/**
* Generates the SQL for an KeyComparisonQualifier, eg:
*
* ship.city = bill.city
* T1.city = T2.city
*
* - parameter _q: KeyComparisonQualifier to build
* - returns: the SQL for the qualifier
*/
func sqlStringForKeyComparisonQualifier(_ _q: KeyComparisonQualifier)
-> String?
{
/* generate operator */
// TODO: do something about caseInsensitiveLike (TO_UPPER?)
var sb = ""
guard let l = sqlStringForExpression(_q.leftExpression) else { return nil }
guard let r = sqlStringForExpression(_q.rightExpression) else { return nil }
sb += l
sb += sqlStringForSelector(_q.operation, nil, false)
sb += r
return sb
}
/**
* Calls sqlStringForQualifier() on each of the given qualifiers and joins
* the results using the given _op (either " AND " or " OR ").
*
* Note that we do not add empty qualifiers (such which returned an empty
* String as their SQL representation).
*
* - parameters:
* - _qs: set of qualifiers
* - _op: operation to use, including spaces, eg " AND "
* - returns: String containing the SQL for all qualifiers
*/
func sqlStringForJoinedQualifiers(_ _qs : [ Qualifier ], _ _op: String)
-> String?
{
guard !_qs.isEmpty else { return nil }
if _qs.count == 1 { return sqlStringForQualifier(_qs[0]) }
var sb = ""
for q in _qs {
guard let s = sqlStringForQualifier(q), !s.isEmpty else { continue }
/* do not add empty qualifiers as per doc */ // TBD: explain
// TBD: check for sqlTrueExpression, sqlFalseExpression?!
if !sb.isEmpty { sb += _op }
sb += "( \(s) )"
}
return sb
}
/**
* Calls sqlStringForJoinedQualifiers with the " AND " operator.
*
* - parameter qs: qualifiers to conjoin
* - returns: SQL representation of the qualifiers
*/
public func sqlStringForConjoinedQualifiers(_ qs: [ Qualifier ]) -> String? {
return self.sqlStringForJoinedQualifiers(qs, " AND ")
}
/**
* Calls sqlStringForJoinedQualifiers with the " OR " operator.
*
* - parameter qs: qualifiers to disjoin
* - returns: SQL representation of the qualifiers
*/
public func sqlStringForDisjoinedQualifiers(_ qs: [ Qualifier ]) -> String? {
return self.sqlStringForJoinedQualifiers(qs, " OR ")
}
/**
* Converts the shell patterns used in Qualifiers into SQL % patterns.
* Example:
*
* name LIKE '?ello*World*'
* name LIKE '_ello%World%'
*
* - parameter _pattern: shell based pattern
* - returns: SQL pattern
*/
public func sqlPatternFromShellPattern(_ _pattern: String) -> String {
// hm, should we escape as %%?
return _pattern.reduce("") { res, c in
switch c {
case "%": return res + "\\%"
case "*": return res + "%"
case "_": return res + "\\_"
case "?": return res + "_"
default: return res + String(c)
}
}
}
#if false // TODO
func sqlStringForCSVKeyValueQualifier(_ q: CSVKeyValueQualifier) -> String {
/* the default implementation just builds a LIKE qualifier */
return self.sqlStringForQualifier(_q.rewriteAsPlainQualifier());
}
func sqlStringForOverlapsQualifier(_ q: OverlapsQualifier) -> String {
/* the default implementation just builds the range qualifier manually */
return self.sqlStringForQualifier(_q.rewriteAsPlainQualifier());
}
#endif
/* expressions */
/**
* This method 'renders' expressions as SQL. This is similiar to an
* Qualifier, but can lead to non-bool values. In fact, an Qualifier
* can be used here (leads to a true/false value).
*
* The feature is that value expressions can be used in SELECT lists. Instead
* of plain Attribute's, we can select stuff like SUM(lineItems.amount).
*
* Usually you need to embed the actual in an NamedExpression, so that the
* value has a distinct name in the resulting dictionary.
*
* - parameter _expr: the expression to render (Attribute, Key, Qualifier,
* Case, Aggregate, NamedExpression)
* - returns: SQL code which calculates the expression
*/
func sqlStringForExpression(_ _expr: Any?) -> String? {
if (_expr == nil ||
_expr is String ||
_expr is Int ||
_expr is Double ||
_expr is Bool)
{
// TBD: not sure whether this is correct
return formatValue(_expr)
}
if let a = _expr as? Attribute {
return formatSQLString(sqlStringForAttribute(a), a.readFormat)
}
if let k = _expr as? Key {
// TBD: check what sqlStringForKeyValueQualifier does?
return sqlStringForKey(k)
}
if let q = _expr as? Qualifier {
return sqlStringForQualifier(q)
}
#if false // TODO
if let c = _expr as? Case {
log.error("Case generation not supported yet:", c)
return nil
}
#endif
log.error("unsupported expression:", _expr)
return nil
}
public func sqlStringForKey(_ _key: Key) -> String? {
let k = _key.key
/* generate lhs */
// TBD: use sqlStringForExpression with Key?
guard let sqlCol = sqlStringForAttributeNamed(k) else {
log.error("got no SQL string for attribute of key \(k):", _key)
return nil
}
guard let a = entity?[attribute: k] else { return sqlCol }
let aCol = formatSQLString(sqlCol, a.readFormat)
// TODO: unless the DB supports a specific case-search LIKE, we need
// to perform an upper
return aCol
}
/* DDL */
open func addCreateClauseForAttribute(_ attribute: Attribute,
in entity: Entity? = nil)
{
let isPrimaryKey = (entity?.primaryKeyAttributeNames ?? [])
.contains(attribute.name)
/* separator */
if !listString.isEmpty {
listString += ",\n"
}
/* column name */
let c = attribute.columnName ?? attribute.name
listString += sqlStringFor(schemaObjectName: c)
listString += " "
/* column type */
listString += columnTypeStringForAttribute(attribute)
/* constraints */
/* Note: we do not add primary keys, done in a separate step */
let s = allowsNullClauseForConstraint(attribute.allowsNull ?? true)
listString += s
if isPrimaryKey {
listString += " PRIMARY KEY"
}
}
open func sqlForForeignKeyConstraint(_ rs: Relationship) -> String? {
// This is for constraint statements, some databases can also attach the
// constraint directly to the column. (which should be handled by the
// method above).
// person_id INTEGER NOT NULL,
// FOREIGN KEY(person_id) REFERENCES person(person_id) DEFERRABLE
guard let destTable = rs.destinationEntity?.externalName
?? rs.destinationEntity?.name
else {
return nil
}
var sql = "FOREIGN KEY ( "
var isFirst = true
for join in rs.joins {
if isFirst { isFirst = false } else { sql += ", " }
guard let propName = join.sourceName ?? join.source?.name
else { return nil }
guard let attr = rs.entity[attribute: propName] else { return nil }
let columnName = attr.columnName ?? attr.name
sql += sqlStringFor(schemaObjectName: columnName)
}
sql += " ) REFERENCES "
sql += sqlStringFor(schemaObjectName: destTable)
sql += " ( "
isFirst = true
for join in rs.joins {
if isFirst { isFirst = false } else { sql += ", " }
guard let propName = join.destinationName ?? join.destination?.name
else { return nil }
guard let attr = rs.destinationEntity?[attribute: propName]
else { return nil }
let columnName = attr.columnName ?? attr.name
sql += sqlStringFor(schemaObjectName: columnName)
}
sql += " )"
if let updateRule = rs.updateRule {
switch updateRule {
case .applyDefault: sql += " ON UPDATE SET DEFAULT"
case .cascade: sql += " ON UPDATE CASCADE"
case .deny: sql += " ON UPDATE RESTRICT"
case .noAction: sql += " ON UPDATE NO ACTION"
case .nullify: sql += " ON UPDATE SET NULL"
}
}
if let deleteRule = rs.deleteRule {
switch deleteRule {
case .applyDefault: sql += " ON DELETE SET DEFAULT"
case .cascade: sql += " ON DELETE CASCADE"
case .deny: sql += " ON DELETE RESTRICT"
case .noAction: sql += " ON DELETE NO ACTION"
case .nullify: sql += " ON DELETE SET NULL"
}
}
return sql
}
open func externalTypeForValueType(_ type: AttributeValue.Type) -> String? {
// FIXME: I don't like this stuff
guard let et =
ZeeQLTypes.externalTypeFor(swiftType: type.optionalBaseType ?? type,
includeConstraint: false)
else {
log.error("Could not derive external type from Swift type:", type)
return nil
}
return et
}
open func externalTypeForTypelessAttribute(_ attr: Attribute) -> String {
log.warn("attribute has no type", attr)
if let cn = attr.columnName, cn.hasSuffix("_id") { return "INT" }
if attr.name.hasSuffix("Id") || attr.name.hasSuffix("ID") { return "INT" }
// TODO: More smartness. Though it doesn't really belong here but in a
// model postprocessing step.
return "TEXT"
}
open func columnTypeStringForAttribute(_ attr: Attribute) -> String {
let extType : String
if let t = attr.externalType {
extType = t
}
else if let t = attr.valueType, let et = externalTypeForValueType(t) {
extType = et
}
else {
extType = externalTypeForTypelessAttribute(attr)
}
if let precision = attr.precision, let width = attr.width {
return "\(extType)(\(precision),\(width))"
}
else if let width = attr.width {
return "\(extType)(\(width))"
}
return extType
}
public func allowsNullClauseForConstraint(_ allowNull: Bool) -> String {
return allowNull ? " NULL" : " NOT NULL";
}
/* escaping */
/**
* This function escapes single quotes and backslashes with itself. Eg:
*
* Hello 'World'
* Hello ''World''
*
* @param _value - String to escape
* @return escaped String
*/
public func escapeSQLString(_ _value: String) -> String {
guard !_value.isEmpty else { return "" }
return _value.reduce("") { res, c in
switch c {
case "\\": return res + "\\\\"
case "'": return res + "''"
default: return res + String(c)
}
}
}
// MARK: - Description
public func appendToDescription(_ ms: inout String) {
if statement.isEmpty {
ms += " EMPTY"
}
else {
ms += " "
ms += statement
}
}
}
/**
* Implemented by Attribute and Entity to return the SQL to be used for
* those objects.
*
* Eg the Attribute takes its columnName() and calls
* sqlStringFor(schemaObjectName:) with it on the given SQLExpression.
*/
public protocol SQLValue {
/**
* Called by sqlStringFor(attribute:) and other methods to convert an
* object to a SQL expression.
*/
func valueFor(SQLExpression context: SQLExpression) -> String
}
/**
* When the SQLExpression generates SQL for a given qualifier, it
* first checks whether the qualifier implements this protocol. If so, it
* lets the qualifier object generate the SQL instead of relying on the default
* mechanisms.
*/
public protocol QualifierSQLGeneration {
func sqlStringForSQLExpression(_ expr: SQLExpression) -> String
}
// MARK: - Helpers
fileprivate extension String {
var numberOfDots : Int {
return reduce(0) { $1 == "." ? ($0 + 1) : $0 }
}
var lastRelPath : String {
guard let r = range(of: ".", options: .backwards) else { return "" }
return String(self[self.startIndex..<r.lowerBound])
}
}
| 29727a634bcba750bed042221d18a895 | 30.362857 | 80 | 0.588724 | false | false | false | false |
flathead/Flame | refs/heads/develop | Flame/VectorMath.swift | mit | 1 | //
// VectorMath.swift
// VectorMath
//
// Version 0.1
//
// Created by Nick Lockwood on 24/11/2014.
// Copyright (c) 2014 Nick Lockwood. All rights reserved.
//
// Distributed under the permissive zlib License
// Get the latest version from here:
//
// https://github.com/nicklockwood/VectorMath
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
import Foundation
//MARK: Types
typealias Scalar = Float
struct Vector2 {
var x: Scalar
var y: Scalar
}
struct Vector3 {
var x: Scalar
var y: Scalar
var z: Scalar
}
struct Vector4 {
var x: Scalar
var y: Scalar
var z: Scalar
var w: Scalar
}
struct Matrix3 {
var m11: Scalar
var m12: Scalar
var m13: Scalar
var m21: Scalar
var m22: Scalar
var m23: Scalar
var m31: Scalar
var m32: Scalar
var m33: Scalar
}
struct Matrix4 {
var m11: Scalar
var m12: Scalar
var m13: Scalar
var m14: Scalar
var m21: Scalar
var m22: Scalar
var m23: Scalar
var m24: Scalar
var m31: Scalar
var m32: Scalar
var m33: Scalar
var m34: Scalar
var m41: Scalar
var m42: Scalar
var m43: Scalar
var m44: Scalar
}
struct Quaternion {
var x: Scalar
var y: Scalar
var z: Scalar
var w: Scalar
}
//MARK: Scalar
extension Scalar {
static let Pi = Scalar(M_PI)
static let HalfPi = Scalar(M_PI_2)
static let QuarterPi = Scalar(M_PI_4)
static let TwoPi = Scalar(M_PI * 2)
static let DegreesPerRadian = 180 / Pi
static let RadiansPerDegree = Pi / 180
static let Epsilon: Scalar = 0.0001
}
func ~=(lhs: Scalar, rhs: Scalar) -> Bool {
return abs(lhs - rhs) < .Epsilon
}
//MARK: Vector2
extension Vector2: Equatable, Hashable {
static let Zero = Vector2(0, 0)
static let X = Vector2(1, 0)
static let Y = Vector2(0, 1)
var hashValue: Int {
return x.hashValue &+ y.hashValue
}
var lengthSquared: Scalar {
return x * x + y * y
}
var length: Scalar {
return sqrt(lengthSquared)
}
var inverse: Vector2 {
return -self
}
init(_ x: Scalar, _ y: Scalar) {
self.init(x: x, y: y)
}
init(_ v: [Scalar]) {
assert(v.count == 2, "array must contain 2 elements, contained \(v.count)")
x = v[0]
y = v[1]
}
func toArray() -> [Scalar] {
return [x, y]
}
func dot(v: Vector2) -> Scalar {
return x * v.x + y * v.y
}
func cross(v: Vector2) -> Scalar {
return x * v.y - y * v.x
}
func normalized() -> Vector2 {
let lengthSquared = self.lengthSquared
if lengthSquared ~= 0 || lengthSquared ~= 1 {
return self
}
return self / sqrt(lengthSquared)
}
func rotatedBy(radians: Scalar) -> Vector2 {
let cs = cos(radians)
let sn = sin(radians)
return Vector2(x * cs - y * sn, x * sn + y * cs)
}
func rotatedBy(radians: Scalar, around pivot: Vector2) -> Vector2 {
return (self - pivot).rotatedBy(radians) + pivot
}
func angleWith(v: Vector2) -> Scalar {
if self == v {
return 0
}
let t1 = normalized()
let t2 = v.normalized()
let cross = t1.cross(t2)
let dot = max(-1, min(1, t1.dot(t2)))
return atan2(cross, dot)
}
func interpolatedWith(v: Vector2, t: Scalar) -> Vector2 {
return self + (v - self) * t
}
}
prefix func -(v: Vector2) -> Vector2 {
return Vector2(-v.x, -v.y)
}
func +(lhs: Vector2, rhs: Vector2) -> Vector2 {
return Vector2(lhs.x + rhs.x, lhs.y + rhs.y)
}
func -(lhs: Vector2, rhs: Vector2) -> Vector2 {
return Vector2(lhs.x - rhs.x, lhs.y - rhs.y)
}
func *(lhs: Vector2, rhs: Vector2) -> Vector2 {
return Vector2(lhs.x * rhs.x, lhs.y * rhs.y)
}
func *(lhs: Vector2, rhs: Scalar) -> Vector2 {
return Vector2(lhs.x * rhs, lhs.y * rhs)
}
func *(lhs: Vector2, rhs: Matrix3) -> Vector2 {
return Vector2(
lhs.x * rhs.m11 + lhs.y * rhs.m21 + rhs.m31,
lhs.x * rhs.m12 + lhs.y * rhs.m22 + rhs.m32
)
}
func /(lhs: Vector2, rhs: Vector2) -> Vector2 {
return Vector2(lhs.x / rhs.x, lhs.y / rhs.y)
}
func /(lhs: Vector2, rhs: Scalar) -> Vector2 {
return Vector2(lhs.x / rhs, lhs.y / rhs)
}
func ==(lhs: Vector2, rhs: Vector2) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
func ~=(lhs: Vector2, rhs: Vector2) -> Bool {
return lhs.x ~= rhs.x && lhs.y ~= rhs.y
}
//MARK: Vector3
extension Vector3: Equatable, Hashable {
static let Zero = Vector3(0, 0, 0)
static let X = Vector3(1, 0, 0)
static let Y = Vector3(0, 1, 0)
static let Z = Vector3(0, 0, 1)
var hashValue: Int {
return x.hashValue &+ y.hashValue &+ z.hashValue
}
var lengthSquared: Scalar {
return x * x + y * y + z * z
}
var length: Scalar {
return sqrt(lengthSquared)
}
var inverse: Vector3 {
return -self
}
var xy: Vector2 {
get {
return Vector2(x, y)
}
set (v) {
x = v.x
y = v.y
}
}
var xz: Vector2 {
get {
return Vector2(x, z)
}
set (v) {
x = v.x
z = v.y
}
}
var yz: Vector2 {
get {
return Vector2(y, z)
}
set (v) {
y = v.x
z = v.y
}
}
init(_ x: Scalar, _ y: Scalar, _ z: Scalar) {
self.init(x: x, y: y, z: z)
}
init(_ v: [Scalar]) {
assert(v.count == 3, "array must contain 3 elements, contained \(v.count)")
x = v[0]
y = v[1]
z = v[2]
}
func toArray() -> [Scalar] {
return [x, y, z]
}
func dot(v: Vector3) -> Scalar {
return x * v.x + y * v.y + z * v.z
}
func cross(v: Vector3) -> Vector3 {
return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)
}
func normalized() -> Vector3 {
let lengthSquared = self.lengthSquared
if lengthSquared ~= 0 || lengthSquared ~= 1 {
return self
}
return self / sqrt(lengthSquared)
}
func interpolatedWith(v: Vector3, t: Scalar) -> Vector3 {
return self + (v - self) * t
}
}
prefix func -(v: Vector3) -> Vector3 {
return Vector3(-v.x, -v.y, -v.z)
}
func +(lhs: Vector3, rhs: Vector3) -> Vector3 {
return Vector3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
}
func -(lhs: Vector3, rhs: Vector3) -> Vector3 {
return Vector3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)
}
func *(lhs: Vector3, rhs: Vector3) -> Vector3 {
return Vector3(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z)
}
func *(lhs: Vector3, rhs: Scalar) -> Vector3 {
return Vector3(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs)
}
func *(lhs: Vector3, rhs: Matrix3) -> Vector3 {
return Vector3(
lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31,
lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32,
lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33
)
}
func *(lhs: Vector3, rhs: Matrix4) -> Vector3 {
return Vector3(
lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31 + rhs.m41,
lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32 + rhs.m42,
lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33 + rhs.m43
)
}
func *(v: Vector3, q: Quaternion) -> Vector3 {
let qv = q.xyz
let uv = qv.cross(v)
let uuv = qv.cross(uv)
return v + (uv * 2 * q.w) + (uuv * 2)
}
func /(lhs: Vector3, rhs: Vector3) -> Vector3 {
return Vector3(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z)
}
func /(lhs: Vector3, rhs: Scalar) -> Vector3 {
return Vector3(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs)
}
func ==(lhs: Vector3, rhs: Vector3) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
func ~=(lhs: Vector3, rhs: Vector3) -> Bool {
return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z
}
//MARK: Vector4
extension Vector4: Equatable, Hashable {
static let Zero = Vector4(0, 0, 0, 0)
static let X = Vector4(1, 0, 0, 0)
static let Y = Vector4(0, 1, 0, 0)
static let Z = Vector4(0, 0, 1, 0)
static let W = Vector4(0, 0, 0, 1)
var hashValue: Int {
return x.hashValue &+ y.hashValue &+ z.hashValue &+ w.hashValue
}
var lengthSquared: Scalar {
return x * x + y * y + z * z + w * w
}
var length: Scalar {
return sqrt(lengthSquared)
}
var inverse: Vector4 {
return -self
}
var xyz: Vector3 {
get {
return Vector3(x, y, z)
}
set (v) {
x = v.x
y = v.y
z = v.z
}
}
var xy: Vector2 {
get {
return Vector2(x, y)
}
set (v) {
x = v.x
y = v.y
}
}
var xz: Vector2 {
get {
return Vector2(x, z)
}
set (v) {
x = v.x
z = v.y
}
}
var yz: Vector2 {
get {
return Vector2(y, z)
}
set (v) {
y = v.x
z = v.y
}
}
init(_ x: Scalar, _ y: Scalar, _ z: Scalar, _ w: Scalar) {
self.init(x: x, y: y, z: z, w: w)
}
init(_ xyz: Vector3, _ w: Scalar) {
self.init(x: xyz.x, y: xyz.y, z: xyz.z, w: w)
}
init(_ v: [Scalar]) {
assert(v.count == 4, "array must contain 4 elements, contained \(v.count)")
x = v[0]
y = v[1]
z = v[2]
w = v[3]
}
func toArray() -> [Scalar] {
return [x, y, z, w]
}
func dot(v: Vector4) -> Scalar {
return x * v.x + y * v.y + z * v.z + w * v.w
}
func normalized() -> Vector4 {
let lengthSquared = self.lengthSquared
if lengthSquared ~= 0 || lengthSquared ~= 1 {
return self
}
return self / sqrt(lengthSquared)
}
func interpolatedWith(v: Vector4, t: Scalar) -> Vector4 {
return self + (v - self) * t
}
}
prefix func -(v: Vector4) -> Vector4 {
return Vector4(-v.x, -v.y, -v.z, -v.w)
}
func +(lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w)
}
func -(lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w)
}
func *(lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w)
}
func *(lhs: Vector4, rhs: Scalar) -> Vector4 {
return Vector4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs)
}
func *(lhs: Vector4, rhs: Matrix4) -> Vector4 {
return Vector4(
lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31 + lhs.w * rhs.m41,
lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32 + lhs.w * rhs.m42,
lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33 + lhs.w * rhs.m43,
lhs.x * rhs.m14 + lhs.y * rhs.m24 + lhs.z * rhs.m34 + lhs.w * rhs.m44
)
}
func /(lhs: Vector4, rhs: Vector4) -> Vector4 {
return Vector4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w)
}
func /(lhs: Vector4, rhs: Scalar) -> Vector4 {
return Vector4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs)
}
func ==(lhs: Vector4, rhs: Vector4) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w
}
func ~=(lhs: Vector4, rhs: Vector4) -> Bool {
return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z && lhs.w ~= rhs.w
}
//MARK: Matrix3
extension Matrix3: Equatable, Hashable {
static let Identity = Matrix3(1, 0 ,0 ,0, 1, 0, 0, 0, 1)
var hashValue: Int {
var hash = m11.hashValue &+ m12.hashValue &+ m13.hashValue
hash = hash &+ m21.hashValue &+ m22.hashValue &+ m23.hashValue
hash = hash &+ m31.hashValue &+ m32.hashValue &+ m33.hashValue
return hash
}
init(_ m11: Scalar, _ m12: Scalar, _ m13: Scalar,
_ m21: Scalar, _ m22: Scalar, _ m23: Scalar,
_ m31: Scalar, _ m32: Scalar, _ m33: Scalar) {
self.m11 = m11 // 0
self.m12 = m12 // 1
self.m13 = m13 // 2
self.m21 = m21 // 3
self.m22 = m22 // 4
self.m23 = m23 // 5
self.m31 = m31 // 6
self.m32 = m32 // 7
self.m33 = m33 // 8
}
init(scale: Vector2) {
self.init(
scale.x, 0, 0,
0, scale.y, 0,
0, 0, 1
)
}
init(translation: Vector2) {
self.init(
1, 0, 0,
0, 1, 0,
translation.x, translation.y, 1
)
}
init(rotation radians: Scalar) {
let cs = cos(radians)
let sn = sin(radians)
self.init(
cs, sn, 0,
-sn, cs, 0,
0, 0, 1
)
}
init(_ m: [Scalar]) {
assert(m.count == 9, "array must contain 9 elements, contained \(m.count)")
self.init(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
func toArray() -> [Scalar] {
return [m11, m12, m13, m21, m22, m23, m31, m32, m33]
}
var adjugate: Matrix3 {
return Matrix3(
m22 * m33 - m23 * m32,
m13 * m32 - m12 * m33,
m12 * m23 - m13 * m22,
m23 * m31 - m21 * m33,
m11 * m33 - m13 * m31,
m13 * m21 - m11 * m23,
m21 * m32 - m22 * m31,
m12 * m31 - m11 * m32,
m11 * m22 - m12 * m21
)
}
var determinant: Scalar {
return (m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32)
- (m13 * m22 * m31 + m11 * m23 * m32 + m12 * m21 * m33)
}
var transpose: Matrix3 {
return Matrix3(m11, m21, m31, m12, m22, m32, m13, m23, m33)
}
var inverse: Matrix3 {
return adjugate * (1 / determinant)
}
func interpolatedWith(m: Matrix3, t: Scalar) -> Matrix3 {
return Matrix3(
m11 + (m.m11 - m11) * t,
m12 + (m.m12 - m12) * t,
m13 + (m.m13 - m13) * t,
m21 + (m.m21 - m21) * t,
m22 + (m.m22 - m22) * t,
m23 + (m.m23 - m23) * t,
m31 + (m.m31 - m31) * t,
m32 + (m.m32 - m32) * t,
m33 + (m.m33 - m33) * t
)
}
}
prefix func -(m: Matrix3) -> Matrix3 {
return m.inverse
}
func *(lhs: Matrix3, rhs: Matrix3) -> Matrix3 {
return Matrix3(
lhs.m11 * rhs.m11 + lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13,
lhs.m12 * rhs.m11 + lhs.m22 * rhs.m12 + lhs.m32 * rhs.m13,
lhs.m13 * rhs.m11 + lhs.m23 * rhs.m12 + lhs.m33 * rhs.m13,
lhs.m11 * rhs.m21 + lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23,
lhs.m12 * rhs.m21 + lhs.m22 * rhs.m22 + lhs.m32 * rhs.m23,
lhs.m13 * rhs.m21 + lhs.m23 * rhs.m22 + lhs.m33 * rhs.m23,
lhs.m11 * rhs.m31 + lhs.m21 * rhs.m32 + lhs.m31 * rhs.m33,
lhs.m12 * rhs.m31 + lhs.m22 * rhs.m32 + lhs.m32 * rhs.m33,
lhs.m13 * rhs.m31 + lhs.m23 * rhs.m32 + lhs.m33 * rhs.m33
)
}
func *(lhs: Matrix3, rhs: Vector2) -> Vector2 {
return rhs * lhs
}
func *(lhs: Matrix3, rhs: Vector3) -> Vector3 {
return rhs * lhs
}
func *(lhs: Matrix3, rhs: Scalar) -> Matrix3 {
return Matrix3(
lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs,
lhs.m21 * rhs, lhs.m22 * rhs, lhs.m23 * rhs,
lhs.m31 * rhs, lhs.m32 * rhs, lhs.m33 * rhs
)
}
func ==(lhs: Matrix3, rhs: Matrix3) -> Bool {
if lhs.m11 != rhs.m11 { return false }
if lhs.m12 != rhs.m12 { return false }
if lhs.m13 != rhs.m13 { return false }
if lhs.m21 != rhs.m21 { return false }
if lhs.m22 != rhs.m22 { return false }
if lhs.m23 != rhs.m23 { return false }
if lhs.m31 != rhs.m31 { return false }
if lhs.m32 != rhs.m32 { return false }
if lhs.m33 != rhs.m33 { return false }
return true
}
func ~=(lhs: Matrix3, rhs: Matrix3) -> Bool {
if !(lhs.m11 ~= rhs.m11) { return false }
if !(lhs.m12 ~= rhs.m12) { return false }
if !(lhs.m13 ~= rhs.m13) { return false }
if !(lhs.m21 ~= rhs.m21) { return false }
if !(lhs.m22 ~= rhs.m22) { return false }
if !(lhs.m23 ~= rhs.m23) { return false }
if !(lhs.m31 ~= rhs.m31) { return false }
if !(lhs.m32 ~= rhs.m32) { return false }
if !(lhs.m33 ~= rhs.m33) { return false }
return true
}
//MARK: Matrix4
extension Matrix4: Equatable, Hashable {
static let Identity = Matrix4(1, 0 ,0 ,0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
var hashValue: Int {
var hash = m11.hashValue &+ m12.hashValue &+ m13.hashValue &+ m14.hashValue
hash = hash &+ m21.hashValue &+ m22.hashValue &+ m23.hashValue &+ m24.hashValue
hash = hash &+ m31.hashValue &+ m32.hashValue &+ m33.hashValue &+ m34.hashValue
hash = hash &+ m41.hashValue &+ m42.hashValue &+ m43.hashValue &+ m44.hashValue
return hash
}
init(_ m11: Scalar, _ m12: Scalar, _ m13: Scalar, _ m14: Scalar,
_ m21: Scalar, _ m22: Scalar, _ m23: Scalar, _ m24: Scalar,
_ m31: Scalar, _ m32: Scalar, _ m33: Scalar, _ m34: Scalar,
_ m41: Scalar, _ m42: Scalar, _ m43: Scalar, _ m44: Scalar) {
self.m11 = m11 // 0
self.m12 = m12 // 1
self.m13 = m13 // 2
self.m14 = m14 // 3
self.m21 = m21 // 4
self.m22 = m22 // 5
self.m23 = m23 // 6
self.m24 = m24 // 7
self.m31 = m31 // 8
self.m32 = m32 // 9
self.m33 = m33 // 10
self.m34 = m34 // 11
self.m41 = m41 // 12
self.m42 = m42 // 13
self.m43 = m43 // 14
self.m44 = m44 // 15
}
init(scale s: Vector3) {
self.init(
s.x, 0, 0, 0,
0, s.y, 0, 0,
0, 0, s.z, 0,
0, 0, 0, 1
)
}
init(translation t: Vector3) {
self.init(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
t.x, t.y, t.z, 1
)
}
init(rotation axisAngle: Vector4) {
self.init(quaternion: Quaternion(axisAngle: axisAngle))
}
init(quaternion q: Quaternion) {
self.init(
1 - 2 * (q.y * q.y + q.z * q.z), 2 * (q.x * q.y + q.z * q.w), 2 * (q.x * q.z - q.y * q.w), 0,
2 * (q.x * q.y - q.z * q.w), 1 - 2 * (q.x * q.x + q.z * q.z), 2 * (q.y * q.z + q.x * q.w), 0,
2 * (q.x * q.z + q.y * q.w), 2 * (q.y * q.z - q.x * q.w), 1 - 2 * (q.x * q.x + q.y * q.y), 0,
0, 0, 0, 1
)
}
init(fovx: Scalar, fovy: Scalar, near: Scalar, far: Scalar) {
self.init(fovy: fovy, aspect: fovx / fovy, near: near, far: far)
}
init(fovx: Scalar, aspect: Scalar, near: Scalar, far: Scalar) {
self.init(fovy: fovx / aspect, aspect: aspect, near: near, far: far)
}
init(fovy: Scalar, aspect: Scalar, near: Scalar, far: Scalar) {
let dz = far - near
assert(dz > 0, "far value must be greater than near")
assert(fovy > 0, "field of view must be nonzero and positive")
assert(aspect > 0, "aspect ratio must be nonzero and positive")
let r = fovy / 2
let cotangent = cos(r) / sin(r)
self.init(
cotangent / aspect, 0, 0, 0,
0, cotangent, 0, 0,
0, 0, -(far + near) / dz, -1,
0, 0, -2 * near * far / dz, 0
)
}
init(top: Scalar, right: Scalar, bottom: Scalar, left: Scalar, near: Scalar, far: Scalar) {
let dx = right - left
let dy = top - bottom
let dz = far - near
self.init(
2 / dx, 0, 0, 0,
0, 2 / dy, 0, 0,
0, 0, -2 / dz, 0,
-(right + left) / dx, -(top + bottom) / dy, -(far + near) / dz, 1
)
}
init(_ m: [Scalar]) {
assert(m.count == 16, "array must contain 16 elements, contained \(m.count)")
m11 = m[0]
m12 = m[1]
m13 = m[2]
m14 = m[3]
m21 = m[4]
m22 = m[5]
m23 = m[6]
m24 = m[7]
m31 = m[8]
m32 = m[9]
m33 = m[10]
m34 = m[11]
m41 = m[12]
m42 = m[13]
m43 = m[14]
m44 = m[15]
}
func toArray() -> [Scalar] {
return [m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44]
}
var adjugate: Matrix4 {
var m = Matrix4.Identity
m.m11 = m22 * m33 * m44 - m22 * m34 * m43
m.m11 += -m32 * m23 * m44 + m32 * m24 * m43
m.m11 += m42 * m23 * m34 - m42 * m24 * m33
m.m21 = -m21 * m33 * m44 + m21 * m34 * m43
m.m21 += m31 * m23 * m44 - m31 * m24 * m43
m.m21 += -m41 * m23 * m34 + m41 * m24 * m33
m.m31 = m21 * m32 * m44 - m21 * m34 * m42
m.m31 += -m31 * m22 * m44 + m31 * m24 * m42
m.m31 += m41 * m22 * m34 - m41 * m24 * m32
m.m41 = -m21 * m32 * m43 + m21 * m33 * m42
m.m41 += m31 * m22 * m43 - m31 * m23 * m42
m.m41 += -m41 * m22 * m33 + m41 * m23 * m32
m.m12 = -m12 * m33 * m44 + m12 * m34 * m43
m.m12 += m32 * m13 * m44 - m32 * m14 * m43
m.m12 += -m42 * m13 * m34 + m42 * m14 * m33
m.m22 = m11 * m33 * m44 - m11 * m34 * m43
m.m22 += -m31 * m13 * m44 + m31 * m14 * m43
m.m22 += m41 * m13 * m34 - m41 * m14 * m33
m.m32 = -m11 * m32 * m44 + m11 * m34 * m42
m.m32 += m31 * m12 * m44 - m31 * m14 * m42
m.m32 += -m41 * m12 * m34 + m41 * m14 * m32
m.m42 = m11 * m32 * m43 - m11 * m33 * m42
m.m42 += -m31 * m12 * m43 + m31 * m13 * m42
m.m42 += m41 * m12 * m33 - m41 * m13 * m32
m.m13 = m12 * m23 * m44 - m12 * m24 * m43
m.m13 += -m22 * m13 * m44 + m22 * m14 * m43
m.m13 += m42 * m13 * m24 - m42 * m14 * m23
m.m23 = -m11 * m23 * m44 + m11 * m24 * m43
m.m23 += m21 * m13 * m44 - m21 * m14 * m43
m.m23 += -m41 * m13 * m24 + m41 * m14 * m23
m.m33 = m11 * m22 * m44 - m11 * m24 * m42
m.m33 += -m21 * m12 * m44 + m21 * m14 * m42
m.m33 += m41 * m12 * m24 - m41 * m14 * m22
m.m43 = -m11 * m22 * m43 + m11 * m23 * m42
m.m43 += m21 * m12 * m43 - m21 * m13 * m42
m.m43 += -m41 * m12 * m23 + m41 * m13 * m22
m.m14 = -m12 * m23 * m34 + m12 * m24 * m33
m.m14 += m22 * m13 * m34 - m22 * m14 * m33
m.m14 += -m32 * m13 * m24 + m32 * m14 * m23
m.m24 = m11 * m23 * m34 - m11 * m24 * m33
m.m24 += -m21 * m13 * m34 + m21 * m14 * m33
m.m24 += m31 * m13 * m24 - m31 * m14 * m23
m.m34 = -m11 * m22 * m34 + m11 * m24 * m32
m.m34 += m21 * m12 * m34 - m21 * m14 * m32
m.m34 += -m31 * m12 * m24 + m31 * m14 * m22
m.m44 = m11 * m22 * m33 - m11 * m23 * m32
m.m44 += -m21 * m12 * m33 + m21 * m13 * m32
m.m44 += m31 * m12 * m23 - m31 * m13 * m22
return m
}
private func determinantForAdjugate(m: Matrix4) -> Scalar {
return m11 * m.m11 + m12 * m.m21 + m13 * m.m31 + m14 * m.m41
}
var determinant: Scalar {
return determinantForAdjugate(adjugate)
}
var transpose: Matrix4 {
return Matrix4(
m11, m21, m31, m41,
m12, m22, m32, m42,
m13, m23, m33, m43,
m14, m24, m34, m44
)
}
var inverse: Matrix4 {
let adjugate = self.adjugate
let determinant = determinantForAdjugate(adjugate)
return adjugate * (1 / determinant)
}
}
prefix func -(m: Matrix4) -> Matrix4 {
return m.inverse
}
func *(lhs: Matrix4, rhs: Matrix4) -> Matrix4 {
var m = Matrix4.Identity
m.m11 = lhs.m11 * rhs.m11 + lhs.m21 * rhs.m12
m.m11 += lhs.m31 * rhs.m13 + lhs.m41 * rhs.m14
m.m12 = lhs.m12 * rhs.m11 + lhs.m22 * rhs.m12
m.m12 += lhs.m32 * rhs.m13 + lhs.m42 * rhs.m14
m.m13 = lhs.m13 * rhs.m11 + lhs.m23 * rhs.m12
m.m13 += lhs.m33 * rhs.m13 + lhs.m43 * rhs.m14
m.m14 = lhs.m14 * rhs.m11 + lhs.m24 * rhs.m12
m.m14 += lhs.m34 * rhs.m13 + lhs.m44 * rhs.m14
m.m21 = lhs.m11 * rhs.m21 + lhs.m21 * rhs.m22
m.m21 += lhs.m31 * rhs.m23 + lhs.m41 * rhs.m24
m.m22 = lhs.m12 * rhs.m21 + lhs.m22 * rhs.m22
m.m22 += lhs.m32 * rhs.m23 + lhs.m42 * rhs.m24
m.m23 = lhs.m13 * rhs.m21 + lhs.m23 * rhs.m22
m.m23 += lhs.m33 * rhs.m23 + lhs.m43 * rhs.m24
m.m24 = lhs.m14 * rhs.m21 + lhs.m24 * rhs.m22
m.m24 += lhs.m34 * rhs.m23 + lhs.m44 * rhs.m24
m.m31 = lhs.m11 * rhs.m31 + lhs.m21 * rhs.m32
m.m31 += lhs.m31 * rhs.m33 + lhs.m41 * rhs.m34
m.m32 = lhs.m12 * rhs.m31 + lhs.m22 * rhs.m32
m.m32 += lhs.m32 * rhs.m33 + lhs.m42 * rhs.m34
m.m33 = lhs.m13 * rhs.m31 + lhs.m23 * rhs.m32
m.m33 += lhs.m33 * rhs.m33 + lhs.m43 * rhs.m34
m.m34 = lhs.m14 * rhs.m31 + lhs.m24 * rhs.m32
m.m34 += lhs.m34 * rhs.m33 + lhs.m44 * rhs.m34
m.m41 = lhs.m11 * rhs.m41 + lhs.m21 * rhs.m42
m.m41 += lhs.m31 * rhs.m43 + lhs.m41 * rhs.m44
m.m42 = lhs.m12 * rhs.m41 + lhs.m22 * rhs.m42
m.m42 += lhs.m32 * rhs.m43 + lhs.m42 * rhs.m44
m.m43 = lhs.m13 * rhs.m41 + lhs.m23 * rhs.m42
m.m43 += lhs.m33 * rhs.m43 + lhs.m43 * rhs.m44
m.m44 = lhs.m14 * rhs.m41 + lhs.m24 * rhs.m42
m.m44 += lhs.m34 * rhs.m43 + lhs.m44 * rhs.m44
return m
}
func *(lhs: Matrix4, rhs: Vector3) -> Vector3 {
return rhs * lhs
}
func *(lhs: Matrix4, rhs: Vector4) -> Vector4 {
return rhs * lhs
}
func *(lhs: Matrix4, rhs: Scalar) -> Matrix4 {
return Matrix4(
lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs, lhs.m14 * rhs,
lhs.m21 * rhs, lhs.m22 * rhs, lhs.m23 * rhs, lhs.m24 * rhs,
lhs.m31 * rhs, lhs.m32 * rhs, lhs.m33 * rhs, lhs.m34 * rhs,
lhs.m41 * rhs, lhs.m42 * rhs, lhs.m43 * rhs, lhs.m44 * rhs
)
}
func ==(lhs: Matrix4, rhs: Matrix4) -> Bool {
if lhs.m11 != rhs.m11 { return false }
if lhs.m12 != rhs.m12 { return false }
if lhs.m13 != rhs.m13 { return false }
if lhs.m14 != rhs.m14 { return false }
if lhs.m21 != rhs.m21 { return false }
if lhs.m22 != rhs.m22 { return false }
if lhs.m23 != rhs.m23 { return false }
if lhs.m24 != rhs.m24 { return false }
if lhs.m31 != rhs.m31 { return false }
if lhs.m32 != rhs.m32 { return false }
if lhs.m33 != rhs.m33 { return false }
if lhs.m34 != rhs.m34 { return false }
if lhs.m41 != rhs.m41 { return false }
if lhs.m42 != rhs.m42 { return false }
if lhs.m43 != rhs.m43 { return false }
if lhs.m44 != rhs.m44 { return false }
return true
}
func ~=(lhs: Matrix4, rhs: Matrix4) -> Bool {
if !(lhs.m11 ~= rhs.m11) { return false }
if !(lhs.m12 ~= rhs.m12) { return false }
if !(lhs.m13 ~= rhs.m13) { return false }
if !(lhs.m14 ~= rhs.m14) { return false }
if !(lhs.m21 ~= rhs.m21) { return false }
if !(lhs.m22 ~= rhs.m22) { return false }
if !(lhs.m23 ~= rhs.m23) { return false }
if !(lhs.m24 ~= rhs.m24) { return false }
if !(lhs.m31 ~= rhs.m31) { return false }
if !(lhs.m32 ~= rhs.m32) { return false }
if !(lhs.m33 ~= rhs.m33) { return false }
if !(lhs.m34 ~= rhs.m34) { return false }
if !(lhs.m41 ~= rhs.m41) { return false }
if !(lhs.m42 ~= rhs.m42) { return false }
if !(lhs.m43 ~= rhs.m43) { return false }
if !(lhs.m44 ~= rhs.m44) { return false }
return true
}
//MARK: Quaternion
extension Quaternion: Equatable, Hashable {
static let Zero = Quaternion(0, 0, 0, 0)
static let Identity = Quaternion(0, 0, 0, 1)
var hashValue: Int {
return x.hashValue &+ y.hashValue &+ z.hashValue &+ w.hashValue
}
var lengthSquared: Scalar {
return x * x + y * y + z * z + w * w
}
var length: Scalar {
return sqrt(lengthSquared)
}
var inverse: Quaternion {
return -self
}
var xyz: Vector3 {
get {
return Vector3(x, y, z)
}
set (v) {
x = v.x
y = v.y
z = v.z
}
}
var pitch: Scalar {
return atan2(2 * (y * z + w * x), w * w - x * x - y * y + z * z)
}
var yaw: Scalar {
return asin(-2 * (x * z - w * y))
}
var roll: Scalar {
return atan2(2 * (x * y + w * z), w * w + x * x - y * y - z * z)
}
init(_ x: Scalar, _ y: Scalar, _ z: Scalar, _ w: Scalar) {
self.init(x: x, y: y, z: z, w: w)
}
init(axisAngle: Vector4) {
let r = axisAngle.w * 0.5
let scale = sin(r)
let a = axisAngle.xyz * scale
self.init(a.x, a.y, a.z, cos(r))
}
init(pitch: Scalar, yaw: Scalar, roll: Scalar) {
let sy = sin(yaw * 0.5)
let cy = cos(yaw * 0.5)
let sz = sin(roll * 0.5)
let cz = cos(roll * 0.5)
let sx = sin(pitch * 0.5)
let cx = cos(pitch * 0.5)
self.init(
cy * cz * cx - sy * sz * sx,
sy * sz * cx + cy * cz * sx,
sy * cz * cx + cy * sz * sx,
cy * sz * cx - sy * cz * sx
)
}
init(rotationMatrix m: Matrix4) {
let diagonal = m.m11 + m.m22 + m.m33 + 1
if diagonal ~= 0 {
let scale = sqrt(diagonal) * 2
self.init(
(m.m32 - m.m23) / scale,
(m.m13 - m.m31) / scale,
(m.m21 - m.m12) / scale,
0.25 * scale
)
} else if m.m11 > max(m.m22, m.m33) {
let scale = sqrt(1 + m.m11 - m.m22 - m.m33) * 2
self.init(
0.25 * scale,
(m.m21 + m.m12) / scale,
(m.m13 + m.m31) / scale,
(m.m32 - m.m23) / scale
)
} else if m.m22 > m.m33 {
let scale = sqrt(1 + m.m22 - m.m11 - m.m33) * 2
self.init(
(m.m21 + m.m12) / scale,
0.25 * scale,
(m.m32 + m.m23) / scale,
(m.m13 - m.m31) / scale
)
} else {
let scale = sqrt(1 + m.m33 - m.m11 - m.m22) * 2
self.init(
(m.m13 + m.m31) / scale,
(m.m32 + m.m23) / scale,
0.25 * scale,
(m.m21 - m.m12) / scale
)
}
}
init(_ v: [Scalar]) {
assert(v.count == 4, "array must contain 4 elements, contained \(v.count)")
x = v[0]
y = v[1]
z = v[2]
w = v[3]
}
func toAxisAngle() -> Vector4 {
let scale = xyz.length
if scale ~= 0 || scale ~= .TwoPi {
return .Z
} else {
return Vector4(x / scale, y / scale, z / scale, acos(w) * 2)
}
}
func toPitchYawRoll() -> (pitch: Scalar, yaw: Scalar, roll: Scalar) {
return (pitch, yaw, roll)
}
func toArray() -> [Scalar] {
return [x, y, z, w]
}
func dot(v: Quaternion) -> Scalar {
return x * v.x + y * v.y + z * v.z + w * v.w
}
func normalized() -> Quaternion {
let lengthSquared = self.lengthSquared
if lengthSquared ~= 0 || lengthSquared ~= 1 {
return self
}
return self / sqrt(lengthSquared)
}
func interpolatedWith(q: Quaternion, t: Scalar) -> Quaternion {
let dot = max(-1, min(1, self.dot(q)))
if dot ~= 1 {
return (self + (q - self) * t).normalized()
}
let theta = acos(dot) * t
let t1 = self * cos(theta)
let t2 = (q - (self * dot)).normalized() * sin(theta)
return t1 + t2
}
}
prefix func -(q: Quaternion) -> Quaternion {
return Quaternion(-q.x, -q.y, -q.z, q.w)
}
func +(lhs: Quaternion, rhs: Quaternion) -> Quaternion {
return Quaternion(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w)
}
func -(lhs: Quaternion, rhs: Quaternion) -> Quaternion {
return Quaternion(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w)
}
func *(lhs: Quaternion, rhs: Quaternion) -> Quaternion {
return Quaternion(
lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y,
lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z,
lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x,
lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z
)
}
func *(lhs: Quaternion, rhs: Vector3) -> Vector3 {
return rhs * lhs
}
func *(lhs: Quaternion, rhs: Scalar) -> Quaternion {
return Quaternion(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs)
}
func /(lhs: Quaternion, rhs: Scalar) -> Quaternion {
return Quaternion(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs)
}
func ==(lhs: Quaternion, rhs: Quaternion) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w
}
func ~=(lhs: Quaternion, rhs: Quaternion) -> Bool {
return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z && lhs.w ~= rhs.w
}
| c78eb8f6c03c2edf8259fd900e6a7f08 | 25.891622 | 105 | 0.482907 | false | false | false | false |
tectijuana/patrones | refs/heads/master | Bloque1SwiftArchivado/PracticasSwift/AlejandroEspinoza/Ejercicio8.swift | gpl-3.0 | 1 | /* Espinoza Covarrubias Alejandro 13211465 */
/* Patrones de diseño */
/* Capitulo 2 */
/* Ejercicio 8 */
/* Imprimir un número real N, su inverso aditivo y su multiplicativo inveros (si lo tiene) */
/* Importa librería para utlizar funciones matemáticas */
import Foundation
/* Declaración de variables */
var numero = 1.0
print("\tNumero\t|\tAditivo inverso\t|\tMultiplicativo inverso\t")
print("------------------------------------------------------------------------")
/* Ciclo while que realiza la tabla */
while numero <= 10
{
/* Calcular el inverso aditivo */
var InvAdi = numero
/* Calcular el multiplicativo inverso */
var InvMul = 1 / numero
/* Imprime los resultados */
print("\t\(numero)\t|\t-\(InvAdi)\t\t|\t" + (String(format:"%.5f",InvMul)) + "\t")
/* Suma al valor de número una unidad */
numero = numero + 1
} | aed797ec42479b9d024f4ddb6c35aed1 | 21.578947 | 93 | 0.611435 | false | false | false | false |
KiiPlatform/thing-if-iOSSample | refs/heads/master | SampleProject/TriggerCommandEditViewController.swift | mit | 1 | //
// TriggerCommandEditViewController.swift
// SampleProject
//
// Created by Yongping on 8/27/15.
// Copyright © 2015 Kii Corporation. All rights reserved.
//
import UIKit
import ThingIFSDK
protocol TriggerCommandEditViewControllerDelegate {
func saveCommands(schemaName: String,
schemaVersion: Int,
actions: [Dictionary<String, AnyObject>],
targetID: String?,
title: String?,
commandDescription: String?,
metadata: Dictionary<String, AnyObject>?)
}
class TriggerCommandEditViewController: CommandEditViewController {
var delegate: TriggerCommandEditViewControllerDelegate?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var targetIdSection = SectionStruct(headerTitle: "Target thing ID",
items: [])
var titleSection = SectionStruct(headerTitle: "Title", items: [])
var descriptionSection = SectionStruct(headerTitle: "Description",
items: [])
var metadataSection = SectionStruct(headerTitle: "Meta data",
items: [])
if let command = self.commandStruct {
if let targetID = command.targetID {
targetIdSection.items.append(targetID)
}
if let title = command.title {
titleSection.items.append(title)
}
if let description = command.commandDescription {
descriptionSection.items.append(description)
}
if let metadata = command.metadata {
if let data = try? NSJSONSerialization.dataWithJSONObject(
metadata, options: .PrettyPrinted) {
metadataSection.items.append(
String(data:data,
encoding:NSUTF8StringEncoding)!)
}
}
}
sections += [targetIdSection, titleSection, descriptionSection,
metadataSection]
}
override func tableView(
tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
if sections[indexPath.section].headerTitle == "Target thing ID" {
let cell = tableView.dequeueReusableCellWithIdentifier(
"TargetIDCell",
forIndexPath: indexPath)
if let items = sections[indexPath.section].items
where !items.isEmpty {
let value = items[indexPath.row] as! String
(cell.viewWithTag(202) as! UITextField).text = value
}
return cell
} else if sections[indexPath.section].headerTitle == "Title" {
let cell = tableView.dequeueReusableCellWithIdentifier(
"CommandTitleCell",
forIndexPath: indexPath)
if let items = sections[indexPath.section].items
where !items.isEmpty {
let value = items[indexPath.row] as! String
(cell.viewWithTag(203) as! UITextField).text = value
}
return cell
} else if sections[indexPath.section].headerTitle == "Description" {
let cell = tableView.dequeueReusableCellWithIdentifier(
"CommandDescriptionCell",
forIndexPath: indexPath)
if let items = sections[indexPath.section].items
where !items.isEmpty {
let value = items[indexPath.row] as! String
(cell.viewWithTag(204) as! UITextView).text = value
}
return cell
} else if sections[indexPath.section].headerTitle == "Meta data" {
let cell = tableView.dequeueReusableCellWithIdentifier(
"CommandMetadataCell", forIndexPath: indexPath)
if let items = sections[indexPath.section].items
where !items.isEmpty {
let value = items[indexPath.row] as! String
(cell.viewWithTag(205) as! UITextView).text = value
}
return cell
} else {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
}
override func tableView(
tableView: UITableView,
heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
if sections[indexPath.section].headerTitle == "Description" {
return 130
} else if sections[indexPath.section].headerTitle == "Meta data" {
return 130
} else {
return super.tableView(tableView,
heightForRowAtIndexPath: indexPath)
}
}
@IBAction func tapSaveCommand(sender: AnyObject) {
// generate actions array
var actions = [Dictionary<String, AnyObject>]()
if let actionsItems = sections[2].items {
for actionItem in actionsItems {
if let actionCellData = actionItem as? ActionStruct {
// action should be like: ["actionName": ["requiredStatus": value] ], where value can be Bool, Int or Double
actions.append(actionCellData.getActionDict())
}
}
}
// the defaultd schema and schemaVersion from predefined schem dict
let schema: String? = (self.view.viewWithTag(200) as? UITextField)?.text
let schemaVersion: Int?
if let schemaVersionTextFiled = self.view.viewWithTag(201) as? UITextField {
schemaVersion = Int(schemaVersionTextFiled.text!)!
} else {
schemaVersion = nil
}
let targetID: String?
if let text = (self.view.viewWithTag(202) as? UITextField)?.text
where !text.isEmpty {
targetID = text
} else {
targetID = nil
}
let title: String?
if let text = (self.view.viewWithTag(203) as? UITextField)?.text
where !text.isEmpty {
title = text
} else {
title = nil
}
let description: String?
if let text = (self.view.viewWithTag(204) as? UITextView)?.text
where !text.isEmpty {
description = text
} else {
description = nil
}
let metadata: Dictionary<String, AnyObject>?
if let text = (self.view.viewWithTag(205) as? UITextView)?.text {
metadata = try? NSJSONSerialization.JSONObjectWithData(
text.dataUsingEncoding(NSUTF8StringEncoding)!,
options: .MutableContainers) as! Dictionary<String, AnyObject>
} else {
metadata = nil
}
if self.delegate != nil {
delegate?.saveCommands(schema!,
schemaVersion: schemaVersion!,
actions: actions,
targetID: targetID,
title: title,
commandDescription: description,
metadata: metadata)
}
self.navigationController?.popViewControllerAnimated(true)
}
}
| 65a547ad159e0eefbced12021082c55c | 38.284946 | 128 | 0.559327 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | CommonKit/Source/UserIndicators/UserIndicator.swift | apache-2.0 | 1 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
/// A `UserIndicator` represents the state of a temporary visual indicator, such as loading spinner, success notification or an error message. It does not directly manage the UI, instead it delegates to a `presenter`
/// whenever the UI should be shown or hidden.
///
/// More than one `UserIndicator` may be requested by the system at the same time (e.g. global syncing vs local refresh),
/// and the `UserIndicatorQueue` will ensure that only one indicator is shown at a given time, putting the other in a pending queue.
///
/// A client that requests an indicator can specify a default timeout after which the indicator is dismissed, or it has to be manually
/// responsible for dismissing it via `cancel` method, or by deallocating itself.
public class UserIndicator {
public enum State {
case pending
case executing
case completed
}
private let request: UserIndicatorRequest
private let completion: () -> Void
public private(set) var state: State
public init(request: UserIndicatorRequest, completion: @escaping () -> Void) {
self.request = request
self.completion = completion
state = .pending
}
deinit {
complete()
}
internal func start() {
guard state == .pending else {
return
}
state = .executing
request.presenter.present()
switch request.dismissal {
case .manual:
break
case .timeout(let interval):
Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in
self?.complete()
}
}
}
/// Cancel the indicator, triggering any dismissal action / animation
///
/// Note: clients can call this method directly, if they have access to the `UserIndicator`. Alternatively
/// deallocating the `UserIndicator` will call `cancel` automatically.
/// Once cancelled, `UserIndicatorQueue` will automatically start the next `UserIndicator` in the queue.
public func cancel() {
complete()
}
private func complete() {
guard state != .completed else {
return
}
if state == .executing {
request.presenter.dismiss()
}
state = .completed
completion()
}
}
public extension UserIndicator {
func store<C>(in collection: inout C) where C: RangeReplaceableCollection, C.Element == UserIndicator {
collection.append(self)
}
}
public extension Collection where Element == UserIndicator {
func cancelAll() {
forEach {
$0.cancel()
}
}
}
| 7cd449d0257411d1c3fa10c42f04eb36 | 31.378641 | 216 | 0.649175 | false | false | false | false |
flowsprenger/RxLifx-Swift | refs/heads/master | RxLifxApi/RxLifxApi/Command/DeviceGetGroupCommand.swift | mit | 1 | /*
Copyright 2017 Florian Sprenger
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 RxLifx
import LifxDomain
import RxSwift
public class DeviceGetGroupCommand {
public class func create(light: Light, ackRequired: Bool = false, responseRequired: Bool = false) -> Observable<Result<StateGroup>> {
let message = Message.createMessageWithPayload(GetGroup(), target: light.target, source: light.lightSource.source)
message.header.ackRequired = ackRequired
message.header.responseRequired = responseRequired
return AsyncLightCommand.sendMessage(lightSource: light.lightSource, light: light, message: message)
}
}
| 768e907d2484a84528ef109082e6b472 | 50.6875 | 137 | 0.788392 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | refs/heads/master | bluefruitconnect/Platform/OSX/Controllers/UartViewController.swift | mit | 1 | //
// UartViewController.swift
// bluefruitconnect
//
// Created by Antonio García on 26/09/15.
// Copyright © 2015 Adafruit. All rights reserved.
//
import Cocoa
class UartViewController: NSViewController {
// UI Outlets
@IBOutlet var baseTextView: NSTextView!
@IBOutlet weak var baseTextVisibilityView: NSScrollView!
@IBOutlet weak var baseTableView: NSTableView!
@IBOutlet weak var baseTableVisibilityView: NSScrollView!
@IBOutlet weak var hexModeSegmentedControl: NSSegmentedControl!
@IBOutlet weak var displayModeSegmentedControl: NSSegmentedControl!
@IBOutlet weak var mqttStatusButton: NSButton!
@IBOutlet weak var inputTextField: NSTextField!
@IBOutlet weak var echoButton: NSButton!
@IBOutlet weak var eolButton: NSButton!
@IBOutlet weak var sentBytesLabel: NSTextField!
@IBOutlet weak var receivedBytesLabel: NSTextField!
@IBOutlet var saveDialogCustomView: NSView!
@IBOutlet weak var saveDialogPopupButton: NSPopUpButton!
// Data
private let uartData = UartModuleManager()
// UI
private static var dataFont = Font(name: "CourierNewPSMT", size: 13)!
private var txColor = Preferences.uartSentDataColor
private var rxColor = Preferences.uartReceveivedDataColor
private let timestampDateFormatter = NSDateFormatter()
private var tableCachedDataBuffer : [UartDataChunk]?
private var tableModeDataMaxWidth : CGFloat = 0
// Export
private var exportFileDialog : NSSavePanel?
// MARK:
override func viewDidLoad() {
super.viewDidLoad()
// Init Data
uartData.delegate = self
timestampDateFormatter.setLocalizedDateFormatFromTemplate("HH:mm:ss:SSSS")
// Init UI
hexModeSegmentedControl.selectedSegment = Preferences.uartIsInHexMode ? 1:0
displayModeSegmentedControl.selectedSegment = Preferences.uartIsDisplayModeTimestamp ? 1:0
echoButton.state = Preferences.uartIsEchoEnabled ? NSOnState:NSOffState
eolButton.state = Preferences.uartIsAutomaticEolEnabled ? NSOnState:NSOffState
// UI
baseTableVisibilityView.scrollerStyle = NSScrollerStyle.Legacy // To avoid autohide behaviour
reloadDataUI()
// Mqtt init
let mqttManager = MqttManager.sharedInstance
if (MqttSettings.sharedInstance.isConnected) {
mqttManager.delegate = uartData
mqttManager.connectFromSavedSettings()
}
}
override func viewWillAppear() {
super.viewWillAppear()
registerNotifications(true)
mqttUpdateStatusUI()
}
override func viewDidDisappear() {
super.viewDidDisappear()
registerNotifications(false)
}
deinit {
let mqttManager = MqttManager.sharedInstance
mqttManager.disconnect()
}
// MARK: - Preferences
func registerNotifications(register : Bool) {
let notificationCenter = NSNotificationCenter.defaultCenter()
if (register) {
notificationCenter.addObserver(self, selector: #selector(UartViewController.preferencesUpdated(_:)), name: Preferences.PreferencesNotifications.DidUpdatePreferences.rawValue, object: nil)
}
else {
notificationCenter.removeObserver(self, name: Preferences.PreferencesNotifications.DidUpdatePreferences.rawValue, object: nil)
}
}
func preferencesUpdated(notification : NSNotification) {
txColor = Preferences.uartSentDataColor
rxColor = Preferences.uartReceveivedDataColor
reloadDataUI()
}
// MARK: - UI Updates
func reloadDataUI() {
let displayMode = Preferences.uartIsDisplayModeTimestamp ? UartModuleManager.DisplayMode.Table : UartModuleManager.DisplayMode.Text
baseTableVisibilityView.hidden = displayMode == .Text
baseTextVisibilityView.hidden = displayMode == .Table
switch(displayMode) {
case .Text:
if let textStorage = self.baseTextView.textStorage {
let isScrollAtTheBottom = baseTextView.enclosingScrollView?.verticalScroller?.floatValue == 1
textStorage.beginEditing()
textStorage.replaceCharactersInRange(NSMakeRange(0, textStorage.length), withAttributedString: NSAttributedString()) // Clear text
for dataChunk in uartData.dataBuffer {
addChunkToUIText(dataChunk)
}
textStorage .endEditing()
if isScrollAtTheBottom {
baseTextView.scrollRangeToVisible(NSMakeRange(textStorage.length, 0))
}
}
case .Table:
//let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || baseTableView.enclosingScrollView?.verticalScroller?.floatValue == 1
let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || NSLocationInRange(tableCachedDataBuffer!.count-1, baseTableView.rowsInRect(baseTableView.visibleRect))
baseTableView.sizeLastColumnToFit()
baseTableView.reloadData()
if isScrollAtTheBottom {
baseTableView.scrollToEndOfDocument(nil)
}
}
updateBytesUI()
}
func updateBytesUI() {
if let blePeripheral = uartData.blePeripheral {
let localizationManager = LocalizationManager.sharedInstance
sentBytesLabel.stringValue = String(format: localizationManager.localizedString("uart_sentbytes_format"), arguments: [blePeripheral.uartData.sentBytes])
receivedBytesLabel.stringValue = String(format: localizationManager.localizedString("uart_recievedbytes_format"), arguments: [blePeripheral.uartData.receivedBytes])
}
}
// MARK: - UI Actions
@IBAction func onClickEcho(sender: NSButton) {
Preferences.uartIsEchoEnabled = echoButton.state == NSOnState
reloadDataUI()
}
@IBAction func onClickEol(sender: NSButton) {
Preferences.uartIsAutomaticEolEnabled = eolButton.state == NSOnState
}
@IBAction func onChangeHexMode(sender: AnyObject) {
Preferences.uartIsInHexMode = sender.selectedSegment == 1
reloadDataUI()
}
@IBAction func onChangeDisplayMode(sender: NSSegmentedControl) {
Preferences.uartIsDisplayModeTimestamp = sender.selectedSegment == 1
reloadDataUI()
}
@IBAction func onClickClear(sender: NSButton) {
uartData.clearData()
tableModeDataMaxWidth = 0
reloadDataUI()
}
@IBAction func onClickSend(sender: AnyObject) {
let text = inputTextField.stringValue
var newText = text
// Eol
if (Preferences.uartIsAutomaticEolEnabled) {
newText += "\n"
}
uartData.sendMessageToUart(newText)
inputTextField.stringValue = ""
}
@IBAction func onClickExport(sender: AnyObject) {
exportData()
}
@IBAction func onClickMqtt(sender: AnyObject) {
let mqttManager = MqttManager.sharedInstance
let status = mqttManager.status
if status != .Connected && status != .Connecting {
if let serverAddress = MqttSettings.sharedInstance.serverAddress where !serverAddress.isEmpty {
// Server address is defined. Start connection
mqttManager.delegate = uartData
mqttManager.connectFromSavedSettings()
}
else {
// Server address not defined
let localizationManager = LocalizationManager.sharedInstance
let alert = NSAlert()
alert.messageText = localizationManager.localizedString("uart_mqtt_undefinedserver")
alert.addButtonWithTitle(localizationManager.localizedString("dialog_ok"))
alert.addButtonWithTitle(localizationManager.localizedString("uart_mqtt_editsettings"))
alert.alertStyle = .WarningAlertStyle
alert.beginSheetModalForWindow(self.view.window!) { [unowned self] (returnCode) -> Void in
if returnCode == NSAlertSecondButtonReturn {
let preferencesViewController = self.storyboard?.instantiateControllerWithIdentifier("PreferencesViewController") as! PreferencesViewController
self.presentViewControllerAsModalWindow(preferencesViewController)
}
}
}
}
else {
mqttManager.disconnect()
}
mqttUpdateStatusUI()
}
// MARK: - Export
private func exportData() {
let localizationManager = LocalizationManager.sharedInstance
// Check if data is empty
guard uartData.dataBuffer.count > 0 else {
let alert = NSAlert()
alert.messageText = localizationManager.localizedString("uart_export_nodata")
alert.addButtonWithTitle(localizationManager.localizedString("dialog_ok"))
alert.alertStyle = .WarningAlertStyle
alert.beginSheetModalForWindow(self.view.window!, completionHandler: nil)
return
}
// Show save dialog
exportFileDialog = NSSavePanel()
exportFileDialog!.delegate = self
exportFileDialog!.message = localizationManager.localizedString("uart_export_save_message")
exportFileDialog!.prompt = localizationManager.localizedString("uart_export_save_prompt")
exportFileDialog!.canCreateDirectories = true
exportFileDialog!.accessoryView = saveDialogCustomView
for exportFormat in uartData.exportFormats {
saveDialogPopupButton.addItemWithTitle(exportFormat.rawValue)
}
updateSaveFileName()
if let window = self.view.window {
exportFileDialog!.beginSheetModalForWindow(window) {[unowned self] (result) -> Void in
if result == NSFileHandlingPanelOKButton {
if let url = self.exportFileDialog!.URL {
// Save
var text : String?
let exportFormatSelected = self.uartData.exportFormats[self.saveDialogPopupButton.indexOfSelectedItem]
let dataBuffer = self.uartData.dataBuffer
switch(exportFormatSelected) {
case .txt:
text = UartDataExport.dataAsText(dataBuffer)
case .csv:
text = UartDataExport.dataAsCsv(dataBuffer)
case .json:
text = UartDataExport.dataAsJson(dataBuffer)
break
case .xml:
text = UartDataExport.dataAsXml(dataBuffer)
break
}
// Write data
do {
try text?.writeToURL(url, atomically: true, encoding: NSUTF8StringEncoding)
}
catch let error {
DLog("Error exporting file \(url.absoluteString): \(error)")
}
}
}
}
}
}
@IBAction func onExportFormatChanged(sender: AnyObject) {
updateSaveFileName()
}
private func updateSaveFileName() {
if let exportFileDialog = exportFileDialog {
let isInHexMode = Preferences.uartIsInHexMode
let exportFormatSelected = uartData.exportFormats[saveDialogPopupButton.indexOfSelectedItem]
exportFileDialog.nameFieldStringValue = "uart\(isInHexMode ? ".hex" : "").\(exportFormatSelected.rawValue)"
}
}
}
// MARK: - DetailTab
extension UartViewController : DetailTab {
func tabWillAppear() {
reloadDataUI()
// Check if characteristics are ready
let isUartReady = uartData.isReady()
inputTextField.enabled = isUartReady
inputTextField.backgroundColor = isUartReady ? NSColor.whiteColor() : NSColor.blackColor().colorWithAlphaComponent(0.1)
}
func tabWillDissapear() {
if !Config.uartShowAllUartCommunication {
uartData.dataBufferEnabled = false
}
}
func tabReset() {
// Peripheral should be connected
uartData.dataBufferEnabled = true
uartData.blePeripheral = BleManager.sharedInstance.blePeripheralConnected // Note: this will start the service discovery
}
}
// MARK: - NSOpenSavePanelDelegate
extension UartViewController: NSOpenSavePanelDelegate {
}
// MARK: - NSTableViewDataSource
extension UartViewController: NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if (Preferences.uartIsEchoEnabled) {
tableCachedDataBuffer = uartData.dataBuffer
}
else {
tableCachedDataBuffer = uartData.dataBuffer.filter({ (dataChunk : UartDataChunk) -> Bool in
dataChunk.mode == .RX
})
}
return tableCachedDataBuffer!.count
}
}
// MARK: NSTableViewDelegate
extension UartViewController: NSTableViewDelegate {
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
var cell : NSTableCellView?
let dataChunk = tableCachedDataBuffer![row]
if let columnIdentifier = tableColumn?.identifier {
switch(columnIdentifier) {
case "TimestampColumn":
cell = tableView.makeViewWithIdentifier("TimestampCell", owner: self) as? NSTableCellView
let date = NSDate(timeIntervalSinceReferenceDate: dataChunk.timestamp)
let dateString = timestampDateFormatter.stringFromDate(date)
cell!.textField!.stringValue = dateString
case "DirectionColumn":
cell = tableView.makeViewWithIdentifier("DirectionCell", owner: self) as? NSTableCellView
cell!.textField!.stringValue = dataChunk.mode == .RX ? "RX" : "TX"
case "DataColumn":
cell = tableView.makeViewWithIdentifier("DataCell", owner: self) as? NSTableCellView
let color = dataChunk.mode == .TX ? txColor : rxColor
if let attributedText = UartModuleManager.attributeTextFromData(dataChunk.data, useHexMode: Preferences.uartIsInHexMode, color: color, font: UartViewController.dataFont) {
//DLog("row \(row): \(attributedText.string)")
// Display
cell!.textField!.attributedStringValue = attributedText
// Update column width (if needed)
let width = attributedText.size().width
tableModeDataMaxWidth = max(tableColumn!.width, width)
dispatch_async(dispatch_get_main_queue(), { // Important: Execute async. This change should be done outside the delegate method to avoid weird reuse cell problems (reused cell shows old data and cant be changed).
if (tableColumn!.width < self.tableModeDataMaxWidth) {
tableColumn!.width = self.tableModeDataMaxWidth
}
});
}
else {
//DLog("row \(row): <empty>")
cell!.textField!.attributedStringValue = NSAttributedString()
}
default:
cell = nil
}
}
return cell;
}
func tableViewSelectionDidChange(notification: NSNotification) {
}
func tableViewColumnDidResize(notification: NSNotification) {
if let tableColumn = notification.userInfo?["NSTableColumn"] as? NSTableColumn {
if (tableColumn.identifier == "DataColumn") {
// If the window is resized, maintain the column width
if (tableColumn.width < tableModeDataMaxWidth) {
tableColumn.width = tableModeDataMaxWidth
}
//DLog("column: \(tableColumn), width: \(tableColumn.width)")
}
}
}
}
// MARK: - UartModuleDelegate
extension UartViewController: UartModuleDelegate {
func addChunkToUI(dataChunk : UartDataChunk) {
// Check that the view has been initialized before updating UI
guard baseTableView != nil else {
return;
}
let displayMode = Preferences.uartIsDisplayModeTimestamp ? UartModuleManager.DisplayMode.Table : UartModuleManager.DisplayMode.Text
switch(displayMode) {
case .Text:
if let textStorage = self.baseTextView.textStorage {
let isScrollAtTheBottom = baseTextView.enclosingScrollView?.verticalScroller?.floatValue == 1
addChunkToUIText(dataChunk)
if isScrollAtTheBottom {
// if scroll was at the bottom then autoscroll to the new bottom
baseTextView.scrollRangeToVisible(NSMakeRange(textStorage.length, 0))
}
}
case .Table:
let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || NSLocationInRange(tableCachedDataBuffer!.count-1, baseTableView.rowsInRect(baseTableView.visibleRect))
//let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || baseTableView.enclosingScrollView?.verticalScroller?.floatValue == 1
baseTableView.reloadData()
if isScrollAtTheBottom {
// if scroll was at the bottom then autoscroll to the new bottom
baseTableView.scrollToEndOfDocument(nil)
}
}
updateBytesUI()
}
private func addChunkToUIText(dataChunk : UartDataChunk) {
if (Preferences.uartIsEchoEnabled || dataChunk.mode == .RX) {
let color = dataChunk.mode == .TX ? txColor : rxColor
let attributedString = UartModuleManager.attributeTextFromData(dataChunk.data, useHexMode: Preferences.uartIsInHexMode, color: color, font: UartViewController.dataFont)
if let textStorage = self.baseTextView.textStorage, attributedString = attributedString {
textStorage.appendAttributedString(attributedString)
}
}
}
func mqttUpdateStatusUI() {
let status = MqttManager.sharedInstance.status
let localizationManager = LocalizationManager.sharedInstance
var buttonTitle = localizationManager.localizedString("uart_mqtt_status_default")
switch (status) {
case .Connecting:
buttonTitle = localizationManager.localizedString("uart_mqtt_status_connecting")
case .Connected:
buttonTitle = localizationManager.localizedString("uart_mqtt_status_connected")
default:
buttonTitle = localizationManager.localizedString("uart_mqtt_status_disconnected")
}
mqttStatusButton.title = buttonTitle
}
func mqttError(message: String, isConnectionError: Bool) {
let localizationManager = LocalizationManager.sharedInstance
let alert = NSAlert()
alert.messageText = isConnectionError ? localizationManager.localizedString("uart_mqtt_connectionerror_title"): message
alert.addButtonWithTitle(localizationManager.localizedString("dialog_ok"))
if (isConnectionError) {
alert.addButtonWithTitle(localizationManager.localizedString("uart_mqtt_editsettings_action"))
alert.informativeText = message
}
alert.alertStyle = .WarningAlertStyle
alert.beginSheetModalForWindow(self.view.window!) { [unowned self] (returnCode) -> Void in
if isConnectionError && returnCode == NSAlertSecondButtonReturn {
let preferencesViewController = self.storyboard?.instantiateControllerWithIdentifier("PreferencesViewController") as! PreferencesViewController
self.presentViewControllerAsModalWindow(preferencesViewController)
}
}
}
}
// MARK: - CBPeripheralDelegate
extension UartViewController: CBPeripheralDelegate {
// Pass peripheral callbacks to UartData
func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
uartData.peripheral(peripheral, didModifyServices: invalidatedServices)
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
uartData.peripheral(peripheral, didDiscoverServices:error)
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
uartData.peripheral(peripheral, didDiscoverCharacteristicsForService: service, error: error)
// Check if ready
if uartData.isReady() {
// Enable input
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
if self.inputTextField != nil { // could be nil if the viewdidload has not been executed yet
self.inputTextField.enabled = true
self.inputTextField.backgroundColor = NSColor.whiteColor()
}
});
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
uartData.peripheral(peripheral, didUpdateValueForCharacteristic: characteristic, error: error)
}
}
| 648abc27181863ecf692b26714d037e4 | 39.494585 | 236 | 0.624588 | false | false | false | false |
pman215/ToastNotifications | refs/heads/master | ToastNotifications/ViewAnimationTaskQueue.swift | mit | 1 | //
// ViewAnimationTaskQueue.swift
// ToastNotifications
//
// Created by pman215 on 6/6/16.
// Copyright © 2016 pman215. All rights reserved.
//
import Foundation
/**
Describes the possible states of a `ViewAnimationTaskQueue`
+ New: Queue was initialized and is ready to queue tasks and start processing
them
+ Processing: Queue started processing tasks. Queueing more tasks is not
allowed
+ Finished: Queue processed all tasks in the queue.
*/
internal enum ViewAnimationTaskQueueState {
case new
case processing
case finished
}
internal protocol ViewAnimationTaskQueueDelegate: class {
/**
Called when a `ViewAnimationTaskQueue` finished processing all queued tasks
*/
func queueDidFinishProcessing(_ queue: ViewAnimationTaskQueue)
}
/**
A `ViewAnimationTaskQueue` coordinates the execution of `ViewAnimationTask`
objects. When a task is added to the queue it will start execution immediately
as long as there are no other task being processed. Tasks are processed in a
FIFO order
A queue is a single-shot object, once it has finished processing all its tasks,
the queue should be disposed.
*/
internal class ViewAnimationTaskQueue {
fileprivate var queue = [ViewAnimationTask]()
fileprivate(set) var state: ViewAnimationTaskQueueState
var tasks: [ViewAnimationTask] {
return queue
}
weak var delegate: ViewAnimationTaskQueueDelegate?
init() {
state = .new
}
func queue(task: ViewAnimationTask) {
task.queue = self
queue.append(task)
}
func dequeue(task: ViewAnimationTask) {
switch state {
case .processing:
remove(task)
processTask()
case .new:
assertionFailure("ViewAnimationTaskQueue should be processing")
case .finished:
assertionFailure("ViewAnimationTaskQueue can't process tasks after finishing")
}
}
func process() {
switch state {
case .new:
state = .processing
processTask()
case .processing:
assertionFailure("ViewAnimationTaskQueue is already processing")
case .finished:
assertionFailure("ViewAnimationTaskQueue is done processing.")
}
}
func cancel() {
switch state {
case .new, .processing:
cancelAllTasks()
state = .finished
case .finished:
assertionFailure("ViewAnimationTaskQueue is done processing.")
}
}
}
private extension ViewAnimationTaskQueue {
func processTask() {
if let firstTask = queue.first {
firstTask.animate()
} else {
state = .finished
delegate?.queueDidFinishProcessing(self)
}
}
func cancelAllTasks() {
queue.forEach {
$0.cancel()
$0.queue = nil
}
queue.removeAll()
}
func remove(_ task: ViewAnimationTask) {
if let _task = queue.first , _task === task {
let dequeueTask = queue.removeFirst()
dequeueTask.queue = nil
} else {
assertionFailure("Trying to dequeue unrecognized task \(task)")
}
}
}
| 343a037dc7c9cd87fdf46298513fd295 | 21.887324 | 90 | 0.632308 | false | false | false | false |
jigneshsheth/multi-collectionview-flowlayout | refs/heads/master | MultiCollectionView/CustomCollectionViewFlowLayout.swift | mit | 1 | //
// CustomCollectionViewFlowLayout.swift
// MultiCollectionView
//
// Created by Jigs Sheth on 1/20/15.
// Copyright (c) 2015 Jigs Sheth. All rights reserved.
//
import UIKit
import QuartzCore
class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {
var indexPathsToAnimate:[AnyObject] = [AnyObject]()
private class func flowlayout(itemSize:CGSize,minLineSpacing:CGFloat, minItemSpacing:CGFloat) -> CustomCollectionViewFlowLayout{
var flowlayout = CustomCollectionViewFlowLayout()
flowlayout.itemSize = itemSize
flowlayout.minimumInteritemSpacing = minItemSpacing
flowlayout.minimumLineSpacing = minLineSpacing
flowlayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
return flowlayout
}
class func smallListLayout(viewWidth:CGFloat) -> CustomCollectionViewFlowLayout{
return flowlayout(CGSizeMake(viewWidth - 30 ,80), minLineSpacing: 5, minItemSpacing: 5)
}
class func mediumListLayout(viewWidth:CGFloat) -> CustomCollectionViewFlowLayout{
return flowlayout(CGSizeMake(viewWidth - 30,280), minLineSpacing: 5, minItemSpacing: 5)
}
class func gridLayout(viewWidth:CGFloat) -> CustomCollectionViewFlowLayout{
let itemWidth = (viewWidth - 30) / 2
return flowlayout(CGSizeMake(itemWidth, itemWidth), minLineSpacing: 5, minItemSpacing: 5)
}
override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?{
var att = self.layoutAttributesForItemAtIndexPath(itemIndexPath)
if self.indexPathsToAnimate.count > 0 {
var obj:AnyObject? = self.indexPathsToAnimate[itemIndexPath.row]
if let o: AnyObject = obj {
att.transform = CGAffineTransformRotate(CGAffineTransformMakeScale(0.2, 0.2), CGFloat(M_PI))
att.center = CGPointMake(CGRectGetMaxX(self.collectionView!.bounds), CGRectGetMaxX(self.collectionView!.bounds))
self.indexPathsToAnimate.removeAtIndex(itemIndexPath.row)
}}
return att
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
var oldBounds = self.collectionView?.bounds
if let oldBounds = oldBounds {
if !CGSizeEqualToSize(oldBounds.size, newBounds.size) {
return true
}
}
return false
}
override func prepareForCollectionViewUpdates(updateItems: [AnyObject]!) {
super.prepareForCollectionViewUpdates(updateItems)
var indexPaths = [AnyObject]()
for updateItem in updateItems {
var item:UICollectionViewUpdateItem = updateItem as! UICollectionViewUpdateItem
switch item.updateAction {
case UICollectionUpdateAction.Insert:
indexPaths.append(item.indexPathAfterUpdate!)
break
case UICollectionUpdateAction.Delete:
indexPaths.append(item.indexPathBeforeUpdate!)
break
case UICollectionUpdateAction.Move:
indexPaths.append(item.indexPathBeforeUpdate!)
indexPaths.append(item.indexPathAfterUpdate!)
break
default:
println("Unhandled case:: \(updateItems)")
break
}
}
self.indexPathsToAnimate = indexPaths
}
}
| 7f24427a2f1f62a421585de104f1e2f0 | 34.177778 | 132 | 0.734997 | false | false | false | false |
ErikLuimes/KGFloatingDrawer | refs/heads/master | Pod/Classes/KGDrawerViewController.swift | mit | 1 | //
// KGDrawerViewController.swift
// KGDrawerViewController
//
// Created by Kyle Goddard on 2015-02-10.
// Copyright (c) 2015 Kyle Goddard. All rights reserved.
//
import UIKit
public enum KGDrawerSide: CGFloat {
case None = 0
case Left = 1
case Right = -1
}
public class KGDrawerViewController: UIViewController {
let defaultDuration:NSTimeInterval = 0.3
// MARK: Initialization
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func loadView() {
view = drawerView
}
private var _drawerView: KGDrawerView?
var drawerView: KGDrawerView {
get {
if let retVal = _drawerView {
return retVal
}
let rect = UIScreen.mainScreen().bounds
let retVal = KGDrawerView(frame: rect)
_drawerView = retVal
return retVal
}
}
// TODO: Add ability to supply custom animator.
private var _animator: KGDrawerSpringAnimator?
public var animator: KGDrawerSpringAnimator {
get {
if let retVal = _animator {
return retVal
}
let retVal = KGDrawerSpringAnimator()
_animator = retVal
return retVal
}
}
// MARK: Interaction
public func openDrawer(side: KGDrawerSide, animated:Bool, complete: (finished: Bool) -> Void) {
if currentlyOpenedSide != side {
if let sideView = drawerView.viewContainerForDrawerSide(side) {
let centerView = drawerView.centerViewContainer
if currentlyOpenedSide != .None {
closeDrawer(side, animated: animated) { finished in
self.animator.openDrawer(side, drawerView: sideView, centerView: centerView, animated: animated, complete: complete)
}
} else {
self.animator.openDrawer(side, drawerView: sideView, centerView: centerView, animated: animated, complete: complete)
}
addDrawerGestures()
drawerView.willOpenDrawer(self)
}
}
currentlyOpenedSide = side
}
public func closeDrawer(side: KGDrawerSide, animated: Bool, complete: (finished: Bool) -> Void) {
if (currentlyOpenedSide == side && currentlyOpenedSide != .None) {
if let sideView = drawerView.viewContainerForDrawerSide(side) {
let centerView = drawerView.centerViewContainer
animator.dismissDrawer(side, drawerView: sideView, centerView: centerView, animated: animated, complete: complete)
currentlyOpenedSide = .None
restoreGestures()
drawerView.willCloseDrawer(self)
}
}
}
public func toggleDrawer(side: KGDrawerSide, animated: Bool, complete: (finished: Bool) -> Void) {
if side != .None {
if side == currentlyOpenedSide {
closeDrawer(side, animated: animated, complete: complete)
} else {
openDrawer(side, animated: animated, complete: complete)
}
}
}
// MARK: Gestures
func addDrawerGestures() {
centerViewController?.view.userInteractionEnabled = false
drawerView.centerViewContainer.addGestureRecognizer(toggleDrawerTapGestureRecognizer)
}
func restoreGestures() {
drawerView.centerViewContainer.removeGestureRecognizer(toggleDrawerTapGestureRecognizer)
centerViewController?.view.userInteractionEnabled = true
}
func centerViewContainerTapped(sender: AnyObject) {
closeDrawer(currentlyOpenedSide, animated: true) { (finished) -> Void in
// Do nothing
}
}
// MARK: Helpers
func viewContainer(side: KGDrawerSide) -> UIViewController? {
switch side {
case .Left:
return self.leftViewController
case .Right:
return self.rightViewController
case .None:
return nil
}
}
func replaceViewController(sourceViewController: UIViewController?, destinationViewController: UIViewController, container: UIView) {
sourceViewController?.willMoveToParentViewController(nil)
sourceViewController?.view.removeFromSuperview()
sourceViewController?.removeFromParentViewController()
self.addChildViewController(destinationViewController)
container.addSubview(destinationViewController.view)
let destinationView = destinationViewController.view
destinationView.translatesAutoresizingMaskIntoConstraints = false
container.removeConstraints(container.constraints)
let views: [String:UIView] = ["v1" : destinationView]
container.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v1]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
container.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v1]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
destinationViewController.didMoveToParentViewController(self)
}
// MARK: Private computed properties
public var currentlyOpenedSide: KGDrawerSide = .None
// MARK: Accessors
private var _leftViewController: UIViewController?
public var leftViewController: UIViewController? {
get {
return _leftViewController
}
set {
self.replaceViewController(self.leftViewController, destinationViewController: newValue!, container: self.drawerView.leftViewContainer)
_leftViewController = newValue!
}
}
private var _rightViewController: UIViewController?
public var rightViewController: UIViewController? {
get {
return _rightViewController
}
set {
self.replaceViewController(self.rightViewController, destinationViewController: newValue!, container: self.drawerView.rightViewContainer)
_rightViewController = newValue
}
}
private var _centerViewController: UIViewController?
public var centerViewController: UIViewController? {
get {
return _centerViewController
}
set {
self.replaceViewController(self.centerViewController, destinationViewController: newValue!, container: self.drawerView.centerViewContainer)
_centerViewController = newValue
}
}
private lazy var toggleDrawerTapGestureRecognizer: UITapGestureRecognizer = {
[unowned self] in
let gesture = UITapGestureRecognizer(target: self, action: "centerViewContainerTapped:")
return gesture
}()
public var leftDrawerWidth: CGFloat {
get {
return drawerView.leftViewContainerWidth
}
set {
drawerView.leftViewContainerWidth = newValue
}
}
public var rightDrawerWidth: CGFloat {
get {
return drawerView.rightViewContainerWidth
}
set {
drawerView.rightViewContainerWidth = newValue
}
}
public var leftDrawerRevealWidth: CGFloat {
get {
return drawerView.leftViewContainerWidth
}
}
public var rightDrawerRevealWidth: CGFloat {
get {
return drawerView.rightViewContainerWidth
}
}
public var backgroundImage: UIImage? {
get {
return drawerView.backgroundImageView.image
}
set {
drawerView.backgroundImageView.image = newValue
}
}
// MARK: Status Bar
override public func childViewControllerForStatusBarHidden() -> UIViewController? {
return centerViewController
}
override public func childViewControllerForStatusBarStyle() -> UIViewController? {
return centerViewController
}
// MARK: Memory Management
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 7b1007780abeb01dd36677786dfb23fb | 32.046512 | 165 | 0.628196 | false | false | false | false |
TifaTsubasa/TTReflect | refs/heads/master | TTReflect/ReflectJson.swift | mit | 1 | //
// ReflectJson.swift
// TTReflect
//
// Created by Tsuf on 2017/12/15.
// Copyright © 2017年 tifatsubasa. All rights reserved.
//
import UIKit
protocol ReflectJson {
func toJSONModel() -> AnyObject?
func toJSONString() -> String?
}
extension ReflectJson {
func getMirrorKeyValues(_ mirror: Mirror?) -> [String: Any] { // iOS8+
var keyValues = [String: Any]()
guard let mirror = mirror else { return keyValues }
for case let (label?, value) in mirror.children {
keyValues[label] = value
}
if mirror.superclassMirror?.subjectType != NSObject.self {
getMirrorKeyValues(mirror.superclassMirror).forEach({ (key, value) in
keyValues[key] = value
})
}
return keyValues
}
//将数据转成可用的JSON模型
func toJSONModel() -> AnyObject? {
let replacePropertys = (self as? TTReflectProtocol)?.setupMappingReplaceProperty?() ?? [:]
let mirror = Mirror(reflecting: self)
let keyValues = getMirrorKeyValues(mirror)
if mirror.children.count > 0 {
var result: [String: AnyObject] = [:]
for (label, value) in keyValues {
let sourceLabel = replacePropertys.keys.contains(label) ? replacePropertys[label]! : label
debugPrint("source label: ", sourceLabel)
if let jsonValue = value as? ReflectJson {
if let hasResult = jsonValue.toJSONModel() {
// debugPrint("has result: ", label, "-", hasResult)
result[sourceLabel] = hasResult
} else {
let valueMirror = Mirror(reflecting: value)
if valueMirror.superclassMirror?.subjectType != NSObject.self {
// debugPrint("not object: ", label, "-", value)
result[sourceLabel] = value as AnyObject
}
}
}
}
return result as AnyObject
}
return nil
}
//将数据转成JSON字符串
func toJSONString() -> String? {
guard let jsonModel = self.toJSONModel() else {
return ""
}
// debugPrint(jsonModel)
//利用OC的json库转换成Data,
let data = try? JSONSerialization.data(withJSONObject: jsonModel,
options: [])
//Data转换成String打印输出
let str = String(data: data!, encoding: .utf8)
return str
}
}
extension NSObject: ReflectJson { }
extension String: ReflectJson { }
extension Int: ReflectJson { }
extension Double: ReflectJson { }
extension Bool: ReflectJson { }
extension Dictionary: ReflectJson { }
//扩展Array,格式化输出
extension Array: ReflectJson {
//将数据转成可用的JSON模型
func toJSONModel() -> AnyObject? {
var result: [AnyObject] = []
for value in self {
if let jsonValue = value as? ReflectJson , let jsonModel = jsonValue.toJSONModel(){
result.append(jsonModel)
}
}
return result as AnyObject
}
}
| 966cde699ea27d4f2b56895bf183e84e | 28.574468 | 98 | 0.627338 | false | false | false | false |
bnickel/SEUICollectionViewLayout | refs/heads/master | Code Survey/Code Survey/HeadingView.swift | mit | 1 | //
// HeadingView.swift
// Code Survey
//
// Created by Brian Nickel on 11/5/14.
// Copyright (c) 2014 Brian Nickel. All rights reserved.
//
import UIKit
private let SizingHeadingView:HeadingView = HeadingView.nib!.instantiateWithOwner(nil, options: nil)[0] as! HeadingView
class HeadingView: UICollectionReusableView {
@IBOutlet weak var label: UILabel!
override var bounds:CGRect {
didSet {
label?.preferredMaxLayoutWidth = CGRectGetWidth(bounds)
}
}
override var frame:CGRect {
didSet {
label?.preferredMaxLayoutWidth = CGRectGetWidth(frame)
}
}
var text:String {
get {
return label.text ?? ""
}
set(value) {
label.text = value
}
}
class var nib:UINib? {
return UINib(nibName: "HeadingView", bundle: nil)
}
class func heightForText(text:String, width:CGFloat) -> CGFloat {
SizingHeadingView.label.text = text
return SizingHeadingView.label.sizeThatFits(CGSizeMake(width, 0)).height + 1
}
}
| f7b732333c0df4199a1d129f92ff165b | 22.808511 | 119 | 0.603217 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Incremental/Dependencies/protocol-conformer-fine.swift | apache-2.0 | 15 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
private struct Test : InterestingProto {}
// CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int
// CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double
public var x = Test().make() + 0
// CHECK-DEPS-DAG: topLevel interface '' InterestingProto false
// CHECK-DEPS-DAG: member interface 4main{{8IntMaker|11DoubleMaker}}P make false
// CHECK-DEPS-DAG: nominal interface 4main{{8IntMaker|11DoubleMaker}}P '' false
| 03894bd71acfd7d14fab2888a6709dbe | 53.782609 | 203 | 0.726984 | false | true | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Services/SiteAssemblyService.swift | gpl-2.0 | 1 |
import Foundation
// MARK: - EnhancedSiteCreationService
/// Working implementation of a `SiteAssemblyService`.
///
final class EnhancedSiteCreationService: LocalCoreDataService, SiteAssemblyService {
// MARK: Properties
/// A service for interacting with WordPress accounts.
private let accountService: AccountService
/// A service for interacting with WordPress blogs.
private let blogService: BlogService
/// A facade for WPCOM services.
private let remoteService: WordPressComServiceRemote
/// The site creation request that's been enqueued.
private var creationRequest: SiteCreationRequest?
/// This handler is called with changes to the site assembly status.
private var statusChangeHandler: SiteAssemblyStatusChangedHandler?
/// The most recently created blog corresponding to the site creation request; `nil` otherwise.
private(set) var createdBlog: Blog?
// MARK: LocalCoreDataService
override init(managedObjectContext context: NSManagedObjectContext) {
self.accountService = AccountService(managedObjectContext: context)
self.blogService = BlogService(managedObjectContext: context)
let api: WordPressComRestApi
if let wpcomApi = accountService.defaultWordPressComAccount()?.wordPressComRestApi {
api = wpcomApi
} else {
api = WordPressComRestApi.defaultApi(userAgent: WPUserAgent.wordPress())
}
self.remoteService = WordPressComServiceRemote(wordPressComRestApi: api)
super.init(managedObjectContext: context)
}
// MARK: SiteAssemblyService
private(set) var currentStatus: SiteAssemblyStatus = .idle {
didSet {
DispatchQueue.main.async { [weak self] in
guard let self = self else {
return
}
self.statusChangeHandler?(self.currentStatus)
}
}
}
/// This method serves as the entry point for creating an enhanced site. It consists of a few steps:
/// 1. The creation request is first validated.
/// 2. If a site passes validation, a new service invocation triggers creation.
/// 3. The details of the created Blog are persisted to the client.
///
/// Previously the site's theme & tagline were set post-creation. This is now handled on the server via Headstart.
///
/// - Parameters:
/// - creationRequest: the request with which to initiate site creation.
/// - changeHandler: this closure is invoked when site assembly status changes occur.
///
func createSite(creationRequest: SiteCreationRequest, changeHandler: SiteAssemblyStatusChangedHandler? = nil) {
self.creationRequest = creationRequest
self.statusChangeHandler = changeHandler
beginAssembly()
validatePendingRequest()
}
// MARK: Private behavior
private func beginAssembly() {
currentStatus = .inProgress
}
private func endFailedAssembly() {
currentStatus = .failed
}
private func endSuccessfulAssembly() {
// Here we designate the new site as the last used, so that it will be presented post-creation
if let siteUrl = createdBlog?.url {
RecentSitesService().touch(site: siteUrl)
StoreContainer.shared.statsWidgets.refreshStatsWidgetsSiteList()
}
currentStatus = .succeeded
}
private func performRemoteSiteCreation() {
guard let request = creationRequest else {
self.endFailedAssembly()
return
}
let validatedRequest = SiteCreationRequest(request: request)
remoteService.createWPComSite(request: validatedRequest) { result in
// Our result is of type SiteCreationResult, which can be either success or failure
switch result {
case .success(let response):
// A successful response includes a separate success field advising of the outcome of the call.
// In my testing, this has never been `false`, but we will be cautious.
guard response.success == true else {
DDLogError("The service response indicates that it failed.")
self.endFailedAssembly()
return
}
self.synchronize(createdSite: response.createdSite)
case .failure(let creationError):
DDLogError("\(creationError)")
self.endFailedAssembly()
}
}
}
private func synchronize(createdSite: CreatedSite) {
guard let defaultAccount = accountService.defaultWordPressComAccount() else {
endFailedAssembly()
return
}
let xmlRpcUrlString = createdSite.xmlrpcString
let blog: Blog
if let existingBlog = blogService.findBlog(withXmlrpc: xmlRpcUrlString, in: defaultAccount) {
blog = existingBlog
} else {
blog = blogService.createBlog(with: defaultAccount)
blog.xmlrpc = xmlRpcUrlString
}
// The response payload returns a number encoded as a JSON string
if let wpcomSiteIdentifier = Int(createdSite.identifier) {
blog.dotComID = NSNumber(value: wpcomSiteIdentifier)
}
blog.url = createdSite.urlString
blog.settings?.name = createdSite.title
// the original service required a separate call to update the tagline post-creation
blog.settings?.tagline = creationRequest?.tagline
defaultAccount.defaultBlog = blog
ContextManager.sharedInstance().save(managedObjectContext) { [weak self] in
guard let self = self else {
return
}
self.blogService.syncBlogAndAllMetadata(blog, completionHandler: {
self.accountService.updateUserDetails(for: defaultAccount,
success: {
self.createdBlog = blog
self.endSuccessfulAssembly()
},
failure: { error in self.endFailedAssembly() })
})
}
}
private func validatePendingRequest() {
guard let requestPendingValidation = creationRequest else {
endFailedAssembly()
return
}
remoteService.createWPComSite(request: requestPendingValidation) { result in
switch result {
case .success:
self.performRemoteSiteCreation()
case .failure(let validationError):
DDLogError("\(validationError)")
self.endFailedAssembly()
}
}
}
}
| 78a5d5dc4f4e42056572be6758e5335f | 35.5 | 118 | 0.624745 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | refs/heads/master | 04-App Architecture/Swift 3/Playgrounds/Enumerated Types.playground/Pages/Methods.xcplaygroundpage/Contents.swift | mit | 2 | //: 
//:
//: [Previous](@previous)
//:
//: ## Methods
//:
//: As we saw in the previous section, enumerated types (like classes and structures) can also have methods and therefore computed properties.
//:
//: - **instance methods** - functions that a concerned with an instance of the enum, have access to `self` and can mutate `self` (known as *mutating* methods). You need an instance of a enum to use these.
//: - **type methods** - belong to the type and no particular instance. You can call these without an instance of an enum.
//:
//: Here is a simple example:
enum ToggleSwitch : String {
//These are the two possible cases with raw types "on" and "off"
case on
case off
//The following instance method simply returns another instance (note the name is an adjective)
func toggled() -> ToggleSwitch {
switch (self)
{
case .on:
return .off
case .off:
return .on
}
}
//Where a function name is a verb, by convention this suggests self-modification. Such methods change `self` (the instance), so must be marked as `mutating`
mutating func toggle() {
//The instance is replaced with a completely new instance (with a different case in this example)
self = self.toggled()
}
//This type function does not operate on a particular instance, but is part of the Enumerated Type itself
static func & (lhs: ToggleSwitch, rhs: ToggleSwitch) -> ToggleSwitch {
//Here comes that pattern matching again - matching a tuple is always handy
let tuple = (lhs, rhs)
switch tuple {
case (.on, .on):
return .on
default:
return .off
}
}
//Calculated properties are allowed (stored are not for enum) - they are a type of instance method
var description : String {
get {
if self == .on {
return "SWITCH IS ON"
} else {
return "SWITCH IS OFF"
}
}
}
//The initialiser can also be defined. This one ensures the default to always be off. This is not mutating as it's involved in creation, not change
init() {
self = .off
}
//You can also write other initialisers
init(isOn n : Bool) {
if (n) {
self = .on
} else {
self = .off
}
}
}
//: The enum has a number of methods. The initialisers `init()` and `init(isOn n : Bool)` are useful for safely setting the default state. You can therefore initialise this enum in various ways.
//:
//: 1. Simple assignment
let toggle0 : ToggleSwitch = .off
//: 2. Invoke the initialiser
let toggle1 = ToggleSwitch()
//: 3. Alternative initialiser (similar to a convenience initialiser)
let toggle2 = ToggleSwitch(isOn: true)
//: 4. Using a raw value
if let toggle3 = ToggleSwitch(rawValue: "on") { //With raw values, it could fail, so the return is Optional....
toggle3
}
if let toggle4 = ToggleSwitch(rawValue: "ON") { //...as shown here
toggle4
} else {
print("That failed - wrong case?")
}
//: In this example, `toggle3` and `toggle4` are Optional types (remember that initialisation with raw values can fail). `toggle3` has a wrapped value whereas `toggle4` is `nil`.
//:
//: The enum has a number of methods. Starting with the initialiser `init()` we first set the default state to `.off`.
var sw1 = ToggleSwitch()
sw1.description
//: We can obtain another instance with the opposite state (original unmodified). Note the value semantics and the method naming convention used here (it's an adjective, not a verb).
let sw2 = sw1.toggled()
sw1.description
//: We can change the state of an instance (mutating). Note again the method naming convention is to use a verb in an imperative tense. This is an in-place modification.
sw1.toggle()
sw1.description
//: The custom operator & is a type-method (`self` is the Type, not an instance)
ToggleSwitch.on & ToggleSwitch.on
ToggleSwitch.on & ToggleSwitch.off
//:
//: Notes:
//:
//: - enums are value types
//: - enums cannot have stored properties
//: - enums can have computed properties and methods
//: - enums can have instance methods with access to the instance value self
//: - a method that changes self must be marked as mutating
//: - enums can have type methods where self refers to the type
//:
//: ## Extensions
//: Let's now add some further methods to the enum from outside the original definition. We use an *extension* to do this
extension ToggleSwitch {
//Add an initialiser
init(withString s : String) {
if s.lowercased() == "on" {
self = .on
} else {
self = .off
}
}
}
//: Note - an initialiser does not need `mutating` as `self` being initialised, not changed.
//:
//: Initialise with the new initialiser
let sw3 = ToggleSwitch(withString: "ON")
sw3.description
//: ## Value Semantics
//: Like structures, enumerated types are *value types*
var v1 = ToggleSwitch.on
var v2 = v1
//: `v2` is now a logical and independent copy of `v1`
v2.toggle()
//: `v2` is mutated by the `toggle` method while leaving `v1` unaffected.
v1.description
v2.description
//:By default, properties of value types are not mutated from within an instance method [\[1\]](References). The `toggle` method has the keyword `mutating` to override this.
//:
//: ### Subscripts
//: You can even define what it means to use a subscript
enum FemaleShoeSize {
case uk(Int)
case usa(Int)
func ukSize() -> FemaleShoeSize {
switch self {
case .uk:
return self
case .usa(let s):
return .uk(s-2)
}
}
func usSize() -> FemaleShoeSize {
switch self {
case .uk(let s):
return .usa(s+2)
case .usa:
return self
}
}
subscript(index : Int) -> Int? {
get {
switch self {
case .uk(1...10) where (index > 0 && index <= 10):
return index
case .usa(3...12):
return index+2
default:
return nil
}
}
}
}
//: Let's create an instance of this type with value `uk` and associated data (size) 8.
let shoe = FemaleShoeSize.uk(8)
shoe[0]
shoe[1]
shoe[2]
//: We can calculate the equivalent size in the USA
shoe.usSize()
//: We can then use subscripts to see all the sizes converted to the USA system
shoe.usSize()[1]
shoe.usSize()[2]
//: - Note: Just because this type has a subscript does not mean you can iterate over it. The following code will not compile as `FemaleShoeSize` does not conform to the `Sequence` protocol.
//: ````
//: for m in shoe {
//: m
//: }
//: ````
//: [Next - Advanced Topics](@next)
| 000dc8dc953cf9c4ab7fda1fa2483938 | 31.497561 | 205 | 0.648004 | false | false | false | false |
yurapriv/vapor-tutorial | refs/heads/master | Sources/App/Models/Acronym.swift | mit | 1 | import Vapor
final class Acronym: Model {
var id: Node?
var exists: Bool = false
var short: String
var long: String
init(short: String, long: String) {
self.id = nil
self.short = short
self.long = long
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
short = try node.extract("short")
long = try node.extract("long")
}
static func prepare(_ database: Database) throws {
try database.create("Acronyms") { users in
users.id()
users.string("short")
users.string("long")
}
}
static func revert(_ database: Database) throws {
try database.delete("Acronyms")
}
//MARK: NodeRepresentable
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"short": short,
"long": long
])
}
}
| d0a8792477d36e5cc6286e90f013aeb6 | 19.55102 | 54 | 0.509434 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | Scripts/BuildPhases/LintAppLocalizedStringsUsage.swift | gpl-2.0 | 1 | import Foundation
// MARK: Xcodeproj entry point type
/// The main entry point type to parse `.xcodeproj` files
class Xcodeproj {
let projectURL: URL // points to the "<projectDirectory>/<projectName>.xcodeproj/project.pbxproj" file
private let pbxproj: PBXProjFile
/// Semantic type for strings that correspond to an object' UUID in the `pbxproj` file
typealias ObjectUUID = String
/// Builds an `Xcodeproj` instance by parsing the `.xcodeproj` or `.pbxproj` file at the provided URL.
init(url: URL) throws {
projectURL = url.pathExtension == "xcodeproj" ? URL(fileURLWithPath: "project.pbxproj", relativeTo: url) : url
let data = try Data(contentsOf: projectURL)
let decoder = PropertyListDecoder()
pbxproj = try decoder.decode(PBXProjFile.self, from: data)
}
/// An internal mapping listing the parent ObjectUUID for each ObjectUUID.
/// - Built by recursing top-to-bottom in the various `PBXGroup` objects of the project to visit all the children objects,
/// and storing which parent object they belong to.
/// - Used by the `resolveURL` method to find the real path of a `PBXReference`, as we need to navigate from the `PBXReference` object
/// up into the chain of parent `PBXGroup` containers to construct the successive relative paths of groups using `sourceTree = "<group>"`
private lazy var referrers: [ObjectUUID: ObjectUUID] = {
var referrers: [ObjectUUID: ObjectUUID] = [:]
func recurseIfGroup(objectID: ObjectUUID) {
guard let group = try? (self.pbxproj.object(id: objectID) as PBXGroup) else { return }
for childID in group.children {
referrers[childID] = objectID
recurseIfGroup(objectID: childID)
}
}
recurseIfGroup(objectID: self.pbxproj.rootProject.mainGroup)
return referrers
}()
}
// Convenience methods and properties
extension Xcodeproj {
/// Builds an `Xcodeproj` instance by parsing the `.xcodeproj` or `pbxproj` file at the provided path
convenience init(path: String) throws {
try self.init(url: URL(fileURLWithPath: path))
}
/// The directory where the `.xcodeproj` resides.
var projectDirectory: URL { projectURL.deletingLastPathComponent().deletingLastPathComponent() }
/// The list of `PBXNativeTarget` targets in the project. Convenience getter for `PBXProjFile.nativeTargets`
var nativeTargets: [PBXNativeTarget] { pbxproj.nativeTargets }
/// The list of `PBXBuildFile` files a given `PBXNativeTarget` will build. Convenience getter for `PBXProjFile.buildFiles(for:)`
func buildFiles(for target: PBXNativeTarget) -> [PBXBuildFile] { pbxproj.buildFiles(for: target) }
/// Finds the full path / URL of a `PBXBuildFile` based on the groups it belongs to and their `sourceTree` attribute
func resolveURL(to buildFile: PBXBuildFile) throws -> URL? {
if let fileRefID = buildFile.fileRef, let fileRefObject = try? self.pbxproj.object(id: fileRefID) as PBXFileReference {
return try resolveURL(objectUUID: fileRefID, object: fileRefObject)
} else {
// If the `PBXBuildFile` is pointing to `XCVersionGroup` (like `*.xcdatamodel`) and `PBXVariantGroup` (like `*.strings`)
// (instead of a `PBXFileReference`), then in practice each file in the group's `children` will be built by the Build Phase.
// In practice we can skip parsing those in our case and save some CPU, as we don't have a need to lint those non-source-code files.
return nil // just skip those (but don't throw — those are valid use cases in any pbxproj, just ones we don't care about)
}
}
/// Finds the full path / URL of a PBXReference (`PBXFileReference` of `PBXGroup`) based on the groups it belongs to and their `sourceTree` attribute
private func resolveURL<T: PBXReference>(objectUUID: ObjectUUID, object: T) throws -> URL? {
if objectUUID == self.pbxproj.rootProject.mainGroup { return URL(fileURLWithPath: ".", relativeTo: projectDirectory) }
switch object.sourceTree {
case .absolute:
guard let path = object.path else { throw ProjectInconsistencyError.incorrectAbsolutePath(id: objectUUID) }
return URL(fileURLWithPath: path)
case .group:
guard let parentUUID = referrers[objectUUID] else { throw ProjectInconsistencyError.orphanObject(id: objectUUID, object: object) }
let parentGroup = try self.pbxproj.object(id: parentUUID) as PBXGroup
guard let groupURL = try resolveURL(objectUUID: parentUUID, object: parentGroup) else { return nil }
return object.path.map { groupURL.appendingPathComponent($0) } ?? groupURL
case .projectRoot:
return object.path.map { URL(fileURLWithPath: $0, relativeTo: projectDirectory) } ?? projectDirectory
case .buildProductsDir, .devDir, .sdkDir:
print("\(self.projectURL.path): warning: Reference \(objectUUID) is relative to \(object.sourceTree.rawValue), which is not supported by the linter")
return nil
}
}
}
// MARK: - Implementation Details
/// "Parent" type for all the PBX... types of objects encountered in a pbxproj
protocol PBXObject: Decodable {
static var isa: String { get }
}
extension PBXObject {
static var isa: String { String(describing: self) }
}
/// "Parent" type for PBXObjects referencing relative path information (`PBXFileReference`, `PBXGroup`)
protocol PBXReference: PBXObject {
var name: String? { get }
var path: String? { get }
var sourceTree: Xcodeproj.SourceTree { get }
}
/// Types used to parse and decode the internals of a `*.xcodeproj/project.pbxproj` file
extension Xcodeproj {
/// An error `thrown` when an inconsistency is found while parsing the `.pbxproj` file.
enum ProjectInconsistencyError: Swift.Error, CustomStringConvertible {
case objectNotFound(id: ObjectUUID)
case unexpectedObjectType(id: ObjectUUID, expectedType: Any.Type, found: PBXObject)
case incorrectAbsolutePath(id: ObjectUUID)
case orphanObject(id: ObjectUUID, object: PBXObject)
var description: String {
switch self {
case .objectNotFound(id: let id):
return "Unable to find object with UUID `\(id)`"
case .unexpectedObjectType(id: let id, expectedType: let expectedType, found: let found):
return "Object with UUID `\(id)` was expected to be of type \(expectedType) but found \(found) instead"
case .incorrectAbsolutePath(id: let id):
return "Object `\(id)` has `sourceTree = \(Xcodeproj.SourceTree.absolute)` but no `path`"
case .orphanObject(id: let id, object: let object):
return "Unable to find parent group of \(object) (`\(id)`) during file path resolution"
}
}
}
/// Type used to represent and decode the root object of a `.pbxproj` file.
struct PBXProjFile: Decodable {
let rootObject: ObjectUUID
let objects: [String: PBXObjectWrapper]
// Convenience methods
/// Returns the `PBXObject` instance with the given `ObjectUUID`, by looking it up in the list of `objects` registered in the project.
func object<T: PBXObject>(id: ObjectUUID) throws -> T {
guard let wrapped = objects[id] else { throw ProjectInconsistencyError.objectNotFound(id: id) }
guard let obj = wrapped.wrappedValue as? T else {
throw ProjectInconsistencyError.unexpectedObjectType(id: id, expectedType: T.self, found: wrapped.wrappedValue)
}
return obj
}
/// Returns the `PBXObject` instance with the given `ObjectUUID`, by looking it up in the list of `objects` registered in the project.
func object<T: PBXObject>(id: ObjectUUID) -> T? {
try? object(id: id) as T
}
/// The `PBXProject` corresponding to the `rootObject` of the project file.
var rootProject: PBXProject { try! object(id: rootObject) }
/// The `PBXGroup` corresponding to the main groop serving as root for the whole hierarchy of files and groups in the project.
var mainGroup: PBXGroup { try! object(id: rootProject.mainGroup) }
/// The list of `PBXNativeTarget` targets found in the project.
var nativeTargets: [PBXNativeTarget] { rootProject.targets.compactMap(object(id:)) }
/// The list of `PBXBuildFile` build file references included in a given target.
func buildFiles(for target: PBXNativeTarget) -> [PBXBuildFile] {
guard let sourceBuildPhase: PBXSourcesBuildPhase = target.buildPhases.lazy.compactMap(object(id:)).first else { return [] }
return sourceBuildPhase.files.compactMap(object(id:)) as [PBXBuildFile]
}
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents the root project object.
struct PBXProject: PBXObject {
let mainGroup: ObjectUUID
let targets: [ObjectUUID]
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a native target (i.e. a target building an app, app extension, bundle...).
/// - note: Does not represent other types of targets like `PBXAggregateTarget`, only native ones.
struct PBXNativeTarget: PBXObject {
let name: String
let buildPhases: [ObjectUUID]
let productType: String
var knownProductType: ProductType? { ProductType(rawValue: productType) }
enum ProductType: String, Decodable {
case app = "com.apple.product-type.application"
case appExtension = "com.apple.product-type.app-extension"
case unitTest = "com.apple.product-type.bundle.unit-test"
case uiTest = "com.apple.product-type.bundle.ui-testing"
case framework = "com.apple.product-type.framework"
}
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a "Compile Sources" build phase containing a list of files to compile.
/// - note: Does not represent other types of Build Phases that could exist in the project, only "Compile Sources" one
struct PBXSourcesBuildPhase: PBXObject {
let files: [ObjectUUID]
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a single build file in a `PBXSourcesBuildPhase` build phase.
struct PBXBuildFile: PBXObject {
let fileRef: ObjectUUID?
}
/// This type is used to indicate what a file reference in the project is actually relative to
enum SourceTree: String, Decodable, CustomStringConvertible {
case absolute = "<absolute>"
case group = "<group>"
case projectRoot = "SOURCE_ROOT"
case buildProductsDir = "BUILT_PRODUCTS_DIR"
case devDir = "DEVELOPER_DIR"
case sdkDir = "SDKROOT"
var description: String { rawValue }
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a reference to a file contained in the project tree.
struct PBXFileReference: PBXReference {
let name: String?
let path: String?
let sourceTree: SourceTree
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a group (aka "folder") contained in the project tree.
struct PBXGroup: PBXReference {
let name: String?
let path: String?
let sourceTree: SourceTree
let children: [ObjectUUID]
}
/// Fallback type for any unknown `PBXObject` type.
struct UnknownPBXObject: PBXObject {
let isa: String
}
/// Wrapper helper to decode any `PBXObject` based on the value of their `isa` field
@propertyWrapper
struct PBXObjectWrapper: Decodable, CustomDebugStringConvertible {
let wrappedValue: PBXObject
static let knownTypes: [PBXObject.Type] = [
PBXProject.self,
PBXGroup.self,
PBXFileReference.self,
PBXNativeTarget.self,
PBXSourcesBuildPhase.self,
PBXBuildFile.self
]
init(from decoder: Decoder) throws {
let untypedObject = try UnknownPBXObject(from: decoder)
if let objectType = Self.knownTypes.first(where: { $0.isa == untypedObject.isa }) {
self.wrappedValue = try objectType.init(from: decoder)
} else {
self.wrappedValue = untypedObject
}
}
var debugDescription: String { String(describing: wrappedValue) }
}
}
// MARK: - Lint method
/// The outcome of running our lint logic on a file
enum LintResult { case ok, skipped, violationsFound([(line: Int, col: Int)]) }
/// Lint a given file for usages of `NSLocalizedString` instead of `AppLocalizedString`
func lint(fileAt url: URL, targetName: String) throws -> LintResult {
guard ["m", "swift"].contains(url.pathExtension) else { return .skipped }
let content = try String(contentsOf: url)
var lineNo = 0
var violations: [(line: Int, col: Int)] = []
content.enumerateLines { line, _ in
lineNo += 1
guard line.range(of: "\\s*//", options: .regularExpression) == nil else { return } // Skip commented lines
guard let range = line.range(of: "NSLocalizedString") else { return }
// Violation found, report it
let colNo = line.distance(from: line.startIndex, to: range.lowerBound)
let message = "Use `AppLocalizedString` instead of `NSLocalizedString` in source files that are used in the `\(targetName)` extension target. See paNNhX-nP-p2 for more info."
print("\(url.path):\(lineNo):\(colNo): error: \(message)")
violations.append((lineNo, colNo))
}
return violations.isEmpty ? .ok : .violationsFound(violations)
}
// MARK: - Main (Script Code entry point)
// 1st arg = project path
let args = CommandLine.arguments.dropFirst()
guard let projectPath = args.first, !projectPath.isEmpty else { print("You must provide the path to the xcodeproj as first argument."); exit(1) }
do {
let project = try Xcodeproj(path: projectPath)
// 2nd arg (optional) = name of target to lint
let targetsToLint: [Xcodeproj.PBXNativeTarget]
if let targetName = args.dropFirst().first, !targetName.isEmpty {
print("Selected target: \(targetName)")
targetsToLint = project.nativeTargets.filter { $0.name == targetName }
} else {
print("Linting all app extension targets")
targetsToLint = project.nativeTargets.filter { $0.knownProductType == .appExtension }
}
// Lint each requested target
var violationsFound = 0
for target in targetsToLint {
let buildFiles: [Xcodeproj.PBXBuildFile] = project.buildFiles(for: target)
print("Linting the Build Files for \(target.name):")
for buildFile in buildFiles {
guard let fileURL = try project.resolveURL(to: buildFile) else { continue }
let result = try lint(fileAt: fileURL.absoluteURL, targetName: target.name)
print(" - \(fileURL.relativePath) [\(result)]")
if case .violationsFound(let list) = result { violationsFound += list.count }
}
}
print("Done! \(violationsFound) violation(s) found.")
exit(violationsFound > 0 ? 1 : 0)
} catch let error {
print("\(projectPath): error: Error while parsing the project file \(projectPath): \(error.localizedDescription)")
exit(2)
}
| b5faf4468f3f63632817077e9027911b | 47.766871 | 182 | 0.659957 | false | false | false | false |
brokenhandsio/SteamPress | refs/heads/master | Sources/SteamPress/Services/NumericPostFormatter.swift | mit | 1 | import Foundation
import Vapor
struct NumericPostDateFormatter: ServiceType {
static func makeService(for container: Container) throws -> NumericPostDateFormatter {
return .init()
}
let formatter: DateFormatter
init() {
self.formatter = DateFormatter()
self.formatter.calendar = Calendar(identifier: .iso8601)
self.formatter.locale = Locale(identifier: "en_US_POSIX")
self.formatter.timeZone = TimeZone(secondsFromGMT: 0)
self.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
}
}
| a248e7834719cdaef00da47b00c063b5 | 28.842105 | 90 | 0.679012 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/NCFleetConfiguration.swift | lgpl-2.1 | 2 | //
// NCFleetConfiguration.swift
// Neocom
//
// Created by Artem Shimanski on 15.02.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
public class NCFleetConfiguration: NSObject, NSCoding {
var pilots: [Int: String]?
var links: [Int: Int]?
override init() {
super.init()
}
public required init?(coder aDecoder: NSCoder) {
if let d = aDecoder.decodeObject(forKey: "pilots") as? [String: String] {
pilots = Dictionary(d.map{ (Int($0) ?? $0.hashValue, $1) },
uniquingKeysWith: { (first, _) in first})
}
else {
pilots = aDecoder.decodeObject(forKey: "pilots") as? [Int: String]
}
if let d = aDecoder.decodeObject(forKey: "links") as? [String: String] {
links = Dictionary(d.map{ (Int($0) ?? $0.hashValue, Int($1) ?? $1.hashValue) },
uniquingKeysWith: { (first, _) in first})
}
else {
links = aDecoder.decodeObject(forKey: "links") as? [Int: Int]
}
super.init()
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(pilots, forKey: "pilots")
aCoder.encode(links, forKey: "links")
}
}
| b2ac09d9a4ddefe41983820cc60bd29a | 25.585366 | 82 | 0.644037 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | GoDToolOSX/View Controllers/GoDTextureImporterViewController.swift | gpl-2.0 | 1 | //
// GoDTextureImporterViewController.swift
// GoD Tool
//
// Created by The Steez on 07/03/2019.
//
import Cocoa
class GoDTextureImporterViewController: GoDTableViewController {
@IBOutlet var filenameField: NSTextField!
@IBOutlet var detailsField: NSTextField!
var currentFile : XGFiles?
var importer : GoDTextureImporter?
@IBOutlet var imageView: NSImageView!
@IBOutlet var thresholdSlider: NSSlider!
@IBAction func setColourThreshold(_ sender: NSSlider) {
XGColour.colourThreshold = sender.integerValue
self.loadImage()
}
@IBAction func save(_ sender: Any) {
self.saveImage()
}
var fileList: [XGFiles] = {
var allSupportedImages = [XGFiles]()
for folder in XGFolders.ISOExport("").subfolders {
allSupportedImages += folder.files.filter({ (file) -> Bool in
let gtxFile = XGFiles.nameAndFolder(file.fileName.replacingOccurrences(of: file.fileExtension, with: ""), file.folder)
return XGFileTypes.imageFormats.contains(file.fileType)
&& gtxFile.exists && gtxFile.fileType == .gtx
})
}
return allSupportedImages
}()
func loadImage() {
if let current = currentFile, current.exists {
let gtxFile = XGFiles.nameAndFolder(current.fileName.replacingOccurrences(of: current.fileExtension, with: ""), current.folder)
if let data = gtxFile.data {
let textureData = GoDTexture(data: data)
importer = GoDTextureImporter(oldTextureData: textureData, newImage: XGImage(nsImage: current.image))
importer?.replaceTextureData()
imageView.image = importer?.texture.image.nsImage
detailsField.stringValue = "Texture Format: \(textureData.format.name)"
+ (textureData.isIndexed ? "\nPalette Format: \(textureData.paletteFormat.name)" : "")
+ "\nMax Colours: \(textureData.isIndexed ? textureData.format.paletteCount.string : "None")"
+ "\nColours in image: \(XGImage.loadImageData(fromFile: current)?.colourCount.string ?? "Unknowm")"
}
}
}
func saveImage() {
if let imp = self.importer {
imp.texture.save()
}
}
override func numberOfRows(in tableView: NSTableView) -> Int {
return max(fileList.count, 1)
}
override func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 50
}
override func tableView(_ tableView: GoDTableView, didSelectRow row: Int) {
super.tableView(tableView, didSelectRow: row)
if row == -1 {
return
}
let list = fileList
if row < list.count {
let file = list[row]
self.filenameField.stringValue = file.fileName
if file.exists {
self.currentFile = file
self.loadImage()
}
} else {
self.table.reloadData()
}
}
override func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = super.tableView(tableView, viewFor: tableColumn, row: row) as? GoDTableCellView
cell?.setBackgroundColour(GoDDesign.colourWhite())
if fileList.count == 0 {
cell?.setTitle("No images to import. Export and decode some texture files from the ISO.")
}
let list = fileList
if row < list.count, list[row].exists {
let file = list[row]
cell?.setTitle(file.fileName)
} else {
self.table.reloadData()
}
if self.table.selectedRow == row {
cell?.addBorder(colour: GoDDesign.colourBlack(), width: 1)
} else {
cell?.removeBorder()
}
return cell
}
}
| ec160a663204a1b23633eaacfb9d5fc6 | 26.636364 | 130 | 0.702452 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/DebugInfo/generic_arg2.swift | apache-2.0 | 6 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
// CHECK: define hidden void @_TFC12generic_arg25Class3foo{{.*}}, %swift.type* %U
// CHECK: [[Y:%.*]] = getelementptr inbounds %C12generic_arg25Class, %C12generic_arg25Class* %2, i32 0, i32 0, i32 0
// store %swift.opaque* %[[Y]], %swift.opaque** %[[Y_SHADOW:.*]], align
// CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %y.addr, metadata ![[U:.*]], metadata !{{[0-9]+}})
// Make sure there is no conflicting dbg.value for this variable.x
// CHECK-NOT: dbg.value{{.*}}metadata ![[U]]
class Class <T> {
// CHECK: ![[U]] = !DILocalVariable(name: "y", arg: 2{{.*}} line: [[@LINE+1]],
func foo<U>(_ x: T, y: U) {}
func bar(_ x: String, y: Int64) {}
init() {}
}
func main() {
var object: Class<String> = Class()
var x = "hello"
var y : Int64 = 1234
object.bar(x, y: y)
object.foo(x, y: y)
}
main()
| 293b421a36086a79dc02296490c4c781 | 33.346154 | 116 | 0.597984 | false | false | false | false |
mcudich/TemplateKit | refs/heads/master | Examples/TodoMVC/Source/CountText.swift | mit | 1 | //
// CountText.swift
// Example
//
// Created by Matias Cudich on 10/8/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
import TemplateKit
struct CountTextProperties: Properties {
static var tagName = "CountText"
var core = CoreProperties()
var textStyle = TextStyleProperties()
var count: String?
init() {}
init(_ properties: [String: Any]) {
core = CoreProperties(properties)
textStyle = TextStyleProperties(properties)
count = properties.cast("count")
}
mutating func merge(_ other: CountTextProperties) {
core.merge(other.core)
textStyle.merge(other.textStyle)
merge(&count, other.count)
}
}
func ==(lhs: CountTextProperties, rhs: CountTextProperties) -> Bool {
return lhs.count == rhs.count && lhs.equals(otherProperties: rhs)
}
class CountText: Component<EmptyState, CountTextProperties, UIView> {
override func render() -> Template {
var properties = TextProperties()
properties.text = self.properties.count
properties.textStyle = self.properties.textStyle
return Template(text(properties))
}
}
| 7e25eb724f31989733abcc94dc0b8187 | 21.755102 | 69 | 0.707623 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SILGen/protocol_optional.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
@objc protocol P1 {
@objc optional func method(_ x: Int)
@objc optional var prop: Int { get }
@objc optional subscript (i: Int) -> Int { get }
}
// CHECK-LABEL: sil hidden @_T017protocol_optional0B13MethodGenericyx1t_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalMethodGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_owned (Int) -> ()> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<@callee_owned (Int) -> ()>
// CHECK: dynamic_method_br [[T]] : $T, #P1.method!1.foreign
var methodRef = t.method
}
// CHECK: } // end sil function '_T017protocol_optional0B13MethodGenericyx1t_tAA2P1RzlF'
// CHECK-LABEL: sil hidden @_T017protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalPropertyGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.prop!getter.1.foreign
var propertyRef = t.prop
}
// CHECK: } // end sil function '_T017protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T017protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalSubscriptGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: [[INTCONV:%[0-9]+]] = function_ref @_T0S2i{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5
// CHECK: [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign
var subscriptRef = t[5]
}
// CHECK: } // end sil function '_T017protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F'
| f4d76e20fda61defb24fe034a080c20a | 52.205479 | 148 | 0.55484 | false | false | false | false |
RedRoster/rr-ios | refs/heads/master | RedRoster/Login/NewUserViewController.swift | apache-2.0 | 1 | //
// NewUserViewController.swift
// RedRoster
//
// Created by Daniel Li on 4/3/16.
// Copyright © 2016 dantheli. All rights reserved.
//
import UIKit
class NewUserViewController: UIPageViewController {
fileprivate(set) var pages: [UIViewController] = []
func createNewUserPage(_ topText: String?, bottomText: String?, imageName: String?, isLastPage: Bool = false) -> NewUserPage? {
guard let newUserPage = storyboard?.instantiateViewController(withIdentifier: "NewUserPage") as? NewUserPage else { return nil }
newUserPage.topText = topText
newUserPage.bottomText = bottomText
newUserPage.imageName = imageName
newUserPage.isLastPage = isLastPage
return newUserPage
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
view.backgroundColor = UIColor.rosterRed()
// Instantiate pages
pages = [createNewUserPage("View courses and add them to your schedule",
bottomText: "See reviews by former students or write your own",
imageName: nil) ?? NewUserPage(),
createNewUserPage("Edit your profile and view your schedules",
bottomText: "Swipe to the right on any screen to get to the menu",
imageName: nil,
isLastPage: true) ?? NewUserPage()]
// Set first page
if let firstPage = pages.first {
setViewControllers([firstPage], direction: .forward, animated: true, completion: nil)
}
}
}
extension NewUserViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let currentIndex = pages.index(of: viewController) else { return nil }
let previousIndex = currentIndex - 1
guard previousIndex >= 0 && previousIndex < pages.count else { return nil }
return pages[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let currentIndex = pages.index(of: viewController) else { return nil }
let nextIndex = currentIndex + 1
guard nextIndex >= 0 && nextIndex < pages.count else { return nil }
return pages[nextIndex]
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pages.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first,
let firstViewControllerIndex = pages.index(of: firstViewController) else {
return 0
}
return firstViewControllerIndex
}
}
| 8cebdb081e61824ab9f85bfe816b279d | 38.723684 | 149 | 0.636635 | false | false | false | false |
paidy/paidy-ios | refs/heads/master | PaidyCheckoutSDK/PaidyCheckoutSDK/AuthorizeSuccessViewController.swift | mit | 1 | //
// AuthorizeSuccessViewController.swift
// Paidycheckoutsdk
//
// Copyright (c) 2015 Paidy. All rights reserved.
//
import UIKit
class AuthorizeSuccessViewController: UIViewController {
@IBOutlet var countdownTime: UILabel!
@IBOutlet var completedButton: UIButton!
var countTime = 8
var timer = NSTimer()
// default init
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
let frameworkBundle = NSBundle(identifier: "com.paidy.PaidyCheckoutSDK")
super.init(nibName: "AuthorizeSuccessViewController", bundle: frameworkBundle)
}
// requried init
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// create countdown
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown:"), userInfo: nil, repeats: true)
// button style
completedButton.layer.cornerRadius = 5
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// OK button pressed
@IBAction func okButton(sender: UIButton) {
timer.invalidate()
close()
}
func countDown(timer: NSTimer) {
// count down 8 seconds
countTime--
countdownTime.text = "\(countTime)"
// close on reaching 0
if(countTime == 0) {
timer.invalidate()
close()
}
}
func close() {
let paidyCheckoutViewController: PaidyCheckOutViewController = self.parentViewController as! PaidyCheckOutViewController
paidyCheckoutViewController.sendResult()
}
}
| 6c98c97925710fb2cd09411fb0a55bfe | 26.53125 | 135 | 0.646992 | false | false | false | false |
dvxiaofan/Pro-Swift-Learning | refs/heads/master | Part-01/01-PatternMatching/09-Where.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
let numbers = [1, 2, 3, 4, 5]
for num in numbers where num % 2 == 0 {
print(num)
}
let names: [String?] = ["xiaofan", nil, "xiaoming", nil, "hahha"]
for name in names where name != nil {
print(name)
}
for case let name? in names {
print(name)
}
| 33789e5107b31a99b0d304724cb71c8b | 16.315789 | 65 | 0.613982 | false | false | false | false |
devincoughlin/swift | refs/heads/master | test/Profiler/coverage_closures.swift | apache-2.0 | 7 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sil -module-name coverage_closures %s | %FileCheck %s
func bar(arr: [(Int32) -> Int32]) {
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 (Swift.Int32) -> Swift.Int32 in coverage_closures.bar
// CHECK-NEXT: [[@LINE+1]]:13 -> [[@LINE+1]]:42 : 0
for a in [{ (b : Int32) -> Int32 in b }] {
a(0)
}
}
func foo() {
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE+1]]:12 -> [[@LINE+1]]:59 : 0
let c1 = { (i1 : Int32, i2 : Int32) -> Bool in i1 < i2 }
// CHECK-LABEL: sil_coverage_map {{.*}}// f1 #1 ((Swift.Int32, Swift.Int32) -> Swift.Bool) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE+1]]:55 -> {{.*}}:4 : 0
func f1(_ closure : (Int32, Int32) -> Bool) -> Bool {
// CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 () throws -> Swift.Bool in f1
// CHECK-NEXT: [[@LINE+1]]:29 -> [[@LINE+1]]:42 : 0
return closure(0, 1) && closure(1, 0)
}
f1(c1)
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #2 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE+1]]:6 -> [[@LINE+1]]:27 : 0
f1 { i1, i2 in i1 > i2 }
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #3 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE+3]]:6 -> [[@LINE+3]]:48 : 0
// CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 () throws -> {{.*}} in coverage_closures.foo
// CHECK-NEXT: [[@LINE+1]]:36 -> [[@LINE+1]]:46 : 0
f1 { left, right in left == 0 || right == 1 }
}
// SR-2615: Display coverage for implicit member initializers without crashing
struct C1 {
// CHECK-LABEL: sil_coverage_map{{.*}}// variable initialization expression of coverage_closures.C1
// CHECK-NEXT: [[@LINE+1]]:24 -> [[@LINE+1]]:34 : 0
private var errors = [String]()
}
// rdar://39200851: Closure in init method covered twice
class C2 {
init() {
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 () -> () in coverage_closures.C2.init()
// CHECK-NEXT: [[@LINE+2]]:13 -> [[@LINE+4]]:6 : 0
// CHECK-NEXT: }
let _ = { () in
print("hello")
}
}
}
| f844f74202bbd981c6dad3f8c2646fe1 | 40.109091 | 160 | 0.592216 | false | false | false | false |
ivygulch/IVGFoundation | refs/heads/master | IVGFoundation/source/common/NextResponderHelper.swift | mit | 1 | //
// NextResponderHelper.swift
// IVGFoundation
//
// Created by Douglas Sjoquist on 11/28/17.
// Copyright © 2017 Ivy Gulch. All rights reserved.
//
import UIKit
public protocol UITextInputTraitsWithReturnKeyType : UITextInputTraits {
// redeclare the returnKeyType property of the parent protocol, but this time as mandatory
var returnKeyType: UIReturnKeyType { get set }
}
extension UITextField: UITextInputTraitsWithReturnKeyType {}
extension UITextView: UITextInputTraitsWithReturnKeyType {}
public class NextResponderHelper {
private var values: [UIResponder: UIResponder] = [:]
private var automaticallySetReturnKeyType: Bool
private var textFieldDelegate: UITextFieldDelegate!
public init(automaticallySetReturnKeyType: Bool = true, textFieldDelegate: UITextFieldDelegate? = nil) {
self.automaticallySetReturnKeyType = automaticallySetReturnKeyType
self.textFieldDelegate = NextResponderHelperTextFieldDelegate(nextResponderHelper: self, textFieldDelegate: textFieldDelegate)
}
public func register(responder: UIResponder?, next nextResponder: UIResponder?) {
guard let responder = responder else { return }
values[responder] = nextResponder
if automaticallySetReturnKeyType {
if let textInputTraits = responder as? UITextInputTraitsWithReturnKeyType {
textInputTraits.returnKeyType = (nextResponder == nil) ? .default : .next
}
}
if let textField = responder as? UITextField {
textField.delegate = textFieldDelegate
}
}
@discardableResult public func finish(responder: UIResponder?) -> Bool {
guard let responder = responder else { return false }
guard let nextResponder = values[responder] else {
responder.resignFirstResponder()
return false
}
if Thread.isMainThread {
nextResponder.becomeFirstResponder()
} else {
DispatchQueue.main.async {
nextResponder.becomeFirstResponder()
}
}
return true
}
}
fileprivate class NextResponderHelperTextFieldDelegate: NSObject, UITextFieldDelegate {
let nextResponderHelper: NextResponderHelper
let textFieldDelegate: UITextFieldDelegate?
init(nextResponderHelper: NextResponderHelper, textFieldDelegate: UITextFieldDelegate?) {
self.nextResponderHelper = nextResponderHelper
self.textFieldDelegate = textFieldDelegate
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
nextResponderHelper.finish(responder: textField)
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return textFieldDelegate?.textFieldShouldBeginEditing?(textField) ?? true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
textFieldDelegate?.textFieldDidBeginEditing?(textField)
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return textFieldDelegate?.textFieldShouldEndEditing?(textField) ?? true
}
func textFieldDidEndEditing(_ textField: UITextField){
textFieldDelegate?.textFieldDidEndEditing?(textField)
}
@available(iOS 10.0, *)
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
textFieldDelegate?.textFieldDidEndEditing?(textField, reason: reason)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return textFieldDelegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return textFieldDelegate?.textFieldShouldClear?(textField) ?? true
}
}
| 07e656dbb4c09bfa471613ac7d660106 | 35.838095 | 134 | 0.717166 | false | false | false | false |
buyiyang/iosstar | refs/heads/master | iOSStar/Scenes/Market/Controller/MarketViewController.swift | gpl-3.0 | 4 | //
// MarketViewController.swift
// iOSStar
//
// Created by J-bb on 17/4/20.
// Copyright © 2017年 sum. All rights reserved.
//
import UIKit
class MarketViewController: UIViewController, SubViewItemSelectDelegate{
var menuView:MarketMenuView?
override func viewDidLoad() {
super.viewDidLoad()
YD_CountDownHelper.shared.start()
setCustomTitle(title: "明星热度")
translucent(clear: true)
let color = UIColor.white
navigationController?.navigationBar.setBackgroundImage(color.imageWithColor(), for: .default)
automaticallyAdjustsScrollViewInsets = false
menuView = MarketMenuView(frame: CGRect(x: 0, y: 64, width: kScreenWidth, height: kScreenHeight))
menuView?.items = ["明星"]
menuView?.menuView?.isScreenWidth = true
menuView?.delegate = self
view.addSubview(menuView!)
perform(#selector(setTypes), with: nil, afterDelay: 0.5)
}
func selectItem(starModel: MarketListModel) {
if checkLogin() {
let storyBoard = UIStoryboard(name: "Market", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "MarketDetail") as! MarketDetailViewController
vc.starModel = starModel
navigationController?.pushViewController(vc, animated: true)
}
}
func setTypes() {
menuView?.types = [MarketClassifyModel]()
}
func requestTypeList() {
AppAPIHelper.marketAPI().requestTypeList(complete: { (response) in
if let models = response as? [MarketClassifyModel] {
var titles = [String]()
// let customModel = MarketClassifyModel()
//customModel.name = "自选"
//models.insert(customModel, at: 0)
for model in models {
titles.append(model.name)
}
self.menuView?.items = titles
self.menuView?.types = models
}
}, error: errorBlockFunc())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func searchAction() {
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
YD_CountDownHelper.shared.marketListRefresh = nil
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
YD_CountDownHelper.shared.marketListRefresh = { [weak self] (result)in
self?.menuView?.requestDataWithIndexPath()
}
}
}
| 3a72d5d9dd2d10b83104032db93d22ab | 31.123457 | 120 | 0.616449 | false | false | false | false |
optimizely/swift-sdk | refs/heads/master | Sources/Data Model/ProjectConfig.swift | apache-2.0 | 1 | //
// Copyright 2019-2022, Optimizely, Inc. and contributors
//
// 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
class ProjectConfig {
var project: Project! {
didSet {
updateProjectDependentProps()
}
}
let logger = OPTLoggerFactory.getLogger()
// local runtime forcedVariations [UserId: [ExperimentId: VariationId]]
// NOTE: experiment.forcedVariations use [ExperimentKey: VariationKey] instead of ids
var whitelistUsers = AtomicProperty(property: [String: [String: String]]())
var experimentKeyMap = [String: Experiment]()
var experimentIdMap = [String: Experiment]()
var experimentFeatureMap = [String: [String]]()
var eventKeyMap = [String: Event]()
var attributeKeyMap = [String: Attribute]()
var featureFlagKeyMap = [String: FeatureFlag]()
var featureFlagKeys = [String]()
var rolloutIdMap = [String: Rollout]()
var allExperiments = [Experiment]()
var flagVariationsMap = [String: [Variation]]()
var allSegments = [String]()
// MARK: - Init
init(datafile: Data) throws {
var project: Project
do {
project = try JSONDecoder().decode(Project.self, from: datafile)
} catch {
throw OptimizelyError.dataFileInvalid
}
if !isValidVersion(version: project.version) {
throw OptimizelyError.dataFileVersionInvalid(project.version)
}
self.project = project
updateProjectDependentProps() // project:didSet is not fired in init. explicitly called.
}
convenience init(datafile: String) throws {
try self.init(datafile: Data(datafile.utf8))
}
init() {}
func updateProjectDependentProps() {
self.allExperiments = project.experiments + project.groups.map { $0.experiments }.flatMap { $0 }
self.experimentKeyMap = {
var map = [String: Experiment]()
allExperiments.forEach { exp in
map[exp.key] = exp
}
return map
}()
self.experimentIdMap = {
var map = [String: Experiment]()
allExperiments.forEach { map[$0.id] = $0 }
return map
}()
self.experimentFeatureMap = {
var experimentFeatureMap = [String: [String]]()
project.featureFlags.forEach { (ff) in
ff.experimentIds.forEach {
if var arr = experimentFeatureMap[$0] {
arr.append(ff.id)
experimentFeatureMap[$0] = arr
} else {
experimentFeatureMap[$0] = [ff.id]
}
}
}
return experimentFeatureMap
}()
self.eventKeyMap = {
var eventKeyMap = [String: Event]()
project.events.forEach { eventKeyMap[$0.key] = $0 }
return eventKeyMap
}()
self.attributeKeyMap = {
var map = [String: Attribute]()
project.attributes.forEach { map[$0.key] = $0 }
return map
}()
self.featureFlagKeyMap = {
var map = [String: FeatureFlag]()
project.featureFlags.forEach { map[$0.key] = $0 }
return map
}()
self.featureFlagKeys = {
return project.featureFlags.map { $0.key }
}()
self.rolloutIdMap = {
var map = [String: Rollout]()
project.rollouts.forEach { map[$0.id] = $0 }
return map
}()
// all variations for each flag
// - datafile does not contain a separate entity for this.
// - we collect variations used in each rule (experiment rules and delivery rules)
self.flagVariationsMap = {
var map = [String: [Variation]]()
project.featureFlags.forEach { flag in
var variations = [Variation]()
getAllRulesForFlag(flag).forEach { rule in
rule.variations.forEach { variation in
if variations.filter({ $0.id == variation.id }).first == nil {
variations.append(variation)
}
}
}
map[flag.key] = variations
}
return map
}()
self.allSegments = {
let audiences = project.typedAudiences ?? []
return Array(Set(audiences.flatMap { $0.getSegments() }))
}()
}
func getAllRulesForFlag(_ flag: FeatureFlag) -> [Experiment] {
var rules = flag.experimentIds.compactMap { experimentIdMap[$0] }
let rollout = self.rolloutIdMap[flag.rolloutId]
rules.append(contentsOf: rollout?.experiments ?? [])
return rules
}
}
// MARK: - Persistent Data
extension ProjectConfig {
func whitelistUser(userId: String, experimentId: String, variationId: String) {
whitelistUsers.performAtomic { whitelist in
var dict = whitelist[userId] ?? [String: String]()
dict[experimentId] = variationId
whitelist[userId] = dict
}
}
func removeFromWhitelist(userId: String, experimentId: String) {
whitelistUsers.performAtomic { whitelist in
whitelist[userId]?.removeValue(forKey: experimentId)
}
}
func getWhitelistedVariationId(userId: String, experimentId: String) -> String? {
if let dict = whitelistUsers.property?[userId] {
return dict[experimentId]
}
logger.d(.userHasNoForcedVariation(userId))
return nil
}
func isValidVersion(version: String) -> Bool {
// old versions (< 4) of datafiles not supported
return ["4"].contains(version)
}
}
// MARK: - Project Access
extension ProjectConfig {
/**
* Get sendFlagDecisions value.
*/
var sendFlagDecisions: Bool {
return project.sendFlagDecisions ?? false
}
/**
* ODP API server publicKey.
*/
var publicKeyForODP: String? {
return project.integrations?.filter { $0.key == "odp" }.first?.publicKey
}
/**
* ODP API server host.
*/
var hostForODP: String? {
return project.integrations?.filter { $0.key == "odp" }.first?.host
}
/**
* Get an Experiment object for a key.
*/
func getExperiment(key: String) -> Experiment? {
return experimentKeyMap[key]
}
/**
* Get an Experiment object for an Id.
*/
func getExperiment(id: String) -> Experiment? {
return experimentIdMap[id]
}
/**
* Get an experiment Id for the human readable experiment key
**/
func getExperimentId(key: String) -> String? {
return getExperiment(key: key)?.id
}
/**
* Get a Group object for an Id.
*/
func getGroup(id: String) -> Group? {
return project.groups.filter { $0.id == id }.first
}
/**
* Get a Feature Flag object for a key.
*/
func getFeatureFlag(key: String) -> FeatureFlag? {
return featureFlagKeyMap[key]
}
/**
* Get all Feature Flag objects.
*/
func getFeatureFlags() -> [FeatureFlag] {
return project.featureFlags
}
/**
* Get a Rollout object for an Id.
*/
func getRollout(id: String) -> Rollout? {
return rolloutIdMap[id]
}
/**
* Gets an event for a corresponding event key
*/
func getEvent(key: String) -> Event? {
return eventKeyMap[key]
}
/**
* Gets an event id for a corresponding event key
*/
func getEventId(key: String) -> String? {
return getEvent(key: key)?.id
}
/**
* Get an attribute for a given key.
*/
func getAttribute(key: String) -> Attribute? {
return attributeKeyMap[key]
}
/**
* Get an attribute Id for a given key.
**/
func getAttributeId(key: String) -> String? {
return getAttribute(key: key)?.id
}
/**
* Get an audience for a given audience id.
*/
func getAudience(id: String) -> Audience? {
return project.getAudience(id: id)
}
/**
* Returns true if experiment belongs to any feature, false otherwise.
*/
func isFeatureExperiment(id: String) -> Bool {
return !(experimentFeatureMap[id]?.isEmpty ?? true)
}
/**
* Get forced variation for a given experiment key and user id.
*/
func getForcedVariation(experimentKey: String, userId: String) -> DecisionResponse<Variation> {
let reasons = DecisionReasons()
guard let experiment = getExperiment(key: experimentKey) else {
return DecisionResponse(result: nil, reasons: reasons)
}
if let id = getWhitelistedVariationId(userId: userId, experimentId: experiment.id) {
if let variation = experiment.getVariation(id: id) {
let info = LogMessage.userHasForcedVariation(userId, experiment.key, variation.key)
logger.d(info)
reasons.addInfo(info)
return DecisionResponse(result: variation, reasons: reasons)
}
let info = LogMessage.userHasForcedVariationButInvalid(userId, experiment.key)
logger.d(info)
reasons.addInfo(info)
return DecisionResponse(result: nil, reasons: reasons)
}
logger.d(.userHasNoForcedVariationForExperiment(userId, experiment.key))
return DecisionResponse(result: nil, reasons: reasons)
}
/**
* Set forced variation for a given experiment key and user id according to a given variation key.
*/
func setForcedVariation(experimentKey: String, userId: String, variationKey: String?) -> Bool {
guard let experiment = getExperiment(key: experimentKey) else {
return false
}
guard var variationKey = variationKey else {
logger.d(.variationRemovedForUser(userId, experimentKey))
self.removeFromWhitelist(userId: userId, experimentId: experiment.id)
return true
}
// TODO: common function to trim all keys
variationKey = variationKey.trimmingCharacters(in: NSCharacterSet.whitespaces)
guard !variationKey.isEmpty else {
logger.e(.variationKeyInvalid(experimentKey, variationKey))
return false
}
guard let variation = experiment.getVariation(key: variationKey) else {
logger.e(.variationKeyInvalid(experimentKey, variationKey))
return false
}
self.whitelistUser(userId: userId, experimentId: experiment.id, variationId: variation.id)
logger.d(.userMappedToForcedVariation(userId, experiment.id, variation.id))
return true
}
func getFlagVariationByKey(flagKey: String, variationKey: String) -> Variation? {
if let variations = flagVariationsMap[flagKey] {
return variations.filter { $0.key == variationKey }.first
}
return nil
}
}
| fd0b71ebd4985df1a7fc9e52bc98f42b | 30.135065 | 104 | 0.573872 | false | false | false | false |
WickedColdfront/Slide-iOS | refs/heads/master | Pods/SAHistoryNavigationViewController/SAHistoryNavigationViewController/SAHistoryNavigationTransitionController.swift | apache-2.0 | 2 | //
// SAHistoryNavigationTransitionController.swift
// SAHistoryNavigationViewController
//
// Created by 鈴木大貴 on 2015/05/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
class SAHistoryNavigationTransitionController: NSObject, UIViewControllerAnimatedTransitioning {
//MARK: - Static constants
fileprivate struct Const {
static let defaultDuration: TimeInterval = 0.3
}
//MARK: - Properties
fileprivate(set) var navigationControllerOperation: UINavigationControllerOperation
fileprivate var currentTransitionContext: UIViewControllerContextTransitioning?
fileprivate var backgroundView: UIView?
fileprivate var alphaView: UIView?
//MARK: - Initializers
required init(operation: UINavigationControllerOperation) {
navigationControllerOperation = operation
super.init()
}
//MARK: Life cycle
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return Const.defaultDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)?.view,
let toView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)?.view
else { return }
let containerView = transitionContext.containerView
currentTransitionContext = transitionContext
switch navigationControllerOperation {
case .push:
pushAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .pop:
popAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .none:
let cancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!cancelled)
}
}
func forceFinish() {
let navigationControllerOperation = self.navigationControllerOperation
guard let backgroundView = backgroundView, let alphaView = alphaView else { return }
let dispatchTime = DispatchTime.now() + Double(Int64((Const.defaultDuration + 0.1) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime) { [weak self] in
guard let currentTransitionContext = self?.currentTransitionContext else { return }
let toViewContoller = currentTransitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let fromViewContoller = currentTransitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
guard let fromView = fromViewContoller?.view, let toView = toViewContoller?.view else { return }
switch navigationControllerOperation {
case .push:
self?.pushAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .pop:
self?.popAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .none:
let cancelled = currentTransitionContext.transitionWasCancelled
currentTransitionContext.completeTransition(!cancelled)
}
self?.currentTransitionContext = nil
self?.backgroundView = nil
self?.alphaView = nil
}
}
//MARK: - Pop animations
fileprivate func popAnimation(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .black
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
toView.frame = containerView.bounds
containerView.addSubview(toView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .black
containerView.addSubview(alphaView)
self.alphaView = alphaView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
let completion: (Bool) -> Void = { [weak self] finished in
if finished {
self?.popAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
toView.frame.origin.x = -(toView.frame.size.width / 4.0)
alphaView.alpha = 0.4
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: .curveEaseOut, animations: {
toView.frame.origin.x = 0
fromView.frame.origin.x = containerView.frame.size.width
alphaView.alpha = 0.0
}, completion: completion)
}
fileprivate func popAniamtionCompletion(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
toView.transform = CGAffineTransform.identity
toView.removeFromSuperview()
} else {
fromView.removeFromSuperview()
}
backgroundView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
//MARK: - pushAnimations
fileprivate func pushAnimation(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .black
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .black
alphaView.alpha = 0.0
containerView.addSubview(alphaView)
self.alphaView = alphaView
toView.frame = containerView.bounds
toView.frame.origin.x = containerView.frame.size.width
containerView.addSubview(toView)
let completion: (Bool) -> Void = { [weak self] finished in
if finished {
self?.pushAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: .curveEaseOut, animations: {
fromView.frame.origin.x = -(fromView.frame.size.width / 4.0)
toView.frame.origin.x = 0.0
alphaView.alpha = 0.4
}, completion: completion)
}
fileprivate func pushAniamtionCompletion(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
toView.removeFromSuperview()
}
fromView.transform = CGAffineTransform.identity
backgroundView.removeFromSuperview()
fromView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
}
| 6480a833fccca05cb86981937eff4571 | 43.718232 | 182 | 0.678404 | false | false | false | false |
schluchter/berlin-transport | refs/heads/master | berlin-transport/berlin-trnsprt/BTMapUtilities.swift | mit | 1 | //
// BTMapUtilities.swift
// berlin-transport
//
// Created by Thomas Schluchter on 10/27/14.
// Copyright (c) 2014 Thomas Schluchter. All rights reserved.
//
import Foundation
import MapKit
import CoreLocation
public class BTMapUtils {
public class func centerBetweenPoints(one: CLLocationCoordinate2D, _ two: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
let latitudeDelta = abs(one.latitude - two.latitude) / 2.0
let longitudeDelta = abs(one.longitude - two.longitude) / 2.0
let latNew = latitudeDelta + min(one.latitude, two.latitude)
let longNew = longitudeDelta + min(one.longitude, two.longitude)
return CLLocationCoordinate2DMake(latNew, longNew)
}
public class func formatDistance(distance: Int) -> String {
let formatter = MKDistanceFormatter()
formatter.units = MKDistanceFormatterUnits.Metric
formatter.unitStyle = MKDistanceFormatterUnitStyle.Abbreviated
return formatter.stringFromDistance(CLLocationDistance(distance))
}
}
| ed0eafb8cdcc8eb21692efae24045064 | 32 | 129 | 0.694215 | false | false | false | false |
collinhundley/APCustomBlurView | refs/heads/master | Example/Blur/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Blur
//
// Created by Collin Hundley on 1/16/16.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainViewController = MainViewController()
self.window!.rootViewController = mainViewController
self.window!.makeKeyAndVisible()
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.Appsidian.Blur" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
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 = NSBundle.mainBundle().URLForResource("Blur", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns 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
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Blur.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
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
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 80adfe9e7489e1a4b96c87662fbce136 | 53.591304 | 291 | 0.70532 | false | false | false | false |
tarrencev/BitWallet | refs/heads/master | BitWallet/TransactionsTableViewController.swift | mit | 1 | //
// TransactionsTableViewController.swift
// BitWallet
//
// Created by Tarrence van As on 8/15/14.
// Copyright (c) 2014 tva. All rights reserved.
//
import UIKit
class TransactionsTableViewController: UITableViewController {
var transactions: Array<Transaction> = []
override func viewDidLoad() {
super.viewDidLoad()
let sendInitiatorCellNib = UINib(nibName: "TransactionsTableViewCell", bundle: nil)
tableView.registerNib(sendInitiatorCellNib, forCellReuseIdentifier: "transactionsCell")
self.tableView.backgroundColor = .clearColor()
Chain.sharedInstance().getAddressTransactions(UserInfoManager.getPublicAddress(), limit: 2, completionHandler: { (response, error) -> Void in
if response != nil {
let responseDictionary = response as NSDictionary,
resultsArray = responseDictionary["results"] as Array<NSDictionary>
for transactionData in resultsArray {
let transaction = Transaction(rawData: transactionData)
self.transactions.append(transaction)
}
self.tableView.reloadData()
} else {
println(error)
}
})
}
func viewIsScrollingOnScreen() {
println("scrolling on screen")
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("transactionsCell", forIndexPath: indexPath) as TransactionsTableViewCell
let transaction = transactions[indexPath.row],
addresses = transaction.amount
cell.setUser(transaction.outputs[0].addresses[0])
cell.setAmount(String(transaction.amount))
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65
}
}
| 91e82c04f192db80f0a226dcf244f565 | 32.539474 | 149 | 0.640643 | false | false | false | false |
SereivoanYong/Charts | refs/heads/master | Source/Charts/Data/Implementations/Standard/BarEntry.swift | apache-2.0 | 1 | //
// BarEntry.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class BarEntry: Entry {
/// the values the stacked barchart holds
fileprivate var _yVals: [CGFloat]?
/// the ranges for the individual stack values - automatically calculated
fileprivate var _ranges: [Range]?
/// the sum of all negative values this entry (if stacked) contains
fileprivate var _negativeSum: CGFloat = 0.0
/// the sum of all positive values this entry (if stacked) contains
fileprivate var _positiveSum: CGFloat = 0.0
/// Constructor for normal bars (not stacked).
public override init(x: CGFloat, y: CGFloat, icon: UIImage? = nil, data: Any? = nil) {
super.init(x: x, y: y, icon: icon, data: data)
}
/// Constructor for stacked bar entries. One data object for whole stack
public init(x: CGFloat, yValues: [CGFloat], icon: UIImage? = nil, data: Any? = nil) {
super.init(x: x, y: BarEntry.calcSum(values: yValues), icon: icon, data: data)
self._yVals = yValues
calcPosNegSum()
calcRanges()
}
open func sumBelow(stackIndex :Int) -> CGFloat
{
if _yVals == nil
{
return 0
}
var remainder = 0.0 as CGFloat
var index = _yVals!.count - 1
while (index > stackIndex && index >= 0)
{
remainder += _yVals![index]
index -= 1
}
return remainder
}
/// - returns: The sum of all negative values this entry (if stacked) contains. (this is a positive number)
open var negativeSum: CGFloat {
return _negativeSum
}
/// - returns: The sum of all positive values this entry (if stacked) contains.
open var positiveSum: CGFloat {
return _positiveSum
}
open func calcPosNegSum()
{
if _yVals == nil
{
_positiveSum = 0.0
_negativeSum = 0.0
return
}
var sumNeg = 0.0 as CGFloat
var sumPos = 0.0 as CGFloat
for f in _yVals!
{
if f < 0.0
{
sumNeg += -f
}
else
{
sumPos += f
}
}
_negativeSum = sumNeg
_positiveSum = sumPos
}
/// Splits up the stack-values of the given bar-entry into Range objects.
/// - parameter entry:
/// - returns:
open func calcRanges()
{
let values = yValues
if values?.isEmpty != false
{
return
}
if _ranges == nil
{
_ranges = [Range]()
}
else
{
_ranges?.removeAll()
}
_ranges?.reserveCapacity(values!.count)
var negRemain = -negativeSum
var posRemain = 0.0 as CGFloat
for i in 0 ..< values!.count
{
let value = values![i]
if value < 0
{
_ranges?.append(Range(from: negRemain, to: negRemain - value))
negRemain -= value
}
else
{
_ranges?.append(Range(from: posRemain, to: posRemain + value))
posRemain += value
}
}
}
// MARK: Accessors
/// the values the stacked barchart holds
open var isStacked: Bool { return _yVals != nil }
/// the values the stacked barchart holds
open var yValues: [CGFloat]?
{
get { return self._yVals }
set
{
self.y = BarEntry.calcSum(values: newValue)
self._yVals = newValue
calcPosNegSum()
calcRanges()
}
}
/// - returns: The ranges of the individual stack-entries. Will return null if this entry is not stacked.
open var ranges: [Range]?
{
return _ranges
}
/// Calculates the sum across all values of the given stack.
///
/// - parameter vals:
/// - returns:
fileprivate static func calcSum(values: [CGFloat]?) -> CGFloat
{
guard let values = values
else { return 0.0 }
var sum = 0.0 as CGFloat
for f in values
{
sum += f
}
return sum
}
}
| 68c61c710effa43ea90715ef8e797266 | 20.802198 | 109 | 0.585938 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/URLSession/URLSession/UICopyLabel.swift | mit | 1 | //
// UICopyLabel.swift
// URLSession
//
// Created by 黄伯驹 on 2017/9/11.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
// http://www.hangge.com/blog/cache/detail_1085.html
// http://www.jianshu.com/p/10a6900cc904
class UICopyLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
func sharedInit() {
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(showMenu)))
}
@objc func showMenu(sender: UILongPressGestureRecognizer) {
switch sender.state {
case .began:
becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
default:
break
}
}
//复制
override func copy(_ sender: Any?) {
let board = UIPasteboard.general
board.string = text
let menu = UIMenuController.shared
menu.setMenuVisible(false, animated: true)
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.copy(_:)) {
return true
}
return false
}
}
| a4a539c56db5add4f618197e582a4a3e | 24.412698 | 101 | 0.598376 | false | false | false | false |
alirsamar/BiOS | refs/heads/master | Stage_5/beginning-ios-pirate-fleet-pirate-fleet-1-init/Pirate Fleet/Settings.swift | mit | 2 | //
// Settings.swift
// Pirate Fleet
//
// Created by Jarrod Parkes on 8/25/15.
// Copyright © 2015 Udacity, Inc. All rights reserved.
//
// MARK: - ReadyState: String
enum ReadyState: String {
case ShipsNotReady = "You do not have the correct amount of ships. Check the Debug Area for more specific details."
case ShipsMinesNotReady = "You do not have the correct amount of ships/mines. Check the Debug Area for more specific details."
case ReadyToPlay = "All Ready!"
case Invalid = "Invalid Ready State!"
}
// MARK: - Settings
struct Settings {
static let DefaultGridSize = GridSize(width: 8, height: 8)
static let ComputerDifficulty = Difficulty.Advanced
static let RequiredShips: [ShipSize:Int] = [
.Small: 1,
.Medium: 2,
.Large: 1,
.XLarge: 1
]
static let RequiredMines = 2
static let DefaultMineText = "Boom!"
struct Messages {
static let GameOverTitle = "Game Over"
static let GameOverWin = "You won! Congrats!"
static let GameOverLose = "You've been defeated by the computer."
static let UnableToStartTitle = "Cannot Start Game"
static let ShipsNotReady = "NOTE: You need one small ship (size 2), two medium ships (size 3), one large ship (size 4), one x-large ship (size 5)."
static let ShipsMinesNotReady = "NOTE: You need one small ship (size 2), two medium ships (size 3), one large ship (size 4), one x-large ship (size 5), and two mines."
static let HumanHitMine = "You've hit a mine! The computer has been rewarded an extra move on their next turn."
static let ComputerHitMine = "The computer has hit a mine! You've been awarded an extra move on your next turn."
static let ResetAction = "Reset Game"
static let DismissAction = "Continue"
}
struct Images {
static let Water = "Water"
static let Hit = "Hit"
static let Miss = "Miss"
static let ShipEndRight = "ShipEndRight"
static let ShipEndLeft = "ShipEndLeft"
static let ShipEndDown = "ShipEndDown"
static let ShipEndUp = "ShipEndUp"
static let ShipBodyHorz = "ShipBodyHorz"
static let ShipBodyVert = "ShipBodyVert"
static let WoodenShipPlaceholder = "WoodenShipPlaceholder"
static let Mine = "Mine"
static let MineHit = "MineHit"
}
} | a9f40ee70ef86d4f83d525a4a40b4f4f | 36.015152 | 175 | 0.642916 | false | false | false | false |
xdliu002/TAC_communication | refs/heads/master | PodsDemo/PodsDemo/MainTableViewController.swift | mit | 1 | //
// MainTableViewController.swift
// PodsDemo
//
// Created by Harold LIU on 3/16/16.
// Copyright © 2016 Tongji Apple Club. All rights reserved.
//
import UIKit
import LTNavigationBar
class MainTableViewController: UITableViewController {
let NAVBAR_CHANGE_POINT:CGFloat = 50
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor())
tableView.dataSource = self
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let color = UIColor.lxd_BlueColor()
let offsetY = scrollView.contentOffset.y
if offsetY > NAVBAR_CHANGE_POINT
{
let alpha = min(1, 1-((NAVBAR_CHANGE_POINT+64-offsetY)/64))
navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(alpha))
}
else
{
navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(0))
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
scrollViewDidScroll(tableView)
tableView.delegate = self
navigationController?.navigationBar.shadowImage = UIImage()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
tableView.delegate = nil
navigationController?.navigationBar.lt_reset()
}
//MARK:- Delegate && Datasource
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Header"
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
cell.textLabel?.text = "balalala"
return cell
}
func injected() {
print("I've been injected: (self)")
}
}
| db7520376dd45b53f8cf50947aae7fb5 | 27.686047 | 125 | 0.651398 | false | false | false | false |
irfanlone/Collection-View-in-a-collection-view-cell | refs/heads/master | Collections-CollectionView/MainCollectionViewCell.swift | mit | 1 | //
// MainCollectionViewCell.swift
// Collections-CollectionView
//
// Created by Irfan Lone on 4/8/16.
// Copyright © 2016 Ilone Labs. All rights reserved.
//
import UIKit
protocol CollectionViewSelectedProtocol {
func collectionViewSelected(_ collectionViewItem : Int)
}
class MainCollectionViewCell: UICollectionViewCell {
var collectionViewDataSource : UICollectionViewDataSource!
var collectionViewDelegate : UICollectionViewDelegate!
var collectionView : UICollectionView!
var delegate : CollectionViewSelectedProtocol!
var collectionViewOffset: CGFloat {
set {
collectionView.contentOffset.x = newValue
}
get {
return collectionView.contentOffset.x
}
}
func initializeCollectionViewWithDataSource<D: UICollectionViewDataSource,E: UICollectionViewDelegate>(_ dataSource: D, delegate :E, forRow row: Int) {
self.collectionViewDataSource = dataSource
self.collectionViewDelegate = delegate
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flowLayout)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseChildCollectionViewCellIdentifier)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self.collectionViewDataSource
collectionView.delegate = self.collectionViewDelegate
collectionView.tag = row
self.addSubview(collectionView)
self.collectionView = collectionView
var frame = self.bounds
frame.size.width = 80
frame.size.height = 25
let button = UIButton(frame: frame)
button.setTitle("Details >", for: UIControlState())
button.setTitleColor(UIColor.purple, for: UIControlState())
button.titleLabel?.font = UIFont(name: "Gillsans", size: 14)
button.addTarget(self, action: #selector(MainCollectionViewCell.buttonAction(_:)), for: UIControlEvents.touchUpInside)
self.addSubview(button)
collectionView.reloadData()
}
func buttonAction(_ sender: UIButton!) {
self.delegate.collectionViewSelected(collectionView.tag)
}
}
| 1bf2c6efe3da6cea54d55f91d9401942 | 30.868421 | 155 | 0.682494 | false | false | false | false |
rcobelli/GameOfficials | refs/heads/master | SwiftyJSON.swift | mit | 1 | // SwiftyJSON.swift
//
// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Error
///Error domain
public let ErrorDomain: String = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int = 999
public let ErrorIndexOutOfBounds: Int = 900
public let ErrorWrongType: Int = 901
public let ErrorNotExist: Int = 500
public let ErrorInvalidJSON: Int = 490
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type :Int{
case number
case string
case bool
case array
case dictionary
case null
case unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) {
do {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(jsonObject: object)
} catch let aError as NSError {
if error != nil {
error?.pointee = aError
}
self.init(jsonObject: NSNull())
}
}
/**
Creates a JSON object
- parameter object: the object
- note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)`
- returns: the created JSON object
*/
public init(_ object: Any) {
switch object {
case let object as [JSON] where object.count > 0:
self.init(array: object)
case let object as [String: JSON] where object.count > 0:
self.init(dictionary: object)
case let object as Data:
self.init(data: object)
default:
self.init(jsonObject: object)
}
}
/**
Parses the JSON string into a JSON object
- parameter json: the JSON string
- returns: the created JSON object
*/
public init(parseJSON jsonString: String) {
if let data = jsonString.data(using: .utf8) {
self.init(data)
} else {
self.init(NSNull())
}
}
/**
Creates a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
@available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`")
public static func parse(_ json: String) -> JSON {
return json.data(using: String.Encoding.utf8)
.flatMap{ JSON(data: $0) } ?? JSON(NSNull())
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
fileprivate init(jsonObject: Any) {
self.object = jsonObject
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
fileprivate init(array: [JSON]) {
self.init(array.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
- parameter jsonDictionary: A Swift dictionary of JSON objects
- returns: The created JSON
*/
fileprivate init(dictionary: [String: JSON]) {
var newDictionary = [String: Any](minimumCapacity: dictionary.count)
for (key, json) in dictionary {
newDictionary[key] = json.object
}
self.init(newDictionary)
}
/**
Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONs getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
*/
public mutating func merge(with other: JSON) throws {
try self.merge(with: other, typecheck: true)
}
/**
Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONS getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- returns: New merged JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
*/
public func merged(with other: JSON) throws -> JSON {
var merged = self
try merged.merge(with: other, typecheck: true)
return merged
}
// Private woker function which does the actual merging
// Typecheck is set to true for the first recursion level to prevent total override of the source JSON
fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws {
if self.type == other.type {
switch self.type {
case .dictionary:
for (key, _) in other {
try self[key].merge(with: other[key], typecheck: false)
}
case .array:
self = JSON(self.arrayValue + other.arrayValue)
default:
self = other
}
} else {
if typecheck {
throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."])
} else {
self = other
}
}
}
/// Private object
fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String : Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var rawBool: Bool = false
/// Private type
fileprivate var _type: Type = .null
/// prviate error
fileprivate var _error: NSError? = nil
/// Object in JSON
public var object: Any {
get {
switch self.type {
case .array:
return self.rawArray
case .dictionary:
return self.rawDictionary
case .string:
return self.rawString
case .number:
return self.rawNumber
case .bool:
return self.rawBool
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .bool
self.rawBool = number.boolValue
} else {
_type = .number
self.rawNumber = number
}
case let string as String:
_type = .string
self.rawString = string
case _ as NSNull:
_type = .null
case _ as [JSON]:
_type = .array
case nil:
_type = .null
case let array as [Any]:
_type = .array
self.rawArray = array
case let dictionary as [String : Any]:
_type = .dictionary
self.rawDictionary = dictionary
default:
_type = .unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// JSON type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null JSON
@available(*, unavailable, renamed:"null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
public enum Index<T: Any>: Comparable
{
case array(Int)
case dictionary(DictionaryIndex<String, T>)
case null
static public func ==(lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left == right
case (.dictionary(let left), .dictionary(let right)):
return left == right
case (.null, .null): return true
default:
return false
}
}
static public func <(lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left < right
case (.dictionary(let left), .dictionary(let right)):
return left < right
default:
return false
}
}
}
public typealias JSONIndex = Index<JSON>
public typealias JSONRawIndex = Index<Any>
extension JSON: Collection
{
public typealias Index = JSONRawIndex
public var startIndex: Index
{
switch type
{
case .array:
return .array(rawArray.startIndex)
case .dictionary:
return .dictionary(rawDictionary.startIndex)
default:
return .null
}
}
public var endIndex: Index
{
switch type
{
case .array:
return .array(rawArray.endIndex)
case .dictionary:
return .dictionary(rawDictionary.endIndex)
default:
return .null
}
}
public func index(after i: Index) -> Index
{
switch i
{
case .array(let idx):
return .array(rawArray.index(after: idx))
case .dictionary(let idx):
return .dictionary(rawDictionary.index(after: idx))
default:
return .null
}
}
public subscript (position: Index) -> (String, JSON)
{
switch position
{
case .array(let idx):
return (String(idx), JSON(self.rawArray[idx]))
case .dictionary(let idx):
let (key, value) = self.rawDictionary[idx]
return (key, JSON(value))
default:
return ("", JSON.null)
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey
{
case index(Int)
case key(String)
}
public protocol JSONSubscriptType {
var jsonKey:JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.key(self)
}
}
extension JSON {
/// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error.
fileprivate subscript(index index: Int) -> JSON {
get {
if self.type != .array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
fileprivate subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
fileprivate subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .index(let index): return self[index: index]
case .key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .index(let index): self[index: index] = newValue
case .key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
let array = elements
self.init(dictionaryLiteral: array)
}
public init(dictionaryLiteral elements: [(String, Any)]) {
let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in
let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in
if let value = dictionary[key] {
return (key, value)
}
return nil
}
return JSON(dictionaryLiteral: initializeElement)
}
var dict = [String : Any](minimumCapacity: elements.count)
for element in elements {
let elementToSet: Any
if let json = element.1 as? JSON {
elementToSet = json.object
} else if let jsonArray = element.1 as? [JSON] {
elementToSet = JSON(jsonArray).object
} else if let dictionary = element.1 as? [String : Any] {
elementToSet = jsonFromDictionaryLiteral(dictionary).object
} else if let dictArray = element.1 as? [[String : Any]] {
let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) }
elementToSet = JSON(jsonArray).object
} else {
elementToSet = element.1
}
dict[element.0] = elementToSet
}
self.init(dict)
}
}
extension JSON: Swift.ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Any...) {
self.init(elements as Any)
}
}
extension JSON: Swift.ExpressibleByNilLiteral {
@available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions")
public init(nilLiteral: ()) {
self.init(NSNull() as Any)
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
if JSON(rawValue).type == .unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: Any {
return self.object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(self.object) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
}
return try JSONSerialization.data(withJSONObject: self.object, options: opt)
}
public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
do {
return try _rawString(encoding, options: [.jsonSerialization: opt])
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
public func rawString(_ options: [writtingOptionsKeys: Any]) -> String? {
let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8
let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10
do {
return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth)
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
fileprivate func _rawString(
_ encoding: String.Encoding = .utf8,
options: [writtingOptionsKeys: Any],
maxObjectDepth: Int = 10
) throws -> String? {
if (maxObjectDepth < 0) {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"])
}
switch self.type {
case .dictionary:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try self.rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let dict = self.object as? [String: Any?] else {
return nil
}
let body = try dict.keys.map { key throws -> String in
guard let value = dict[key] else {
return "\"\(key)\": null"
}
guard let unwrappedValue = value else {
return "\"\(key)\": null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"])
}
if nestedValue.type == .string {
return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return "\"\(key)\": \(nestedString)"
}
}
return "{\(body.joined(separator: ","))}"
} catch _ {
return nil
}
case .array:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try self.rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let array = self.object as? [Any?] else {
return nil
}
let body = try array.map { value throws -> String in
guard let unwrappedValue = value else {
return "null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"])
}
if nestedValue.type == .string {
return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return nestedString
}
}
return "[\(body.joined(separator: ","))]"
} catch _ {
return nil
}
case .string:
return self.rawString
case .number:
return self.rawNumber.stringValue
case .bool:
return self.rawBool.description
case .null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options:.prettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [Any]
public var arrayObject: [Any]? {
get {
switch self.type {
case .array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .dictionary {
var d = [String : JSON](minimumCapacity: rawDictionary.count)
for (key, value) in rawDictionary {
d[key] = JSON(value)
}
return d
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : Any]
public var dictionaryObject: [String : Any]? {
get {
switch self.type {
case .dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON { // : Swift.Bool
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .bool:
return self.rawBool
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = newValue as Bool
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .bool:
return self.rawBool
case .number:
return self.rawNumber.boolValue
case .string:
return ["true", "y", "t"].contains() { (truthyString) in
return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame
}
default:
return false
}
}
set {
self.object = newValue
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .string:
return self.object as? String
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSString(string:newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .string:
return self.object as? String ?? ""
case .number:
return self.rawNumber.stringValue
case .bool:
return (self.object as? Bool).map { String($0) } ?? ""
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .number:
return self.rawNumber
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .string:
let decimal = NSDecimalNumber(string: self.object as? String)
if decimal == NSDecimalNumber.notANumber { // indicates parse error
return NSDecimalNumber.zero
}
return decimal
case .number:
return self.object as? NSNumber ?? NSNumber(value: 0)
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return NSNumber(value: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
public func exists() -> Bool{
if let errorValue = error, errorValue.code == ErrorNotExist ||
errorValue.code == ErrorIndexOutOfBounds ||
errorValue.code == ErrorWrongType {
return false
}
return true
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var url: URL? {
get {
switch self.type {
case .string:
// Check for existing percent escapes first to prevent double-escaping of % character
if let _ = self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) {
return Foundation.URL(string: self.rawString)
} else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
// We have to use `Foundation.URL` otherwise it conflicts with the variable name.
return Foundation.URL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int: Int?
{
get
{
return self.number?.intValue
}
set
{
if let newValue = newValue
{
self.object = NSNumber(value: newValue)
} else
{
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.uintValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.uintValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.int8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: Int(newValue))
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.int8Value
}
set {
self.object = NSNumber(value: Int(newValue))
}
}
public var uInt8: UInt8? {
get {
return self.number?.uint8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.uint8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.int16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.int16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.uint16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.uint16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.int32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.int32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.uint32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.uint32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.int64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.int64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.uint64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.uint64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber == rhs.rawNumber
case (.string, .string):
return lhs.rawString == rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber <= rhs.rawNumber
case (.string, .string):
return lhs.rawString <= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber >= rhs.rawNumber
case (.string, .string):
return lhs.rawString >= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber > rhs.rawNumber
case (.string, .string):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber < rhs.rawNumber
case (.string, .string):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(value: true)
private let falseNumber = NSNumber(value: false)
private let trueObjCType = String(cString: trueNumber.objCType)
private let falseObjCType = String(cString: falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
var isBool:Bool {
get {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedSame
}
}
func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedAscending
}
}
func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
}
func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedDescending
}
}
func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedAscending
}
}
public enum writtingOptionsKeys {
case jsonSerialization
case castNilToNSNull
case maxObjextDepth
case encoding
}
| 9530fd7809dd8b96c2bb8248c8f84775 | 26.963636 | 265 | 0.54667 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | refs/heads/good | NoteOptionTableViewController.swift | mit | 1 | //
// NoteOptionTableViewController.swift
// SwiftGL
//
// Created by jerry on 2016/2/19.
// Copyright © 2016年 Jerry Chan. All rights reserved.
//
import UIKit
enum NoteOptionAction{
case drawRevision
case none
}
class NoteOptionTableViewController: UITableViewController {
weak var delegate:PaintViewController!
override func viewWillAppear(_ animated: Bool) {
view.layer.cornerRadius = 0
}
@IBOutlet weak var enterRevisionModeButton: UITableViewCell!
var action:NoteOptionAction = .none
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.cellForRow(at: indexPath) ==
enterRevisionModeButton
{
//delegate.
action = .drawRevision
dismiss(animated: true, completion: {})
delegate.noteOptionDrawRevisionTouched()
}
}
}
| 2670bc4569ca591e3cfc25fbd1bdbf34 | 26.757576 | 92 | 0.665939 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-fuzzing/19114-clang-namespacedecl-namespacedecl.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol B : a {
case c,
typealias e = [ {
struct g<d<T where k.a<T>: b {
class A {
println( 1 )
class
let a {
case c,
struct A {
protocol a {
struct g<d where B : b = j
var d = a<T> (v: e.b { func e
typealias e = [ {
{
i>: e
func a<T>: b {
case ,
func b
{
struct g<T>: b {
func < {
func < {
class
protocol B : e
let end = [ {
let end = 0 as a
protocol a {
{
struct A<T>: a {
class
class
{
case c,
class A {
i>: d<T>: e
let f = [Void{
println( 1 )
var d = [Void{
let end = [Void{
deinit {
case c,
class B? {
struct A {
class
class B : e.h
typealias e : a {
case ,
protocol B : e
var d where k.b = [ {
func b
case c,
let end = [ {
typealias e = B? {
}
let f = 0 as a
case c,
struct g<T>
case ,
class
class
class A {
case c,
let a {
class
class
deinit {
class
func a<T where B {
class
func a<d<T where B : B, leng
var d where B : a {
class
struct A {
class A {
case c,
func a
typealias e : B<T>
let f = [Void{
let f = [ {
struct A<T> (v: d<d where k.a<T where k.b {
let end = 0 as a
"
func a<T where k.h
let end = [Void{
func a
case c,
class
let end = [Void{
println( 1 )
deinit {
func a
class
func a"
let end = [ {
let end = a<d: B, leng
protocol B : B<T> (v: B, leng
var b {
case c,
case c,
case c,
var d where k.h
protocol B : b {
struct A {
protocol A {
typealias e : d: e
let end = [Void{
let end = B<T> (v: e
case c,
class B : d<T>
{
class a {
case c,
let a {
case c,
{
let a {
struct A<T>: e
class B : e
struct A {
case c,
case c,
{
"
class
func a<d
case c,
typealias e = j
func a
class B<T>
let a {
class
class
func a<d where B : d
class
let end = [Void{
{
let a {
case c,
protocol a {
var b = [Void{
0.b = a<T> (v: a {
class
let f = [Void{
var b {
case c,
class a {
case ,
case c,
protocol a {
class B {
case c,
}
typealias e = B? {
func a
typealias e = [ {
let end = B? {
class
class d
func b
let a {
func e.a
0.b {
let end = [Void{
0.b {
}
{
var b {
let end = [ {
class B<T>
var d where k.h
func b
func e
typealias e = 0 as a
class A {
protocol a {
let end = [ {
{
deinit {
let a {
case c,
class
let end = [ {
"
class
let end = j
let a {
let end = a
class a {
"
func e.h
let end = j
class
protocol B : b = [ {
func b
typealias e : b { func b
func < {
struct A<d where B {
struct A<T> (v: b {
class
"
protocol c {
func a<d = [Void{
| 104f26c9bf871d1eca3cdc7d10b0fd3e | 10.637681 | 87 | 0.601494 | false | false | false | false |
kingka/SwiftWeiBo | refs/heads/master | SwiftWeiBo/SwiftWeiBo/Classes/Home/StatusesCell.swift | mit | 1 | //
// StatusesCell.swift
// SwiftWeiBo
//
// Created by Imanol on 16/4/18.
// Copyright © 2016年 imanol. All rights reserved.
//
import UIKit
import SDWebImage
class StatusesCell: UITableViewCell {
var widthConstraint : NSLayoutConstraint?
var heightConstraint : NSLayoutConstraint?
///topConstraint是用来控制当没有配图的时候,去除顶部的10像素约束
var topConstraint : NSLayoutConstraint?
var statuses : Statuses?
{
didSet{
context.attributedText = EmoticonPackage.changeText2AttributeText(statuses?.text ?? "")
topView.statuses = statuses
//计算配图尺寸
picView.statuses = statuses?.retweeted_status != nil ? statuses?.retweeted_status : statuses
let caculateSize = picView.calculateSize()
//picView的总体大小
widthConstraint?.constant = caculateSize.width
heightConstraint?.constant = caculateSize.height
topConstraint?.constant = caculateSize.height==1 ? 0 : 10
}
}
func rowHeight(status : Statuses) ->CGFloat{
//为了计算行高
self.statuses = status
//刷新 cell
self.layoutIfNeeded()
//返回底部最大的Y值
return CGRectGetMaxY(bottomView.frame)
}
func setupUI(){
topView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.top.equalTo(contentView)
make.height.lessThanOrEqualTo(100)
}
context.snp_makeConstraints { (make) -> Void in
make.top.equalTo(topView.snp_bottom).offset(10)
make.left.equalTo(topView).offset(10)
make.right.equalTo(contentView).offset(-15)
}
bottomView.snp_makeConstraints { (make) -> Void in
make.width.equalTo(contentView)
make.left.equalTo(contentView)
make.top.equalTo(picView.snp_bottom).offset(10)
make.height.equalTo(35)
//make.bottom.equalTo(contentView.snp_bottom).offset(-10)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(context)
contentView.addSubview(bottomView)
contentView.addSubview(picView)
contentView.addSubview(topView)
//bottomView.backgroundColor = UIColor.grayColor()
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
///MARK: - LAZY LOADING
lazy var topView : statusTopView = statusTopView()
lazy var context : UILabel = {
let label = UILabel.createLabel(UIColor.darkGrayColor(), fontSize: 15)
label.numberOfLines = 0
return label
}()
lazy var bottomView : statusBottomView = statusBottomView()
lazy var picView : picViews = picViews()
}
| bdd77571c4960e62a19ecceeed458947 | 28.616071 | 105 | 0.612903 | false | false | false | false |
adrfer/swift | refs/heads/master | test/SILGen/enum.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | FileCheck %s
public enum Optional<T> {
case Some(T), None
}
enum Boolish {
case falsy
case truthy
}
// CHECK-LABEL: sil hidden @_TFs13Boolish_casesFT_T_
func Boolish_cases() {
// CHECK: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type
// CHECK-NEXT: [[FALSY:%[0-9]+]] = enum $Boolish, #Boolish.falsy!enumelt
_ = Boolish.falsy
// CHECK-NEXT: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type
// CHECK-NEXT: [[TRUTHY:%[0-9]+]] = enum $Boolish, #Boolish.truthy!enumelt
_ = Boolish.truthy
}
struct Int {}
enum Optionable {
case nought
case mere(Int)
}
// CHECK-LABEL: sil hidden @_TFs16Optionable_casesFSiT_
func Optionable_cases(x: Int) {
// CHECK: [[FN:%.*]] = function_ref @_TFOs10Optionable4mereFMS_FSiS_
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type
// CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
// CHECK-NEXT: strong_release [[CTOR]]
_ = Optionable.mere
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type
// CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int
_ = Optionable.mere(x)
}
// CHECK-LABEL: sil shared [transparent] @_TFOs10Optionable4mereFMS_FSiS_
// CHECK: [[FN:%.*]] = function_ref @_TFOs10Optionable4merefMS_FSiS_
// CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0)
// CHECK-NEXT: return [[METHOD]]
// CHECK-NEXT: }
// CHECK-LABEL: sil shared [transparent] @_TFOs10Optionable4merefMS_FSiS_
// CHECK: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int
// CHECK-NEXT: return [[RES]] : $Optionable
// CHECK-NEXT: }
protocol P {}
struct S : P {}
enum AddressOnly {
case nought
case mere(P)
case phantom(S)
}
// CHECK-LABEL: sil hidden @_TFs17AddressOnly_casesFVs1ST_
func AddressOnly_cases(s: S) {
// CHECK: [[FN:%.*]] = function_ref @_TFOs11AddressOnly4mereFMS_FPs1P_S_
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
// CHECK-NEXT: strong_release [[CTOR]]
_ = AddressOnly.mere
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: inject_enum_addr [[NOUGHT]]
// CHECK-NEXT: destroy_addr [[NOUGHT]]
// CHECK-NEXT: dealloc_stack [[NOUGHT]]
_ = AddressOnly.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[MERE:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[PAYLOAD]]
// CHECK-NEXT: store %0 to [[PAYLOAD_ADDR]]
// CHECK-NEXT: inject_enum_addr [[MERE]]
// CHECK-NEXT: destroy_addr [[MERE]]
// CHECK-NEXT: dealloc_stack [[MERE]]
_ = AddressOnly.mere(s)
// Address-only enum vs loadable payload
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[PHANTOM:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1
// CHECK-NEXT: store %0 to [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1
// CHECK-NEXT: destroy_addr [[PHANTOM]]
// CHECK-NEXT: dealloc_stack [[PHANTOM]]
_ = AddressOnly.phantom(s)
// CHECK: return
}
// CHECK-LABEL: sil shared [transparent] @_TFOs11AddressOnly4mereFMS_FPs1P_S_
// CHECK: [[FN:%.*]] = function_ref @_TFOs11AddressOnly4merefMS_FPs1P_S_
// CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0)
// CHECK-NEXT: return [[METHOD]] : $@callee_owned (@out AddressOnly, @in P) -> ()
// CHECK-NEXT: }
// CHECK-LABEL: sil shared [transparent] @_TFOs11AddressOnly4merefMS_FPs1P_S_
// CHECK: [[RET_DATA:%.*]] = init_enum_data_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1
// CHECK-NEXT: copy_addr [take] %1 to [initialization] [[RET_DATA]] : $*P
// CHECK-NEXT: inject_enum_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1
// CHECK: return
// CHECK-NEXT: }
enum PolyOptionable<T> {
case nought
case mere(T)
}
// CHECK-LABEL: sil hidden @_TFs20PolyOptionable_casesurFxT_
func PolyOptionable_cases<T>(t: T) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $PolyOptionable<T>
// CHECK-NEXT: inject_enum_addr [[NOUGHT]]
// CHECK-NEXT: destroy_addr [[NOUGHT]]
// CHECK-NEXT: dealloc_stack [[NOUGHT]]
_ = PolyOptionable<T>.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
// CHECK-NEXT: [[MERE:%.*]] = alloc_stack $PolyOptionable<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]
// CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[MERE]]
// CHECK-NEXT: destroy_addr [[MERE]]
// CHECK-NEXT: dealloc_stack [[MERE]]
_ = PolyOptionable<T>.mere(t)
// CHECK-NEXT: destroy_addr %0
// CHECK: return
}
// The substituted type is loadable and trivial here
// CHECK-LABEL: sil hidden @_TFs32PolyOptionable_specialized_casesFSiT_
func PolyOptionable_specialized_cases(t: Int) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.nought!enumelt
_ = PolyOptionable<Int>.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.mere!enumelt.1, %0
_ = PolyOptionable<Int>.mere(t)
// CHECK: return
}
// Regression test for a bug where temporary allocations created as a result of
// tuple implosion were not deallocated in enum constructors.
struct String { var ptr: Builtin.NativeObject }
enum Foo { case A(P, String) }
// CHECK-LABEL: sil shared [transparent] @_TFOs3Foo1AFMS_FTPs1P_SS_S_
// CHECK: [[FN:%.*]] = function_ref @_TFOs3Foo1AfMS_FTPs1P_SS_S_
// CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0)
// CHECK-NEXT: return [[METHOD]]
// CHECK-NEXT: }
// CHECK-LABEL: sil shared [transparent] @_TFOs3Foo1AfMS_FTPs1P_SS_S_
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Foo, #Foo.A!enumelt.1
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1
// CHECK-NEXT: copy_addr [take] %1 to [initialization] [[LEFT]] : $*P
// CHECK-NEXT: store %2 to [[RIGHT]]
// CHECK-NEXT: inject_enum_addr %0 : $*Foo, #Foo.A!enumelt.1
// CHECK: return
// CHECK-NEXT: }
func Foo_cases() {
_ = Foo.A
}
| 757eb8d66962d753d8a1434d7c73a83a | 35.201058 | 115 | 0.628033 | false | false | false | false |
troystribling/BlueCap | refs/heads/master | Examples/BlueCap/BlueCap/Utils/ConfigStore.swift | mit | 1 | //
// ConfigStore.swift
// BlueCap
//
// Created by Troy Stribling on 8/29/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import BlueCapKit
import CoreBluetooth
import CoreLocation
// MARK: Defaults
struct Defaults {
static let serviceScanMode: ServiceScanMode = .promiscuous
static let peripheralSortOrder: PeripheralSortOrder = .discoveryDate
}
// MARK: Service Scan Mode
enum ServiceScanMode: Int {
case promiscuous = 0
case service = 1
init?(_ stringValue: String) {
switch stringValue {
case "Promiscuous":
self = .promiscuous
case "Service":
self = .service
default:
return nil
}
}
init?(_ rawValue: Int) {
switch rawValue {
case 0:
self = .promiscuous
case 1:
self = .service
default:
return nil
}
}
var stringValue: String {
switch self {
case .promiscuous:
return "Promiscuous"
case .service:
return "Service"
}
}
}
// MARK: Peripheral Sort Order
enum PeripheralSortOrder: Int {
case discoveryDate = 0
case rssi = 1
init?(_ stringValue: String) {
switch stringValue {
case "Discovery Date":
self = .discoveryDate
case "RSSI":
self = .rssi
default:
return nil
}
}
init?(_ rawValue: Int) {
switch rawValue {
case 0:
self = .discoveryDate
case 1:
self = .rssi
default:
return nil
}
}
var stringValue: String {
switch self {
case .discoveryDate:
return "Discovery Date"
case .rssi:
return "RSSI"
}
}
}
// MARK: - ConfigStore -
class ConfigStore {
// MARK: Scan Mode
class func getScanMode() -> ServiceScanMode {
let rawValue = UserDefaults.standard.integer(forKey: "scanMode")
if let serviceScanMode = ServiceScanMode(rawValue) {
return serviceScanMode
} else {
return Defaults.serviceScanMode
}
}
class func setScanMode(_ scanMode: ServiceScanMode) {
UserDefaults.standard.set(scanMode.rawValue, forKey:"scanMode")
}
// MARK: Scan Duration
class func getScanDurationEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "scanDurationEnabled")
}
class func setScanDurationEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"scanDurationEnabled")
}
class func getScanDuration() -> UInt {
let timeout = UserDefaults.standard.integer(forKey: "scanDuration")
return UInt(timeout)
}
class func setScanDuration(_ duration: UInt) {
UserDefaults.standard.set(Int(duration), forKey:"scanDuration")
}
// MARK: Peripheral Connection Timeout
class func getPeripheralConnectionTimeoutEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "peripheralConnectionTimeoutEnabled")
}
class func setPeripheralConnectionTimeoutEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"peripheralConnectionTimeoutEnabled")
}
class func getPeripheralConnectionTimeout () -> UInt {
let timeout = UserDefaults.standard.integer(forKey: "peripheralConnectionTimeout")
return UInt(timeout)
}
class func setPeripheralConnectionTimeout(_ peripheralConnectionTimeout: UInt) {
UserDefaults.standard.set(Int(peripheralConnectionTimeout), forKey:"peripheralConnectionTimeout")
}
// MARK: Characteristic Read Write Timeout
class func getCharacteristicReadWriteTimeout() -> UInt {
let characteristicReadWriteTimeout = UserDefaults.standard.integer(forKey: "characteristicReadWriteTimeout")
return UInt(characteristicReadWriteTimeout)
}
class func setCharacteristicReadWriteTimeout(_ characteristicReadWriteTimeout: UInt) {
UserDefaults.standard.set(Int(characteristicReadWriteTimeout), forKey:"characteristicReadWriteTimeout")
}
// MARK: Maximum Disconnections
class func getPeripheralMaximumDisconnectionsEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "peripheralMaximumDisconnectionsEnabled")
}
class func setPeripheralMaximumDisconnectionsEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"peripheralMaximumDisconnectionsEnabled")
}
class func getPeripheralMaximumDisconnections() -> UInt {
let maximumDisconnections = UserDefaults.standard.integer(forKey: "peripheralMaximumDisconnections")
return UInt(maximumDisconnections)
}
class func setPeripheralMaximumDisconnections(_ maximumDisconnections: UInt) {
UserDefaults.standard.set(Int(maximumDisconnections), forKey:"peripheralMaximumDisconnections")
}
// MARK: Maximum Timeouts
class func getPeripheralMaximumTimeoutsEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "peripheralMaximumTimeoutsEnabled")
}
class func setPeripheralMaximumTimeoutsEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"peripheralMaximumTimeoutsEnabled")
}
class func getPeripheralMaximumTimeouts() -> UInt {
let maximumTimeouts = UserDefaults.standard.integer(forKey: "peripheralMaximumTimeouts")
return UInt(maximumTimeouts)
}
class func setPeripheralMaximumTimeouts(_ maximumTimeouts: UInt) {
UserDefaults.standard.set(Int(maximumTimeouts), forKey:"peripheralMaximumTimeouts")
}
// MARK: Maximum Peripherals Connected
class func getMaximumPeripheralsConnected() -> Int {
return UserDefaults.standard.integer(forKey: "maximumPeripheralsConnected")
}
class func setMaximumPeripheralsConnected(_ maximumConnections: Int) {
UserDefaults.standard.set(maximumConnections, forKey:"maximumPeripheralsConnected")
}
// MARK: Maximum Discovered Peripherals
class func getMaximumPeripheralsDiscovered() -> Int {
return UserDefaults.standard.integer(forKey: "maximumPeripheralsDiscovered")
}
class func setMaximumPeripheralsDiscovered(_ maximumPeripherals: Int) {
UserDefaults.standard.set(maximumPeripherals, forKey:"maximumPeripheralsDiscovered")
}
// MARK: Peripheral Sort Order
class func getPeripheralSortOrder() -> PeripheralSortOrder {
let rawValue = UserDefaults.standard.integer(forKey: "peripheralSortOrder")
if let peripheralSortOrder = PeripheralSortOrder(rawValue) {
return peripheralSortOrder
} else {
return Defaults.peripheralSortOrder
}
}
class func setPeripheralSortOrder(_ sortOrder: PeripheralSortOrder) {
UserDefaults.standard.set(sortOrder.rawValue, forKey:"peripheralSortOrder")
}
// MARK: Scanned Services
class func getScannedServices() -> [String : CBUUID] {
if let storedServices = UserDefaults.standard.dictionary(forKey: "services") {
var services = [String: CBUUID]()
for (name, uuid) in storedServices {
if let uuid = uuid as? String {
services[name] = CBUUID(string: uuid)
}
}
return services
} else {
return [:]
}
}
class func getScannedServiceNames() -> [String] {
return Array(self.getScannedServices().keys)
}
class func getScannedServiceUUIDs() -> [CBUUID] {
return Array(self.getScannedServices().values)
}
class func getScannedServiceUUID(_ name: String) -> CBUUID? {
let services = self.getScannedServices()
if let uuid = services[name] {
return uuid
} else {
return nil
}
}
class func setScannedServices(_ services:[String: CBUUID]) {
var storedServices = [String:String]()
for (name, uuid) in services {
storedServices[name] = uuid.uuidString
}
UserDefaults.standard.set(storedServices, forKey:"services")
}
class func addScannedService(_ name :String, uuid: CBUUID) {
var services = self.getScannedServices()
services[name] = uuid
self.setScannedServices(services)
}
class func removeScannedService(_ name: String) {
var beacons = self.getScannedServices()
beacons.removeValue(forKey: name)
self.setScannedServices(beacons)
}
}
| 3661130d569508965e2e9ad597fae10c | 30.381295 | 116 | 0.654746 | false | false | false | false |
miletliyusuf/MakeItHybrid | refs/heads/master | Pod/Classes/MakeItHybrid.swift | mit | 1 | import UIKit
import Foundation
public class MakeItHybrid:NSObject,UIWebViewDelegate {
public var superView:UIView
var webView = UIWebView()
var loadingView = UIActivityIndicatorView()
public override init() {
superView = UIView()
}
public func makeHybridWithUrlString(urlString:NSString) {
let url = NSURL(string: urlString as String)
let requestObject = NSURLRequest(URL: url!)
webView.delegate = self
superView.addSubview(webView)
webView.setTranslatesAutoresizingMaskIntoConstraints(false)
let view:Dictionary = ["webView":webView]
let hConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[webView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
let vConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[webView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
superView.addConstraints(hConst)
superView.addConstraints(vConst)
webView.loadRequest(requestObject)
}
public func webViewDidFinishLoad(webView: UIWebView) {
loadingView.hidden = true
}
public func webViewDidStartLoad(webView: UIWebView) {
loadingView.setTranslatesAutoresizingMaskIntoConstraints(false)
loadingView.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
superView.addSubview(loadingView)
let view:Dictionary = ["loadingView":loadingView]
let hConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[loadingView]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
let vConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[loadingView]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
superView.addConstraints(hConst)
superView.addConstraints(vConst)
loadingView.startAnimating()
}
} | b00a1a7fffc5365e20a213501468ed7f | 36.083333 | 152 | 0.782462 | false | false | false | false |
jamesjmtaylor/weg-ios | refs/heads/master | weg-ios/Extensions/UIColor+AppColors.swift | mit | 1 | //
// UIColor+AppColors.swift
// weg-ios
//
// Created by Taylor, James on 4/28/18.
// Copyright © 2018 James JM Taylor. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
static func clear() -> UIColor {return UIColor.init(hex: "00000000")}
static func sixtyAlpa() -> UIColor {return UIColor.init(hex: "99000000")}
static func fiftyAlpa() -> UIColor {return UIColor.init(hex: "80000000")}
static func fortyAlpa() -> UIColor {return UIColor.init(hex: "66000000")}
static func colorPrimary() -> UIColor {return UIColor.init(hex: "FF000000")}
static func colorPrimaryDark() -> UIColor {return UIColor.init(hex: "FF000000")}
static func colorAccent() -> UIColor {return UIColor.init(hex: "FFFF0000")}
static func gray() -> UIColor {return UIColor.init(hex: "FFAAAAAA")}
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let a = (rgbValue & 0xff000000) >> 24
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(
red: CGFloat(r) / 0xff,
green: CGFloat(g) / 0xff,
blue: CGFloat(b) / 0xff,
alpha: CGFloat(a) / 0xff
)
}
}
| 0a4f5e9f47dd397ca356b8165efc57dc | 33 | 84 | 0.605452 | false | false | false | false |
Shivol/Swift-CS333 | refs/heads/master | playgrounds/uiKit/UIKitCatalog.playground/Pages/UITextField.xcplaygroundpage/Contents.swift | mit | 2 | import UIKit
import PlaygroundSupport
class Controller: NSObject, UITextViewDelegate {
let label: UILabel!
@objc func editingDidEnd(sender: UITextField) {
if let newValue = sender.text {
label.text = newValue
}
}
init(with label: UILabel){
self.label = label
}
// MARK: UITextViewDelegate
func textViewDidEndEditing(_ textView: UITextView) {
label.text = textView.text
}
}
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 250))
containerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
textField.borderStyle = .roundedRect
textField.placeholder = "username"
containerView.addSubview(textField)
let pass = UITextField(frame: CGRect(x: 0, y: 50, width: 250, height: 30))
pass.borderStyle = .line
pass.textColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1)
pass.placeholder = "password"
pass.isSecureTextEntry = true
pass.autocorrectionType = .no
pass.clearButtonMode = .always
containerView.addSubview(pass)
let imageBack = UITextField(frame: CGRect(x: 0, y: 100, width: 250, height: 30))
imageBack.background = #imageLiteral(resourceName: "gradient.png")
imageBack.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
imageBack.tintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
imageBack.textAlignment = NSTextAlignment.center
imageBack.tag = 3
containerView.addSubview(imageBack)
let textView = UITextView(frame: CGRect(x: 0, y: 150, width: 250, height: 30))
textView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
textView.textAlignment = NSTextAlignment.justified
containerView.addSubview(textView)
let displayLabel = UILabel(frame: CGRect(x: 0, y: 200, width: 250, height: 30))
displayLabel.textAlignment = .center
containerView.addSubview(displayLabel)
let controller = Controller(with: displayLabel)
textField.addTarget(controller, action: #selector(Controller.editingDidEnd(sender:)), for: .editingDidEnd)
pass.addTarget(controller, action: #selector(Controller.editingDidEnd(sender:)), for: .editingDidEnd)
imageBack.addTarget(controller, action: #selector(Controller.editingDidEnd(sender:)), for: .editingDidEnd)
textView.delegate = controller
PlaygroundPage.current.liveView = containerView
| 64b002b663e97998aee4acd2ef3e3f18 | 35.073529 | 110 | 0.741133 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/CIFilter/issue-21-core-image-explorer-master/Core Image Explorer/FilterDetailViewController.swift | mit | 1 | //
// FilterDetailViewController.swift
// Core Image Explorer
//
// Created by Warren Moore on 1/6/15.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import UIKit
class FilterDetailViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var filterName: String!
var filter: CIFilter!
var filteredImageView: FilteredImageView!
var parameterAdjustmentView: ParameterAdjustmentView!
var constraints = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
filter = CIFilter(name: filterName)
navigationItem.title = filter.attributes[kCIAttributeFilterDisplayName] as? String
addSubviews()
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.setStatusBarStyle(.lightContent, animated: animated)
navigationController?.navigationBar.barStyle = .black
tabBarController?.tabBar.barStyle = .black
applyConstraintsForInterfaceOrientation(UIApplication.shared.statusBarOrientation)
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval)
{
applyConstraintsForInterfaceOrientation(toInterfaceOrientation)
}
func filterParameterDescriptors() -> [ScalarFilterParameter] {
let inputNames = (filter.inputKeys as [String]).filter { (parameterName) -> Bool in
return (parameterName as String) != "inputImage"
}
let attributes = filter.attributes
return inputNames.compactMap { (inputName: String) -> ScalarFilterParameter? in
let attribute = attributes[inputName] as! [String : AnyObject]
guard attribute[kCIAttributeSliderMin] != nil else { return nil }
// strip "input" from the start of the parameter name to make it more presentation-friendly
let displayName = String(inputName.dropFirst(5))
let minValue = (attribute[kCIAttributeSliderMin] as! NSNumber).floatValue
let maxValue = (attribute[kCIAttributeSliderMax] as! NSNumber).floatValue
let defaultValue = (attribute[kCIAttributeDefault] as! NSNumber).floatValue
return ScalarFilterParameter(name: displayName, key: inputName,
minimumValue: minValue, maximumValue: maxValue, currentValue: defaultValue)
}
}
func addSubviews() {
filteredImageView = FilteredImageView(frame: view.bounds)
filteredImageView.inputImage = UIImage(named: kSampleImageName)
filteredImageView.filter = filter
filteredImageView.contentMode = .scaleAspectFit
filteredImageView.clipsToBounds = true
filteredImageView.backgroundColor = view.backgroundColor
filteredImageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(filteredImageView)
parameterAdjustmentView = ParameterAdjustmentView(frame: view.bounds, parameters: filterParameterDescriptors())
parameterAdjustmentView.translatesAutoresizingMaskIntoConstraints = false
parameterAdjustmentView.setAdjustmentDelegate(filteredImageView)
view.addSubview(parameterAdjustmentView)
}
func applyConstraintsForInterfaceOrientation(_ interfaceOrientation: UIInterfaceOrientation) {
view.removeConstraints(constraints)
constraints.removeAll(keepingCapacity: true)
if interfaceOrientation.isLandscape {
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 0.5, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 1, constant: -66))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .leading, relatedBy: .equal,
toItem: view, attribute: .leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .trailing, relatedBy: .equal,
toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 0.5, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 1, constant: 0))
} else {
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 0.5, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .leading, relatedBy: .equal,
toItem: view, attribute: .leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .bottom, relatedBy: .equal,
toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .leading, relatedBy: .equal,
toItem: view, attribute: .leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 0.5, constant: -88))
}
self.view.addConstraints(constraints)
}
}
| b54ff6b7a199166903f200b42564c802 | 53.869919 | 121 | 0.700104 | false | false | false | false |
Zglove/DouYu | refs/heads/master | DYTV/DYTV/Classes/Home/Controller/FunnyViewController.swift | mit | 1 | //
// FunnyViewController.swift
// DYTV
//
// Created by people on 2016/11/9.
// Copyright © 2016年 people2000. All rights reserved.
//
import UIKit
//MARK:- 定义常量
private let kTopMargin: CGFloat = 8
class FunnyViewController: BaseAnchorViewController {
//MARK:- 懒加载属性
fileprivate lazy var funnyVM: FunnyViewModel = FunnyViewModel()
}
//MARK:- 设置UI界面
extension FunnyViewController {
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0)
}
}
//MARK:- 请求数据
extension FunnyViewController {
override func loadData(){
//1.给父类中的viewmodel进行赋值
baseVM = funnyVM
//2.请求数据
funnyVM.loadFunnyData{
//2.1刷新表格
self.collectionView.reloadData()
//2.2.数据请求完成
self.loadDataFinished()
}
}
}
| d490c5ad4d73a4e3524d3ffc30ed79ff | 18.071429 | 97 | 0.626404 | false | false | false | false |
LiuXingCode/LXScollContentViewSwift | refs/heads/master | LXScrollContentView/LXScrollContentViewLib/LXSegmentBarStyle.swift | mit | 1 | //
// LXSegmentBarStyle.swift
// LXScrollContentView
//
// Created by 刘行 on 2017/5/23.
// Copyright © 2017年 刘行. All rights reserved.
//
import UIKit
public class LXSegmentBarStyle {
var backgroundColor : UIColor = UIColor.white
var normalTitleColor : UIColor = UIColor.black
var selectedTitleColor : UIColor = UIColor.red
var titleFont : UIFont = UIFont.systemFont(ofSize: 14)
var indicatorColor : UIColor = UIColor.red
var indicatorHeight : CGFloat = 2.0
// var indicatorExtraW : CGFloat = 5.0
var indicatorBottomMargin : CGFloat = 0
var itemMinMargin : CGFloat = 24.0
}
| ebfbaa13b38dccbd2d649482606febd9 | 19.75 | 58 | 0.653614 | false | false | false | false |
loiwu/SCoreData | refs/heads/master | Dog Walk/Dog Walk/CoreDataStack.swift | mit | 1 | //
// CoreDataStack.swift
// Dog Walk
//
// Created by loi on 1/26/15.
// Copyright (c) 2015 GWrabbit. All rights reserved.
//
import CoreData
class CoreDataStack {
let context:NSManagedObjectContext
let psc:NSPersistentStoreCoordinator
let model:NSManagedObjectModel
let store:NSPersistentStore?
init() {
// 1 - load the managed object model from disk into a NSManagedObjectModel object.
// getting a URL to the momd directory that contains the compiled version of the .xcdatamodeld file.
let bundle = NSBundle.mainBundle()
let modelURL = bundle.URLForResource("Dog Walk", withExtension: "momd")
model = NSManagedObjectModel(contentsOfURL: modelURL!)!
// 2 - the persistent store coordinator mediates between the persistent store and NSManagedObjectModel
psc = NSPersistentStoreCoordinator(managedObjectModel: model)
// 3 - The NSManagedObjectContext takes no arguments to initialize.
context = NSManagedObjectContext()
context.persistentStoreCoordinator = psc
// 4 - the persistent store coordinator hands you an NSPersistentStore object as a side effect of attaching a persistent store type.
// simply have to specify the store type (NSSQLiteStoreType in this case), the URL location of the store file and some configuration options.
let documentURL = applicationDocumentsDirectory()
let storeURL = documentURL.URLByAppendingPathComponent("Dog Walk")
let options = [NSMigratePersistentStoresAutomaticallyOption: true]
var error: NSError? = nil
store = psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error)
if store == nil {
println("Error adding persistent store: \(error)")
abort()
}
}
func saveContext() {
var error: NSError? = nil
if context.hasChanges && !context.save(&error) {
println("Could not save: \(error), \(error?.userInfo)")
}
}
func applicationDocumentsDirectory() -> NSURL {
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) as [NSURL]
return urls[0]
}
}
| 2c6533438a1a246cd04bbca3e45a6abb | 38.295082 | 149 | 0.665832 | false | false | false | false |
Punch-In/PunchInIOSApp | refs/heads/master | PunchIn/MKButton.swift | mit | 1 | //
// MKButton.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
@IBDesignable
public class MKButton : UIButton
{
@IBInspectable public var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(maskEnabled)
}
}
@IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable public var ripplePercent: Float = 0.9 {
didSet {
mkLayer.ripplePercent = ripplePercent
}
}
@IBInspectable public var backgroundLayerCornerRadius: CGFloat = 0.0 {
didSet {
mkLayer.setBackgroundLayerCornerRadius(backgroundLayerCornerRadius)
}
}
// animations
@IBInspectable public var shadowAniEnabled: Bool = true
@IBInspectable public var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable public var rippleAniDuration: Float = 0.75
@IBInspectable public var backgroundAniDuration: Float = 1.0
@IBInspectable public var shadowAniDuration: Float = 0.65
@IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var shadowAniTimingFunction: MKTimingFunction = .EaseOut
@IBInspectable public var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(rippleLayerColor)
}
}
@IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override public var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
// MARK - initilization
override public init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupLayer()
}
// MARK - setup methods
private func setupLayer() {
adjustsImageWhenHighlighted = false
cornerRadius = 2.5
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setCircleLayerColor(rippleLayerColor)
}
// MARK - location tracking methods
override public func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
if rippleLocation == .TapLocation {
mkLayer.didChangeTapLocation(touch.locationInView(self))
}
// rippleLayer animation
mkLayer.animateScaleForCircleLayer(0.45, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration))
// backgroundLayer animation
if backgroundAniEnabled {
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration))
}
// shadow animation for self
if shadowAniEnabled {
let shadowRadius = layer.shadowRadius
let shadowOpacity = layer.shadowOpacity
let duration = CFTimeInterval(shadowAniDuration)
mkLayer.animateSuperLayerShadow(10, toRadius: shadowRadius, fromOpacity: 0, toOpacity: shadowOpacity, timingFunction: shadowAniTimingFunction, duration: duration)
}
return super.beginTrackingWithTouch(touch, withEvent: event)
}
}
| ce88b411f44af1ea9508f86bdb748a88 | 32.655462 | 174 | 0.666167 | false | false | false | false |
fengweiru/FWRClassifyChooseView | refs/heads/master | swift/FWRClassifyChooseViewDemo/FWRClassifyChooseViewDemo/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// FWRClassifyChooseViewDemo
//
// Created by medzone on 15/11/12.
// Copyright © 2015 medzone. All rights reserved.
//
import UIKit
class ViewController: UIViewController,ClassifyChooseViewProtocol {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "例子"
self.view.backgroundColor = UIColor.whiteColor()
self.automaticallyAdjustsScrollViewInsets = false
let categoryArray:Array<String> = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"]
var detailArray = [NSArray]()
detailArray.append(["0","1","2","3","4","5","6","7","8"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4"])
detailArray.append(["0","1"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
let chooseView = ClassifyChooseView.init(frame: CGRectMake(0, 64, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height-64), sectionArray: categoryArray, itemArray: detailArray)
chooseView!.delegate = self
self.view.addSubview(chooseView!)
}
//MARK:-ClassifyChooseView
func didSelectItemAtIndexPath(indexPath: NSIndexPath) {
let message = String.stringByAppendingFormat("第\(indexPath.section)组第\(indexPath.item)个")
let alert = UIAlertController.init(title: "你点击了", message: "\(message)", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
let cancelAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancelAction)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 8ff9577d3b7427cddde0840295f58e00 | 51.650794 | 269 | 0.540549 | false | false | false | false |
dreamsxin/swift | refs/heads/master | test/Interpreter/SDK/c_pointers.swift | apache-2.0 | 2 | // RUN: rm -rf %t && mkdir %t
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %target-run %t/a.out | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
#if os(OSX)
import AppKit
typealias XXColor = NSColor
#endif
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
typealias XXColor = UIColor
#endif
// Exercise some common APIs that make use of C pointer arguments.
//
// Typed C pointers
//
let rgb = CGColorSpaceCreateDeviceRGB()
let cgRed = CGColor(colorSpace: rgb, components: [1.0, 0.0, 0.0, 1.0])!
let nsRed = XXColor(cgColor: cgRed)
var r: CGFloat = 0.5, g: CGFloat = 0.5, b: CGFloat = 0.5, a: CGFloat = 0.5
#if os(OSX)
nsRed!.getRed(&r, green: &g, blue: &b, alpha: &a)
#else
nsRed.getRed(&r, green: &g, blue: &b, alpha: &a)
#endif
// CHECK-LABEL: Red is:
print("Red is:")
print("<\(r) \(g) \(b) \(a)>") // CHECK-NEXT: <1.0 0.0 0.0 1.0>
//
// Void C pointers
//
// FIXME: Array type annotation should not be required
let data = NSData(bytes: [1.5, 2.25, 3.125] as [Double],
length: sizeof(Double.self) * 3)
var fromData = [0.25, 0.25, 0.25]
let notFromData = fromData
data.getBytes(&fromData, length: sizeof(Double.self) * 3)
// CHECK-LABEL: Data is:
print("Data is:")
print(fromData[0]) // CHECK-NEXT: 1.5
print(fromData[1]) // CHECK-NEXT: 2.25
print(fromData[2]) // CHECK-NEXT: 3.125
// CHECK-LABEL: Independent data is:
print("Independent data is:")
print(notFromData[0]) // CHECK-NEXT: 0.25
print(notFromData[1]) // CHECK-NEXT: 0.25
print(notFromData[2]) // CHECK-NEXT: 0.25
//
// ObjC pointers
//
class Canary: NSObject {
deinit {
print("died")
}
}
var CanaryAssocObjectHandle: UInt8 = 0
// Attach an associated object with a loud deinit so we can see that the
// error died.
func hangCanary(_ o: AnyObject) {
objc_setAssociatedObject(o, &CanaryAssocObjectHandle, Canary(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
// CHECK-LABEL: NSError out:
print("NSError out:")
autoreleasepool {
do {
let s = try NSString(contentsOfFile: "/hopefully/does/not/exist\u{1B}",
encoding: NSUTF8StringEncoding)
_preconditionFailure("file should not actually exist")
} catch {
print(error._code) // CHECK-NEXT: 260
hangCanary(error as NSError)
}
}
// The result error should have died with the autorelease pool
// CHECK-NEXT: died
class DumbString: NSString {
override func character(at x: Int) -> unichar { _preconditionFailure("nope") }
override var length: Int { return 0 }
convenience init(contentsOfFile s: String, encoding: NSStringEncoding) throws {
self.init()
throw NSError(domain: "Malicious Mischief", code: 594, userInfo: nil)
}
}
// CHECK-LABEL: NSError in:
print("NSError in:")
autoreleasepool {
do {
try DumbString(contentsOfFile: "foo", encoding: NSUTF8StringEncoding)
} catch {
print(error._domain) // CHECK-NEXT: Malicious Mischief
print(error._code) // CHECK-NEXT: 594
hangCanary(error as NSError)
}
}
// The result error should have died with the autorelease pool
// CHECK-NEXT: died
let s = "Hello World"
puts(s)
// CHECK-NEXT: Hello World
//
// C function pointers
//
var unsorted = [3, 14, 15, 9, 2, 6, 5]
qsort(&unsorted, unsorted.count, sizeofValue(unsorted[0])) { a, b in
return Int32(UnsafePointer<Int>(a!).pointee - UnsafePointer<Int>(b!).pointee)
}
// CHECK-NEXT: [2, 3, 5, 6, 9, 14, 15]
print(unsorted)
| edbd17e153aa3f69e68d6ccd9509ed04 | 24.58209 | 81 | 0.663652 | false | false | false | false |
belatrix/iOSAllStars | refs/heads/master | AllStarsV2/AllStarsV2/iPhone/Classes/Animations/ContactsToProfileTransition.swift | apache-2.0 | 1 | //
// ContactsToProfileTransition.swift
// AllStarsV2
//
// Created by Kenyi Rodriguez Vergara on 21/08/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
class ContactsToProfileInteractiveTransition : InteractiveTransition{
var initialScale : CGFloat = 0
@objc func gestureTransitionMethod(_ gesture : UIPanGestureRecognizer){
let view = self.navigationController.view!
if gesture.state == .began {
self.interactiveTransition = UIPercentDrivenInteractiveTransition()
self.navigationController.popViewController(animated: true)
}else if gesture.state == .changed{
let translation = gesture.translation(in: view)
let delta = fabs(translation.x / view.bounds.width)
self.interactiveTransition?.update(delta)
}else{
self.interactiveTransition?.finish()
self.interactiveTransition = nil
}
}
}
class ContactsToProfileTransition: ControllerTransition {
override func createInteractiveTransition(navigationController: UINavigationController) -> InteractiveTransition? {
let interactiveTransition = ContactsToProfileInteractiveTransition()
interactiveTransition.navigationController = navigationController
interactiveTransition.gestureTransition = UIPanGestureRecognizer(target: interactiveTransition, action: #selector(interactiveTransition.gestureTransitionMethod(_:)))
interactiveTransition.navigationController.view.addGestureRecognizer(interactiveTransition.gestureTransition!)
return interactiveTransition
}
override func animatePush(toContext context : UIViewControllerContextTransitioning) {
let fromVC = self.controllerOrigin as! ContactsViewController
let toVC = self.controllerDestination as! UserProfileViewController
let cellSelected = fromVC.cellSelected!
let containerView = context.containerView
containerView.backgroundColor = .white
let fromView = context.view(forKey: .from)!
let toView = context.view(forKey: .to)!
fromView.frame = UIScreen.main.bounds
containerView.addSubview(fromView)
toView.frame = UIScreen.main.bounds
containerView.addSubview(toView)
let imgUser = ImageUserProfile()
let relativeFrame = fromVC.clvContacts.convert(cellSelected.frame, to: containerView)
imgUser.frame.origin.x = relativeFrame.origin.x + cellSelected.imgUser.frame.origin.x
imgUser.frame.origin.y = relativeFrame.origin.y + cellSelected.imgUser.frame.origin.y
imgUser.frame.size = cellSelected.imgUser.frame.size
imgUser.objUser = cellSelected.objContact
containerView.addSubview(imgUser)
imgUser.image = cellSelected.imgUser.imgUser.image
let newCenter = CGPoint(x: 78, y: 149)
let delta = 140 / cellSelected.imgUser.frame.size.height
imgUser.setInitialVisualConfiguration()
toVC.constraintTopHeader.constant = -64
toVC.imgUser!.alpha = 0
toVC.viewContainerInfo.alpha = 0
toVC.constraintTopSections.constant = UIScreen.main.bounds.size.height
toVC.constraintBottomSections.constant = UIScreen.main.bounds.size.height
toView.backgroundColor = .clear
cellSelected.imgUser.alpha = 0
containerView.layoutIfNeeded()
UIView.animate(withDuration: 0.2, animations: {
fromView.alpha = 0
}) { (_) in
toView.backgroundColor = .white
UIView.animate(withDuration: 0.2, animations: {
toVC.constraintTopHeader.constant = 0
containerView.layoutIfNeeded()
}, completion: { (_) in
UIView.animate(withDuration: 0.2, animations: {
toVC.viewContainerInfo.alpha = 1
containerView.layoutIfNeeded()
}, completion: { (_) in
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
toVC.constraintTopSections.constant = 0
toVC.constraintBottomSections.constant = 0
containerView.layoutIfNeeded()
}) { (_) in
fromView.alpha = 1
cellSelected.imgUser.alpha = 1
context.completeTransition(true)
}
})
})
}
UIView.animate(withDuration: 0.6, delay: 0.2, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
imgUser.animateBordeWidthFromValue(imgUser.borderImage, toValue: 5 / delta)
imgUser.transform = CGAffineTransform(scaleX: delta, y: delta)
imgUser.center = newCenter
}) { (_) in
imgUser.alpha = 0
toVC.imgUser!.alpha = 1
imgUser.removeFromSuperview()
}
}
override func animatePop(toContext context : UIViewControllerContextTransitioning) {
let fromVC = self.controllerOrigin as! UserProfileViewController
let toVC = self.controllerDestination as! ContactsViewController
let cellSelected = toVC.cellSelected!
let containerView = context.containerView
containerView.backgroundColor = .white
let fromView = context.view(forKey: .from)!
let toView = context.view(forKey: .to)!
let duration = self.transitionDuration(using: context)
toView.frame = UIScreen.main.bounds
containerView.addSubview(toView)
fromView.frame = UIScreen.main.bounds
containerView.addSubview(fromView)
let imgUser = ImageUserProfile()
imgUser.frame = CGRect(x: 8, y: 79, width: 140, height: 140)
imgUser.objUser = fromVC.objUser
imgUser.setInitialVisualConfiguration()
imgUser.image = cellSelected.imgUser.imgUser.image
containerView.addSubview(imgUser)
imgUser.borderImage = 5
fromVC.imgUser!.alpha = 0
toView.alpha = 1
cellSelected.imgUser.alpha = 0
let delta = cellSelected.imgUser.frame.size.height / 140
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
fromVC.constraintTopSections.constant = UIScreen.main.bounds.size.height
fromVC.constraintBottomSections.constant = UIScreen.main.bounds.size.height
fromVC.viewContainerInfo.alpha = 0
fromVC.constraintTopHeader.constant = -64
fromView.backgroundColor = .clear
imgUser.animateBordeWidthFromValue(5, toValue: 0)
imgUser.transform = CGAffineTransform(scaleX: delta, y: delta)
var relativeFrame = toVC.clvContacts.convert(cellSelected.frame, to: containerView)
relativeFrame.origin.x = relativeFrame.origin.x + cellSelected.imgUser.frame.origin.x
relativeFrame.origin.y = relativeFrame.origin.y + cellSelected.imgUser.frame.origin.y
imgUser.center = CGPoint(x: relativeFrame.origin.x + cellSelected.imgUser.frame.size.width / 2, y: relativeFrame.origin.y + cellSelected.imgUser.frame.size.height / 2)
containerView.layoutIfNeeded()
}) { (_) in
imgUser.alpha = 0
cellSelected.imgUser.alpha = 1
imgUser.removeFromSuperview()
context.completeTransition(true)
}
}
override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.9
}
}
| e25e84bfb857d1d6d31cc94d65ad2a1b | 36.662281 | 179 | 0.600792 | false | false | false | false |
brunopinheiro/sabadinho | refs/heads/master | Sabadinho/Controllers/MonthViewController.swift | mit | 1 | //
// MonthViewController.swift
// Sabadinho
//
// Created by Bruno Pinheiro on 14/02/18.
// Copyright © 2018 Bruno Pinheiro. All rights reserved.
//
import Foundation
import UIKit
class MonthViewController: UITableViewController {
private var monthViewModel: MonthViewModel?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.Palette.gray
tableView.separatorStyle = .none
}
func bind(_ monthViewModel: MonthViewModel) {
self.monthViewModel = monthViewModel
tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return monthViewModel?.weeksCount ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return monthViewModel?.daysWithin(week: MonthViewController.weekFrom(section: section)).count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let viewModel = monthViewModel?.day(indexPath.row, ofWeek: MonthViewController.weekFrom(section: indexPath.section)) else {
return UITableViewCell()
}
let cell = MonthTableViewCell()
cell.bind(viewModel)
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = MonthSectionHeaderView()
header.titleLabel?.text = DayViewModel.titleFor(week: MonthViewController.weekFrom(section: section))
return header
}
}
private extension MonthViewController {
static func weekFrom(section: Int) -> Int {
return section + 1
}
}
| 7a2a44837eff26e5e7fab0009a446d3e | 28.053571 | 133 | 0.736325 | false | false | false | false |
maicki/plank | refs/heads/master | Tests/CoreTests/StringExtensionsTests.swift | apache-2.0 | 1 | //
// StringExtensionsTests.swift
// plank
//
// Created by Michael Schneider on 6/16/17.
//
//
import XCTest
@testable import Core
class StringExtensionsTests: XCTestCase {
func testUppercaseFirst() {
XCTAssert("plank".uppercaseFirst == "Plank")
XCTAssert("Plank".uppercaseFirst == "Plank")
XCTAssert("plAnK".uppercaseFirst == "PlAnK")
}
func testLowercaseFirst() {
XCTAssert("Plank".lowercaseFirst == "plank")
XCTAssert("PlAnK".lowercaseFirst == "plAnK")
}
func testSuffixSubstring() {
XCTAssert("plank".suffixSubstring(2) == "nk")
}
func testSnakeCaseToCamelCase() {
XCTAssert("created_at".snakeCaseToCamelCase() == "CreatedAt")
XCTAssert("created_aT".snakeCaseToCamelCase() == "CreatedAT")
XCTAssert("CreatedAt".snakeCaseToCamelCase() == "CreatedAt")
}
func testSnakeCaseToPropertyName() {
XCTAssert("created_at".snakeCaseToPropertyName() == "createdAt")
XCTAssert("CreatedAt".snakeCaseToPropertyName() == "createdAt")
XCTAssert("created_At".snakeCaseToPropertyName() == "createdAt")
XCTAssert("CreatedAt".snakeCaseToPropertyName() == "createdAt")
XCTAssert("CreaTedAt".snakeCaseToPropertyName() == "creaTedAt")
XCTAssert("Created_At".snakeCaseToPropertyName() == "createdAt")
XCTAssert("Test_url".snakeCaseToPropertyName() == "testURL")
XCTAssert("url_test".snakeCaseToPropertyName() == "urlTest")
}
func testSnakeCaseToCapitalizedPropertyName() {
XCTAssert("created_at".snakeCaseToCapitalizedPropertyName() == "CreatedAt")
XCTAssert("CreatedAt".snakeCaseToCapitalizedPropertyName() == "CreatedAt")
}
func testReservedKeywordSubstitution() {
XCTAssert("nil".snakeCaseToCapitalizedPropertyName() == "NilProperty")
}
}
| a44dccd9c4c9afab91b915d79ebed39c | 32.071429 | 83 | 0.670086 | false | true | false | false |
gerbot150/SwiftyFire | refs/heads/master | swift/SwiftyFire/main.swift | mit | 1 | //
// main.swift
// SwiftyJSONModelMaker
//
// Created by Gregory Bateman on 2017-03-03.
// Copyright © 2017 Gregory Bateman. All rights reserved.
//
import Foundation
func main() {
var name: String?
let tokenizer = Tokenizer()
let parser = Parser()
let swiftifier = Swiftifier()
do {
let input: (name: String?, text: String)
try input = getInput()
name = input.name
let text = input.text
try tokenizer.tokenize(text)
try parser.parse(tokens: tokenizer.tokens)
try swiftifier.swiftifyJSON(parser.topLevelNode, with: name)
} catch {
print("ERROR: \(error), program will exit\n")
return
}
printHeader(with: name)
printImports()
print(swiftifier.swiftifiedJSON)
}
func getInput() throws -> (String?, String) {
var name: String? = nil
var text = ""
let arguments = CommandLine.arguments
if arguments.count < 2 { // Input from standard input
while let line = readLine(strippingNewline: true) {
text += line
}
let ignorableCharacters = CharacterSet.controlCharacters.union(CharacterSet.whitespacesAndNewlines)
text = text.trimmingCharacters(in: ignorableCharacters)
} else { // Input from file
do {
try text = String(contentsOfFile: arguments[1], encoding: .utf8)
// These commands are apparently not usable in the current version of
// Swift on linux - or I couldn't find the library to link them properly
// but the characters are handled accordingly in the tokenizer
// text = text.components(separatedBy: "\r").joined(separator: "")
// text = text.components(separatedBy: "\n").joined(separator: "")
// text = text.components(separatedBy: "\t").joined(separator: " ")
name = arguments[1]
while let range = name?.range(of: "/") {
name = name?.substring(from: range.upperBound)
}
if let range = name?.range(of: ".") {
name = name?.substring(to: range.lowerBound)
}
name = name?.capitalCased
} catch {
throw error
}
}
return (name, text)
}
func printHeader(with name: String?) {
print("//")
print("// \(name ?? "Object").swift")
print("//")
print("// Created by SwiftyFire on \(getDate())")
print("// SwiftyFire is a development tool made by Greg Bateman")
print("// It was created to reduce the tedious amount of time required to create")
print("// model classes when using SwiftyJSON to parse JSON in swift")
print("//")
print()
}
func printImports() {
print("import SwiftyJSON")
print()
}
func getDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: Date())
}
main()
| 13f65019bed869b6d9bbf8176df4e206 | 30.365591 | 107 | 0.605074 | false | false | false | false |
CPRTeam/CCIP-iOS | refs/heads/master | Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift | gpl-3.0 | 3 | //
// UInt128.swift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
import Foundation
struct UInt128: Equatable, ExpressibleByIntegerLiteral {
let i: (a: UInt64, b: UInt64)
typealias IntegerLiteralType = UInt64
init(integerLiteral value: IntegerLiteralType) {
self = UInt128(value)
}
init(_ raw: Array<UInt8>) {
self = raw.prefix(MemoryLayout<UInt128>.stride).withUnsafeBytes({ (rawBufferPointer) -> UInt128 in
let arr = rawBufferPointer.bindMemory(to: UInt64.self)
return UInt128((arr[0].bigEndian, arr[1].bigEndian))
})
}
init(_ raw: ArraySlice<UInt8>) {
self.init(Array(raw))
}
init(_ i: (a: UInt64, b: UInt64)) {
self.i = i
}
init(a: UInt64, b: UInt64) {
self.init((a, b))
}
init(_ b: UInt64) {
self.init((0, b))
}
// Bytes
var bytes: Array<UInt8> {
var at = self.i.a.bigEndian
var bt = self.i.b.bigEndian
let ar = Data(bytes: &at, count: MemoryLayout.size(ofValue: at))
let br = Data(bytes: &bt, count: MemoryLayout.size(ofValue: bt))
var result = Data()
result.append(ar)
result.append(br)
return result.bytes
}
static func ^ (n1: UInt128, n2: UInt128) -> UInt128 {
UInt128((n1.i.a ^ n2.i.a, n1.i.b ^ n2.i.b))
}
static func & (n1: UInt128, n2: UInt128) -> UInt128 {
UInt128((n1.i.a & n2.i.a, n1.i.b & n2.i.b))
}
static func >> (value: UInt128, by: Int) -> UInt128 {
var result = value
for _ in 0..<by {
let a = result.i.a >> 1
let b = result.i.b >> 1 + ((result.i.a & 1) << 63)
result = UInt128((a, b))
}
return result
}
// Equatable.
static func == (lhs: UInt128, rhs: UInt128) -> Bool {
lhs.i == rhs.i
}
static func != (lhs: UInt128, rhs: UInt128) -> Bool {
!(lhs == rhs)
}
}
| 60266858a779fd2fb4ffb25b4604aef1 | 28.188889 | 217 | 0.64941 | false | false | false | false |
domenicosolazzo/practice-swift | refs/heads/master | CoreData/Writing to CoreData/Writing to CoreData/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Writing to CoreData
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let entityName = NSStringFromClass(Person.classForCoder())
let person = NSEntityDescription.insertNewObject(
forEntityName: entityName,
into: managedObjectContext!) as! Person
// Current year
let now = Date()
let calendar = Calendar.current
let calendarComponents = (calendar as NSCalendar).components(NSCalendar.Unit.year, from: now)
let year = calendarComponents.year
print("Year \(year)")
person.firstName = "Domenico"
person.lastName = "Solazzo"
person.age = NSNumber(value: (UInt(year!) - UInt(1982)))
print("Current age: \((year! - 1982))")
var savingError: NSError?
do {
try managedObjectContext!.save()
print("Successfully saved the person")
} catch var error1 as NSError {
savingError = error1
if savingError != nil{
print("Error saving the person. Error: \(savingError)")
}
}
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: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Writing_to_CoreData" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
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: "Writing_to_CoreData", 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("Writing_to_CoreData.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 var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
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()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| f743784880dbef25d1f7034c6cd07abe | 49.04698 | 290 | 0.678423 | false | false | false | false |
OctMon/OMExtension | refs/heads/master | OMExtension/OMExtension/Source/UIKit/OMFont.swift | mit | 1 | //
// OMFont.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// 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
#if !os(macOS)
import UIKit
public extension UIFont {
struct OM {
public enum Family: String {
case academyEngravedLET = "Academy Engraved LET"
case alNile = "Al Nile"
case americanTypewriter = "American Typewriter"
case appleColorEmoji = "Apple Color Emoji"
case appleSDGothicNeo = "Apple SD Gothic Neo"
case arial = "Arial"
case arialHebrew = "Arial Hebrew"
case arialRoundedMTBold = "Arial Rounded MT Bold"
case avenir = "Avenir"
case avenirNext = "Avenir Next"
case avenirNextCondensed = "Avenir Next Condensed"
case banglaSangamMN = "Bangla Sangam MN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case baskerville = "Baskerville"
case bodoni72 = "Bodoni 72"
case bodoni72Oldstyle = "Bodoni 72 Oldstyle"
case bodoni72Smallcaps = "Bodoni 72 Smallcaps"
case bodoniOrnaments = "Bodoni Ornaments"
case bradleyHand = "Bradley Hand"
case chalkboardSE = "Chalkboard SE"
case chalkduster = "Chalkduster"
case cochin = "Cochin"
case copperplate = "Copperplate"
case courier = "Courier"
case courierNew = "Courier New"
case damascus = "Damascus"
case devanagariSangamMN = "Devanagari Sangam MN"
case didot = "Didot"
case dINAlternate = "DIN Alternate" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case dINCondensed = "DIN Condensed" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case euphemiaUCAS = "Euphemia UCAS"
case farah = "Farah"
case futura = "Futura"
case geezaPro = "Geeza Pro"
case georgia = "Georgia"
case gillSans = "Gill Sans"
case gujaratiSangamMN = "Gujarati Sangam MN"
case gurmukhiMN = "Gurmukhi MN"
case heitiSC = "Heiti SC"
case heitiTC = "Heiti TC"
case helvetica = "Helvetica"
case helveticaNeue = "Helvetica Neue"
case hiraginoKakuGothicProN = "Hiragino Kaku Gothic ProN"
case hiraginoMinchoProN = "Hiragino Mincho ProN"
case hoeflerText = "Hoefler Text"
case iowanOldStyle = "Iowan Old Style" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case kailasa = "Kailasa"
case kannadaSangamMN = "Kannada Sangam MN"
case khmerSangamMN = "Khmer Sangam MN" /*@available(*, introduced=8.0)*/
case kohinoorBangla = "Kohinoor Bangla" /*@available(*, introduced=8.0)*/
case kohinoorDevanagari = "Kohinoor Devanagari" /*@available(*, introduced=8.0)*/
case laoSangamMN = "Lao Sangam MN" /*@available(*, introduced=8.0)*/
case malayalamSangamMN = "Malayalam Sangam MN"
case marion = "Marion" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case markerFelt = "Marker Felt"
case menlo = "Menlo"
case mishafi = "Mishafi"
case noteworthy = "Noteworthy"
case optima = "Optima"
case oriyaSangamMN = "Oriya Sangam MN"
case palatino = "Palatino"
case papyrus = "Papyrus"
case partyLET = "Party LET"
case savoyeLET = "Savoye LET"
case sinhalaSangamMN = "Sinhala Sangam MN"
case snellRoundhand = "Snell Roundhand"
case superclarendon = "Superclarendon" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case symbol = "Symbol"
case tamilSangamMN = "Tamil Sangam MN"
case teluguSangamMN = "Telugu Sangam MN"
case thonburi = "Thonburi"
case timesNewRoman = "Times New Roman"
case trebuchetMS = "Trebuchet MS"
case verdana = "Verdana"
case zapfDingbats = "Zapf Dingbats"
case zapfino = "Zapfino"
}
public enum Font : String {
case academyEngravedLetPlain = "AcademyEngravedLetPlain"
case alNile = "AlNile"
case alNileBold = "AlNile-Bold"
case americanTypewriter = "AmericanTypewriter"
case americanTypewriterBold = "AmericanTypewriter-Bold"
case americanTypewriterCondensed = "AmericanTypewriter-Condensed"
case americanTypewriterCondensedBold = "AmericanTypewriter-CondensedBold"
case americanTypewriterCondensedLight = "AmericanTypewriter-CondensedLight"
case americanTypewriterLight = "AmericanTypewriter-Light"
case appleColorEmoji = "AppleColorEmoji"
case appleSDGothicNeoBold = "AppleSDGothicNeo-Bold"
case appleSDGothicNeoLight = "AppleSDGothicNeo-Light"
case appleSDGothicNeoMedium = "AppleSDGothicNeo-Medium"
case appleSDGothicNeoRegular = "AppleSDGothicNeo-Regular"
case appleSDGothicNeoSemiBold = "AppleSDGothicNeo-SemiBold"
case appleSDGothicNeoThin = "AppleSDGothicNeo-Thin"
case appleSDGothicNeoUltraLight = "AppleSDGothicNeo-UltraLight" /*@available(*, introduced=9.0)*/
case arialBoldItalicMT = "Arial-BoldItalicMT"
case arialBoldMT = "Arial-BoldMT"
case arialHebrew = "ArialHebrew"
case arialHebrewBold = "ArialHebrew-Bold"
case arialHebrewLight = "ArialHebrew-Light"
case arialItalicMT = "Arial-ItalicMT"
case arialMT = "ArialMT"
case arialRoundedMTBold = "ArialRoundedMTBold"
case aSTHeitiLight = "ASTHeiti-Light"
case aSTHeitiMedium = "ASTHeiti-Medium"
case avenirBlack = "Avenir-Black"
case avenirBlackOblique = "Avenir-BlackOblique"
case avenirBook = "Avenir-Book"
case avenirBookOblique = "Avenir-BookOblique"
case avenirHeavyOblique = "Avenir-HeavyOblique"
case avenirHeavy = "Avenir-Heavy"
case avenirLight = "Avenir-Light"
case avenirLightOblique = "Avenir-LightOblique"
case avenirMedium = "Avenir-Medium"
case avenirMediumOblique = "Avenir-MediumOblique"
case avenirNextBold = "AvenirNext-Bold"
case avenirNextBoldItalic = "AvenirNext-BoldItalic"
case avenirNextCondensedBold = "AvenirNextCondensed-Bold"
case avenirNextCondensedBoldItalic = "AvenirNextCondensed-BoldItalic"
case avenirNextCondensedDemiBold = "AvenirNextCondensed-DemiBold"
case avenirNextCondensedDemiBoldItalic = "AvenirNextCondensed-DemiBoldItalic"
case avenirNextCondensedHeavy = "AvenirNextCondensed-Heavy"
case avenirNextCondensedHeavyItalic = "AvenirNextCondensed-HeavyItalic"
case avenirNextCondensedItalic = "AvenirNextCondensed-Italic"
case avenirNextCondensedMedium = "AvenirNextCondensed-Medium"
case avenirNextCondensedMediumItalic = "AvenirNextCondensed-MediumItalic"
case avenirNextCondensedRegular = "AvenirNextCondensed-Regular"
case avenirNextCondensedUltraLight = "AvenirNextCondensed-UltraLight"
case avenirNextCondensedUltraLightItalic = "AvenirNextCondensed-UltraLightItalic"
case avenirNextDemiBold = "AvenirNext-DemiBold"
case avenirNextDemiBoldItalic = "AvenirNext-DemiBoldItalic"
case avenirNextHeavy = "AvenirNext-Heavy"
case avenirNextItalic = "AvenirNext-Italic"
case avenirNextMedium = "AvenirNext-Medium"
case avenirNextMediumItalic = "AvenirNext-MediumItalic"
case avenirNextRegular = "AvenirNext-Regular"
case avenirNextUltraLight = "AvenirNext-UltraLight"
case avenirNextUltraLightItalic = "AvenirNext-UltraLightItalic"
case avenirOblique = "Avenir-Oblique"
case avenirRoman = "Avenir-Roman"
case banglaSangamMN = "BanglaSangamMN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case banglaSangamMNBold = "BanglaSangamMN-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case baskerville = "Baskerville"
case baskervilleBold = "Baskerville-Bold"
case baskervilleBoldItalic = "Baskerville-BoldItalic"
case baskervilleItalic = "Baskerville-Italic"
case baskervilleSemiBold = "Baskerville-SemiBold"
case baskervilleSemiBoldItalic = "Baskerville-SemiBoldItalic"
case bodoniOrnamentsITCTT = "BodoniOrnamentsITCTT"
case bodoniSvtyTwoITCTTBold = "BodoniSvtyTwoITCTT-Bold"
case bodoniSvtyTwoITCTTBook = "BodoniSvtyTwoITCTT-Book"
case bodoniSvtyTwoITCTTBookIta = "BodoniSvtyTwoITCTT-BookIta"
case bodoniSvtyTwoOSITCTTBold = "BodoniSvtyTwoOSITCTT-Bold"
case bodoniSvtyTwoOSITCTTBook = "BodoniSvtyTwoOSITCTT-Book"
case bodoniSvtyTwoOSITCTTBookIt = "BodoniSvtyTwoOSITCTT-BookIt"
case bodoniSvtyTwoSCITCTTBook = "BodoniSvtyTwoSCITCTT-Book"
case bradleyHandITCTTBold = "BradleyHandITCTT-Bold"
case chalkboardSEBold = "ChalkboardSE-Bold"
case chalkboardSELight = "ChalkboardSE-Light"
case chalkboardSERegular = "ChalkboardSE-Regular"
case chalkduster = "Chalkduster"
case cochin = "Cochin"
case cochinBold = "Cochin-Bold"
case cochinBoldItalic = "Cochin-BoldItalic"
case cochinItalic = "Cochin-Italic"
case copperplate = "Copperplate"
case copperplateBold = "Copperplate-Bold"
case copperplateLight = "Copperplate-Light"
case courier = "Courier"
case courierBold = "Courier-Bold"
case courierBoldOblique = "Courier-BoldOblique"
case courierNewPSBoldItalicMT = "CourierNewPS-BoldItalicMT"
case courierNewPSBoldMT = "CourierNewPS-BoldMT"
case courierNewPSItalicMT = "CourierNewPS-ItalicMT"
case courierNewPSMT = "CourierNewPSMT"
case courierOblique = "Courier-Oblique"
case damascus = "Damascus"
case damascusBold = "DamascusBold"
case damascusMedium = "DamascusMedium"
case damascusSemiBold = "DamascusSemiBold"
case devanagariSangamMN = "DevanagariSangamMN"
case devanagariSangamMNBold = "DevanagariSangamMN-Bold"
case didot = "Didot"
case didotBold = "Didot-Bold"
case didotItalic = "Didot-Italic"
case dINAlternateBold = "DINAlternate-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case dINCondensedBold = "DINCondensed-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case diwanMishafi = "DiwanMishafi"
case euphemiaUCAS = "EuphemiaUCAS"
case euphemiaUCASBold = "EuphemiaUCAS-Bold"
case euphemiaUCASItalic = "EuphemiaUCAS-Italic"
case farah = "Farah"
case futuraCondensedExtraBold = "Futura-ExtraBold"
case futuraCondensedMedium = "Futura-CondensedMedium"
case futuraMedium = "Futura-Medium"
case futuraMediumItalicm = "Futura-MediumItalic"
case geezaPro = "GeezaPro"
case geezaProBold = "GeezaPro-Bold"
case geezaProLight = "GeezaPro-Light"
case georgia = "Georgia"
case georgiaBold = "Georgia-Bold"
case georgiaBoldItalic = "Georgia-BoldItalic"
case georgiaItalic = "Georgia-Italic"
case gillSans = "GillSans"
case gillSansBold = "GillSans-Bold"
case gillSansBoldItalic = "GillSans-BoldItalic"
case gillSansItalic = "GillSans-Italic"
case gillSansLight = "GillSans-Light"
case gillSansLightItalic = "GillSans-LightItalic"
case gujaratiSangamMN = "GujaratiSangamMN"
case gujaratiSangamMNBold = "GujaratiSangamMN-Bold"
case gurmukhiMN = "GurmukhiMN"
case gurmukhiMNBold = "GurmukhiMN-Bold"
case helvetica = "Helvetica"
case helveticaBold = "Helvetica-Bold"
case helveticaBoldOblique = "Helvetica-BoldOblique"
case helveticaLight = "Helvetica-Light"
case helveticaLightOblique = "Helvetica-LightOblique"
case helveticaNeue = "HelveticaNeue"
case helveticaNeueBold = "HelveticaNeue-Bold"
case helveticaNeueBoldItalic = "HelveticaNeue-BoldItalic"
case helveticaNeueCondensedBlack = "HelveticaNeue-CondensedBlack"
case helveticaNeueCondensedBold = "HelveticaNeue-CondensedBold"
case helveticaNeueItalic = "HelveticaNeue-Italic"
case helveticaNeueLight = "HelveticaNeue-Light"
case helveticaNeueMedium = "HelveticaNeue-Medium"
case helveticaNeueMediumItalic = "HelveticaNeue-MediumItalic"
case helveticaNeueThin = "HelveticaNeue-Thin"
case helveticaNeueThinItalic = "HelveticaNeue-ThinItalic"
case helveticaNeueUltraLight = "HelveticaNeue-UltraLight"
case helveticaNeueUltraLightItalic = "HelveticaNeue-UltraLightItalic"
case helveticaOblique = "Helvetica-Oblique"
case hiraKakuProNW3 = "HiraKakuProN-W3"
case hiraKakuProNW6 = "HiraKakuProN-W6"
case hiraMinProNW3 = "HiraMinProN-W3"
case hiraMinProNW6 = "HiraMinProN-W6"
case hoeflerTextBlack = "HoeflerText-Black"
case hoeflerTextBlackItalic = "HoeflerText-BlackItalic"
case hoeflerTextItalic = "HoeflerText-Italic"
case hoeflerTextRegular = "HoeflerText-Regular"
case iowanOldStyleBold = "IowanOldStyle-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case iowanOldStyleBoldItalic = "IowanOldStyle-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case iowanOldStyleItalic = "IowanOldStyle-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case iowanOldStyleRoman = "IowanOldStyle-Roman" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case kailasa = "Kailasa"
case kailasaBold = "Kailasa-Bold"
case kannadaSangamMN = "KannadaSangamMN"
case kannadaSangamMNBold = "KannadaSangamMN-Bold"
case khmerSangamMN = "KhmerSangamMN" /*@available(*, introduced=8.0)*/
case kohinoorBanglaLight = "KohinoorBangla-Light" /*@available(*, introduced=9.0)*/
case kohinoorBanglaMedium = "KohinoorBangla-Medium" /*@available(*, introduced=9.0)*/
case kohinoorBanglaRegular = "KohinoorBangla-Regular" /*@available(*, introduced=9.0)*/
case kohinoorDevanagariLight = "KohinoorDevanagari-Light" /*@available(*, introduced=8.0)*/
case kohinoorDevanagariMedium = "KohinoorDevanagari-Medium" /*@available(*, introduced=8.0)*/
case kohinoorDevanagariBook = "KohinoorDevanagari-Book" /*@available(*, introduced=8.0)*/
case laoSangamMN = "LaoSangamMN" /*@available(*, introduced=8.0)*/
case malayalamSangamMN = "MalayalamSangamMN"
case malayalamSangamMNBold = "MalayalamSangamMN-Bold"
case marionBold = "Marion-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case marionItalic = "Marion-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case marionRegular = "Marion-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case markerFeltThin = "MarkerFelt-Thin"
case markerFeltWide = "MarkerFelt-Wide"
case menloBold = "Menlo-Bold"
case menloBoldItalic = "Menlo-BoldItalic"
case menloItalic = "Menlo-Italic"
case menloRegular = "Menlo-Regular"
case noteworthyBold = "Noteworthy-Bold"
case noteworthyLight = "Noteworthy-Light"
case optimaBold = "Optima-Bold"
case optimaBoldItalic = "Optima-BoldItalic"
case optimaExtraBlack = "Optima-ExtraBold"
case optimaItalic = "Optima-Italic"
case optimaRegular = "Optima-Regular"
case oriyaSangamMN = "OriyaSangamMN"
case oriyaSangamMNBold = "OriyaSangamMN-Bold"
case palatinoBold = "Palatino-Bold"
case palatinoBoldItalic = "Palatino-BoldItalic"
case palatinoItalic = "Palatino-Italic"
case palatinoRoman = "Palatino-Roman"
case papyrus = "Papyrus"
case papyrusCondensed = "Papyrus-Condensed"
case partyLetPlain = "PartyLetPlain"
case savoyeLetPlain = "SavoyeLetPlain"
case sinhalaSangamMN = "SinhalaSangamMN"
case sinhalaSangamMNBold = "SinhalaSangamMN-Bold"
case snellRoundhand = "SnellRoundhand"
case snellRoundhandBlack = "SnellRoundhand-Black"
case snellRoundhandBold = "SnellRoundhand-Bold"
case sTHeitiSCLight = "STHeitiSC-Light"
case sTHeitiSCMedium = "STHeitiSC-Medium"
case sTHeitiTCLight = "STHeitiTC-Light"
case sTHeitiTCMedium = "STHeitiTC-Medium"
case superclarendonBlack = "Superclarendon-Black" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonBlackItalic = "Superclarendon-BalckItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonBold = "Superclarendon-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonBoldItalic = "Superclarendon-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonItalic = "Superclarendon-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonLight = "Superclarendon-Light" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonLightItalic = "Superclarendon-LightItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonRegular = "Superclarendon-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case symbol = "Symbol"
case tamilSangamMN = "TamilSangamMN"
case tamilSangamMNBold = "TamilSangamMN-Bold"
case teluguSangamMN = "TeluguSangamMN"
case teluguSangamMNBold = "TeluguSangamMN-Bold"
case thonburi = "Thonburi"
case thonburiBold = "Thonburi-Bold"
case thonburiLight = "Thonburi-Light"
case timesNewRomanPSBoldItalicMT = "TimesNewRomanPS-BoldItalic"
case timesNewRomanPSBoldMT = "TimesNewRomanPS-Bold"
case timesNewRomanPSItalicMT = "TimesNewRomanPS-ItalicMT"
case timesNewRomanPSMT = "TimesNewRomanPSMT"
case trebuchetBoldItalic = "Trebuchet-BoldItalic"
case trebuchetMS = "TrebuchetMS"
case trebuchetMSBold = "TrebuchetMS-Bold"
case trebuchetMSItalic = "TrebuchetMS-Italic"
case verdana = "Verdana"
case verdanaBold = "Verdana-Bold"
case verdanaBoldItalic = "Verdana-BoldItalic"
case verdanaItalic = "Verdana-Italic"
}
}
convenience init?(omFontName: OM.Font, size: CGFloat) {
self.init(name: omFontName.rawValue, size: size)
}
}
#endif
| b0ee49b18ce7f7fccb43b6e4450c0485 | 58.817439 | 173 | 0.651073 | false | false | false | false |
cliffpanos/True-Pass-iOS | refs/heads/master | iOSApp/CheckIn/Managers/PassManager.swift | apache-2.0 | 1 | //
// PassManager.swift
// True Pass
//
// Created by Cliff Panos on 8/6/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import UIKit
import CoreData
class PassManager {
//MARK: - Handle Guest Pass Functionality with Core Data
static func save(pass: TPPass?, firstName: String, lastName: String, andEmail email: String, andImage imageData: Data?, from startTime: Date, to endTime: Date, forLocation locationID: String) -> TPPass {
let managedContext = C.appDelegate.persistentContainer.viewContext
let pass = pass ?? TPPass(.TPPass)
pass.firstName = firstName
pass.lastName = lastName
pass.email = email
pass.startDate = startTime
pass.endDate = endTime
pass.accessCodeQR = "\(Date().addingTimeInterval(TimeInterval(arc4random())).timeIntervalSince1970)"
pass.isActive = true
pass.didCheckIn = false
pass.locationIdentifier = locationID
pass.phoneNumber = ""
if let data = imageData, let image = UIImage(data: data) {
print("OLD IMAGE SIZE: \(data.count)")
let resizedImage = image.drawAspectFill(in: CGRect(x: 0, y: 0, width: 240, height: 240))
let reducedData = UIImagePNGRepresentation(resizedImage)
print("NEW IMAGE SIZE: \(reducedData!.count)")
pass.imageData = data
}
let passService = FirebaseService(entity: .TPPass)
let identifier = passService.newIdentifierKey
passService.enterData(forIdentifier: identifier, data: pass)
passService.addChildData(forIdentifier: identifier, key: "startDate", value: pass.startDate!.timeIntervalSince1970)
passService.addChildData(forIdentifier: identifier, key: "endDate", value: pass.endDate!.timeIntervalSince1970)
let passListService = FirebaseService(entity: .TPPassList)
passListService.addChildData(forIdentifier: Accounts.userIdentifier, key: identifier, value: locationID)
passListService.addChildData(forIdentifier: locationID, key: identifier, value: Accounts.userIdentifier)
//passListService.reference.child(Accounts.userIdentifier).setValue(locationID)
//passListService.reference.child(locationID).setValue(Accounts.userIdentifier)
guard let data = pass.imageData as Data? else { return pass }
FirebaseStorage.shared.uploadImage(data: data, for: .TPPass, withIdentifier: identifier) { metadata, error in
if let error = error { print("Error uploading pass image!!") }
}
defer {
let passData = PassManager.preparedData(forPass: pass)
let newPassInfo = [WCD.KEY: WCD.singleNewPass, WCD.passPayload: passData] as [String : Any]
C.session?.transferUserInfo(newPassInfo)
}
return pass
}
static func delete(pass: TPPass, andInformWatchKitApp sendMessage: Bool = true) -> Bool {
//DELETE PASS FROM FIREBASE
let passListService = FirebaseService(entity: .TPPassList)
//Remove from TPPassList/locationIdentifier/passIdentifier
passListService.reference.child(pass.locationIdentifier!).child(pass.identifier!).removeValue()
//Remove from TPPassList/userIdentifier/passIdentifier
passListService.reference.child(Accounts.userIdentifier).child(pass.identifier!).removeValue()
let passService = FirebaseService(entity: .TPPass)
passService.reference.child(pass.identifier!).removeValue()
FirebaseStorage.shared.deleteImage(forEntity: .TPPass, withIdentifier: pass.identifier!)
let data = PassManager.preparedData(forPass: pass, includingImage: false) //Do NOT include image
defer {
if sendMessage {
let deletePassInfo = [WCD.KEY: WCD.deletePass, WCD.passPayload: data] as [String : Any]
C.session?.transferUserInfo(deletePassInfo)
}
}
if let vc = UIWindow.presented.viewController as? PassDetailViewController {
vc.navigationController?.popViewController(animated: true)
}
return true
}
static func preparedData(forPass pass: TPPass, includingImage: Bool = true) -> Data {
var dictionary = pass.dictionaryWithValues(forKeys: ["name", "email", "startDate", "endDate", "didCheckIn"])
if includingImage, let imageData = pass.imageData as Data?, let image = UIImage(data: imageData) {
let res = 60.0
let resizedImage = image.drawAspectFill(in: CGRect(x: 0, y: 0, width: res, height: res))
let reducedData = UIImagePNGRepresentation(resizedImage)
print("Contact Image Message Size: \(reducedData?.count ?? 0)")
dictionary["image"] = reducedData
} else {
dictionary["image"] = nil
}
return NSKeyedArchiver.archivedData(withRootObject: dictionary) //Binary data
}
}
| f860dd07085bf6fcc4db6c846ff10953 | 41.154472 | 207 | 0.641273 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.