repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vector-im/vector-ios | RiotSwiftUI/Modules/Room/NotificationSettings/Coordinator/RoomNotificationSettingsCoordinator.swift | 1 | 4156 | //
// 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
import SwiftUI
final class RoomNotificationSettingsCoordinator: RoomNotificationSettingsCoordinatorType {
// MARK: - Properties
// MARK: Private
private var roomNotificationSettingsViewModel: RoomNotificationSettingsViewModelType
private let roomNotificationSettingsViewController: UIViewController
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: RoomNotificationSettingsCoordinatorDelegate?
// MARK: - Setup
init(room: MXRoom, presentedModally: Bool = true) {
let roomNotificationService = MXRoomNotificationSettingsService(room: room)
let avatarData: AvatarProtocol?
let showAvatar = presentedModally
if #available(iOS 14.0.0, *) {
avatarData = showAvatar ? AvatarInput(
mxContentUri: room.summary.avatar,
matrixItemId: room.roomId,
displayName: room.summary.displayname
) : nil
} else {
avatarData = showAvatar ? RoomAvatarViewData(
roomId: room.roomId,
displayName: room.summary.displayname,
avatarUrl: room.summary.avatar,
mediaManager: room.mxSession.mediaManager
) : nil
}
let viewModel: RoomNotificationSettingsViewModel
let viewController: UIViewController
if #available(iOS 14.0.0, *) {
let swiftUIViewModel = RoomNotificationSettingsSwiftUIViewModel(
roomNotificationService: roomNotificationService,
avatarData: avatarData,
displayName: room.summary.displayname,
roomEncrypted: room.summary.isEncrypted)
let avatarService: AvatarServiceProtocol = AvatarService(mediaManager: room.mxSession.mediaManager)
let view = RoomNotificationSettings(viewModel: swiftUIViewModel, presentedModally: presentedModally)
.addDependency(avatarService)
let host = VectorHostingController(rootView: view)
viewModel = swiftUIViewModel
viewController = host
} else {
viewModel = RoomNotificationSettingsViewModel(
roomNotificationService: roomNotificationService,
avatarData: avatarData,
displayName: room.summary.displayname,
roomEncrypted: room.summary.isEncrypted)
viewController = RoomNotificationSettingsViewController.instantiate(with: viewModel)
}
self.roomNotificationSettingsViewModel = viewModel
self.roomNotificationSettingsViewController = viewController
}
// MARK: - Public methods
func start() {
self.roomNotificationSettingsViewModel.coordinatorDelegate = self
}
func toPresentable() -> UIViewController {
return self.roomNotificationSettingsViewController
}
}
// MARK: - RoomNotificationSettingsViewModelCoordinatorDelegate
extension RoomNotificationSettingsCoordinator: RoomNotificationSettingsViewModelCoordinatorDelegate {
func roomNotificationSettingsViewModelDidComplete(_ viewModel: RoomNotificationSettingsViewModelType) {
self.delegate?.roomNotificationSettingsCoordinatorDidComplete(self)
}
func roomNotificationSettingsViewModelDidCancel(_ viewModel: RoomNotificationSettingsViewModelType) {
self.delegate?.roomNotificationSettingsCoordinatorDidCancel(self)
}
}
| apache-2.0 | 0d4166fea5eb333265917fba8ee12018 | 38.961538 | 112 | 0.692974 | 5.828892 | false | false | false | false |
joalbright/Relax | Example/Relax/ItunesTVC.swift | 1 | 1443 | //
// ItunesTVC.swift
// Relax
//
// Created by Jo Albright on 1/15/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
class ItunesTVC: UITableViewController {
var items: [ItunesMedia] = []
override func viewDidLoad() {
super.viewDidLoad()
ItunesAPI.session().start()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
search("daft+punk", entity: "album")
}
func search(_ term: String, entity: String) {
var search = ItunesAPI.Endpoints.search.endpoint
search.parameters = ["term" : term, "entity" : entity]
ItunesSearch.makeRequest(search) {
self.items = $0.results
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EntityCell", for: indexPath)
let item = items[indexPath.row]
cell.textLabel?.text = item.collectionName
cell.detailTextLabel?.text = item.artistName
return cell
}
}
| mit | 3df55e1d30da2607933035df4eb6b96d | 23.440678 | 119 | 0.574896 | 5.041958 | false | false | false | false |
remypanicker/firefox-ios | Account/FxAState.swift | 33 | 12581 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
import Shared
// The version of the state schema we persist.
let StateSchemaVersion = 1
// We want an enum because the set of states is closed. However, each state has state-specific
// behaviour, and the state's behaviour accumulates, so each state is a class. Switch on the
// label to get exhaustive cases.
public enum FxAStateLabel: String {
case EngagedBeforeVerified = "engagedBeforeVerified"
case EngagedAfterVerified = "engagedAfterVerified"
case CohabitingBeforeKeyPair = "cohabitingBeforeKeyPair"
case CohabitingAfterKeyPair = "cohabitingAfterKeyPair"
case Married = "married"
case Separated = "separated"
case Doghouse = "doghouse"
// See http://stackoverflow.com/a/24137319
static let allValues: [FxAStateLabel] = [
EngagedBeforeVerified,
EngagedAfterVerified,
CohabitingBeforeKeyPair,
CohabitingAfterKeyPair,
Married,
Separated,
Doghouse,
]
}
public enum FxAActionNeeded {
case None
case NeedsVerification
case NeedsPassword
case NeedsUpgrade
}
func stateFromJSON(json: JSON) -> FxAState? {
if json.isError {
return nil
}
if let version = json["version"].asInt {
if version == StateSchemaVersion {
return stateFromJSONV1(json)
}
}
return nil
}
func stateFromJSONV1(json: JSON) -> FxAState? {
if let labelString = json["label"].asString {
if let label = FxAStateLabel(rawValue: labelString) {
switch label {
case .EngagedBeforeVerified:
if let
sessionToken = json["sessionToken"].asString?.hexDecodedData,
keyFetchToken = json["keyFetchToken"].asString?.hexDecodedData,
unwrapkB = json["unwrapkB"].asString?.hexDecodedData,
knownUnverifiedAt = json["knownUnverifiedAt"].asInt64,
lastNotifiedUserAt = json["lastNotifiedUserAt"].asInt64 {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: UInt64(knownUnverifiedAt), lastNotifiedUserAt: UInt64(lastNotifiedUserAt),
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .EngagedAfterVerified:
if let
sessionToken = json["sessionToken"].asString?.hexDecodedData,
keyFetchToken = json["keyFetchToken"].asString?.hexDecodedData,
unwrapkB = json["unwrapkB"].asString?.hexDecodedData {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .CohabitingBeforeKeyPair:
if let
sessionToken = json["sessionToken"].asString?.hexDecodedData,
kA = json["kA"].asString?.hexDecodedData,
kB = json["kB"].asString?.hexDecodedData {
return CohabitingBeforeKeyPairState(sessionToken: sessionToken, kA: kA, kB: kB)
}
case .CohabitingAfterKeyPair:
if let
sessionToken = json["sessionToken"].asString?.hexDecodedData,
kA = json["kA"].asString?.hexDecodedData,
kB = json["kB"].asString?.hexDecodedData,
keyPairJSON = JSON.unwrap(json["keyPair"]) as? [String: AnyObject],
keyPair = RSAKeyPair(JSONRepresentation: keyPairJSON),
keyPairExpiresAt = json["keyPairExpiresAt"].asInt64 {
return CohabitingAfterKeyPairState(sessionToken: sessionToken, kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt))
}
case .Married:
if let
sessionToken = json["sessionToken"].asString?.hexDecodedData,
kA = json["kA"].asString?.hexDecodedData,
kB = json["kB"].asString?.hexDecodedData,
keyPairJSON = JSON.unwrap(json["keyPair"]) as? [String: AnyObject],
keyPair = RSAKeyPair(JSONRepresentation: keyPairJSON),
keyPairExpiresAt = json["keyPairExpiresAt"].asInt64,
certificate = json["certificate"].asString,
certificateExpiresAt = json["certificateExpiresAt"].asInt64 {
return MarriedState(sessionToken: sessionToken, kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt),
certificate: certificate, certificateExpiresAt: UInt64(certificateExpiresAt))
}
case .Separated:
return SeparatedState()
case .Doghouse:
return DoghouseState()
}
}
}
return nil
}
// Not an externally facing state!
public class FxAState: JSONLiteralConvertible {
public var label: FxAStateLabel { return FxAStateLabel.Separated } // This is bogus, but we have to do something!
public var actionNeeded: FxAActionNeeded {
// Kind of nice to have this in one place.
switch label {
case .EngagedBeforeVerified: return .NeedsVerification
case .EngagedAfterVerified: return .None
case .CohabitingBeforeKeyPair: return .None
case .CohabitingAfterKeyPair: return .None
case .Married: return .None
case .Separated: return .NeedsPassword
case .Doghouse: return .NeedsUpgrade
}
}
public func asJSON() -> JSON {
return JSON([
"version": StateSchemaVersion,
"label": self.label.rawValue,
])
}
}
public class SeparatedState: FxAState {
override public var label: FxAStateLabel { return FxAStateLabel.Separated }
override public init() {
super.init()
}
}
// Not an externally facing state!
public class ReadyForKeys: FxAState {
let sessionToken: NSData
let keyFetchToken: NSData
let unwrapkB: NSData
init(sessionToken: NSData, keyFetchToken: NSData, unwrapkB: NSData) {
self.sessionToken = sessionToken
self.keyFetchToken = keyFetchToken
self.unwrapkB = unwrapkB
super.init()
}
public override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().asDictionary!
d["sessionToken"] = JSON(sessionToken.hexEncodedString)
d["keyFetchToken"] = JSON(keyFetchToken.hexEncodedString)
d["unwrapkB"] = JSON(unwrapkB.hexEncodedString)
return JSON(d)
}
}
public class EngagedBeforeVerifiedState: ReadyForKeys {
override public var label: FxAStateLabel { return FxAStateLabel.EngagedBeforeVerified }
// Timestamp, in milliseconds after the epoch, when we first knew the account was unverified.
// Use this to avoid nagging the user to verify her account immediately after connecting.
let knownUnverifiedAt: Timestamp
let lastNotifiedUserAt: Timestamp
public init(knownUnverifiedAt: Timestamp, lastNotifiedUserAt: Timestamp, sessionToken: NSData, keyFetchToken: NSData, unwrapkB: NSData) {
self.knownUnverifiedAt = knownUnverifiedAt
self.lastNotifiedUserAt = lastNotifiedUserAt
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
public override func asJSON() -> JSON {
var d = super.asJSON().asDictionary!
d["knownUnverifiedAt"] = JSON(NSNumber(unsignedLongLong: knownUnverifiedAt))
d["lastNotifiedUserAt"] = JSON(NSNumber(unsignedLongLong: lastNotifiedUserAt))
return JSON(d)
}
func withUnwrapKey(unwrapkB: NSData) -> EngagedBeforeVerifiedState {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: knownUnverifiedAt, lastNotifiedUserAt: lastNotifiedUserAt,
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
public class EngagedAfterVerifiedState: ReadyForKeys {
override public var label: FxAStateLabel { return FxAStateLabel.EngagedAfterVerified }
override public init(sessionToken: NSData, keyFetchToken: NSData, unwrapkB: NSData) {
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
func withUnwrapKey(unwrapkB: NSData) -> EngagedAfterVerifiedState {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
// Not an externally facing state!
public class TokenAndKeys: FxAState {
let sessionToken: NSData
public let kA: NSData
public let kB: NSData
init(sessionToken: NSData, kA: NSData, kB: NSData) {
self.sessionToken = sessionToken
self.kA = kA
self.kB = kB
super.init()
}
public override func asJSON() -> JSON {
var d = super.asJSON().asDictionary!
d["sessionToken"] = JSON(sessionToken.hexEncodedString)
d["kA"] = JSON(kA.hexEncodedString)
d["kB"] = JSON(kB.hexEncodedString)
return JSON(d)
}
}
public class CohabitingBeforeKeyPairState: TokenAndKeys {
override public var label: FxAStateLabel { return FxAStateLabel.CohabitingBeforeKeyPair }
}
// Not an externally facing state!
public class TokenKeysAndKeyPair: TokenAndKeys {
let keyPair: KeyPair
// Timestamp, in milliseconds after the epoch, when keyPair expires. After this time, generate a new keyPair.
let keyPairExpiresAt: Timestamp
init(sessionToken: NSData, kA: NSData, kB: NSData, keyPair: KeyPair, keyPairExpiresAt: Timestamp) {
self.keyPair = keyPair
self.keyPairExpiresAt = keyPairExpiresAt
super.init(sessionToken: sessionToken, kA: kA, kB: kB)
}
public override func asJSON() -> JSON {
var d = super.asJSON().asDictionary!
d["keyPair"] = JSON(keyPair.JSONRepresentation())
d["keyPairExpiresAt"] = JSON(NSNumber(unsignedLongLong: keyPairExpiresAt))
return JSON(d)
}
func isKeyPairExpired(now: Timestamp) -> Bool {
return keyPairExpiresAt < now
}
}
public class CohabitingAfterKeyPairState: TokenKeysAndKeyPair {
override public var label: FxAStateLabel { return FxAStateLabel.CohabitingAfterKeyPair }
}
public class MarriedState: TokenKeysAndKeyPair {
override public var label: FxAStateLabel { return FxAStateLabel.Married }
let certificate: String
let certificateExpiresAt: Timestamp
init(sessionToken: NSData, kA: NSData, kB: NSData, keyPair: KeyPair, keyPairExpiresAt: Timestamp, certificate: String, certificateExpiresAt: Timestamp) {
self.certificate = certificate
self.certificateExpiresAt = certificateExpiresAt
super.init(sessionToken: sessionToken, kA: kA, kB: kB, keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
}
public override func asJSON() -> JSON {
var d = super.asJSON().asDictionary!
d["certificate"] = JSON(certificate)
d["certificateExpiresAt"] = JSON(NSNumber(unsignedLongLong: certificateExpiresAt))
return JSON(d)
}
func isCertificateExpired(now: Timestamp) -> Bool {
return certificateExpiresAt < now
}
func withoutKeyPair() -> CohabitingBeforeKeyPairState {
let newState = CohabitingBeforeKeyPairState(sessionToken: sessionToken,
kA: kA, kB: kB)
return newState
}
func withoutCertificate() -> CohabitingAfterKeyPairState {
let newState = CohabitingAfterKeyPairState(sessionToken: sessionToken,
kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
return newState
}
public func generateAssertionForAudience(audience: String, now: Timestamp) -> String {
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSignWith(keyPair.privateKey,
certificate: certificate,
audience: audience,
issuer: "127.0.0.1",
issuedAt: now,
duration: OneHourInMilliseconds)
return assertion
}
}
public class DoghouseState: FxAState {
override public var label: FxAStateLabel { return FxAStateLabel.Doghouse }
override public init() {
super.init()
}
}
| mpl-2.0 | c6bfbc6d8bf350dd855e3d2f5aa88fdb | 37.474006 | 157 | 0.657181 | 5.462875 | false | false | false | false |
noblakit01/PhotoCollectionView | Sources/PhotoView.swift | 1 | 2861 | //
// PhotoCollectionViewCell.swift
// iKidz
//
// Created by luan on 7/7/17.
// Copyright © 2017 Sua Le. All rights reserved.
//
import UIKit
import SwiftyImageCache
public class PhotoView: UIView {
public lazy var imageView: UIImageView! = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.backgroundColor = .black
return imageView
}()
public lazy var loadingView: UIActivityIndicatorView! = {
let loadingView = UIActivityIndicatorView(activityIndicatorStyle: .white)
loadingView.hidesWhenStopped = true
loadingView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(loadingView)
let constraints = [
NSLayoutConstraint(item: loadingView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: loadingView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0),
]
self.addConstraints(constraints)
return loadingView
}()
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
let constraints = [
NSLayoutConstraint(item: imageView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0),
]
addConstraints(constraints)
backgroundColor = UIColor.black
}
func setImage(_ image: UIImage) {
imageView.image = image
}
func setUrl(url: URL, completion: ((String, UIImage?) -> Void)? = nil) {
loadingView.startAnimating()
let urlString = url.absoluteString
ImageCache.default.loadImage(atUrl: url, completion: { [weak self] urlStr, image in
guard let sSelf = self else {
return
}
if urlString == urlStr {
sSelf.imageView.image = image
sSelf.loadingView.stopAnimating()
}
completion?(urlString, image)
})
}
}
| mit | f75380b0fc2b937be11736dfe460e5b3 | 37.133333 | 155 | 0.633566 | 4.973913 | false | false | false | false |
vbudhram/firefox-ios | Client/Frontend/AuthenticationManager/PasscodeEntryViewController.swift | 2 | 3394 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SnapKit
import Shared
import SwiftKeychainWrapper
/// Delegate available for PasscodeEntryViewController consumers to be notified of the validation of a passcode.
@objc protocol PasscodeEntryDelegate: class {
func passcodeValidationDidSucceed()
@objc optional func userDidCancelValidation()
}
/// Presented to the to user when asking for their passcode to validate entry into a part of the app.
class PasscodeEntryViewController: BasePasscodeViewController {
weak var delegate: PasscodeEntryDelegate?
fileprivate var passcodePane: PasscodePane
override init() {
let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo()
passcodePane = PasscodePane(title:nil, passcodeSize:authInfo?.passcode?.count ?? 6)
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = AuthenticationStrings.enterPasscodeTitle
view.addSubview(passcodePane)
passcodePane.snp.makeConstraints { make in
make.bottom.left.right.equalTo(self.view)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
passcodePane.codeInputView.delegate = self
// Don't show the keyboard or allow typing if we're locked out. Also display the error.
if authenticationInfo?.isLocked() ?? false {
displayLockoutError()
passcodePane.codeInputView.isUserInteractionEnabled = false
} else {
passcodePane.codeInputView.becomeFirstResponder()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if authenticationInfo?.isLocked() ?? false {
passcodePane.codeInputView.isUserInteractionEnabled = false
passcodePane.codeInputView.resignFirstResponder()
} else {
passcodePane.codeInputView.becomeFirstResponder()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.view.endEditing(true)
}
override func dismissAnimated() {
delegate?.userDidCancelValidation?()
super.dismissAnimated()
}
}
extension PasscodeEntryViewController: PasscodeInputViewDelegate {
func passcodeInputView(_ inputView: PasscodeInputView, didFinishEnteringCode code: String) {
if let passcode = authenticationInfo?.passcode, passcode == code {
authenticationInfo?.recordValidation()
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
delegate?.passcodeValidationDidSucceed()
} else {
passcodePane.shakePasscode()
failIncorrectPasscode(inputView)
passcodePane.codeInputView.resetCode()
// Store mutations on authentication info object
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
}
}
}
| mpl-2.0 | c421348bbc1ee938a3aeb61533787aae | 35.891304 | 112 | 0.695639 | 5.619205 | false | false | false | false |
0Mooshroom/Learning-Swift | 14_初始化/14_初始化/main.swift | 1 | 3630 | //
// main.swift
// 14_初始化
//
// Created by 赵恒 on 2017/8/25.
// Copyright © 2017年 Mooshroom. All rights reserved.
//
import Foundation
//: 初始化 init()
struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
print("The default temprature is \(f.temperature)")
//: 初始化形式参数
struct Mooshroom {
var name: String
init(name: String) {
self.name = name
}
}
let moo = Mooshroom(name: "moo")
//: 形式参数和实际参数标签和无实际参数
struct Color {
let red, green, blue: Double
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
init(white: Double) {
red = white
green = white
blue = white
}
init(_ red: Double) {
self.red = red
green = 0.0
blue = 0.0
}
}
let color = Color(red: 1, green: 0.1, blue: 0.2)
let halfGray = Color(white: 0.5)
let red = Color(0.5)
//: 可选值类型
class Moo {
var name: String
var age: UInt? {
willSet {
if let newAge = newValue {
print("I am \(newAge)")
}
}
}
init(name: String) {
self.name = name
}
func ask() {
print("\(name) How old are you?")
}
}
let m = Moo(name: "Moo")
m.ask()
m.age = 25
//: 指定初始化器和便捷初始化器
// 规则:
// 1. 指定初始化器必须从它的直系父类调用指定初始化器。
// 2. 便捷初始化器必须从相同的类里调用另一个初始化器。
// 3. 便捷初始化器最终必须调用一个指定初始化器。
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[UnknowName]")
}
}
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) x \(name)"
output += purchased ? " ✔" : " ✘"
return output
}
}
var breakfastList = [
ShoppingListItem(),
ShoppingListItem(name: "Bacon"),
ShoppingListItem(name: "Eggs", quantity: 6)
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
print(item.description)
}
// 打印结果
/*
1 x Orange juice ✔
1 x Bacon ✘
6 x Eggs ✘
*/
//: 可失败初始化器
// 初始化传入无效的形式参数值,或缺少某种外部所需的资源,又或是其他阻止初始化的情况 都需要使用可失败的初始化器
// 在init后面加?
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
let animal = Animal(species: "Cat")
if let tempAnimal = animal {
print("tempAnimal.species = \(tempAnimal.species)")
}
let failure = Animal(species: "")
if failure == nil {
print("Animal init failure.")
}
//: 初始化失败的传递
class Product {
let name: String
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}
class CarItem: Product {
let quantity: Int
init?(name: String, quantity: Int) {
if quantity < 1 { return nil }
self.quantity = quantity
super.init(name: name)
}
}
| mit | c50534ef327faf3e20c3a034f79edd07 | 17.618497 | 57 | 0.579013 | 3.290092 | false | false | false | false |
shahmishal/swift | test/api-digester/Inputs/cake.swift | 1 | 2432 | @_exported import cake
public protocol P1 {}
public protocol P2 {}
public protocol P3: P2, P1 {}
@frozen
public struct S1: P1 {
public static func foo1() {}
mutating public func foo2() {}
internal func foo3() {}
private func foo4() {}
fileprivate func foo5() {}
public func foo6() -> Void {}
}
extension S1: P2 {}
public class C0<T1, T2, T3> {}
public typealias C0Alias = C0<S1, S1, S1>
public class C1: C0Alias {
open class func foo1() {}
public weak var Ins : C1?
public unowned var Ins2 : C1 = C1()
}
public extension C0 where T1 == S1, T2 == S1, T3 == S1 {
func conditionalFooExt() {}
}
public extension C0 {
func unconditionalFooExt() {}
}
public func foo1(_ a: Int = 1, b: S1) {}
public func foo2(_ a: Int = #line, b: S1) {}
public enum Number: Int {
case one
}
public func foo3(_ a: [Int: String]) {}
public extension Int {
public func foo() {}
}
@frozen
public struct fixedLayoutStruct {
public var a = 1
private var b = 2 { didSet {} willSet(value) {} }
var c = 3
@available(*, unavailable)
public let unavailableProperty = 1
}
extension Int: P1 { public func bar() {} }
public protocol ProWithAssociatedType {
associatedtype A
associatedtype B = Int
}
public protocol SubsContainer {
subscript(getter i: Int) -> Int { get }
subscript(setter i: Int) -> Int { get set }
}
public extension ProWithAssociatedType {
func NonReqFunc() {}
var NonReqVar: Int { return 1 }
typealias NonReqAlias = Int
}
public protocol PSuper {
associatedtype T
func foo()
}
public protocol PSub: PSuper {
associatedtype T
func foo()
}
public let GlobalVar = 1
public extension P1 {
static func +(lhs: P1, rhs: P1) -> P1 { return lhs }
}
infix operator ..*..
@usableFromInline
@_fixed_layout
class UsableFromInlineClass {
private var Prop = 1
}
class InternalType {}
extension InternalType {}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public extension PSuper {
func futureFoo() {}
}
public class FutureContainer {
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func futureFoo() {}
@available(macOS 10.15, *)
public func NotfutureFoo() {}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension FutureContainer: P1 {}
extension FutureContainer: P2 {}
@available(macOS 10.1, iOS 10.2, tvOS 10.3, watchOS 3.4, *)
public class PlatformIntroClass {}
@available(swift, introduced: 5)
public class SwiftIntroClass {}
| apache-2.0 | 8fff41843e3276414729cfa50e95fd99 | 18.456 | 59 | 0.674753 | 3.216931 | false | false | false | false |
material-components/material-components-ios-codelabs | MDC-103/Swift/Starter/Shrine/Shrine/LoginViewController.swift | 1 | 12491 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents
class LoginViewController: UIViewController {
let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false;
scrollView.backgroundColor = .white
scrollView.layoutMargins = UIEdgeInsetsMake(0, 16, 0, 16)
return scrollView
}()
let logoImageView: UIImageView = {
let baseImage = UIImage.init(named: "ShrineLogo")
let templatedImage = baseImage?.withRenderingMode(.alwaysTemplate)
let logoImageView = UIImageView(image: templatedImage)
logoImageView.translatesAutoresizingMaskIntoConstraints = false
return logoImageView
}()
let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.text = "SHRINE"
titleLabel.sizeToFit()
return titleLabel
}()
// Text Fields
let usernameTextField: MDCTextField = {
let usernameTextField = MDCTextField()
usernameTextField.translatesAutoresizingMaskIntoConstraints = false
usernameTextField.clearButtonMode = .unlessEditing;
return usernameTextField
}()
let passwordTextField: MDCTextField = {
let passwordTextField = MDCTextField()
passwordTextField.translatesAutoresizingMaskIntoConstraints = false
return passwordTextField
}()
let usernameTextFieldController: MDCTextInputControllerOutlined
let passwordTextFieldController: MDCTextInputControllerOutlined
// Buttons
let cancelButton: MDCButton = {
let cancelButton = MDCButton()
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.setTitle("CANCEL", for: .normal)
cancelButton.addTarget(self, action: #selector(didTapCancel(sender:)), for: .touchUpInside)
return cancelButton
}()
let nextButton: MDCButton = {
let nextButton = MDCButton()
nextButton.translatesAutoresizingMaskIntoConstraints = false
nextButton.setTitle("NEXT", for: .normal)
nextButton.addTarget(self, action: #selector(didTapNext(sender:)), for: .touchUpInside)
return nextButton
}()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
usernameTextFieldController = MDCTextInputControllerOutlined(textInput: usernameTextField)
passwordTextFieldController = MDCTextInputControllerOutlined(textInput: passwordTextField)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
usernameTextFieldController.placeholderText = "Username"
usernameTextField.delegate = self
passwordTextFieldController.placeholderText = "Password"
passwordTextField.delegate = self
registerKeyboardNotifications()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.tintColor = .black
view.addSubview(scrollView)
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView" : scrollView])
)
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView" : scrollView])
)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapTouch))
scrollView.addGestureRecognizer(tapGestureRecognizer)
scrollView.addSubview(titleLabel)
scrollView.addSubview(logoImageView)
// TextFields
scrollView.addSubview(usernameTextField)
scrollView.addSubview(passwordTextField)
// Buttons
scrollView.addSubview(nextButton)
scrollView.addSubview(cancelButton)
// Constraints
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: logoImageView,
attribute: .top,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .top,
multiplier: 1,
constant: 49))
constraints.append(NSLayoutConstraint(item: logoImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerX,
multiplier: 1,
constant: 0))
constraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .top,
relatedBy: .equal,
toItem: logoImageView,
attribute: .bottom,
multiplier: 1,
constant: 22))
constraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .centerX,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerX,
multiplier: 1,
constant: 0))
// Text Fields
constraints.append(NSLayoutConstraint(item: usernameTextField,
attribute: .top,
relatedBy: .equal,
toItem: titleLabel,
attribute: .bottom,
multiplier: 1,
constant: 22))
constraints.append(NSLayoutConstraint(item: usernameTextField,
attribute: .centerX,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerX,
multiplier: 1,
constant: 0))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-[username]-|",
options: [],
metrics: nil,
views: [ "username" : usernameTextField]))
constraints.append(NSLayoutConstraint(item: passwordTextField,
attribute: .top,
relatedBy: .equal,
toItem: usernameTextField,
attribute: .bottom,
multiplier: 1,
constant: 8))
constraints.append(NSLayoutConstraint(item: passwordTextField,
attribute: .centerX,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerX,
multiplier: 1,
constant: 0))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-[password]-|",
options: [],
metrics: nil,
views: [ "password" : passwordTextField]))
// Buttons
constraints.append(NSLayoutConstraint(item: cancelButton,
attribute: .top,
relatedBy: .equal,
toItem: passwordTextField,
attribute: .bottom,
multiplier: 1,
constant: 8))
constraints.append(NSLayoutConstraint(item: cancelButton,
attribute: .centerY,
relatedBy: .equal,
toItem: nextButton,
attribute: .centerY,
multiplier: 1,
constant: 0))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:[cancel]-[next]-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: [ "cancel" : cancelButton, "next" : nextButton]))
constraints.append(NSLayoutConstraint(item: nextButton,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .bottomMargin,
multiplier: 1,
constant: -20))
NSLayoutConstraint.activate(constraints)
// TODO: Theme the interface with our colors
// TODO: Theme the interface with our typography
}
// MARK: - Gesture Handling
@objc func didTapTouch(sender: UIGestureRecognizer) {
view.endEditing(true)
}
// MARK: - Action Handling
@objc func didTapNext(sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@objc func didTapCancel(sender: Any) {
self.dismiss(animated: true, completion: nil)
}
// MARK: - Keyboard Handling
func registerKeyboardNotifications() {
NotificationCenter.default.addObserver(
self,
selector: #selector(self.keyboardWillShow),
name: NSNotification.Name(rawValue: "UIKeyboardWillShowNotification"),
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.keyboardWillShow),
name: NSNotification.Name(rawValue: "UIKeyboardWillChangeFrameNotification"),
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.keyboardWillHide),
name: NSNotification.Name(rawValue: "UIKeyboardWillHideNotification"),
object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
let keyboardFrame =
(notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, keyboardFrame.height, 0);
}
@objc func keyboardWillHide(notification: NSNotification) {
self.scrollView.contentInset = UIEdgeInsets.zero;
}
}
extension LoginViewController: UITextFieldDelegate {
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder();
// TextField
if (textField == passwordTextField) {
let textFieldCharacterCount = textField.text?.count ?? 0
if (textFieldCharacterCount < 8) {
passwordTextFieldController.setErrorText("Password is too short",
errorAccessibilityValue: nil)
} else {
passwordTextFieldController.setErrorText(nil, errorAccessibilityValue: nil)
}
}
return false
}
}
| apache-2.0 | 03e3b242cdffd940dd9c6b22109e1d17 | 40.77592 | 99 | 0.547274 | 6.821955 | false | false | false | false |
DashiDashCam/iOS-App | Dashi/Pods/PromiseKit/Sources/wrap.swift | 1 | 2273 | /**
Create a new pending promise by wrapping another asynchronous system.
This initializer is convenient when wrapping asynchronous systems that
use common patterns. For example:
func fetchKitten() -> Promise<UIImage> {
return PromiseKit.wrap { resolve in
KittenFetcher.fetchWithCompletionBlock(resolve)
}
}
- SeeAlso: Promise.init(resolvers:)
*/
public func wrap<T>(_ body: (@escaping (T?, Error?) -> Void) throws -> Void) -> Promise<T> {
return Promise { fulfill, reject in
try body { obj, err in
if let err = err {
reject(err)
} else if let obj = obj {
fulfill(obj)
} else {
reject(PMKError.invalidCallingConvention)
}
}
}
}
/// For completion-handlers that eg. provide an enum or an error.
public func wrap<T>(_ body: (@escaping (T, Error?) -> Void) throws -> Void) -> Promise<T> {
return Promise { fulfill, reject in
try body { obj, err in
if let err = err {
reject(err)
} else {
fulfill(obj)
}
}
}
}
/// Some APIs unwisely invert the Cocoa standard for completion-handlers.
public func wrap<T>(_ body: (@escaping (Error?, T?) -> Void) throws -> Void) -> Promise<T> {
return Promise { fulfill, reject in
try body { err, obj in
if let err = err {
reject(err)
} else if let obj = obj {
fulfill(obj)
} else {
reject(PMKError.invalidCallingConvention)
}
}
}
}
/// For completion-handlers with just an optional Error
public func wrap(_ body: (@escaping (Error?) -> Void) throws -> Void) -> Promise<Void> {
return Promise { fulfill, reject in
try body { error in
if let error = error {
reject(error)
} else {
#if swift(>=4.0)
fulfill(())
#else
fulfill()
#endif
}
}
}
}
/// For completions that cannot error.
public func wrap<T>(_ body: (@escaping (T) -> Void) throws -> Void) -> Promise<T> {
return Promise { fulfill, _ in
try body(fulfill)
}
}
| mit | c9e172ef22300a899e8d95d9b1af32e5 | 27.772152 | 92 | 0.530576 | 4.354406 | false | false | false | false |
gurenupet/hah-auth-ios-swift | hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/TweakPersistency.swift | 2 | 6886 | //
// TweakPersistency.swift
// SwiftTweaks
//
// Created by Bryan Clark on 11/16/15.
// Copyright © 2015 Khan Academy. All rights reserved.
//
import UIKit
/// Identifies tweaks in TweakPersistency
internal protocol TweakIdentifiable {
var persistenceIdentifier: String { get }
}
/// Caches Tweak values
internal typealias TweakCache = [String: TweakableType]
/// Persists state for tweaks in a TweakCache
internal final class TweakPersistency {
private let diskPersistency: TweakDiskPersistency
private var tweakCache: TweakCache = [:]
init(identifier: String) {
self.diskPersistency = TweakDiskPersistency(identifier: identifier)
self.tweakCache = self.diskPersistency.loadFromDisk()
}
internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T? {
return persistedValueForTweakIdentifiable(AnyTweak(tweak: tweak)) as? T
}
internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T? where T: SignedNumber {
if let currentValue = persistedValueForTweakIdentifiable(AnyTweak(tweak: tweak)) as? T {
// If the tweak can be clipped, then we'll need to clip it - because
// the tweak might've been persisted without a min / max, but then you changed the tweak definition.
// example: you tweaked it to 11, then set a max of 10 - the persisted value is still 11!
return clip(currentValue, tweak.minimumValue, tweak.maximumValue)
}
return nil
}
internal func persistedValueForTweakIdentifiable(_ tweakID: TweakIdentifiable) -> TweakableType? {
return tweakCache[tweakID.persistenceIdentifier]
}
internal func setValue(_ value: TweakableType?, forTweakIdentifiable tweakID: TweakIdentifiable) {
tweakCache[tweakID.persistenceIdentifier] = value
self.diskPersistency.saveToDisk(tweakCache)
}
internal func clearAllData() {
tweakCache = [:]
self.diskPersistency.saveToDisk(tweakCache)
}
}
/// Persists a TweakCache on disk using NSCoding
private final class TweakDiskPersistency {
private let fileURL: URL
private static func fileURLForIdentifier(_ identifier: String) -> URL {
return try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("SwiftTweaks")
.appendingPathComponent("\(identifier)")
.appendingPathExtension("db")
}
private let queue = DispatchQueue(label: "org.khanacademy.swift_tweaks.disk_persistency", attributes: [])
init(identifier: String) {
self.fileURL = TweakDiskPersistency.fileURLForIdentifier(identifier)
self.ensureDirectoryExists()
}
/// Creates a directory (if needed) for our persisted TweakCache on disk
private func ensureDirectoryExists() {
(self.queue).async {
try! FileManager.default.createDirectory(at: self.fileURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil)
}
}
func loadFromDisk() -> TweakCache {
var result: TweakCache!
self.queue.sync {
NSKeyedUnarchiver.setClass(Data.self, forClassName: "Data")
result = (try? Foundation.Data(contentsOf: self.fileURL))
.flatMap(NSKeyedUnarchiver.unarchiveObject(with:))
.flatMap { $0 as? Data }
.map { $0.cache }
?? [:]
}
return result
}
func saveToDisk(_ data: TweakCache) {
self.queue.async {
let data = Data(cache: data)
NSKeyedArchiver.setClassName("Data", for: type(of: data))
let nsData = NSKeyedArchiver.archivedData(withRootObject: data)
try? nsData.write(to: self.fileURL, options: [.atomic])
}
}
/// Implements NSCoding for TweakCache.
/// TweakCache a flat dictionary: [String: TweakableType].
/// However, because re-hydrating TweakableType from its underlying NSNumber gets Bool & Int mixed up,
/// we have to persist a different structure on disk: [TweakViewDataType: [String: AnyObject]]
/// This ensures that if something was saved as a Bool, it's read back as a Bool.
@objc private final class Data: NSObject, NSCoding {
let cache: TweakCache
init(cache: TweakCache) {
self.cache = cache
}
@objc convenience init?(coder aDecoder: NSCoder) {
var cache: TweakCache = [:]
// Read through each TweakViewDataType...
for dataType in TweakViewDataType.allTypes {
// If a sub-dictionary exists for that type,
if let dataTypeDictionary = aDecoder.decodeObject(forKey: dataType.nsCodingKey) as? Dictionary<String, AnyObject> {
// Read through each entry and populate the cache
for (key, value) in dataTypeDictionary {
if let value = Data.tweakableTypeWithAnyObject(value, withType: dataType) {
cache[key] = value
}
}
}
}
self.init(cache: cache)
}
@objc fileprivate func encode(with aCoder: NSCoder) {
// Our "dictionary of dictionaries" that is persisted on disk
var diskPersistedDictionary: [TweakViewDataType : [String: AnyObject]] = [:]
// For each thing in our TweakCache,
for (key, value) in cache {
let dataType = type(of: value).tweakViewDataType
// ... create the "sub-dictionary" if it doesn't already exist for a particular TweakViewDataType
if diskPersistedDictionary[dataType] == nil {
diskPersistedDictionary[dataType] = [:]
}
// ... and set the cached value inside the sub-dictionary.
diskPersistedDictionary[dataType]![key] = value.nsCoding
}
// Now we persist the "dictionary of dictionaries" on disk!
for (key, value) in diskPersistedDictionary {
aCoder.encode(value, forKey: key.nsCodingKey)
}
}
// Reads from the cache, casting to the appropriate TweakViewDataType
private static func tweakableTypeWithAnyObject(_ anyObject: AnyObject, withType type: TweakViewDataType) -> TweakableType? {
switch type {
case .integer: return anyObject as? Int
case .boolean: return anyObject as? Bool
case .cgFloat: return anyObject as? CGFloat
case .double: return anyObject as? Double
case .string: return anyObject as? String
}
}
}
}
private extension TweakViewDataType {
/// Identifies our TweakViewDataType when in NSCoding. See implementation of TweakDiskPersistency.Data
var nsCodingKey: String {
switch self {
case .boolean: return "boolean"
case .integer: return "integer"
case .cgFloat: return "cgfloat"
case .double: return "double"
case .string: return "string"
}
}
}
private extension TweakableType {
/// Gets the underlying value from a Tweakable Type
var nsCoding: AnyObject {
switch type(of: self).tweakViewDataType {
case .boolean: return self as AnyObject
case .integer: return self as AnyObject
case .cgFloat: return self as AnyObject
case .double: return self as AnyObject
case .string: return self as AnyObject
}
}
}
| mit | 88f7fd68e1469153103f226bc6a9350f | 32.75 | 126 | 0.700508 | 4.203297 | false | false | false | false |
hughbe/ui-components | src/Autolayout/UIView+Autolayout.swift | 1 | 1209 | //
// UIView+Autolayout.swift
// Slater
//
// Created by Hugh Bellamy on 14/06/2015.
// Copyright (c) 2015 Hugh Bellamy. All rights reserved.
//
public extension UIView {
public func fillSuperview() {
fillView(superview)
}
public func fillView(view: UIView?) {
if let view = view {
translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
let leftConstraint = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0)
view.addConstraints([ topConstraint, bottomConstraint, leftConstraint, rightConstraint])
updateConstraints()
}
}
}
| mit | dc02f585b3a7d0f69db00cb96607e3f0 | 43.777778 | 166 | 0.66005 | 4.596958 | false | false | false | false |
naturaln0va/Doodler_iOS | Sticker Doodler/CreateDoodleCell.swift | 1 | 890 |
import UIKit
class CreateDoodleCell: UICollectionViewCell {
let imageView = UIImageView(frame: .zero)
override func layoutSubviews() {
super.layoutSubviews()
if imageView.superview == nil {
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
imageView.image = UIImage(named: "new-doodle")?.imageByTintingWithColor(color: UIColor(hex: 0x858e9a))
imageView.contentMode = .center
}
}
}
| mit | fbfb06bab854557f3168f8b7e00c8195 | 33.230769 | 114 | 0.639326 | 5.66879 | false | false | false | false |
sbennett912/SwiftGL | SwiftGL/Vec2.swift | 1 | 5725 | //
// Vec2.swift
// SwiftGL
//
// Created by Scott Bennett on 2014-06-08.
// Copyright (c) 2014 Scott Bennett. All rights reserved.
//
import Darwin
public struct Vec2 {
public var x, y: Float
public init() {
self.x = 0
self.y = 0
}
// Explicit initializers
public init(s: Float) {
self.x = s
self.y = s
}
public init(x: Float) {
self.x = x
self.y = 0
}
public init(x: Float, y: Float) {
self.x = x
self.y = y
}
// Implicit initializers
public init(_ x: Float) {
self.x = x
self.y = 0
}
public init(_ x: Float, _ y: Float) {
self.x = x
self.y = y
}
public var length2: Float {
get {
return x * x + y * y
}
}
public var length: Float {
get {
return sqrt(self.length2)
}
set {
self = length * normalize(self)
}
}
public var ptr: UnsafePointer<Float> {
mutating get {
return withUnsafePointer(to: &self) {
return UnsafeRawPointer($0).assumingMemoryBound(to: Float.self)
}
}
}
// Swizzle (Vec2) Properties
public var xx: Vec2 { get { return Vec2(x: x, y: x) } }
public var yx: Vec2 { get { return Vec2(x: y, y: x) } set(v) { self.y = v.x; self.x = v.y } }
public var xy: Vec2 { get { return Vec2(x: x, y: y) } set(v) { self.x = v.x; self.y = v.y } }
public var yy: Vec2 { get { return Vec2(x: y, y: y) } }
// Swizzle (Vec3) Properties
public var xxx: Vec3 { get { return Vec3(x: x, y: x, z: x) } }
public var yxx: Vec3 { get { return Vec3(x: y, y: x, z: x) } }
public var xyx: Vec3 { get { return Vec3(x: x, y: y, z: x) } }
public var yyx: Vec3 { get { return Vec3(x: y, y: y, z: x) } }
public var xxy: Vec3 { get { return Vec3(x: x, y: x, z: y) } }
public var yxy: Vec3 { get { return Vec3(x: y, y: x, z: y) } }
public var xyy: Vec3 { get { return Vec3(x: x, y: y, z: y) } }
public var yyy: Vec3 { get { return Vec3(x: y, y: y, z: y) } }
// Swizzle (Vec4) Properties
public var xxxx: Vec4 { get { return Vec4(x: x, y: x, z: x, w: x) } }
public var yxxx: Vec4 { get { return Vec4(x: y, y: x, z: x, w: x) } }
public var xyxx: Vec4 { get { return Vec4(x: x, y: y, z: x, w: x) } }
public var yyxx: Vec4 { get { return Vec4(x: y, y: y, z: x, w: x) } }
public var xxyx: Vec4 { get { return Vec4(x: x, y: x, z: y, w: x) } }
public var yxyx: Vec4 { get { return Vec4(x: y, y: x, z: y, w: x) } }
public var xyyx: Vec4 { get { return Vec4(x: x, y: y, z: y, w: x) } }
public var yyyx: Vec4 { get { return Vec4(x: y, y: y, z: y, w: x) } }
public var xxxy: Vec4 { get { return Vec4(x: x, y: x, z: x, w: y) } }
public var yxxy: Vec4 { get { return Vec4(x: y, y: x, z: x, w: y) } }
public var xyxy: Vec4 { get { return Vec4(x: x, y: y, z: x, w: y) } }
public var yyxy: Vec4 { get { return Vec4(x: y, y: y, z: x, w: y) } }
public var xxyy: Vec4 { get { return Vec4(x: x, y: x, z: y, w: y) } }
public var yxyy: Vec4 { get { return Vec4(x: y, y: x, z: y, w: y) } }
public var xyyy: Vec4 { get { return Vec4(x: x, y: y, z: y, w: y) } }
public var yyyy: Vec4 { get { return Vec4(x: y, y: y, z: y, w: y) } }
}
// Make it easier to interpret Vec2 as a string
extension Vec2: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { get { return "(\(x), \(y))" } }
public var debugDescription: String { get { return "Vec2(x: \(x), y: \(y))" } }
}
// Vec2 Prefix Operators
public prefix func - (v: Vec2) -> Vec2 { return Vec2(x: -v.x, y: -v.y) }
// Vec2 Infix Operators
public func + (a: Vec2, b: Vec2) -> Vec2 { return Vec2(x: a.x + b.x, y: a.y + b.y) }
public func - (a: Vec2, b: Vec2) -> Vec2 { return Vec2(x: a.x - b.x, y: a.y - b.y) }
public func * (a: Vec2, b: Vec2) -> Vec2 { return Vec2(x: a.x * b.x, y: a.y * b.y) }
public func / (a: Vec2, b: Vec2) -> Vec2 { return Vec2(x: a.x / b.x, y: a.y / b.y) }
// Vec2 Scalar Operators
public func * (s: Float, v: Vec2) -> Vec2 { return Vec2(x: s * v.x, y: s * v.y) }
public func * (v: Vec2, s: Float) -> Vec2 { return Vec2(x: v.x * s, y: v.y * s) }
public func / (v: Vec2, s: Float) -> Vec2 { return Vec2(x: v.x / s, y: v.y / s) }
// Vec2 Assignment Operators
public func += (a: inout Vec2, b: Vec2) { a = a + b }
public func -= (a: inout Vec2, b: Vec2) { a = a - b }
public func *= (a: inout Vec2, b: Vec2) { a = a * b }
public func /= (a: inout Vec2, b: Vec2) { a = a / b }
public func *= (a: inout Vec2, b: Float) { a = a * b }
public func /= (a: inout Vec2, b: Float) { a = a / b }
// Functions which operate on Vec2
public func length(_ v: Vec2) -> Float { return v.length }
public func length2(_ v: Vec2) -> Float { return v.length2 }
public func normalize(_ v: Vec2) -> Vec2 { return v / v.length }
public func dot(_ a: Vec2, _ b: Vec2) -> Float { return a.x * b.x + a.y * b.y }
public func clamp(_ value: Vec2, min: Float, max: Float) -> Vec2 { return Vec2(clamp(value.x, min: min, max: max), clamp(value.y, min: min, max: max)) }
public func mix(_ a: Vec2, b: Vec2, t: Float) -> Vec2 { return a + (b - a) * t }
public func smoothstep(_ a: Vec2, b: Vec2, t: Float) -> Vec2 { return mix(a, b: b, t: t * t * (3 - 2 * t)) }
public func clamp(_ value: Vec2, min: Vec2, max: Vec2) -> Vec2 { return Vec2(clamp(value.x, min: min.x, max: max.x), clamp(value.y, min: min.y, max: max.y)) }
public func mix(_ a: Vec2, b: Vec2, t: Vec2) -> Vec2 { return a + (b - a) * t }
public func smoothstep(_ a: Vec2, b: Vec2, t: Vec2) -> Vec2 { return mix(a, b: b, t: t * t * (Vec2(s: 3) - 2 * t)) }
| mit | 387046d7a4bda4f261dd06163a1d361f | 37.945578 | 158 | 0.535895 | 2.603456 | false | false | false | false |
xeecos/motionmaker | GIFMaker/CameraSettingCell.swift | 1 | 7176 | //
// CameraSettingCell.swift
// GIFMaker
//
// Created by indream on 15/9/20.
// Copyright © 2015年 indream. All rights reserved.
//
import UIKit
class CameraSettingCell: UITableViewCell {
@IBOutlet weak var focusLabel: UILabel!
@IBOutlet weak var focusSlider: UISlider!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var speedSlider: UISlider!
@IBOutlet weak var isoLabel: UILabel!
@IBOutlet weak var isoSlider: UISlider!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var timeSlider: UISlider!
@IBOutlet weak var intervalLabel: UILabel!
@IBOutlet weak var intervalSlider: UISlider!
var cid:Int16 = 0
var sid:Int16 = 0
weak var tableView:UITableView!
func setCameraIndex(_ sid:Int16, cid:Int16){
self.cid = cid
if(self.cid<0){
self.cid = 0
}
self.sid = sid
if(self.sid<0){
self.sid = 0
}
updateConfig()
}
override func awakeFromNib() {
super.awakeFromNib()
updateConfig()
}
func updateConfig(){
let cam:CameraModel? = DataManager.sharedManager().camera(sid,cid: cid)!
if(cam==nil){
DataManager.sharedManager().createCamera(sid,cid: cid)
}
let focus:Float = Float(cam!.focus)
let speed:Float = Float(cam!.speed)
if((focusSlider) != nil){
focusSlider.value = focus
focusLabel.text = String(format: "%.2f", focusSlider.value/8000.0)
speedSlider.value = 0
speedLabel.text = String(format: "1/%.0f", speed)
isoSlider.value = Float(cam!.iso)
isoLabel.text = String(format: "%.0f", isoSlider.value)
}
if((timeSlider) != nil){
timeSlider.value = 0
timeLabel.text = String(format: "%d %@", cam!.time,NSLocalizedString("secs", comment: ""))
intervalSlider.value = 0
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam!.interval,NSLocalizedString("secs", comment: ""),Int(Float(cam!.time)/Float(cam!.interval)),NSLocalizedString("frames", comment: ""))
}
}
func assignTableView(_ tableView:UITableView){
self.tableView = tableView
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func focusChanged(_ sender: AnyObject) {
focusLabel.text = String(format: "%.2f", focusSlider.value/8000.0)
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.focus = focusSlider.value
tableView.alpha = 0.1
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func speedChanged(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
var scale:Float = 1
if(cam.speed<500){
scale = 3
}
if(cam.speed<300){
scale = 5
}
if(cam.speed<100){
scale = 10
}
if(cam.speed<50){
scale = 20
}
let speed = speedSlider.value/scale
if(Float(cam.speed)+speed<2){
speedLabel.text = String(format: "1/%d", 2)
}else{
speedLabel.text = String(format: "1/%.0f", Float(cam.speed)+speed)
}
tableView.alpha = 0.1
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func speedTouchEnd(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
var scale:Float = 1
if(cam.speed<500){
scale = 3
}
if(cam.speed<300){
scale = 5
}
if(cam.speed<100){
scale = 10
}
if(cam.speed<50){
scale = 20
}
cam.speed += Int16(speedSlider.value/scale)
if(cam.speed<2){
cam.speed = 2
}else if(cam.speed>8000){
cam.speed = 8000
}
speedLabel.text = String(format: "1/%d", cam.speed)
speedSlider.value = 0
tableView.alpha = 1.0
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func focusEnd(_ sender: AnyObject) {
tableView.alpha = 1.0
}
@IBAction func isoEnd(_ sender: AnyObject) {
tableView.alpha = 1.0
}
@IBAction func isoChanged(_ sender: AnyObject) {
isoLabel.text = String(format: "%.0f", isoSlider.value)
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.iso = Int16(isoSlider.value)
tableView.alpha = 0.1
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func timeChanged(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
let time = timeSlider.value/2
timeLabel.text = String(format: "%.1f %@", Float(cam.time)+time,NSLocalizedString("secs", comment: ""))
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)+time)/cam.interval),NSLocalizedString("frames", comment: ""))
}
@IBAction func timeTouchEnd(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.time += Int32(floorf(timeSlider.value/2))
if(cam.time<0){
cam.time = 0
}
timeSlider.value = 0
timeLabel.text = String(format: "%.1f %@", Float(cam.time),NSLocalizedString("secs", comment: ""))
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)/cam.interval)),NSLocalizedString("frames", comment: ""))
}
@IBAction func intervalChanged(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
let interval = intervalSlider.value/4
if((cam.interval+interval)>0.1){
intervalLabel.text = String(format: "%.1f %@ / %d %@", (cam.interval+interval),NSLocalizedString("secs", comment: ""),Int(Float(cam.time)/Float(cam.interval+interval)),NSLocalizedString("frames", comment: ""))
}else{
intervalLabel.text = String(format: "%.1f %@ / %d %@",0.1,NSLocalizedString("secs", comment: ""),Int(Float(cam.time)/0.1),NSLocalizedString("frames", comment: ""))
}
}
@IBAction func intervalTouchEnd(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.interval += intervalSlider.value/4
if(cam.interval<0.1){
cam.interval = 0.1
}
intervalSlider.value = 0
timeLabel.text = String(format: "%.1f %@", Float(cam.time),NSLocalizedString("secs", comment: ""))
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)/cam.interval)),NSLocalizedString("frames", comment: ""))
}
}
| mit | 11469efe96293b530c3b204e2fe04c69 | 37.772973 | 221 | 0.595009 | 4.054833 | false | false | false | false |
IamAlchemist/DemoCI | DemoCI/FilteredImageView.swift | 1 | 4044 | //
// FilteredImageView.swift
// DemoCI
//
// Created by wizard lee on 7/23/16.
// Copyright © 2016 cc.kauhaus. All rights reserved.
//
import UIKit
import GLKit
import OpenGLES
class FilteredImageView: GLKView {
var ciContext: CIContext!
var filter: CIFilter! {
didSet {
setNeedsDisplay()
}
}
var inputImage: UIImage! {
didSet {
setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame, context: EAGLContext(api: .openGLES2))
clipsToBounds = true
ciContext = CIContext(eaglContext: context)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
clipsToBounds = true
context = EAGLContext(api: .openGLES2)
ciContext = CIContext(eaglContext: context)
}
override func draw(_ rect: CGRect) {
guard let ciContext = ciContext, let inputImage = inputImage, let filter = filter
else { return }
let inputCIImage = CIImage(image: inputImage)
filter.setValue(inputCIImage, forKey: kCIInputImageKey)
guard let outputImage = filter.outputImage else { return }
clearBackground()
let inputBounds = inputCIImage!.extent
let drawableBounds = CGRect(x: 0, y: 0, width: drawableWidth, height: drawableHeight)
let targetBounds = imageBoundsForContentMode(inputBounds, toRect: drawableBounds)
ciContext.draw(outputImage, in: targetBounds, from: inputBounds)
}
override func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
func clearBackground() {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
backgroundColor?.getRed(&r, green: &g, blue: &b, alpha: &a)
glClearColor(GLfloat(r), GLfloat(g), GLfloat(b), GLfloat(a))
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
}
func aspectFit(_ fromRect: CGRect, toRect: CGRect) -> CGRect {
let fromAspectRatio = fromRect.size.width / fromRect.size.height;
let toAspectRatio = toRect.size.width / toRect.size.height;
var fitRect = toRect
if (fromAspectRatio > toAspectRatio) {
fitRect.size.height = toRect.size.width / fromAspectRatio;
fitRect.origin.y += (toRect.size.height - fitRect.size.height) * 0.5;
} else {
fitRect.size.width = toRect.size.height * fromAspectRatio;
fitRect.origin.x += (toRect.size.width - fitRect.size.width) * 0.5;
}
return fitRect.integral
}
func aspectFill(_ fromRect: CGRect, toRect: CGRect) -> CGRect {
let fromAspectRatio = fromRect.size.width / fromRect.size.height;
let toAspectRatio = toRect.size.width / toRect.size.height;
var fitRect = toRect
if (fromAspectRatio > toAspectRatio) {
fitRect.size.width = toRect.size.height * fromAspectRatio;
fitRect.origin.x += (toRect.size.width - fitRect.size.width) * 0.5;
} else {
fitRect.size.height = toRect.size.width / fromAspectRatio;
fitRect.origin.y += (toRect.size.height - fitRect.size.height) * 0.5;
}
return fitRect.integral
}
func imageBoundsForContentMode(_ fromRect: CGRect, toRect: CGRect) -> CGRect {
switch contentMode {
case .scaleAspectFill:
return aspectFill(fromRect, toRect: toRect)
case .scaleAspectFit:
return aspectFit(fromRect, toRect: toRect)
default:
return fromRect
}
}
}
extension FilteredImageView: ParameterAdjustmentDelegate {
func parameterValueDidChange(_ param: ScalarFilterParameter) {
filter.setValue(param.currentValue, forKey: param.key)
setNeedsDisplay()
}
}
| mit | 987f5d1f7a521d35b89b1260b60924f9 | 29.628788 | 93 | 0.597329 | 4.512277 | false | false | false | false |
neoneye/SwiftyFORM | Source/Form/FormBuilder.swift | 1 | 2950 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
class AlignLeft {
fileprivate let items: [FormItem]
init(items: [FormItem]) {
self.items = items
}
}
public enum ToolbarMode {
case none
case simple
}
public class FormBuilder {
private var innerItems = [FormItem]()
private var alignLeftItems = [AlignLeft]()
public init() {
}
public var navigationTitle: String?
public var toolbarMode: ToolbarMode = .none
public var suppressHeaderForFirstSection = false
public func removeAll() {
innerItems.removeAll()
}
@discardableResult
public func append(_ item: FormItem) -> FormItem {
innerItems.append(item)
return item
}
public func append(_ items: [FormItem]) {
innerItems += items
}
public func append(_ items: FormItem...) {
innerItems += items
}
public func alignLeft(_ items: [FormItem]) {
let alignLeftItem = AlignLeft(items: items)
alignLeftItems.append(alignLeftItem)
}
public func alignLeftElementsWithClass(_ styleClass: String) {
let items: [FormItem] = innerItems.filter { $0.styleClass == styleClass }
alignLeft(items)
}
public var items: [FormItem] {
return innerItems
}
public func dump(_ prettyPrinted: Bool = true) -> Data {
return DumpVisitor.dump(prettyPrinted, items: innerItems)
}
public func result(_ viewController: UIViewController) -> TableViewSectionArray {
let model = PopulateTableViewModel(viewController: viewController, toolbarMode: toolbarMode)
let v = PopulateTableView(model: model)
if suppressHeaderForFirstSection {
v.installZeroHeightHeader()
}
for item in innerItems {
item.accept(visitor: v)
}
v.closeLastSection()
for alignLeftItem in alignLeftItems {
let widthArray: [CGFloat] = alignLeftItem.items.map {
let v = ObtainTitleWidth()
$0.accept(visitor: v)
return v.width
}
//SwiftyFormLog("widthArray: \(widthArray)")
let width = widthArray.max()!
//SwiftyFormLog("max width: \(width)")
for item in alignLeftItem.items {
let v = AssignTitleWidth(width: width)
item.accept(visitor: v)
}
}
return TableViewSectionArray(sections: v.sections)
}
public func validateAndUpdateUI() {
ReloadPersistentValidationStateVisitor.validateAndUpdateUI(innerItems)
}
public enum FormValidateResult {
case valid
case invalid(item: FormItem, message: String)
}
public func validate() -> FormValidateResult {
for item in innerItems {
let v = ValidateVisitor()
item.accept(visitor: v)
switch v.result {
case .valid:
// SwiftyFormLog("valid")
continue
case .hardInvalid(let message):
//SwiftyFormLog("invalid message \(message)")
return .invalid(item: item, message: message)
case .softInvalid(let message):
//SwiftyFormLog("invalid message \(message)")
return .invalid(item: item, message: message)
}
}
return .valid
}
}
public func += (left: FormBuilder, right: FormItem) {
left.append(right)
}
| mit | 89fab0827fcab1f49dca55ecba4a4bd7 | 22.046875 | 94 | 0.710169 | 3.516091 | false | false | false | false |
ziyincody/MTablesView | MTablesView/Classes/MTablesView.swift | 1 | 8443 | //
// MTablesView.swift
// Pods
//
// Created by Ziyin Wang on 2017-02-18.
//
//
import UIKit
@available(iOS 9.0, *)
public class MTablesView: UIView,UITableViewDelegate,UITableViewDataSource {
public enum tableSegueDirection {
case left
case right
case top
case bottom
}
public var segueDirection:tableSegueDirection = .left
{
didSet
{
setupSegueDirection()
}
}
public var selectingOption:Bool = false
public var delegate:MTableViewDelegate?
lazy var closeAndBackButton:UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(closeOrBack(sender:)), for: .touchUpInside)
button.setTitle("Done", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
return button
}()
var titleLabel:UILabel = {
let label = UILabel()
label.text = "TITLE"
label.textColor = UIColor.white
return label
}()
lazy var mainTable:UITableView = {
let table = UITableView(frame: .zero, style: .grouped)
table.delegate = self
table.dataSource = self
table.register(MainTableCell.self, forCellReuseIdentifier: "MainCell")
return table
}()
lazy var detailedTable:UITableView = {
let table = UITableView(frame: .zero, style: .grouped)
table.delegate = self
table.dataSource = self
table.register(DetailTableCell.self, forCellReuseIdentifier: "DetailCell")
return table
}()
let topView:UIView = {
let view = UIView()
view.backgroundColor = UIColor.black
return view
}()
var sectionTitles:Array<String>?
var mainData:[[String]]?
var detailedData:[[[String]]]?
var selectedDetailData:[String]?
var tableMovingAnchor:NSLayoutConstraint?
var anchors:[NSLayoutConstraint] = []
public init(viewTitle:String, sectionTitles:Array<String>, mainData:[[String]]?, detailedData:[[[String]]]?)
{
super.init(frame: .zero)
self.titleLabel.text = viewTitle
self.sectionTitles = sectionTitles
self.mainData = mainData
self.detailedData = detailedData
addSubview(mainTable)
addSubview(detailedTable)
addSubview(topView)
topView.addSubview(titleLabel)
topView.addSubview(closeAndBackButton)
setupViews()
setupSegueDirection()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews()
{
_ = topView.anchor(topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
closeAndBackButton.translatesAutoresizingMaskIntoConstraints = false
closeAndBackButton.centerYAnchor.constraint(equalTo: topView.centerYAnchor).isActive = true
closeAndBackButton.rightAnchor.constraint(equalTo: topView.rightAnchor, constant: -8).isActive = true
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerXAnchor.constraint(equalTo: topView.centerXAnchor).isActive = true
titleLabel.centerYAnchor.constraint(equalTo: topView.centerYAnchor).isActive = true
anchors = mainTable.anchor(topView.bottomAnchor, left: leftAnchor, bottom: nil, right:nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
mainTable.widthAnchor.constraint(equalTo: widthAnchor, constant: 0).isActive = true
mainTable.heightAnchor.constraint(equalTo: heightAnchor, constant: -topView.frame.size.height).isActive = true
_ = detailedTable.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
detailedTable.widthAnchor.constraint(equalTo: widthAnchor, constant: 0).isActive = true
bringSubview(toFront: mainTable)
bringSubview(toFront: topView)
}
func setupSegueDirection()
{
switch segueDirection {
case .top,.bottom:
tableMovingAnchor = anchors[0]
case .left,.right:
tableMovingAnchor = anchors[1]
}
}
func closeOrBack(sender:UIButton)
{
if sender.currentTitle == "Done"
{
delegate?.moveBackView()
}
else if sender.currentTitle == "Back"
{
sender.setTitle("Done",for:.normal)
moveTable()
}
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if tableView == mainTable
{
if let title = sectionTitles?[section]
{
return title
}
}
return ""
}
public func numberOfSections(in tableView: UITableView) -> Int
{
if tableView == mainTable
{
if let data = mainData
{
return data.count
}
}
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if tableView == mainTable
{
if let data = mainData?[section]
{
return data.count
}
}
if tableView == detailedTable
{
if let data = selectedDetailData
{
return data.count
}
}
return 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if tableView == mainTable
{
let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath) as! MainTableCell
if let data = mainData?[indexPath.section]
{
cell.textLabel?.text = data[indexPath.row]
}
if selectingOption
{
cell.selectedOption = detailedData?[indexPath.section][indexPath.row][0]
}
return cell;
}
if tableView == detailedTable
{
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailCell", for: indexPath) as! DetailTableCell
if let text = selectedDetailData?[indexPath.row]
{
cell.textLabel?.text = text
}
return cell;
}
return UITableViewCell()
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if tableView == mainTable
{
selectedDetailData = detailedData?[indexPath.section][indexPath.row]
detailedTable.reloadData()
closeAndBackButton.setTitle("Back", for: .normal)
moveTable()
}
}
private func moveTable()
{
tableMovingAnchor?.isActive = false
var moveOut = true
if closeAndBackButton.currentTitle == "Back"
{
var anchorConstant:CGFloat = 0
switch segueDirection {
case .top:
anchorConstant = -frame.size.height
case .left:
anchorConstant = -frame.size.width
case .right:
anchorConstant = frame.size.width
case .bottom:
anchorConstant = frame.size.height
}
tableMovingAnchor?.constant = anchorConstant
}
else if closeAndBackButton.currentTitle == "Done"
{
mainTable.deselectRow(at: mainTable.indexPathForSelectedRow!, animated: true)
tableMovingAnchor?.constant = 0
moveOut = false
}
tableMovingAnchor?.isActive = true
UIView.animate(withDuration: 0.5, animations: {
if moveOut
{
self.mainTable.alpha = 0
}
else
{
self.mainTable.alpha = 1
}
self.layoutIfNeeded()
})
}
}
public protocol MTableViewDelegate {
func moveBackView()
}
| mit | 53493028c75d03b6f9f421ac1fc5d1b9 | 29.92674 | 205 | 0.587469 | 5.160758 | false | false | false | false |
brentsimmons/Evergreen | Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift | 1 | 1915 | //
// SingleLineTextFieldSizer.swift
// NetNewsWire
//
// Created by Brent Simmons on 2/19/18.
// Copyright © 2018 Ranchero Software. All rights reserved.
//
import AppKit
// Get the size of an NSTextField configured with a specific font with a specific size.
// Uses a cache.
// Main thready only.
final class SingleLineTextFieldSizer {
let font: NSFont
private let textField: NSTextField
private var cache = [String: NSSize]()
/// Get the NSTextField size for text, given a font.
static func size(for text: String, font: NSFont) -> NSSize {
return sizer(for: font).size(for: text)
}
init(font: NSFont) {
self.textField = NSTextField(labelWithString: "")
self.textField.font = font
self.font = font
}
func size(for text: String) -> NSSize {
if let cachedSize = cache[text] {
return cachedSize
}
textField.stringValue = text
var calculatedSize = textField.fittingSize
calculatedSize.height = ceil(calculatedSize.height)
calculatedSize.width = ceil(calculatedSize.width)
cache[text] = calculatedSize
return calculatedSize
}
static private var sizers = [SingleLineTextFieldSizer]()
static private func sizer(for font: NSFont) -> SingleLineTextFieldSizer {
// We used to use an [NSFont: SingleLineTextFieldSizer] dictionary —
// until, in 10.14.5, we started getting crashes with the message:
// Fatal error: Duplicate keys of type 'NSFont' were found in a Dictionary.
// This usually means either that the type violates Hashable's requirements, or
// that members of such a dictionary were mutated after insertion.
// We use just an array of sizers now — which is totally fine,
// because there’s only going to be like three of them.
if let cachedSizer = sizers.first(where: { $0.font == font }) {
return cachedSizer
}
let newSizer = SingleLineTextFieldSizer(font: font)
sizers.append(newSizer)
return newSizer
}
}
| mit | 9b1a339be5361da702851b63a64bfcb7 | 28.353846 | 87 | 0.722746 | 3.763314 | false | false | false | false |
FredrikSjoberg/SnapStack | SnapStack/Extensions/NSExpression+Extensions.swift | 1 | 1896 | //
// NSExpression+Extensions.swift
// SnapStack
//
// Created by Fredrik Sjöberg on 22/09/15.
// Copyright © 2015 Fredrik Sjöberg. All rights reserved.
//
import Foundation
public func == (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .EqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func != (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .NotEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func < (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .LessThanPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func <= (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .LessThanOrEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func > (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .GreaterThanPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func >= (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .GreaterThanOrEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
} | mit | 8e1bc0dd76223aa8ea2a7ed3eed5ac52 | 56.393939 | 216 | 0.799789 | 5.034574 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/NotificationSettingsViewController.swift | 1 | 14066 | import UIKit
import UserNotifications
import WMF
protocol NotificationSettingsItem {
var title: String { get }
}
struct NotificationSettingsSwitchItem: NotificationSettingsItem {
let title: String
let switchChecker: () -> Bool
let switchAction: (Bool) -> Void
}
struct NotificationSettingsButtonItem: NotificationSettingsItem {
let title: String
let buttonAction: () -> Void
}
struct NotificationSettingsInfoItem: NotificationSettingsItem {
let title: String
}
struct NotificationSettingsSection {
let headerTitle:String
let items: [NotificationSettingsItem]
}
// TODO: These are just here to prevent localization diffs. Reinstate if needed once notifications type screen is complete.
/*
WMFLocalizedString("settings-notifications-learn-more", value:"Learn more about notifications", comment:"A title for a button to learn more about notifications")
WMFLocalizedString("welcome-notifications-tell-me-more-title", value:"More about notifications", comment:"Title for detailed notification explanation")
WMFLocalizedString("welcome-notifications-tell-me-more-storage", value:"Notification preferences are stored on device and not based on personal information or activity.", comment:"An explanation of how notifications are stored")
WMFLocalizedString("welcome-notifications-tell-me-more-creation", value:"Notifications are created and delivered on your device by the app, not from our (or third party) servers.", comment:"An explanation of how notifications are created")
WMFLocalizedString("settings-notifications-info", value:"Be alerted to trending and top read articles on Wikipedia with our push notifications. All provided with respect to privacy and up to the minute data.", comment:"A short description of notifications shown in settings")
WMFLocalizedString("settings-notifications-trending", value:"Trending current events", comment:"Title for the setting for trending notifications")
WMFLocalizedString("settings-notifications-info", value:"Be alerted to trending and top read articles on Wikipedia with our push notifications. All provided with respect to privacy and up to the minute data.", comment:"A short description of notifications shown in settings")
*/
@objc(WMFNotificationSettingsViewController)
class NotificationSettingsViewController: SubSettingsViewController {
var sections = [NotificationSettingsSection]()
var observationToken: NSObjectProtocol?
private let authManager: WMFAuthenticationManager
private let notificationsController: WMFNotificationsController
@objc init(authManager: WMFAuthenticationManager, notificationsController: WMFNotificationsController) {
self.authManager = authManager
self.notificationsController = notificationsController
super.init(nibName: nil, bundle: nil)
notificationsController.deviceTokenDelegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = CommonStrings.pushNotifications
tableView.register(WMFSettingsTableViewCell.wmf_classNib(), forCellReuseIdentifier: WMFSettingsTableViewCell.identifier)
observationToken = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] (note) in
self?.updateSections()
}
}
deinit {
if let token = observationToken {
NotificationCenter.default.removeObserver(token)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateSections()
}
func sectionsForPermissionsNotDetermined() -> [NotificationSettingsSection] {
var updatedSections = [NotificationSettingsSection]()
// TODO: Temporary happy path permissions logic, use proper localized string for title when non-temporary
let notificationSettingsItems: [NotificationSettingsItem] = [NotificationSettingsSwitchItem(title: "Enable push notifications", switchChecker: { () -> Bool in
return false
}, switchAction: { [weak self] (isOn) in
if isOn {
self?.requestPermissionsIfNeededAndRegisterDeviceToken()
}
})]
let notificationSettingsSection = NotificationSettingsSection(headerTitle: WMFLocalizedString("settings-notifications-push-notifications", value:"Push notifications", comment:"A title for a list of Push notifications"), items: notificationSettingsItems)
updatedSections.append(notificationSettingsSection)
return updatedSections
}
private func requestPermissionsIfNeededAndRegisterDeviceToken() {
notificationsController.requestPermissionsIfNecessary {[weak self] isAllowed, error in
DispatchQueue.main.async {
guard let self = self else {
return
}
if let error = error as NSError? {
self.wmf_showAlertWithError(error)
return
}
guard isAllowed else {
self.updateSections()
return
}
guard self.notificationsController.remoteRegistrationDeviceToken != nil else {
self.updateSections()
return
}
self.notificationsController.subscribeToEchoNotifications(completionHandler: {[weak self] error in
DispatchQueue.main.async {
if let error = error as NSError? {
self?.wmf_showAlertWithError(error)
}
self?.updateSections()
}
})
}
}
}
// TODO: Temporary login logic, use proper localized string for titles when non-temporary
func sectionsForNotLoggedIn() -> [NotificationSettingsSection] {
let logInItem: NotificationSettingsItem = NotificationSettingsButtonItem(title: "Log in", buttonAction: {
self.wmf_showLoginOrCreateAccountToThankRevisionAuthorPanel(theme: self.theme, dismissHandler: nil, loginSuccessCompletion: {
self.updateSections()
}, loginDismissedCompletion: nil)
})
return [NotificationSettingsSection(headerTitle: "Please log in first.", items: [logInItem])]
}
func sectionsForPermissionsDenied() -> [NotificationSettingsSection] {
let unauthorizedItems: [NotificationSettingsItem] = [NotificationSettingsButtonItem(title: WMFLocalizedString("settings-notifications-system-turn-on", value:"Turn on Notifications", comment:"Title for a button for turnining on notifications in the system settings"), buttonAction: {
guard let URL = URL(string: UIApplication.openSettingsURLString) else {
return
}
UIApplication.shared.open(URL, options: [:], completionHandler: nil)
})]
return [NotificationSettingsSection(headerTitle: "", items: unauthorizedItems)]
}
// TODO: Temporary subscription failure logic, use proper localized string for titles when non-temporary
func sectionsForSubscriptionFailure() -> [NotificationSettingsSection] {
let subscriptionFailureItem: NotificationSettingsItem = NotificationSettingsInfoItem(title: "Something failed while attempting to set up notifications on your device. Please try again later.")
return [NotificationSettingsSection(headerTitle: "", items: [subscriptionFailureItem])]
}
// TODO: Temporary waiting for device token logic
func sectionsForWaitingForDeviceToken() -> [NotificationSettingsSection] {
let waitingForDeviceTokenItem: NotificationSettingsItem = NotificationSettingsInfoItem(title: "Waiting for device token, will subscribe when it comes in.")
return [NotificationSettingsSection(headerTitle: "", items: [waitingForDeviceTokenItem])]
}
// TODO: Temporary permissions allowed logic, use proper localized string for titles when non-temporary
func sectionsForPermissionsAllowed() -> [NotificationSettingsSection] {
let allowedItems: [NotificationSettingsItem] = [NotificationSettingsButtonItem(title: "Notifications are enabled. Go to iOS settings to disable notifications", buttonAction: {
guard let URL = URL(string: UIApplication.openSettingsURLString) else {
return
}
UIApplication.shared.open(URL, options: [:], completionHandler: nil)
})]
return [NotificationSettingsSection(headerTitle: "", items: allowedItems)]
}
func updateSections() {
tableView.reloadData()
guard authManager.isLoggedIn else {
sections = self.sectionsForNotLoggedIn()
tableView.reloadData()
return
}
notificationsController.notificationPermissionsStatus { [weak self] status in
DispatchQueue.main.async {
guard let self = self else {
return
}
switch status {
case .denied:
self.sections = self.sectionsForPermissionsDenied()
case .notDetermined:
self.sections = self.sectionsForPermissionsNotDetermined()
case .authorized, .provisional, .ephemeral:
guard !self.notificationsController.isWaitingOnDeviceToken() else {
self.sections = self.sectionsForWaitingForDeviceToken()
return
}
guard self.notificationsController.remoteRegistrationDeviceToken != nil else {
self.sections = self.sectionsForSubscriptionFailure()
return
}
self.sections = self.sectionsForPermissionsAllowed()
default:
break
}
self.tableView.reloadData()
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: WMFSettingsTableViewCell.identifier, for: indexPath) as? WMFSettingsTableViewCell else {
return UITableViewCell()
}
let item = sections[indexPath.section].items[indexPath.item]
cell.title = item.title
cell.iconName = nil
if let tc = cell as Themeable? {
tc.apply(theme: theme)
}
if let switchItem = item as? NotificationSettingsSwitchItem {
cell.disclosureType = .switch
cell.disclosureSwitch.isOn = switchItem.switchChecker()
cell.disclosureSwitch.addTarget(self, action: #selector(self.handleSwitchValueChange(_:)), for: .valueChanged)
} else if item is NotificationSettingsInfoItem {
cell.disclosureType = .none
} else {
cell.disclosureType = .viewController
}
return cell
}
@objc func handleSwitchValueChange(_ sender: UISwitch) {
// FIXME: hardcoded item below
let item = sections[0].items[0]
if let switchItem = item as? NotificationSettingsSwitchItem {
switchItem.switchAction(sender.isOn)
}
}
@objc func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = WMFTableHeaderFooterLabelView.wmf_viewFromClassNib() else {
return nil
}
if let th = header as Themeable? {
th.apply(theme: theme)
}
header.text = sections[section].headerTitle
return header
}
@objc func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let header = WMFTableHeaderFooterLabelView.wmf_viewFromClassNib() else {
return 0
}
header.text = sections[section].headerTitle
return header.height(withExpectedWidth: self.view.frame.width - tableView.separatorInset.left - tableView.separatorInset.right)
}
@objc func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = sections[indexPath.section].items[indexPath.item] as? NotificationSettingsButtonItem else {
return
}
item.buttonAction()
tableView.deselectRow(at: indexPath, animated: true)
}
@objc func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return sections[indexPath.section].items[indexPath.item] as? NotificationSettingsSwitchItem == nil
}
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.baseBackground
tableView.backgroundColor = theme.colors.baseBackground
tableView.reloadData()
}
}
extension NotificationSettingsViewController: WMFNotificationsControllerDeviceTokenDelegate {
func didUpdateDeviceTokenStatus(from controller: WMFNotificationsController) {
requestPermissionsIfNeededAndRegisterDeviceToken()
}
}
| mit | 6c598602f0cdb0ee4dc72d3bed9acc72 | 44.521036 | 290 | 0.65932 | 5.868169 | false | false | false | false |
nProdanov/FuelCalculator | Fuel economy smart calc./Fuel economy smart calc./AppDelegate.swift | 1 | 4673 | //
// AppDelegate.swift
// Fuel economy smart calc.
//
// Created by Nikolay Prodanow on 3/17/17.
// Copyright © 2017 Nikolay Prodanow. All rights reserved.
//
import UIKit
import Firebase
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var charges: [Charge]?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if FIRApp.defaultApp() == nil {
FIRApp.configure()
}
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "DbModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 7855cc52786e0466d6090bf5ce8ae517 | 46.673469 | 285 | 0.6753 | 5.854637 | false | false | false | false |
jaropawlak/Signal-iOS | Signal/src/call/NonCallKitCallUIAdaptee.swift | 1 | 5013 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
/**
* Manage call related UI in a pre-CallKit world.
*/
class NonCallKitCallUIAdaptee: CallUIAdaptee {
let TAG = "[NonCallKitCallUIAdaptee]"
let notificationsAdapter: CallNotificationsAdapter
let callService: CallService
// Starting/Stopping incoming call ringing is our apps responsibility for the non CallKit interface.
let hasManualRinger = true
required init(callService: CallService, notificationsAdapter: CallNotificationsAdapter) {
self.callService = callService
self.notificationsAdapter = notificationsAdapter
}
func startOutgoingCall(handle: String) -> SignalCall {
AssertIsOnMainThread()
let call = SignalCall.outgoingCall(localId: UUID(), remotePhoneNumber: handle)
self.callService.handleOutgoingCall(call).then {
Logger.debug("\(self.TAG) handleOutgoingCall succeeded")
}.catch { error in
Logger.error("\(self.TAG) handleOutgoingCall failed with error: \(error)")
}.retainUntilComplete()
return call
}
func reportIncomingCall(_ call: SignalCall, callerName: String) {
AssertIsOnMainThread()
Logger.debug("\(TAG) \(#function)")
self.showCall(call)
// present lock screen notification
if UIApplication.shared.applicationState == .active {
Logger.debug("\(TAG) skipping notification since app is already active.")
} else {
notificationsAdapter.presentIncomingCall(call, callerName: callerName)
}
}
func reportMissedCall(_ call: SignalCall, callerName: String) {
AssertIsOnMainThread()
notificationsAdapter.presentMissedCall(call, callerName: callerName)
}
func answerCall(localId: UUID) {
AssertIsOnMainThread()
guard let call = self.callService.call else {
owsFail("\(self.TAG) in \(#function) No current call.")
return
}
guard call.localId == localId else {
owsFail("\(self.TAG) in \(#function) localId does not match current call")
return
}
self.answerCall(call)
}
func answerCall(_ call: SignalCall) {
AssertIsOnMainThread()
guard call.localId == self.callService.call?.localId else {
owsFail("\(self.TAG) in \(#function) localId does not match current call")
return
}
self.callService.handleAnswerCall(call)
}
func declineCall(localId: UUID) {
AssertIsOnMainThread()
guard let call = self.callService.call else {
owsFail("\(self.TAG) in \(#function) No current call.")
return
}
guard call.localId == localId else {
owsFail("\(self.TAG) in \(#function) localId does not match current call")
return
}
self.declineCall(call)
}
func declineCall(_ call: SignalCall) {
AssertIsOnMainThread()
guard call.localId == self.callService.call?.localId else {
owsFail("\(self.TAG) in \(#function) localId does not match current call")
return
}
self.callService.handleDeclineCall(call)
}
func recipientAcceptedCall(_ call: SignalCall) {
AssertIsOnMainThread()
// no-op
}
func localHangupCall(_ call: SignalCall) {
AssertIsOnMainThread()
// If both parties hang up at the same moment,
// call might already be nil.
guard self.callService.call == nil || call.localId == self.callService.call?.localId else {
owsFail("\(self.TAG) in \(#function) localId does not match current call")
return
}
self.callService.handleLocalHungupCall(call)
}
internal func remoteDidHangupCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.debug("\(TAG) in \(#function) is no-op")
}
internal func remoteBusy(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.debug("\(TAG) in \(#function) is no-op")
}
internal func failCall(_ call: SignalCall, error: CallError) {
AssertIsOnMainThread()
Logger.debug("\(TAG) in \(#function) is no-op")
}
func setIsMuted(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
guard call.localId == self.callService.call?.localId else {
owsFail("\(self.TAG) in \(#function) localId does not match current call")
return
}
self.callService.setIsMuted(call: call, isMuted: isMuted)
}
func setHasLocalVideo(call: SignalCall, hasLocalVideo: Bool) {
AssertIsOnMainThread()
guard call.localId == self.callService.call?.localId else {
owsFail("\(self.TAG) in \(#function) localId does not match current call")
return
}
self.callService.setHasLocalVideo(hasLocalVideo: hasLocalVideo)
}
}
| gpl-3.0 | 202a8acc4f80fbaab0218ebe475eec40 | 28.315789 | 104 | 0.627369 | 4.934055 | false | false | false | false |
shashankpali/ATZAlertController | Example/ATZAlertController/ATZAlertController/ATZAlertController+Helper.swift | 2 | 3768 | // ATZAlertController+Helper.swift
//
// Copyright (c) 2016 Shashank Pali
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import Foundation
import ObjectiveC
private var ATZWindow: UInt8 = 0
extension ATZAlertController
{
var alertWindow: UIWindow!
{
get {
return objc_getAssociatedObject(self, &ATZWindow) as? UIWindow
}
set(newValue) {
objc_setAssociatedObject(self, &ATZWindow, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
class func alertController(title: String, message: String, cancel: String?, destructive: String?, titleArray: NSArray?, style: UIAlertControllerStyle, handler: ((action: UIAlertAction, titleString: String) -> Void)?) -> ATZAlertController
{
let alert = ATZAlertController(title: title, message: message, preferredStyle: style)
if ((titleArray?.count) != nil)
{
for obj in titleArray!
{
let selfAction: UIAlertAction!
if obj is String
{
selfAction = UIAlertAction(title: obj as? String, style: .Default, handler: { (act) in
if ((handler) != nil)
{
handler!(action: act, titleString: act.title!)
}
})
}else
{
let ATZButton = obj as! ATZActionButton
selfAction = UIAlertAction(title: ATZButton.title, style: ATZButton.style, handler: { (act) in
if ((handler) != nil)
{
handler!(action: act, titleString: act.title!)
}
})
}
alert.addAction(selfAction)
}
}
if let _ = cancel
{
let selfAction = UIAlertAction(title: cancel, style: .Cancel, handler: { (act) in
if ((handler) != nil)
{
handler!(action: act, titleString: act.title!)
}
})
alert.addAction(selfAction)
}
if let _ = destructive
{
let selfAction = UIAlertAction(title: destructive, style: .Destructive, handler: { (act) in
if ((handler) != nil)
{
handler!(action: act, titleString: act.title!)
}
})
alert.addAction(selfAction)
}
return alert
}
func showAlertAnimation(animated: Bool)
{
alertWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.tintColor = UIApplication.sharedApplication().delegate!.window??.tintColor
let topWindow = UIApplication.sharedApplication().windows.last
alertWindow.windowLevel = (topWindow?.windowLevel)! + 1
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.presentViewController(self, animated: animated, completion: nil)
}
}
| mit | 06ae99fe252dccc34710a4aeb80f01b5 | 32.642857 | 240 | 0.660563 | 4.556227 | false | false | false | false |
lstn-ltd/lstn-sdk-ios | Example/Tests/Player/PlayerSpy.swift | 1 | 1379 | //
// PlayerSpy.swift
// Lstn
//
// Created by Dan Halliday on 17/10/2016.
// Copyright © 2016 Lstn Ltd. All rights reserved.
//
import Lstn
class PlayerSpy: PlayerDelegate {
var loadingDidStartFired = false
var loadingDidFinishFired = false
var loadingDidFailFired = false
func loadingDidStart() {
self.loadingDidStartFired = true
}
func loadingDidFinish() {
self.loadingDidFinishFired = true
}
func loadingDidFail() {
self.loadingDidFailFired = true
}
var playbackDidStartFired = false
var playbackDidProgressFired = false
var playbackDidStopFired = false
var playbackDidFinishFired = false
var playbackDidFailFired = false
func playbackDidStart() {
self.playbackDidStartFired = true
}
func playbackDidProgress(amount: Double) {
self.playbackDidProgressFired = true
}
func playbackDidStop() {
self.playbackDidStopFired = true
}
func playbackDidFinish() {
self.playbackDidFinishFired = true
}
func playbackDidFail() {
self.playbackDidFailFired = true
}
var requestPreviousItemFired = false
var requestNextItemFired = false
func requestPreviousItem() {
self.requestPreviousItemFired = true
}
func requestNextItem() {
self.requestNextItemFired = true
}
}
| mit | b697be697d56ba0cebb9be355d93be38 | 19.878788 | 51 | 0.666183 | 4.474026 | false | false | false | false |
mownier/photostream | Photostream/UI/Post Composer/PostComposerNavigationController.swift | 1 | 1867 | //
// PostComposerNavigationController.swift
// Photostream
//
// Created by Mounir Ybanez on 25/11/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
protocol PostComposerDelegate: class {
func postComposerDidFinish(with image: UIImage, content: String)
func postComposerDidCancel()
}
class PostComposerNavigationController: UINavigationController {
weak var moduleDelegate: PostComposerDelegate?
var photoPicker: PhotoPickerViewController!
var photoShare: PhotoShareViewController!
required convenience init(photoPicker: PhotoPickerViewController, photoShare: PhotoShareViewController) {
self.init(rootViewController: photoPicker)
self.photoPicker = photoPicker
self.photoShare = photoShare
}
override func loadView() {
super.loadView()
navigationBar.isTranslucent = false
navigationBar.tintColor = UIColor(red: 10/255, green: 10/255, blue: 10/255, alpha: 1)
}
func dismiss() {
dismiss(animated: true, completion: nil)
}
}
extension PostComposerNavigationController: PhotoPickerModuleDelegate {
func photoPickerDidCancel() {
moduleDelegate?.postComposerDidCancel()
dismiss()
}
func photoPickerDidFinish(with image: UIImage?) {
guard image != nil else {
return
}
photoShare.image = image
pushViewController(photoShare, animated: true)
}
}
extension PostComposerNavigationController: PhotoShareModuleDelegate {
func photoShareDidCancel() {
photoShare.image = nil
let _ = popViewController(animated: true)
}
func photoShareDidFinish(with image: UIImage, content: String) {
moduleDelegate?.postComposerDidFinish(with: image, content: content)
dismiss()
}
}
| mit | 28a0a85c3f7bf73d1deec2fcf63084bc | 26.043478 | 109 | 0.685423 | 5.002681 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/social/telegram/SPTelegram.swift | 1 | 1962 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([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 UIKit
struct SPTelegram {
static func share(text: String) {
let urlStringEncoded = text.addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)
let url = NSURL(string: "tg://msg?text=\(urlStringEncoded!)")
let tgURL:NSURL? = url
if UIApplication.shared.canOpenURL(URL(string: "tg://msg?text=test")!) {
UIApplication.shared.openURL(tgURL! as URL )
}
}
static func isSetApp() -> Bool {
if UIApplication.shared.canOpenURL(URL(string: "tg://msg?text=test")!) {
return true
} else {
return false
}
}
static func joinChannel(id: String) {
let url = "https://t.me/joinchat/\(id)"
SPOpener.Link.redirectToBrowserAndOpen(link: url)
}
}
| mit | e734c9bb5de9e36d13ae2ff1f7772c73 | 39.020408 | 98 | 0.692504 | 4.426637 | false | false | false | false |
rzrasel/iOS-Swift-2016-01 | SwiftCLLocationManagerOne/SwiftCLLocationManagerOne/AppDelegate.swift | 2 | 6130 | //
// AppDelegate.swift
// SwiftCLLocationManagerOne
//
// Created by NextDot on 2/7/16.
// Copyright © 2016 RzRasel. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "rz.rasel.SwiftCLLocationManagerOne" 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("SwiftCLLocationManagerOne", 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("SingleViewCoreData.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()
}
}
}
}
| apache-2.0 | 2ddaaa2a93b5ede60b22ac22027a78ef | 54.216216 | 291 | 0.721488 | 5.910318 | false | false | false | false |
EstebanVallejo/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/UILoadingView.swift | 2 | 1746 | //
// UILoadingView.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 30/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import UIKit
public class UILoadingView : UIView {
public init(frame rect: CGRect, text: NSString = "Cargando...".localized) {
super.init(frame: rect)
self.backgroundColor = UIColor.whiteColor()
self.label.text = text as String
self.label.textColor = self.spinner.color
self.spinner.startAnimating()
self.addSubview(self.label)
self.addSubview(self.spinner)
// self.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
self.setNeedsLayout()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public var label : UILabel = {
var l = UILabel()
l.font = UIFont(name: "HelveticaNeue", size: 15)
return l
}()
public var spinner: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
override public func layoutSubviews() {
self.label.sizeToFit()
var labelSize: CGSize = self.label.frame.size
var labelFrame: CGRect = CGRect()
labelFrame.size = labelSize
self.label.frame = labelFrame
// center label and spinner
self.label.center = self.center
self.spinner.center = self.center
// horizontally align
labelFrame = self.label.frame
var spinnerFrame: CGRect = self.spinner.frame
var totalWidth: CGFloat = spinnerFrame.size.width + 5 + labelSize.width
spinnerFrame.origin.x = self.bounds.origin.x + (self.bounds.size.width - totalWidth) / 2
labelFrame.origin.x = spinnerFrame.origin.x + spinnerFrame.size.width + 5
self.label.frame = labelFrame
self.spinner.frame = spinnerFrame
}
}
| mit | 436ef6ae32cc2ea5df3ff5a370620044 | 27.622951 | 129 | 0.732532 | 3.730769 | false | false | false | false |
clarkcb/xsearch | swift/swiftsearch/Sources/swiftsearch/FileTypes.swift | 1 | 7088 | //
// FileTypes.swift
// swiftsearch
//
// Created by Cary Clark on 5/12/15.
// Copyright (c) 2015 Cary Clark. All rights reserved.
//
import Foundation
public enum FileType {
case unknown, archive, binary, code, text, xml
}
class FileTypesXmlParser: NSObject, XMLParserDelegate {
var fileTypeDict: [String: Set<String>] = [:]
let fileTypeNodeName = "filetype"
let extensionsNodeName = "extensions"
let nameAttributeName = "name"
var element = ""
var fileTypeName = ""
var extensions = NSMutableString()
func parseFile(_ filepath: String) -> [String: Set<String>] {
if FileManager.default.fileExists(atPath: filepath) {
let data: Data? = try? Data(contentsOf: URL(fileURLWithPath: filepath))
let inputStream: InputStream? = InputStream(data: data!)
let parser: XMLParser? = XMLParser(stream: inputStream!)
if parser != nil {
parser!.delegate = self
parser!.parse()
}
} else {
print("ERROR: filepath not found: \(filepath)")
}
return fileTypeDict
}
func parser(_: XMLParser, didStartElement elementName: String,
namespaceURI _: String?, qualifiedName _: String?,
attributes attributeDict: [String: String])
{
element = elementName
if (elementName as NSString).isEqual(to: fileTypeNodeName) {
if attributeDict.index(forKey: nameAttributeName) != nil {
fileTypeName = (attributeDict[nameAttributeName]!)
}
extensions = NSMutableString()
extensions = ""
}
}
func parser(_: XMLParser, foundCharacters string: String) {
if element == extensionsNodeName {
extensions.append(string)
}
}
func parser(_: XMLParser, didEndElement elementName: String,
namespaceURI _: String?, qualifiedName _: String?)
{
if (elementName as NSString).isEqual(to: fileTypeNodeName) {
if !extensions.isEqual(nil) {
let exts = extensions.components(separatedBy: whitespace)
fileTypeDict[fileTypeName] = Set(exts)
}
}
}
}
public class FileTypes {
fileprivate static let archive = "archive"
fileprivate static let binary = "binary"
fileprivate static let code = "code"
fileprivate static let searchable = "searchable"
fileprivate static let text = "text"
fileprivate static let unknown = "unknown"
fileprivate static let xml = "xml"
private var fileTypesDict = [String: Set<String>]()
public init() {
// setFileTypesFromXml()
setFileTypesFromJson()
}
private func setFileTypesFromXml() {
let parser = FileTypesXmlParser()
fileTypesDict = parser.parseFile(Config.fileTypesPath)
fileTypesDict[FileTypes.text] = fileTypesDict[FileTypes.text]!.union(fileTypesDict[FileTypes.code]!)
.union(fileTypesDict[FileTypes.xml]!)
fileTypesDict[FileTypes.searchable] =
fileTypesDict[FileTypes.text]!.union(fileTypesDict[FileTypes.binary]!)
.union(fileTypesDict[FileTypes.archive]!)
}
private func setFileTypesFromJson() {
do {
let fileUrl = URL(fileURLWithPath: Config.fileTypesPath)
let data = try Data(contentsOf: fileUrl, options: .mappedIfSafe)
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
if let filetypes = json["filetypes"] as? [[String: Any]] {
for ft in filetypes {
let typeName = ft["type"] as! String
let extensions = ft["extensions"] as! [String]
fileTypesDict[typeName] = Set(extensions)
}
fileTypesDict[FileTypes.text] = fileTypesDict[FileTypes.text]!.union(fileTypesDict[FileTypes.code]!)
.union(fileTypesDict[FileTypes.xml]!)
fileTypesDict[FileTypes.searchable] =
fileTypesDict[FileTypes.text]!.union(fileTypesDict[FileTypes.binary]!)
.union(fileTypesDict[FileTypes.archive]!)
}
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
public static func fromName(_ typeName: String) -> FileType {
let lname = typeName.lowercased()
if lname == text {
return FileType.text
}
if lname == binary {
return FileType.binary
}
if lname == archive {
return FileType.archive
}
if lname == code {
return FileType.code
}
if lname == xml {
return FileType.xml
}
return FileType.unknown
}
public static func toName(_ fileType: FileType) -> String {
if fileType == FileType.text {
return "text"
}
if fileType == FileType.binary {
return "binary"
}
if fileType == FileType.archive {
return "archive"
}
if fileType == FileType.code {
return "code"
}
if fileType == FileType.xml {
return "xml"
}
return "unknown"
}
public func getFileType(_ fileName: String) -> FileType {
if isCodeFile(fileName) {
return FileType.code
}
if isXmlFile(fileName) {
return FileType.xml
}
if isTextFile(fileName) {
return FileType.text
}
if isBinaryFile(fileName) {
return FileType.binary
}
if isArchiveFile(fileName) {
return FileType.archive
}
return FileType.unknown
}
private func isFileOfType(_ fileName: String, _ typeName: String) -> Bool {
fileTypesDict.index(forKey: typeName) != nil &&
fileTypesDict[typeName]!.contains(FileUtil.getExtension(fileName))
}
public func isArchiveFile(_ fileName: String) -> Bool {
isFileOfType(fileName, FileTypes.archive)
}
public func isBinaryFile(_ fileName: String) -> Bool {
isFileOfType(fileName, FileTypes.binary)
}
public func isCodeFile(_ fileName: String) -> Bool {
isFileOfType(fileName, FileTypes.code)
}
public func isSearchableFile(_ fileName: String) -> Bool {
isFileOfType(fileName, FileTypes.searchable)
}
public func isTextFile(_ fileName: String) -> Bool {
isFileOfType(fileName, FileTypes.text)
}
public func isUnknownFile(_ fileName: String) -> Bool {
(fileTypesDict.index(forKey: FileTypes.unknown) != nil &&
fileTypesDict[FileTypes.unknown]!.contains(FileUtil.getExtension(fileName)))
|| !isSearchableFile(fileName)
}
public func isXmlFile(_ fileName: String) -> Bool {
isFileOfType(fileName, FileTypes.xml)
}
}
| mit | d02947e8e5c755d7d61cfe0912be34a6 | 32.121495 | 120 | 0.585638 | 4.769852 | false | false | false | false |
AckeeCZ/ACKReactiveExtensions | ACKReactiveExtensions/Realm/RealmExtensions.swift | 1 | 11103 | //
// RealmExtensions.swift
// Realm
//
// Created by Tomáš Kohout on 01/12/15.
// Copyright © 2015 Ackee s.r.o. All rights reserved.
//
import UIKit
import RealmSwift
import ReactiveCocoa
import ReactiveSwift
#if !COCOAPODS
import ACKReactiveExtensionsCore
#endif
/// Error return in case of Realm operation failure
public struct RealmError: Error {
public let underlyingError: NSError
public init(underlyingError: NSError){
self.underlyingError = underlyingError
}
}
/// Enum which represents RealmCollectionChange
public enum Change<T> {
typealias Element = T
/// Initial value
case initial(T)
/// RealmCollection was updated
case update(T, deletions: [Int], insertions: [Int], modifications: [Int])
}
public extension Reactive where Base: RealmCollection {
/// SignalProducer that sends changes as they happen
var changes: SignalProducer<Change<Base>, RealmError> {
var notificationToken: NotificationToken? = nil
let producer: SignalProducer<Change<Base>, RealmError> = SignalProducer { sink, d in
guard let realm = self.base.realm else {
print("Cannot observe object without Realm")
return
}
func observe() -> NotificationToken? {
return self.base.observe(on: OperationQueue.current?.underlyingQueue) { changes in
switch changes {
case .initial(let initial):
sink.send(value: Change.initial(initial))
case .update(let updates, let deletions, let insertions, let modifications):
sink.send(value: Change.update(updates, deletions: deletions, insertions: insertions, modifications: modifications))
case .error(let e):
sink.send(error: RealmError(underlyingError: e as NSError))
}
}
}
let registerObserverIfPossible: () -> (Bool, NotificationToken?) = {
if !realm.isInWriteTransaction { return (true, observe()) }
return (false, nil)
}
var counter = 0
let maxRetries = 10
func registerWhileNotSuccessful(queue: DispatchQueue) {
let (registered, token) = registerObserverIfPossible()
guard !registered, counter < maxRetries else { notificationToken = token; return }
counter += 1
queue.async { registerWhileNotSuccessful(queue: queue) }
}
if let opQueue = OperationQueue.current, let dispatchQueue = opQueue.underlyingQueue {
registerWhileNotSuccessful(queue: dispatchQueue)
} else {
notificationToken = observe()
}
}.on(terminated: {
notificationToken?.invalidate()
notificationToken = nil
}, disposed: {
notificationToken?.invalidate()
notificationToken = nil
})
return producer
}
/// SignalProducer that sends the latest value
var values: SignalProducer<Base, RealmError> {
return self.changes.map { changes -> Base in
switch changes {
case .initial(let initial):
return initial
case .update(let updates, _, _, _):
return updates
}
}
}
/// Property which represents the latest value
var property: ReactiveSwift.Property<Base> {
return ReactiveSwift.Property(initial: base, then: values.ignoreError() )
}
}
//MARK: Saving
public extension Reactive where Base: Object {
/**
* Reactive save Realm object
*
* - parameter update: Realm should find existing object using primaryKey() and update it if it exists otherwise create new object
* - parameter writeBlock: Closure which allows custom Realm operation instead of default add
*/
func save(update: Realm.UpdatePolicy = .all, writeBlock: ((Realm)->Void)? = nil) -> SignalProducer<Base, RealmError>{
return SignalProducer<Base, RealmError> { sink, d in
do {
let realm = try Realm()
realm.refresh()
try realm.write {
if let writeBlock = writeBlock {
writeBlock(realm)
} else {
realm.add(self.base, update: update)
}
}
sink.send(value: self.base)
sink.sendCompleted()
} catch (let e) {
sink.send(error: RealmError(underlyingError: e as NSError) )
}
}
}
/**
* Reactively delete object
*/
func delete() -> SignalProducer<(), RealmError> {
return SignalProducer { sink, d in
do {
let realm = try Realm()
realm.refresh()
try realm.write {
realm.delete(self.base)
}
sink.send(value: ())
sink.sendCompleted()
} catch (let e) {
sink.send(error: RealmError(underlyingError: e as NSError) )
}
}
}
var changes: SignalProducer<ObjectChange<ObjectBase>, RealmError> {
var notificationToken: NotificationToken? = nil
let producer: SignalProducer<ObjectChange<ObjectBase>, RealmError> = SignalProducer { sink, d in
guard let realm = self.base.realm else {
print("Cannot observe object without Realm")
return
}
func observe() -> NotificationToken? {
return self.base.observe { change in
switch change {
case .error(let e):
sink.send(error: RealmError(underlyingError: e))
default:
sink.send(value: change)
}
}
}
let registerObserverIfPossible: () -> (Bool, NotificationToken?) = {
if !realm.isInWriteTransaction { return (true, observe()) }
return (false, nil)
}
var counter = 0
let maxRetries = 10
func registerWhileNotSuccessful(queue: DispatchQueue) {
let (registered, token) = registerObserverIfPossible()
guard !registered, counter < maxRetries else { notificationToken = token; return }
counter += 1
queue.async { registerWhileNotSuccessful(queue: queue) }
}
if let opQueue = OperationQueue.current, let dispatchQueue = opQueue.underlyingQueue {
registerWhileNotSuccessful(queue: dispatchQueue)
} else {
notificationToken = observe()
}
}.on(terminated: {
notificationToken?.invalidate()
notificationToken = nil
}, disposed: {
notificationToken?.invalidate()
notificationToken = nil
})
return producer
}
var values: SignalProducer<Base, RealmError> {
return self.changes
.filter { if case .deleted = $0 { return false }; return true }
.map { _ in
return self.base
}
}
var property: ReactiveSwift.Property<Base> {
return ReactiveSwift.Property(initial: base, then: values.ignoreError() )
}
}
//MARK: Table view
/// Protocol which allows UITableView to be reloaded automatically when database changes happen
public protocol RealmTableViewReloading {
associatedtype Element: Object
var tableView: UITableView! { get set }
}
public extension Reactive where Base: UIViewController, Base: RealmTableViewReloading {
/// Binding target which updates tableView according to received changes
var changes: BindingTarget<Change<Results<Base.Element>>> {
return makeBindingTarget { vc, changes in
guard let tableView = vc.tableView else { return }
switch changes {
case .initial:
tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
tableView.beginUpdates()
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.endUpdates()
break
}
}
}
}
//MARK: PrimaryKeyEquatable
protocol PrimaryKeyEquatable: AnyObject {
static func primaryKey() -> String?
subscript(key: String) -> Any? { get set }
}
extension Object: PrimaryKeyEquatable {}
precedencegroup PrimaryKeyEquative {
associativity: left
}
infix operator ~== : PrimaryKeyEquative
func ~==(lhs: PrimaryKeyEquatable, rhs: PrimaryKeyEquatable) -> Bool {
//Super ugly but can't find nicer way to assert same types
guard "\(type(of: lhs))" == "\(type(of: rhs))" else {
assertionFailure("Trying to compare different types \(type(of: lhs)) and \(type(of: rhs))")
return false
}
guard let primaryKey = type(of: lhs).primaryKey(), let lValue = lhs[primaryKey],
let rValue = rhs[primaryKey] else {
assertionFailure("Trying to compare object that has no primary key")
return false
}
if let l = lValue as? String, let r = rValue as? String {
return l == r
} else if let l = lValue as? Int, let r = rValue as? Int {
return l == r
} else if let l = lValue as? Int8, let r = rValue as? Int8 {
return l == r
} else if let l = lValue as? Int16, let r = rValue as? Int16 {
return l == r
} else if let l = lValue as? Int32, let r = rValue as? Int32 {
return l == r
} else if let l = lValue as? Int64, let r = rValue as? Int64 {
return l == r
} else {
assertionFailure("Unsupported primary key")
return false
}
}
//MARK: Orphaned Object
extension Realm {
/// Add objects and delete non-present objects from the orphan query
public func add<S: Sequence>(_ objects: S, update: Realm.UpdatePolicy = .all, deleteOrphanedQuery: Results<S.Iterator.Element>) where S.Iterator.Element: Object {
let allObjects = deleteOrphanedQuery.map { $0 }
//This could be faster with set, but we can't redefine hashable
let objectsToDelete = allObjects.filter { old in
!objects.contains(where: {
old ~== $0
})
}
self.delete(objectsToDelete)
self.add(objects, update: update)
}
}
| mit | 55e825c9cda321f9c40709cdcf7a5f27 | 33.04908 | 166 | 0.568919 | 5.087076 | false | false | false | false |
devpunk/cartesian | cartesian/View/DrawProject/Menu/VDrawProjectMenuTextCell.swift | 1 | 2605 | import UIKit
class VDrawProjectMenuTextCell:UICollectionViewCell
{
private weak var imageView:UIImageView!
private weak var labelTitle:UILabel!
private let kImageBottom:CGFloat = 15
private let kTitleHeight:CGFloat = 26
private let kAlphaSelected:CGFloat = 0.15
private let kAlphaNotSelected:CGFloat = 1
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let imageView:UIImageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.isUserInteractionEnabled = false
self.imageView = imageView
let labelTitle:UILabel = UILabel()
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.isUserInteractionEnabled = false
labelTitle.textAlignment = NSTextAlignment.center
labelTitle.font = UIFont.regular(size:12)
labelTitle.textColor = UIColor.black
self.labelTitle = labelTitle
addSubview(imageView)
addSubview(labelTitle)
NSLayoutConstraint.topToTop(
view:imageView,
toView:self)
NSLayoutConstraint.bottomToTop(
view:imageView,
toView:labelTitle,
constant:kImageBottom)
NSLayoutConstraint.equalsHorizontal(
view:imageView,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:labelTitle,
toView:self)
NSLayoutConstraint.height(
view:labelTitle,
constant:kTitleHeight)
NSLayoutConstraint.equalsHorizontal(
view:labelTitle,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
alpha = kAlphaSelected
}
else
{
alpha = kAlphaNotSelected
}
}
//MARK: public
func config(model:MDrawProjectMenuTextItem)
{
imageView.image = model.image
labelTitle.text = model.title
hover()
}
}
| mit | b39dbe5d7c8fc09c12ba25275b417c1e | 24.539216 | 68 | 0.596161 | 5.867117 | false | false | false | false |
enisinanaj/1-and-1.workouts | 1and1.workout/SQLite.swift | 1 | 4124 | //
// SQLite.swift
// microtime.tracker
//
// Created by Andy Miller on 20/11/2016.
// Copyright © 2016 Eni Sinanaj. All rights reserved.
//
import Foundation
import SQLite
class SQLiteProxy {
var db: Connection? = nil
var times: Table? = nil
let id = Expression<Int64>("id")
let startTime = Expression<String>("start_time")
let duration = Expression<Int64>("duration")
let info = Expression<String?>("info")
let category = Expression<String?>("category")
let date = Expression<String?>("date")
init() {
initDB()
}
func initDB() {
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
db = try! Connection("\(path)/db.sqlite3")
if (nil == self.times) {
createTable()
}
}
func createTable() {
let times = Table("times")
try! db!.run(times.create(ifNotExists: true) {t in
t.column(id, primaryKey: .autoincrement)
t.column(startTime)
t.column(duration)
t.column(info)
t.column(category)
t.column(date)
})
}
func insertData(startTime: String, duration: Int64, info: String, category: String) -> Int64 {
if (nil == self.times) {
createTable()
}
let times = Table("times")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d MMM yyyy"
let date = dateFormatter.string(from: Date())
// insert time duration
let insert = times.insert(self.startTime <- startTime,
self.duration <- duration,
self.info <- info,
self.category <- category,
self.date <- date)
return try! db!.run(insert)
}
func getTimes() -> Array<Row> {
let times = Table("times")
let result = try! db!.prepare(times)
return Array(result)
}
func getTimeByID(filterId: Int64) -> Row? {
let times = Table("times")
let query = times.filter(id == filterId + 1)
let result = try! db!.pluck(query)
return result
}
func insertDummy() {
if (nil == self.times) {
createTable()
}
let times = Table("times")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d MMM yyyy"
let dateFromString = dateFormatter.date(from: "20 Aug 2017")
let date = dateFormatter.string(from: dateFromString!)
// insert time duration
let insert = times.insert(self.startTime <- "01M 30S",
self.duration <- 60,
self.info <- "INFO HERE",
self.category <- "IS THIS A CAT",
self.date <- date)
try! db!.run(insert)
}
func getSections() -> Array<Row>? {
let times = Table("times")
let query = times.group(date).order(self.id .desc)
let result = try! db!.prepare(query)
return Array(result)
}
func getRows(forSection: String) -> Array<Row> {
let times = Table("times")
let query = times.filter(date == forSection).order(self.id .desc)
let result = try! db!.prepare(query)
return Array(result)
}
func deleteRow(id: Int64) {
let times = Table("times")
let row = times.filter(self.id == id)
_ = try! db!.run(row.delete())
}
func deleteAllRows() {
let times = Table("times")
_ = try! db!.run(times.drop(ifExists: true))
self.times = nil
}
func deleteRows(forSection: String) {
let times = Table("times")
let row = times.filter(self.date == forSection)
_ = try! db!.run(row.delete())
}
}
| mit | 1b1129c4714baf6c2048876057e09e37 | 27.631944 | 98 | 0.507883 | 4.491285 | false | false | false | false |
Royal-J/TestKitchen1607 | TestKitchen1607/TestKitchen1607/classes/ingredient(食材)/recommend(推荐)/FoodCourse食材课程/view/FCVideoCell.swift | 1 | 1372 | //
// FCVideoCell.swift
// TestKitchen1607
//
// Created by HJY on 2016/11/4.
// Copyright © 2016年 HJY. All rights reserved.
//
import UIKit
class FCVideoCell: UITableViewCell {
//播放视频
var playClosure: (String -> Void)?
//显示数据
var cellModel: FoodCourseSerial? {
didSet {
if cellModel != nil {
showData()
}
}
}
@IBOutlet weak var fcImageView: UIImageView!
@IBOutlet weak var fcLabel: UILabel!
@IBAction func btnClick(sender: UIButton) {
if cellModel?.course_video != nil && playClosure != nil {
playClosure!((cellModel?.course_video)!)
}
}
func showData() {
//图片
let url = NSURL(string: (cellModel?.course_image)!)
fcImageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
//文字
fcLabel.text = "\((cellModel?.video_watchcount)!)做过"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 5978cbcae3aa0f1d043bf6e91e269c5a | 22.526316 | 157 | 0.58091 | 4.576792 | false | false | false | false |
tdscientist/ShelfView-iOS | Example/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift | 1 | 5244 | //
// AnimatedImage.swift
// Kingfisher
//
// Created by onevcat on 2018/09/26.
//
// Copyright (c) 2018 Wei Wang <[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
import ImageIO
/// Represents a set of image creating options used in Kingfisher.
public struct ImageCreatingOptions {
/// The target scale of image needs to be created.
public let scale: CGFloat
/// The expected animation duration if an animated image being created.
public let duration: TimeInterval
/// For an animated image, whether or not all frames should be loaded before displaying.
public let preloadAll: Bool
/// For an animated image, whether or not only the first image should be
/// loaded as a static image. It is useful for preview purpose of an animated image.
public let onlyFirstFrame: Bool
/// Creates an `ImageCreatingOptions` object.
///
/// - Parameters:
/// - scale: The target scale of image needs to be created. Default is `1.0`.
/// - duration: The expected animation duration if an animated image being created.
/// A value less or equal to `0.0` means the animated image duration will
/// be determined by the frame data. Default is `0.0`.
/// - preloadAll: For an animated image, whether or not all frames should be loaded before displaying.
/// Default is `false`.
/// - onlyFirstFrame: For an animated image, whether or not only the first image should be
/// loaded as a static image. It is useful for preview purpose of an animated image.
/// Default is `false`.
public init(
scale: CGFloat = 1.0,
duration: TimeInterval = 0.0,
preloadAll: Bool = false,
onlyFirstFrame: Bool = false)
{
self.scale = scale
self.duration = duration
self.preloadAll = preloadAll
self.onlyFirstFrame = onlyFirstFrame
}
}
// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then
// hold the images for later use.
class GIFAnimatedImage {
let images: [Image]
let duration: TimeInterval
init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) {
let frameCount = CGImageSourceGetCount(imageSource)
var images = [Image]()
var gifDuration = 0.0
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else {
return nil
}
if frameCount == 1 {
gifDuration = .infinity
} else {
// Get current animated GIF frame duration
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil)
as? [String: Any] else
{
return nil
}
let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any]
gifDuration += GIFAnimatedImage.getFrameDuration(from: gifInfo)
}
images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil))
if options.onlyFirstFrame { break }
}
self.images = images
self.duration = gifDuration
}
//Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary.
static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
let defaultFrameDuration = 0.1
guard let gifInfo = gifInfo else { return defaultFrameDuration }
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
let duration = unclampedDelayTime ?? delayTime
guard let frameDuration = duration else { return defaultFrameDuration }
return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
}
}
| mit | 3770478980f5a4381d5a583f7a413970 | 43.067227 | 109 | 0.660946 | 5.076476 | false | false | false | false |
ChaselAn/CodeLibrary | codeLibrary/codeLibrary/ACNavigationBar+Ex.swift | 1 | 1592 | //
// UINavigationBar+Ex.swift
// lucencyNav
//
// Created by ancheng on 16/8/19.
// Copyright © 2016年 ac. All rights reserved.
//
import UIKit
private var key: String = "navigationView"
extension UINavigationBar{
var navigationView: UIView? {
get {
return objc_getAssociatedObject(self, &key) as? UIView
}
set {
objc_setAssociatedObject(self , &key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// 设置背景色
func customMyBackgroundColor(color: UIColor) {
if navigationView != nil {
navigationView?.backgroundColor = color
} else {
setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
shadowImage = UIImage()// 隐藏navigationBar下面的那条黑线
let navView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: -20), size: CGSize(width: UIScreen.mainScreen().bounds.size.width, height: bounds.height + 20)))
navView.userInteractionEnabled = false
insertSubview(navView, atIndex: 0)
navView.backgroundColor = color
navigationView = navView
}
}
// 设置透明度
func customMyBackgroundColorAlpha(alpha: CGFloat) {
guard let navigationView = navigationView else {
return
}
navigationView.backgroundColor = navigationView.backgroundColor?.colorWithAlphaComponent(alpha)
}
/**
解决push进入下一页的bug
*/
func resetNavBar() {
setBackgroundImage(nil , forBarMetrics: UIBarMetrics.Default)
navigationView?.removeFromSuperview()
navigationView = nil
}
} | mit | e6082d10ad2d383cabe79c7d1b5ebe89 | 25.033898 | 162 | 0.685993 | 4.514706 | false | false | false | false |
CosmicMind/Samples | Projects/Programmatic/Card/Card/ViewController (MacPro’s MacBook Pro's conflicted copy 2016-12-21).swift | 1 | 4525 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
class ViewController: UIViewController {
fileprivate var card: Card!
fileprivate var toolbar: Toolbar!
fileprivate var moreButton: IconButton!
fileprivate var contentView: UILabel!
fileprivate var bottomBar: Bar!
fileprivate var dateFormatter: DateFormatter!
fileprivate var dateLabel: UILabel!
fileprivate var favoriteButton: IconButton!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Color.grey.lighten5
prepareDateFormatter()
prepareDateLabel()
prepareFavoriteButton()
prepareMoreButton()
prepareToolbar()
prepareContentView()
prepareBottomBar()
prepareImageCard()
}
}
extension ViewController {
fileprivate func prepareDateFormatter() {
dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
}
fileprivate func prepareDateLabel() {
dateLabel = UILabel()
dateLabel.font = RobotoFont.regular(with: 12)
dateLabel.textColor = Color.blueGrey.base
dateLabel.text = dateFormatter.string(from: Date.distantFuture)
}
fileprivate func prepareFavoriteButton() {
favoriteButton = IconButton(image: Icon.favorite, tintColor: Color.red.base)
}
fileprivate func prepareMoreButton() {
moreButton = IconButton(image: Icon.cm.moreVertical, tintColor: Color.blueGrey.base)
}
fileprivate func prepareToolbar() {
toolbar = Toolbar(rightViews: [moreButton])
toolbar.title = "Material"
toolbar.titleLabel.textAlignment = .left
toolbar.detail = "Build Beautiful Software"
toolbar.detailLabel.textAlignment = .left
toolbar.detailLabel.textColor = Color.blueGrey.base
}
fileprivate func prepareContentView() {
contentView = UILabel()
contentView.numberOfLines = 0
contentView.text = "Material is an animation and graphics framework that is used to create beautiful applications."
contentView.font = RobotoFont.regular(with: 14)
}
fileprivate func prepareBottomBar() {
bottomBar = Bar()
bottomBar.leftViews = [dateLabel]
bottomBar.rightViews = [favoriteButton]
}
fileprivate func prepareImageCard() {
card = Card()
card.toolbar = toolbar
card.toolbarEdgeInsetsPreset = .square3
card.toolbarEdgeInsets.bottom = 0
card.toolbarEdgeInsets.right = 8
card.contentView = contentView
card.contentViewEdgeInsetsPreset = .wideRectangle3
card.bottomBar = bottomBar
card.bottomBarEdgeInsetsPreset = .wideRectangle2
view.layout(card).horizontally(left: 20, right: 20).top(100)
}
}
| bsd-3-clause | 1fe7a9da293b6958995c04716797b071 | 34.912698 | 123 | 0.693702 | 5.118778 | false | false | false | false |
Ferrari-lee/firefox-ios | Storage/Site.swift | 34 | 1345 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
protocol Identifiable {
var id: Int? { get set }
}
public enum IconType: Int {
case Icon = 0
case AppleIcon = 1
case AppleIconPrecomposed = 2
case Guess = 3
case Local = 4
case NoneFound = 5
}
public class Favicon: Identifiable {
var id: Int? = nil
var img: UIImage? = nil
public let url: String
public let date: NSDate
public var width: Int?
public var height: Int?
public let type: IconType
public init(url: String, date: NSDate = NSDate(), type: IconType) {
self.url = url
self.date = date
self.type = type
}
}
// TODO: Site shouldn't have all of these optional decorators. Include those in the
// cursor results, perhaps as a tuple.
public class Site : Identifiable {
var id: Int? = nil
var guid: String? = nil
public let url: String
public let title: String
// Sites may have multiple favicons. We'll return the largest.
public var icon: Favicon?
public var latestVisit: Visit?
public init(url: String, title: String) {
self.url = url
self.title = title
}
}
| mpl-2.0 | d4592576808288dd58e898315697e415 | 23.907407 | 83 | 0.645353 | 3.876081 | false | false | false | false |
BenEmdon/swift-algorithm-club | Palindromes/Palindromes.swift | 1 | 664 | import Cocoa
public func palindromeCheck(text: String?) -> Bool {
if let text = text {
let mutableText = text.trimmingCharacters(in: NSCharacterSet.whitespaces).lowercased()
let length: Int = mutableText.characters.count
if length == 1 || length == 0 {
return true
} else if mutableText[mutableText.startIndex] == mutableText[mutableText.index(mutableText.endIndex, offsetBy: -1)] {
let range = Range<String.Index>(mutableText.index(mutableText.startIndex, offsetBy: 1)..<mutableText.index(mutableText.endIndex, offsetBy: -1))
return palindromeCheck(text: mutableText.substring(with: range))
}
}
return false
}
| mit | 097182ff6639497d984f13010780ee86 | 38.058824 | 149 | 0.710843 | 4.229299 | false | false | false | false |
JoeLago/MHGDB-iOS | Pods/GRDB.swift/GRDB/FTS/FTS3Pattern.swift | 3 | 5660 | /// A full text pattern that can query FTS3 and FTS4 virtual tables.
public struct FTS3Pattern {
/// The raw pattern string. Guaranteed to be a valid FTS3/4 pattern.
public let rawPattern: String
/// Creates a pattern from a raw pattern string; throws DatabaseError on
/// invalid syntax.
///
/// The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries
///
/// try FTS3Pattern(rawPattern: "and") // OK
/// try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND]
public init(rawPattern: String) throws {
// Correctness above all: use SQLite to validate the pattern.
//
// Invalid patterns have SQLite return an error on the first
// call to sqlite3_step() on a statement that matches against
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try db.execute("CREATE VIRTUAL TABLE documents USING fts3()")
try db.execute("SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern])
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
}
// Pattern is valid
self.rawPattern = rawPattern
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAnyTokenIn: "") // nil
/// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS3 pattern
public init?(matchingAnyTokenIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAllTokensIn: "") // nil
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS3 pattern
public init?(matchingAllTokensIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
///
/// FTS3Pattern(matchingPhrase: "") // nil
/// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS3 pattern
public init?(matchingPhrase string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#else
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAnyTokenIn: "") // nil
/// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
public init?(matchingAnyTokenIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAllTokensIn: "") // nil
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
public init?(matchingAllTokensIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
///
/// FTS3Pattern(matchingPhrase: "") // nil
/// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
public init?(matchingPhrase string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#endif
}
extension FTS3Pattern : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
}
/// Returns an FTS3Pattern initialized from *dbValue*, if it contains
/// a suitable value.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern? {
return String
.fromDatabaseValue(dbValue)
.flatMap { try? FTS3Pattern(rawPattern: $0) }
}
}
| mit | 138b6307fec3117bcff7ba4570d50abd | 42.206107 | 119 | 0.629682 | 4.39441 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/External/RCEmojiKit/Views/EmojiPicker/EmojiPickerController.swift | 1 | 3040 | //
// EmojiPickerController.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 12/20/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
final class EmojiPickerController: UIViewController, RCEmojiKitLocalizable {
var emojiPicked: ((String) -> Void)?
var customEmojis: [Emoji] = []
override func loadView() {
view = EmojiPicker()
}
override func viewDidLoad() {
super.viewDidLoad()
ThemeManager.addObserver(view)
guard let picker = view as? EmojiPicker else {
fatalError("View should be an instance of EmojiPicker!")
}
title = localized("emojipicker.title")
picker.emojiPicked = { [unowned self] emoji in
self.emojiPicked?(emoji)
if self.navigationController?.topViewController == self {
self.navigationController?.popViewController(animated: true)
} else {
self.dismiss(animated: true)
}
}
picker.customEmojis = customEmojis
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
center.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
if self.navigationController?.topViewController == self {
navigationController?.navigationBar.topItem?.title = ""
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func keyboardWillShow(_ notification: Notification) {
guard UIDevice.current.userInterfaceIdiom == .phone else { return }
guard
let userInfo = notification.userInfo,
let rect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber
else {
return
}
let convertedRect = view.convert(rect, from: nil)
UIView.animate(withDuration: animationDuration.doubleValue) {
self.additionalSafeAreaInsets.bottom = convertedRect.size.height - self.view.safeAreaInsets.bottom
self.view.layoutIfNeeded()
}
}
override func keyboardWillHide(_ notification: Notification) {
guard UIDevice.current.userInterfaceIdiom == .phone else { return }
guard
let userInfo = notification.userInfo,
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber
else {
return
}
UIView.animate(withDuration: animationDuration.doubleValue) {
self.additionalSafeAreaInsets.bottom = 0
self.view.layoutIfNeeded()
}
}
}
| mit | 6f1420b342e01d70472a673d0fc06d79 | 30.65625 | 136 | 0.65153 | 5.426786 | false | false | false | false |
KlubJagiellonski/pola-ios | BuyPolish/Pola/UI/ProductSearch/ScanCode/ProductCard/CompanyContent/CompanyContentView.swift | 1 | 3757 | import UIKit
final class CompanyContentView: UIView {
let capitalTitleLabel = UILabel()
let capitalProgressView = SecondaryProgressView()
let notGlobalCheckRow = CheckRow()
let registeredCheckRow = CheckRow()
let rndCheckRow = CheckRow()
let workersCheckRow = CheckRow()
let friendButton = UIButton()
let descriptionLabel = UILabel()
private let stackView = UIStackView()
private let padding = CGFloat(14)
override init(frame: CGRect) {
super.init(frame: frame)
translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = padding
stackView.distribution = .fillProportionally
stackView.alignment = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
let localizable = R.string.localizable.self
capitalTitleLabel.font = Theme.normalFont
capitalTitleLabel.textColor = Theme.defaultTextColor
capitalTitleLabel.text = localizable.percentOfPolishHolders()
capitalTitleLabel.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(capitalTitleLabel)
capitalProgressView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(capitalProgressView)
notGlobalCheckRow.text = localizable.notPartOfGlobalCompany()
notGlobalCheckRow.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(notGlobalCheckRow)
registeredCheckRow.text = localizable.isRegisteredInPoland()
registeredCheckRow.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(registeredCheckRow)
rndCheckRow.text = localizable.createdRichSalaryWorkPlaces()
rndCheckRow.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(rndCheckRow)
workersCheckRow.text = localizable.producingInPL()
workersCheckRow.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(workersCheckRow)
friendButton.setImage(R.image.heartFilled(), for: .normal)
friendButton.tintColor = Theme.actionColor
friendButton.setTitle(localizable.thisIsPolaSFriend(),
for: .normal)
friendButton.setTitleColor(Theme.actionColor, for: .normal)
friendButton.titleLabel?.font = Theme.normalFont
let buttontitleHorizontalMargin = CGFloat(7)
friendButton.titleEdgeInsets =
UIEdgeInsets(top: 0, left: buttontitleHorizontalMargin, bottom: 0, right: 0)
friendButton.contentHorizontalAlignment = .left
friendButton.adjustsImageWhenHighlighted = false
friendButton.isHidden = true
friendButton.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(friendButton)
descriptionLabel.font = Theme.normalFont
descriptionLabel.textColor = Theme.defaultTextColor
descriptionLabel.numberOfLines = 0
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(descriptionLabel)
createConstraints()
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createConstraints() {
addConstraints([
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.bottomAnchor.constraint(greaterThanOrEqualTo: bottomAnchor),
])
}
}
| gpl-2.0 | df0696b82051522a4a55ff7e39ca147b | 41.213483 | 88 | 0.727974 | 6.089141 | false | false | false | false |
mcxiaoke/learning-ios | ios_programming_4th/Homepwner-ch9/Homepwner/ItemsViewController.swift | 1 | 4498 | //
// ViewController.swift
// Homepwner
//
// Created by Xiaoke Zhang on 2017/8/16.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import UIKit
class ItemsViewController: UITableViewController {
@IBOutlet var headerView:UIView!
@IBAction func addNewItem(_ sender: AnyObject) {
print("addNewItem")
let newItem = ItemStore.shared.createItem()
let lastRow = ItemStore.shared.allItems.index(of:newItem) ?? 0
let indexPath = IndexPath(row:lastRow, section:0)
tableView.insertRows(at: [indexPath], with: .top)
}
@IBAction func toggleEditMode(_ sender: AnyObject) {
print("toggleEditMode \(self.isEditing)")
guard let v = sender as? UIButton else { return }
if self.isEditing {
v.setTitle("Edit", for: .normal)
self.isEditing = false
} else {
v.setTitle("Done", for: .normal)
self.isEditing = true
}
}
init() {
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "UITableViewCell")
for _ in 0..<5 {
let _ = ItemStore.shared.createItem()
}
headerView = Bundle.main.loadNibNamed("HeaderView", owner: self, options: nil)?[0] as! UIView
tableView.tableHeaderView = headerView
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ItemStore.shared.allItems.count + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
if indexPath.row == ItemStore.shared.allItems.count {
cell.textLabel?.textAlignment = .center
cell.textLabel?.text = "No more items!"
} else {
let item = ItemStore.shared.allItems[indexPath.row]
cell.textLabel?.textAlignment = .left
cell.textLabel?.text = item.description
}
return cell
}
// can not edit last row
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return indexPath.row < ItemStore.shared.allItems.count
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
print("commitEditingStyle \(editingStyle.rawValue) \(indexPath.row)")
if editingStyle == .delete {
let item = ItemStore.shared.allItems[indexPath.row]
ItemStore.shared.allItems -= item
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
/**
// custom delete edit action
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let removeAction = UITableViewRowAction(style: .destructive, title: "Remove", handler:{_,_ in
let item = ItemStore.shared.allItems[indexPath.row]
ItemStore.shared.allItems -= item
tableView.deleteRows(at: [indexPath], with: .fade)
})
return [removeAction]
}
**/
// can not move last row
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.row < ItemStore.shared.allItems.count
}
// can not move to last row
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if proposedDestinationIndexPath.row == ItemStore.shared.allItems.count {
return sourceIndexPath
} else {
return proposedDestinationIndexPath
}
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
print("moveRowAt from \(sourceIndexPath.row) to \(destinationIndexPath.row)")
ItemStore.shared.move(fromIndex: sourceIndexPath.row, toIndex: destinationIndexPath.row)
}
}
| apache-2.0 | c2f9371850d740ef43d9321f8e0e8e10 | 36.14876 | 189 | 0.649611 | 5.033595 | false | false | false | false |
coreyjv/Emby.ApiClient.Swift | Emby.ApiClient/model/connect/ConnectAuthenticationResult.swift | 2 | 672 | //
// ConnectAuthenticationResult.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 07/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
public struct ConnectAuthenticationResult: JSONSerializable
{
public let user: ConnectUser
public let accessToken: String
public init?(jSON: JSON_Object) {
if let accessToken = jSON["AccessToken"] as? String,
let userJSON = jSON["User"] as? JSON_Object,
let user = ConnectUser(jSON: userJSON)
{
self.user = user
self.accessToken = accessToken
}
else {
return nil
}
}
} | mit | 0f9d24383e83485e6601102e0a1c41ad | 23 | 61 | 0.608048 | 4.357143 | false | false | false | false |
Tommy1990/swiftWibo | SwiftWibo/SwiftWibo/Classes/ViewModel/Home/EPMHomeViewModel.swift | 1 | 4267 | //
// EPMHomeViewModel.swift
// SwiftWibo
//
// Created by 马继鵬 on 17/3/24.
// Copyright © 2017年 7TH. All rights reserved.
//
import UIKit
import YYModel
import SDWebImage
class EPMHomeViewModel: NSObject {
//MARKE: 定义数组
var dataArray: [EPMHomeStatueViewModel] = [EPMHomeStatueViewModel]()
//MARKE: 数据获取
func getHomeViewData(isPullUp:Bool,finished:@escaping ((Bool,Int)->())){
var sinceId:Int64 = 0
var maxId:Int64 = 0
if isPullUp {
maxId = dataArray.last?.homeModel?.id ?? 0
if maxId > 0 {
maxId -= 1
}
}else{
sinceId = dataArray.first?.homeModel?.id ?? 0
}
EPMEPMDAL.checkCache(sinceID: sinceId, maxID: maxId) { (response) in
guard let resArr = response else{
finished(false,0)
return
}
// 字典转模型
let statusesArray = NSArray.yy_modelArray(with: EPMHomeModel.self, json: resArr) as! [EPMHomeModel]
// 创建一个临时可变的statusViewModel的空数组
var tempArray:[EPMHomeStatueViewModel] = [EPMHomeStatueViewModel]()
// 遍历statusesArray
for homeModel in statusesArray{
// 实例化statusViewModel
let statueViewModel = EPMHomeStatueViewModel()
// 赋值
statueViewModel.homeModel = homeModel
// 添加元素->statueViewModel
tempArray.append(statueViewModel)
}
// EPMNetworkingTool.shearedTool.loadHomeData(since_id: sinceId, max_id: maxId) { (respond, error) in
// if error != nil{
// finished(false,0)
// return
// }
// guard let res = respond as? [String: Any] else{
// finished(false,0)
// return
// }
// guard let resArr = res["statuses"] as? [[String: Any]] else{
// finished(false,0)
// return
// }
// let staueArr = NSArray.yy_modelArray(with: EPMHomeModel.self, json: resArr) as! [EPMHomeModel]
//
//// print(resArr)
// var temArray: [EPMHomeStatueViewModel] = [EPMHomeStatueViewModel]()
//
// //MARKE: 遍历数组获得
// for model in staueArr{
// let statueModel:EPMHomeStatueViewModel = EPMHomeStatueViewModel()
// statueModel.homeModel = model
// temArray.append(statueModel)
// }
//
self.downLoadSingleImage(tempArray: tempArray, finish: finished)
//MARKE: 加载完成后处理
if isPullUp {
self.dataArray = self.dataArray + tempArray
}else{
self.dataArray = tempArray + self.dataArray
}
}
}
private func downLoadSingleImage(tempArray:[EPMHomeStatueViewModel],finish:@escaping (Bool,Int)->()) {
//创建线程管理
let group = DispatchGroup()
for statueView in tempArray{
if statueView.homeModel?.pic_urls?.count == 1{
//任务开始标记
group.enter()
SDWebImageManager.shared().downloadImage(with: URL(string:statueView.homeModel?.pic_urls?.last?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) in
group.leave()
})
}
if statueView.homeModel?.retweeted_status?.pic_urls?.count == 1{
group.enter()
SDWebImageManager.shared().downloadImage(with: URL(string:statueView.homeModel?.retweeted_status?.pic_urls?.last?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) in
group.leave()
})
}
}
group.notify(queue: DispatchQueue.main){
finish(true,tempArray.count)
}
}
}
| mit | 9c0914f00785d99d6ab78185a2920136 | 33.45 | 219 | 0.506773 | 4.426124 | false | false | false | false |
aizcheryz/HZTableView | HZTableViewSample/HZTableViewSample/HZMaterialTableView/HZMaterialButton.swift | 2 | 9475 | //
// HZMaterialButton.swift
// HZMaterialDesign
//
// Created by Moch Fariz Al Hazmi on 12/31/15.
// Copyright © 2015 alhazme. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
@objc protocol HZMaterialButtonDelegate {
}
enum Shape {
case Default
case Circle
case Square
}
class HZMaterialButton: UIButton {
var materialDelegate: HZMaterialButtonDelegate?
var x: CGFloat = 0 {
didSet {
layer.frame.origin.x = x
}
}
var y: CGFloat = 0 {
didSet {
layer.frame.origin.y = y
}
}
var width: CGFloat = 48 {
didSet {
layer.frame.size.width = width
if shape != .None {
layer.frame.size.height = width
}
setupLayer()
}
}
var height: CGFloat = 48 {
didSet {
layer.frame.size.height = height
if shape != .None {
layer.frame.size.width = height
}
setupLayer()
}
}
var image: UIImage? {
didSet {
setImage(image, forState: .Normal)
}
}
var imageHighlighted: UIImage? {
didSet {
setImage(imageHighlighted, forState: .Highlighted)
}
}
var shape: Shape? {
didSet {
if shape != .None {
if width < height {
frame.size.width = height
}
else {
frame.size.height = width
}
setupLayer()
}
}
}
var shadowColor: UIColor = UIColor.blackColor() {
didSet {
layer.shadowColor = shadowColor.CGColor
}
}
var shadowOpacity: Float = 0.2 {
didSet {
layer.shadowOpacity = shadowOpacity
}
}
var shadowRadius: CGFloat = 5.0 {
didSet {
layer.shadowRadius = shadowRadius
}
}
var shadowOffset: CGSize = CGSizeMake(0, 4.0) {
didSet {
layer.shadowOffset = shadowOffset
}
}
var borderWidth: CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
}
}
var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
enum Position {
case Left
case Right
}
var buttonPosition: Position = .Right
var pulseEffectView = UIView()
var pulseEffectBackgroundView = UIView()
var pulseEffectPercent: Float = 0.8 {
didSet {
setupPulseEffect()
}
}
var pulseEffectColor: UIColor = UIColor(white: 0.9, alpha: 0.5) {
didSet {
pulseEffectView.backgroundColor = pulseEffectColor
}
}
var pulseEffectBackgroundColor: UIColor = UIColor(white: 0.95, alpha: 0.3) {
didSet {
pulseEffectBackgroundView.backgroundColor = pulseEffectBackgroundColor
}
}
var pulseEffectOverBounds: Bool = false
var pulseEffectShadowRadius: Float = 1.0
var pulseEffectShadowEnable: Bool = true
var pulseEffectTrackTouchLocation: Bool = true
var pulseEffectTouchUpAnimationTime: Double = 0.6
var pulseEffectTempShadowRadius: CGFloat = 0
var pulseEffectTempShadowOpacity: Float = 0
var pulseEffectTouchCenterLocation: CGPoint?
var pulseEffectLayer: CAShapeLayer? {
get {
if !pulseEffectOverBounds {
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).CGPath
return maskLayer
}
else {
return nil
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
setupPulseEffect()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
setupPulseEffect()
}
func setupLayer() {
layer.shadowColor = shadowColor.CGColor
layer.shadowOpacity = shadowOpacity
layer.shadowRadius = shadowRadius
layer.shadowOffset = shadowOffset
if shape == .Circle {
layer.cornerRadius = width / 2
}
}
func setupPulseEffect() {
setupPulseEffectView()
setupPulseEffectBackgroundView()
}
func setupPulseEffectView() {
let pulseEffectSize = CGRectGetWidth(bounds) * CGFloat(pulseEffectPercent)
let pulseEffectX = (CGRectGetWidth(bounds) / 2) - (pulseEffectSize / 2)
let pulseEffectY = (CGRectGetHeight(bounds) / 2) - (pulseEffectSize / 2)
let corner = pulseEffectSize / 2
pulseEffectView.backgroundColor = pulseEffectColor
pulseEffectView.frame = CGRectMake(pulseEffectX, pulseEffectY, pulseEffectSize, pulseEffectSize)
pulseEffectView.layer.cornerRadius = corner
}
func setupPulseEffectBackgroundView() {
pulseEffectBackgroundView.backgroundColor = pulseEffectBackgroundColor
pulseEffectBackgroundView.frame = bounds
layer.addSublayer(pulseEffectBackgroundView.layer)
pulseEffectBackgroundView.layer.addSublayer(pulseEffectView.layer)
pulseEffectBackgroundView.alpha = 0
layer.shadowRadius = 0
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowColor = UIColor(white: 0.0, alpha: 0.5).CGColor
}
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
pulseEffectTouchCenterLocation = touch.locationInView(self)
UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.pulseEffectBackgroundView.alpha = 1
}, completion: nil)
pulseEffectView.transform = CGAffineTransformMakeScale(0.5, 0.5)
UIView.animateWithDuration(0.7, delay: 0, options: [UIViewAnimationOptions.CurveEaseOut, UIViewAnimationOptions.AllowUserInteraction],
animations: {
self.pulseEffectView.transform = CGAffineTransformIdentity
}, completion: nil)
if pulseEffectShadowEnable {
pulseEffectTempShadowRadius = layer.shadowRadius
pulseEffectTempShadowOpacity = layer.shadowOpacity
let shadowAnimate = CABasicAnimation(keyPath: "shadowRadius")
shadowAnimate.toValue = pulseEffectShadowRadius
let opacityAnimate = CABasicAnimation(keyPath: "shadowOpacity")
opacityAnimate.toValue = 1
let groupAnimate = CAAnimationGroup()
groupAnimate.duration = 0.7
groupAnimate.fillMode = kCAFillModeForwards
groupAnimate.removedOnCompletion = false
groupAnimate.animations = [shadowAnimate, opacityAnimate]
layer.addAnimation(groupAnimate, forKey: "shadow")
}
return super.beginTrackingWithTouch(touch, withEvent: event)
}
override func cancelTrackingWithEvent(event: UIEvent?) {
super.cancelTrackingWithEvent(event)
animateToNormal()
}
override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
super.endTrackingWithTouch(touch, withEvent: event)
animateToNormal()
}
func animateToNormal() {
UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.pulseEffectBackgroundView.alpha = 1
}, completion: {(success: Bool) -> () in
UIView.animateWithDuration(self.pulseEffectTouchUpAnimationTime, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.pulseEffectBackgroundView.alpha = 0
}, completion: nil)
})
UIView.animateWithDuration(0.7, delay: 0,
options: [.CurveEaseOut, .BeginFromCurrentState, .AllowUserInteraction],
animations: {
self.pulseEffectView.transform = CGAffineTransformIdentity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = self.pulseEffectTempShadowRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = self.pulseEffectTempShadowOpacity
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.removedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
self.layer.addAnimation(groupAnim, forKey:"shadowBack")
}, completion: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
setupPulseEffectView()
if let knownTouchCenterLocation = pulseEffectTouchCenterLocation {
pulseEffectView.center = knownTouchCenterLocation
}
pulseEffectBackgroundView.layer.frame = bounds
pulseEffectBackgroundView.layer.mask = pulseEffectLayer
}
} | mit | 35d047e0cad7b61dd3a04ff6e21ddc07 | 31.899306 | 158 | 0.597213 | 5.358597 | false | false | false | false |
Osnobel/GDGameExtensions | GDGameExtensions/GDInAppPurchase/GDInAppPurchase.swift | 1 | 15854 | //
// GDInAppPurchase.swift
// GDInAppPurchase
//
// Created by Bell on 16/5/28.
// Copyright © 2016年 GoshDo <http://goshdo.sinaapp.com>. All rights reserved.
//
import Foundation
import StoreKit
public extension SKProduct {
public var localizedPrice: String {
get {
let numberFormatter = NSNumberFormatter()
numberFormatter.formatterBehavior = .Behavior10_4
numberFormatter.numberStyle = .CurrencyStyle
numberFormatter.locale = self.priceLocale
return numberFormatter.stringFromNumber(self.price)!
}
}
override public var description: String {
get {
return "Identifier=\(self.productIdentifier) Price=\(self.localizedPrice) Title=\(self.localizedTitle) Description=\(self.localizedDescription)"
}
}
}
public class GDProductStore: NSObject, SKProductsRequestDelegate {
public var loaded: Bool {
get {
return _loaded
}
}
private var _loaded: Bool = true {
didSet {
if _loaded == oldValue {
return
}
if _loaded {
LoadingAnimate.stop()
} else {
LoadingAnimate.start()
}
}
}
private var _store: [String : SKProduct] = [:]
private var _completionHanlder:((SKProduct?, NSError?) -> Void)? = nil
public func preloadProducts(productIdentifiers: Set<String> = []) {
let request = SKProductsRequest(productIdentifiers: productIdentifiers)
request.delegate = self
request.start()
}
public func product(productIdentifier: String, completionHandler handler: ((SKProduct?, NSError?) -> Void)?) {
guard handler != nil else { return }
_completionHanlder = handler
if let product = _store[productIdentifier] {
_completionHanlder!(product, nil)
} else {
let productIdentifiers:Set<String> = [productIdentifier]
let request = SKProductsRequest(productIdentifiers: productIdentifiers)
request.delegate = self
request.start()
_loaded = false
}
}
public func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
_loaded = true
var error: NSError? = nil
if !response.invalidProductIdentifiers.isEmpty {
print("Invalid Product ID: \(response.invalidProductIdentifiers)")
error = NSError(domain: "com.inapppurchase.productstore.invalidproductidentifiers", code: -1, userInfo: [NSLocalizedDescriptionKey:"Invalid Product IDs: \(response.invalidProductIdentifiers)"])
}
let products = response.products
for product in products {
_store[product.productIdentifier] = product
}
if _completionHanlder != nil {
if products.count == 1 && error == nil {
_completionHanlder!(products[0], error)
} else {
_completionHanlder!(nil, error)
}
_completionHanlder = nil
}
}
public func request(request: SKRequest, didFailWithError error: NSError) {
_loaded = true
if _completionHanlder != nil {
_completionHanlder!(nil, error)
_completionHanlder = nil
}
}
}
public extension SKPayment {
override public var description: String {
get {
return "Identifier=\(self.productIdentifier) Quantity=\(self.quantity)"
}
}
}
public extension SKPaymentTransaction {
public var receipt: String? {
get {
guard let url = NSBundle.mainBundle().appStoreReceiptURL else { return nil }
return NSData(contentsOfURL: url)?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
}
override public var description: String {
get {
var _desc = ""
switch self.transactionState {
case .Purchased, .Restored:
_desc += "Identifier=\(self.transactionIdentifier!)"
default:
_desc += "Identifier=Invalid Transaction Identifier"
}
switch self.transactionState {
case .Purchased:
_desc += " State=Purchased"
case .Purchasing:
_desc += " State=Purchasing"
case .Failed:
_desc += " State=Failed"
case .Restored:
_desc += " State=Restored"
default:
_desc += " State=\(self.transactionState.rawValue)"
}
_desc += " Payment={\(self.payment)}"
if self.error != nil {
_desc += " Error={\(self.error!)}"
}
return _desc
}
}
}
public class GDPayment: NSObject, SKPaymentTransactionObserver {
// Singleton
public static func sharedPayment() -> GDPayment {
return _sharedInstance
}
private static let _sharedInstance = GDPayment()
private override init() { super.init() }
// Singleton end
public var loaded: Bool {
get {
return _loaded
}
}
public var productStore: GDProductStore = GDProductStore()
private var _loaded: Bool = true {
didSet {
if _loaded == oldValue {
return
}
if _loaded {
LoadingAnimate.stop()
} else {
LoadingAnimate.start()
}
}
}
private var _completedTransactionHandler:((SKPaymentTransaction?, NSError?) -> Void)? = nil
public func purchase(productIdentifier: String, completedTransactionHandler handler:((SKPaymentTransaction?, NSError?) -> Void)?) {
purchase(productIdentifier, quantity: 1, completedTransactionHandler: handler)
}
public func purchase(productIdentifier: String, quantity: Int, completedTransactionHandler handler:((SKPaymentTransaction?, NSError?) -> Void)?) {
_completedTransactionHandler = handler
guard SKPaymentQueue.canMakePayments() else {
let error = NSError(domain: "com.inapppurchase.payment.cannotmakepayments", code: -2, userInfo: [NSLocalizedDescriptionKey:"In-App Purchase Disable"])
_completedTransactionHandler?(nil, error)
return
}
productStore.product(productIdentifier) { (product, error) -> Void in
if error != nil {
return
}
if product != nil {
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
let payment = SKMutablePayment(product: product!)
if quantity > 1 {
payment.quantity = quantity
}
SKPaymentQueue.defaultQueue().addPayment(payment)
self._loaded = false
}
}
}
public func restore(completedTransactionHandler handler:((SKPaymentTransaction?, NSError?) -> Void)?) {
_completedTransactionHandler = handler
guard SKPaymentQueue.canMakePayments() else {
let error = NSError(domain: "com.inapppurchase.payment.cannotmakepayments", code: -2, userInfo: [NSLocalizedDescriptionKey:"In-App Purchase Disable"])
_completedTransactionHandler?(nil, error)
return
}
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
_loaded = false
}
public func verifyReceipt(transaction:SKPaymentTransaction, completedHandler handler:((NSError?) -> Void)) {
guard let receiptString = transaction.receipt else {
let error = NSError(domain: "com.inapppurchase.payment.transactionreceiptempty", code: -3, userInfo: [NSLocalizedDescriptionKey:"In-App Purchase Transaction Receipt is Empty"])
handler(error)
return
}
postVerifyReceiptRequest(receiptString, completedHandler: handler)
_loaded = false
}
private func postVerifyReceiptRequest(receipt: String, isSandbox: Bool = false, completedHandler handler:((NSError?) -> Void)) {
let httpBodyString = "{\"receipt-data\" : \"\(receipt)\"}"
var verifyReceiptURL = NSURL(string: "https://buy.itunes.apple.com/verifyReceipt")!
if isSandbox {
verifyReceiptURL = NSURL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!
}
let request = NSMutableURLRequest(URL: verifyReceiptURL)
request.HTTPMethod = "POST"
request.HTTPBody = httpBodyString.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
self._loaded = true
guard error == nil else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(error)
})
return
}
guard let validData = data where validData.length > 0 else {
// print("JSON could not be serialized. Input data was nil or zero length.")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let error = NSError(domain: "com.inapppurchase.payment.transactionreceiptemptyverifyfailed", code: -4, userInfo: [NSLocalizedDescriptionKey:"In-App Purchase Transaction Receipt Verify Failed"])
handler(error)
})
return
}
print(String(data: validData, encoding: NSUTF8StringEncoding)!)
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: .AllowFragments)
if let result = JSON as? [String: AnyObject] {
let status = result["status"] as? Int
if status == 21007 {
self._loaded = false
self.postVerifyReceiptRequest(receipt, isSandbox: true, completedHandler: handler)
} else if let receipt = result["receipt"] as? [String: AnyObject] where receipt["bundle_id"] as? String == NSBundle.mainBundle().bundleIdentifier && status == 0 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(nil)
})
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let error = NSError(domain: "com.inapppurchase.payment.transactionreceiptemptyverifyfailed", code: -4, userInfo: [NSLocalizedDescriptionKey:"In-App Purchase Transaction Receipt Verify Failed"])
handler(error)
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let error = NSError(domain: "com.inapppurchase.payment.transactionreceiptemptyverifyfailed", code: -4, userInfo: [NSLocalizedDescriptionKey:"In-App Purchase Transaction Receipt Verify Failed"])
handler(error)
})
}
return
} catch let e as NSError {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(e)
})
return
}
}
task.resume()
session.finishTasksAndInvalidate()
}
private func purchasedTransaction(transaction:SKPaymentTransaction) {
defer {
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
}
_completedTransactionHandler?(transaction, nil)
}
private func restoredTransaction(transaction:SKPaymentTransaction) {
defer {
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
}
_completedTransactionHandler?(transaction, nil)
}
private func failedTransaction(transaction:SKPaymentTransaction) {
defer {
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
}
_completedTransactionHandler?(transaction, transaction.error)
}
// <SKPaymentTransactionObserver> methods
public func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .Purchased:
purchasedTransaction(transaction)
case .Restored:
restoredTransaction(transaction)
case .Failed:
failedTransaction(transaction)
default:
//.Purchasing or .Deferred
break
}
}
}
public func paymentQueue(queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
_loaded = true
defer {
queue.removeTransactionObserver(self)
_completedTransactionHandler = nil
}
}
public func paymentQueue(queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: NSError) {
_loaded = true
defer {
queue.removeTransactionObserver(self)
_completedTransactionHandler = nil
}
_completedTransactionHandler?(nil, error)
}
public func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
_loaded = true
defer {
queue.removeTransactionObserver(self)
_completedTransactionHandler = nil
}
}
public func paymentQueue(queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
_loaded = true
defer {
queue.removeTransactionObserver(self)
_completedTransactionHandler = nil
}
}
}
public class LoadingAnimate {
private static var _view: UIView?
private static let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
private static var animateView: UIView {
get {
if _view == nil {
_view = UIView()
_view!.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8)
_view!.addSubview(activityIndicatorView)
}
return _view!
}
}
private static var rootView: UIView?
private static var rootViewUserInteractionEnabled = false
public static func start() {
rootView = UIApplication.sharedApplication().keyWindow?.subviews.first
if rootView != nil {
let width = min(rootView!.frame.size.width, rootView!.frame.size.height)
animateView.frame = CGRectMake(0, 0, width / 5, width / 5)
animateView.center = CGPointMake(rootView!.bounds.size.width / 2, rootView!.bounds.size.height / 2)
animateView.layer.cornerRadius = width / 30
activityIndicatorView.center = CGPointMake(animateView.bounds.size.width / 2, animateView.bounds.size.height / 2)
activityIndicatorView.startAnimating()
rootView!.addSubview(animateView)
rootViewUserInteractionEnabled = rootView!.userInteractionEnabled
rootView!.userInteractionEnabled = false
}
}
public static func stop() {
activityIndicatorView.stopAnimating()
animateView.removeFromSuperview()
rootView?.userInteractionEnabled = rootViewUserInteractionEnabled
}
} | mit | 8649b43443f2d5b928b624be48b4a7e5 | 38.729323 | 221 | 0.596114 | 5.55007 | false | false | false | false |
dsoisson/SwiftLearningExercises | Exercise12_Extensions.playground/Sources/Account.swift | 1 | 969 | import Foundation
public protocol Account {
var description: String { get }
var customer: Customer { get set }
var balance: Double { get set }
func debit(amount: Double) throws
func credit(amount: Double)
}
extension Account {
public var balance: Double {
get {
if self.description == "Checking"
{
return 0.0
}
else {
return 500.0
}
}
set {
}
}
}
extension Account {
public mutating func debit(amount: Double) throws {
guard (self.balance - amount) >= 0 else {
throw TransactionError.InsufficientFunds(balance: self.balance, debiting: amount)
}
self.balance -= amount
}
public mutating func credit(amount: Double) {
self.balance += amount
}
}
| mit | a66c7bd2cacbeecebf7962b81dbb9c0e | 17.634615 | 93 | 0.486068 | 5.126984 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/swift-protobuf/Sources/protoc-gen-swift/StringUtils.swift | 3 | 3784 | // Sources/protoc-gen-swift/StringUtils.swift - String processing utilities
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
import Foundation
func splitPath(pathname: String) -> (dir:String, base:String, suffix:String) {
var dir = ""
var base = ""
var suffix = ""
for c in pathname.characters {
if c == "/" {
dir += base + suffix + String(c)
base = ""
suffix = ""
} else if c == "." {
base += suffix
suffix = String(c)
} else {
suffix += String(c)
}
}
if suffix.characters.first != "." {
base += suffix
suffix = ""
}
return (dir: dir, base: base, suffix: suffix)
}
func partition(string: String, atFirstOccurrenceOf substring: String) -> (String, String) {
guard let index = string.range(of: substring)?.lowerBound else {
return (string, "")
}
return (string.substring(to: index), string.substring(from: string.index(after: index)))
}
func parseParameter(string: String?) -> [(key:String, value:String)] {
guard let string = string, string.characters.count > 0 else {
return []
}
let parts = string.components(separatedBy: ",")
let asPairs = parts.map { partition(string: $0, atFirstOccurrenceOf: "=") }
let result = asPairs.map { (key:trimWhitespace($0), value:trimWhitespace($1)) }
return result
}
func trimWhitespace(_ s: String) -> String {
return s.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// The protoc parser emits byte literals using an escaped C convention.
/// Fortunately, it uses only a limited subset of the C escapse:
/// \n\r\t\\\'\" and three-digit octal escapes but nothing else.
func escapedToDataLiteral(_ s: String) -> String {
if s.isEmpty {
return "SwiftProtobuf.Internal.emptyData"
}
var out = "Data(bytes: ["
var separator = ""
var escape = false
var octal = 0
var octalAccumulator = 0
for c in s.utf8 {
if octal > 0 {
precondition(c >= 48 && c < 56)
octalAccumulator <<= 3
octalAccumulator |= (Int(c) - 48)
octal -= 1
if octal == 0 {
out += separator
out += "\(octalAccumulator)"
separator = ", "
}
} else if escape {
switch c {
case 110:
out += separator
out += "10"
separator = ", "
case 114:
out += separator
out += "13"
separator = ", "
case 116:
out += separator
out += "9"
separator = ", "
case 48..<56:
octal = 2 // 2 more digits
octalAccumulator = Int(c) - 48
default:
out += separator
out += "\(c)"
separator = ", "
}
escape = false
} else if c == 92 { // backslash
escape = true
} else {
out += separator
out += "\(c)"
separator = ", "
}
}
out += "])"
return out
}
/// Generate a Swift string literal suitable for including in
/// source code
private let hexdigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
func stringToEscapedStringLiteral(_ s: String) -> String {
if s.isEmpty {
return "String()"
}
var out = "\""
for c in s.unicodeScalars {
switch c.value {
case 0:
out += "\\0"
case 1..<32:
let n = Int(c.value)
let hex1 = hexdigits[(n >> 4) & 15]
let hex2 = hexdigits[n & 15]
out += "\\u{" + hex1 + hex2 + "}"
case 34:
out += "\\\""
case 92:
out += "\\\\"
default:
out.append(String(c))
}
}
return out + "\""
}
| mit | 96e76c312e028d8dd48d7214b3682114 | 25.461538 | 104 | 0.553911 | 3.724409 | false | false | false | false |
studyYF/YueShiJia | YueShiJia/YueShiJia/Classes/Subject/Models/YFActiveItem.swift | 1 | 747 | //
// YFActiveItem.swift
// YueShiJia
//
// Created by YangFan on 2017/5/18.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
class YFActiveItem: NSObject {
var virtual_indate: String?
var goods_image: String?
var type_virtual: Int = 0
var hint_virtual: String?
var end_virtual: String?
var goods_name: String?
var store_id: String?
var goods_id: String?
init(dict: [String: Any]) {
super.init()
goods_image = dict["goods_image"] as? String
end_virtual = dict["end_virtual"] as? String
goods_name = dict["goods_name"] as? String
goods_id = dict["goods_id"] as? String
hint_virtual = dict["hint_virtual"] as? String
}
}
| apache-2.0 | 7337f168c788de30b396cebd9a899efd | 19.108108 | 54 | 0.608871 | 3.460465 | false | false | false | false |
robertjpayne/QuerySize | QuerySize.swift | 1 | 1940 | import UIKit
public enum QuerySizeAttribute {
case ByIdiom(UIUserInterfaceIdiom)
case ByScreenMinWidth(CGFloat)
case ByScreenMaxWidth(CGFloat)
case ByScreenMinHeight(CGFloat)
case ByScreenMaxHeight(CGFloat)
var isValid: Bool {
switch self {
case .ByIdiom(let idiom):
return (idiom == UIDevice.currentDevice().userInterfaceIdiom)
case .ByScreenMinWidth(let value):
return (UIScreen.mainScreen().bounds.size.width >= value)
case .ByScreenMaxWidth(let value):
return (UIScreen.mainScreen().bounds.size.width <= value)
case .ByScreenMinHeight(let value):
return (UIScreen.mainScreen().bounds.size.height >= value)
case .ByScreenMaxHeight(let value):
return (UIScreen.mainScreen().bounds.size.height <= value)
}
}
}
public func QuerySize(a1: QuerySizeAttribute, @noescape closure: () -> Void) {
if a1.isValid {
closure()
}
}
public func QuerySize(a1: QuerySizeAttribute, a2: QuerySizeAttribute, @noescape closure: () -> Void) {
if a1.isValid &&
a2.isValid {
closure()
}
}
public func QuerySize(a1: QuerySizeAttribute, a2: QuerySizeAttribute, a3: QuerySizeAttribute, @noescape closure: () -> Void) {
if a1.isValid &&
a2.isValid &&
a3.isValid {
closure()
}
}
public func QuerySize(a1: QuerySizeAttribute, a2: QuerySizeAttribute, a3: QuerySizeAttribute, a4: QuerySizeAttribute, @noescape closure: () -> Void) {
if a1.isValid &&
a2.isValid &&
a3.isValid &&
a4.isValid {
closure()
}
}
public func QuerySize(a1: QuerySizeAttribute, a2: QuerySizeAttribute, a3: QuerySizeAttribute, a4: QuerySizeAttribute, a5: QuerySizeAttribute, @noescape closure: () -> Void) {
if a1.isValid &&
a2.isValid &&
a3.isValid &&
a4.isValid &&
a5.isValid {
closure()
}
} | apache-2.0 | fba4c403cc068554691bba72b507ceca | 29.328125 | 174 | 0.636598 | 3.872255 | false | false | false | false |
byvapps/ByvManager-iOS | ByvManager/Classes/PanicWebViewController.swift | 1 | 2268 | //
// PanicWebViewController.swift
// Pods
//
// Created by Adrian Apodaca on 11/5/17.
//
//
import UIKit
import ByvUtils
class PanicWebViewController: UIViewController, UIWebViewDelegate {
public var webUrl:URL? = nil
var webView: UIWebView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isOpaque = false
self.view.addSubview(webView)
let views = ["webView": webView]
var allConstraints = [NSLayoutConstraint]()
let verticalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[webView]-0-|",
options: [],
metrics: nil,
views: views)
allConstraints += verticalConstraints
webView.delegate = self
let horizontalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[webView]-0-|",
options: [],
metrics: nil,
views: views)
allConstraints += horizontalConstraints
NSLayoutConstraint.activate(allConstraints)
if let webUrl = webUrl {
webView.loadRequest(URLRequest(url: webUrl))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let host = request.url?.host {
if let webUrl = webUrl, webUrl.absoluteString.contains(host) {
return true
}
}
if let url = request.url {
UIApplication.shared.openURL(url)
}
return false
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | e6eeef40f4fd93bb4cc75e685b47e4a8 | 27.708861 | 137 | 0.609347 | 5.504854 | false | false | false | false |
moltin/ios-sdk | Sources/SDK/Utils/Query.swift | 1 | 3782 | //
// Query.swift
// moltin iOS
//
// Created by Craig Tweedy on 22/02/2018.
//
import Foundation
/// `MoltinInclude` represents various resources which can be included into other API calls, such as including the collections assigned to products
/// This struct is for use in the `MoltinRequest.include(...)` method
public struct MoltinInclude: RawRepresentable, Equatable {
public typealias RawValue = String
public var rawValue: String
/// Includes `File` objects
public static let files = MoltinInclude(rawValue: "files")
/// Includes `Product` objects
public static let products = MoltinInclude(rawValue: "products")
/// Includes `Collection` objects
public static let collections = MoltinInclude(rawValue: "collections")
/// Includes `Brand` objects
public static let brands = MoltinInclude(rawValue: "brands")
/// Includes `Category` objects
public static let categories = MoltinInclude(rawValue: "categories")
/// Includes a `File` object representing the main image
public static let mainImage = MoltinInclude(rawValue: "main_image")
/// Includes `TaxItem` objects
public static let taxes = MoltinInclude(rawValue: "tax_items")
public init(rawValue: String) {
self.rawValue = rawValue
}
}
/// `MoltinFilterOperator` represents various operations that can be applied to `MoltinRequest.filter(...)`
/// These parameters allow a user to filter resources.
public struct MoltinFilterOperator: RawRepresentable, Equatable {
public typealias RawValue = String
public var rawValue: String
/// Represents an "equals" filter
public static let equal = MoltinFilterOperator(rawValue: "eq")
/// Represents an "equals" filter
public static let like = MoltinFilterOperator(rawValue: "like")
///Represents a "greater than" filter
public static let greaterThan = MoltinFilterOperator(rawValue: "gt")
///Represents a "greater than or equal to" filter
public static let greaterThanOrEqual = MoltinFilterOperator(rawValue: "ge")
///Represents a "less than" filter
public static let lessThan = MoltinFilterOperator(rawValue: "lt")
///Represents a "less than or equal to" filter
public static let lessThanOrEqual = MoltinFilterOperator(rawValue: "le")
public init(rawValue: String) {
self.rawValue = rawValue
}
}
/// `MoltinQuery` encapsulates all query parameters applied to a request, as well as converting these parameters to `[URLQueryItem]`
open class MoltinQuery {
var withIncludes: [MoltinInclude]?
var withSorting: String?
var withLimit: String?
var withOffset: String?
var withFilter: [(MoltinFilterOperator, String, String)] = []
func toURLQueryItems() -> [URLQueryItem] {
var queryParams: [URLQueryItem] = []
if let includes = self.withIncludes {
queryParams.append(URLQueryItem(name: "include", value: includes.map { $0.rawValue }.joined(separator: ",")))
}
if let sort = self.withSorting {
queryParams.append(URLQueryItem(name: "sort", value: sort))
}
if let limit = self.withLimit {
queryParams.append(URLQueryItem(name: "page[limit]", value: limit))
}
if let offset = self.withOffset {
queryParams.append(URLQueryItem(name: "page[offset]", value: offset))
}
if self.withFilter.count > 0 {
let filterString = self.withFilter.map { (op, key, value) -> String in
return "\(op.rawValue)(\(key),\(value))"
}.joined(separator: ":")
queryParams.append(URLQueryItem(name: "filter", value: filterString))
}
return queryParams
}
}
| mit | e0c2e858c62b4a9c97a10522aa8a103d | 36.078431 | 147 | 0.669223 | 4.70398 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity | EnjoyUniversity/EnjoyUniversity/Classes/Model/UserInfo.swift | 1 | 1354 | //
// UserInfo.swift
// EnjoyUniversity
//
// Created by lip on 17/4/9.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
class UserInfo: NSObject {
/// 用户 ID ,即手机号
var uid:Int64 = 0
/// 头像
var avatar:String?
/// 昵称
var nickname:String?
/// 性别 男0 女1 保密2
var gender:Int = 0
/// 专业班级
var professionclass:String?
/// 学号
var studentid:Int64 = 0
/// 姓名
var name:String?
/// 用户节操值 满分100
var reputation:Int = 0
/// 用户验证信息
var verified:Int = 0
/// 入学年份
var grade:Int = 0
/// 职位(不属于这个表,将就着用) -3表示提交申请,-2表示进行笔试,-1表示进行面试,1表示成员,2表示管理员 3表示社长
var position:Int = -4
init(uid:Int64,avatar:String?,nickname:String,gender:Int,professionclass:String,studentid:Int64,name:String,grade:Int) {
self.uid = uid
self.nickname = nickname
self.avatar = avatar
self.gender = gender
self.professionclass = professionclass
self.name = name
self.studentid = studentid
self.grade = grade
}
override init() {
super.init()
}
}
| mit | d86eb2f4b8470a68636ea0384ae1f35d | 17.758065 | 124 | 0.55546 | 3.248603 | false | false | false | false |
marcoconti83/targone | Sources/String+CommandLineArgument.swift | 1 | 4511 | //Copyright (c) Marco Conti 2015
//
//
//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
extension String {
private static let LongFlagPrefix = "--"
private static let ShortFlagPrefix = "-"
/// Returns whether self has the prefix that identifies the
/// argument as a long flag
func isLongFlagStyle() -> Bool {
return self.hasPrefix(String.LongFlagPrefix)
}
/// Returns whether self has the prefix that identifies the
/// argument as a short flag
func isShortFlagStyle() -> Bool {
return self.hasPrefix(String.ShortFlagPrefix) && !self.isLongFlagStyle()
}
/// Returns whether self is a long flag or short flag style
func isFlagStyle() -> Bool {
return self.isLongFlagStyle() || self.isShortFlagStyle()
}
/// Prepends "--" to self, if it's not already present or `self` starts with "-"
func addLongFlagPrefix() -> String {
if self.isFlagStyle() {
return self
}
return String.LongFlagPrefix + self
}
/// Prepends "-" to `self`, if it's not already present
func addShortFlagPrefix() -> String {
if self.isFlagStyle() {
return self
}
return String.ShortFlagPrefix + self
}
/// Returns `self` without the flag prefix ("--" or "-")
func removeFlagPrefix() -> String {
if(self.isLongFlagStyle()) {
return String(
self[self.index(self.startIndex, offsetBy: 2)...]
)
}
if(self.isShortFlagStyle()) {
return String(
self[self.index(self.startIndex, offsetBy: 1)...]
)
}
return self
}
/**
Returns `self` transformed to the format of a placeholder argument
e.g. from
--output-file
to
OUTPUT_FILE
*/
func placeholderArgumentString() -> String {
var output = self.removeFlagPrefix()
output = String(output.map { $0 == "-" ? "_" : $0 })
return output.uppercased()
}
/**
Returns whether the string is a valid argument name according to
the following rules
- can have a "-" or "--" prefix
- after the prefix (if any) or at the first character (if it has no prefix),
there should be a lowercase or uppercase letter or "_"
- there can be no spaces and no puctuation symbol other than "_" or "-"
*/
func isValidArgumentName() -> Bool {
let withoutPrefix = self.removeFlagPrefix()
if withoutPrefix.count == 0 {
return false
}
// does it have spaces?
if let _ = withoutPrefix.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines) {
return false
}
// does it start with letter?
var firstLetterCharacterSet = CharacterSet.letters
firstLetterCharacterSet.insert(charactersIn: "_")
if !firstLetterCharacterSet.contains(UnicodeScalar(withoutPrefix.utf16.first!)!) {
return false
}
// does it contains only alphanumeric and _ and -?
var validCharacterSet = CharacterSet.alphanumerics
validCharacterSet.insert(charactersIn: "-_")
if let _ = withoutPrefix.rangeOfCharacter(from: validCharacterSet.inverted) {
return false
}
return true
}
}
| mit | 9daf8f4a8ef69a71dbd7b8022b1b178f | 31.927007 | 94 | 0.621148 | 4.829764 | false | false | false | false |
c-Viorel/MBPageControl | ViewController.swift | 1 | 1488 | //
// ViewController.swift
// MBPageControl
//
// Created by Viorel Porumbescu on 04/08/2017.
// Copyright © 2017 Viorel. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var txt1: NSTextField!
@IBOutlet weak var txt2: NSTextField!
@IBOutlet weak var txt3: NSTextField!
@IBOutlet weak var txt4: NSTextField!
@IBOutlet weak var txt5: NSTextField!
@IBOutlet weak var inactive: MBPageControlView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear() {
inactive.isEnabled = false
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func pageControl1Action(_ sender: MBPageControlView) {
txt1.stringValue = "\(sender.indexOfSelectedItem)"
}
@IBAction func pageControl2Action(_ sender: MBPageControlView) {
txt2.stringValue = "\(sender.indexOfSelectedItem)"
}
@IBAction func pageControl3Action(_ sender: MBPageControlView) {
txt3.stringValue = "\(sender.indexOfSelectedItem)"
}
@IBAction func pageControl4Action(_ sender: MBPageControlView) {
txt4.stringValue = "\(sender.indexOfSelectedItem)"
}
@IBAction func pageControl5Action(_ sender: MBPageControlView) {
txt5.stringValue = "\(sender.indexOfSelectedItem)"
}
}
| mit | 911f9f5bbd815d23c02e710379df77ea | 22.983871 | 68 | 0.66846 | 4.533537 | false | false | false | false |
designatednerd/iOS10NotificationSample | ParrotKit/Models/Party.swift | 1 | 1141 | //
// Party.swift
// NotificationSample
//
// Created by Ellen Shapiro (Work) on 9/1/16.
// Copyright © 2016 Designated Nerd Software. All rights reserved.
//
import Foundation
public struct Party {
public static var current = Party()
private init() {
self.parrots = UserDefaultsWrapper.storedParty()
}
public var parrots: [PartyParrot]
private func postUpdateNotification() {
NotificationCenter
.default
.post(name: .PartyUpdated,
object: nil)
}
public mutating func reloadFromDefaults() {
self.parrots = UserDefaultsWrapper.storedParty()
self.postUpdateNotification()
}
public mutating func add(_ parrotToAdd: PartyParrot) {
self.parrots.append(parrotToAdd)
UserDefaultsWrapper.storeParty(self.parrots)
self.postUpdateNotification()
}
public mutating func block(_ parrotToBlock: PartyParrot) {
self.parrots = self.parrots.filter { $0 != parrotToBlock }
UserDefaultsWrapper.storeParty(self.parrots)
self.postUpdateNotification()
}
}
| mit | 456ca6a9d459ba531773dd1990caa219 | 25.511628 | 67 | 0.642105 | 4.634146 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 24--Iron-Tips/IronTips/IronTips/TipsTableViewController.swift | 1 | 5717 | //
// TipsTableViewController.swift
// IronTips
//
// Created by Ben Gohlke on 11/5/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class TipsTableViewController: UITableViewController, UITextFieldDelegate
{
var tips = [PFObject]()
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addTip:")
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
if PFUser.currentUser() == nil
{
performSegueWithIdentifier("ShowLoginModalSegue", sender: self)
}
else
{
refreshTips()
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return tips.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TipCell", forIndexPath: indexPath) as! TipCell
let aTip = tips[indexPath.row]
if let comment = aTip["comment"] as? String
{
if comment == ""
{
cell.textField.becomeFirstResponder()
}
else
{
cell.textField.text = comment
}
}
else
{
cell.textField.becomeFirstResponder()
}
return cell
}
// MARK: - Parse Queries
func refreshTips()
{
if PFUser.currentUser() != nil
{
let query = PFQuery(className: "Tip")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil
{
self.tips = objects!
self.tableView.reloadData()
}
else
{
print(error?.localizedDescription)
}
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Action Handlers
@IBAction func unwindToTipsTableViewController(unwindSegue: UIStoryboardSegue)
{
refreshTips()
}
@IBAction func addTip(sender: UIBarButtonItem)
{
let aTip = PFObject(className: "Tip")
tips.insert(aTip, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - TextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool
{
var rc = false
if textField.text != ""
{
rc = true
textField.resignFirstResponder()
let contentView = textField.superview
let cell = contentView?.superview as? TipCell
let indexPath = tableView.indexPathForCell(cell!)
let aTip = tips[indexPath!.row]
aTip["comment"] = textField.text
aTip.saveInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if succeeded
{
// object was saved to Parse
}
else
{
print(error?.localizedDescription)
}
}
}
return rc
}
}
| cc0-1.0 | 2dfda1dfd15288790215b49511358137 | 28.770833 | 157 | 0.588174 | 5.582031 | false | false | false | false |
Aahung/two-half-password | two-half-password/Controllers/VaultOutlineViewController.swift | 1 | 3452 | //
// VaultItemOutlineViewController.swift
// two-half-password
//
// Created by Xinhong LIU on 15/6/15.
// Copyright © 2015 ParseCool. All rights reserved.
//
import Cocoa
class VaultOutlineViewController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {
var vaultViewController: VaultViewController!
@IBOutlet weak var outlineView: NSOutlineView!
class Category: NSObject {
var type: String
var items: NSMutableArray
init(type: String) {
self.type = type
self.items = NSMutableArray()
}
}
var items: NSMutableDictionary = NSMutableDictionary()
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
func addItems(items: [VaultItem]) {
for item in items {
if self.items[item.type] == nil {
let category = Category(type: item.type)
self.items.setValue(category, forKey: item.type)
}
let category = self.items[item.type] as! Category
category.items.addObject(item)
}
for key in self.items.allKeys as! [String] {
let value = self.items.valueForKey(key) as! Category
value.items.sortUsingComparator({ (this, that) -> NSComparisonResult in
if (this as! VaultItem).title < (that as! VaultItem).title {
return NSComparisonResult.OrderedAscending
} else {
return NSComparisonResult.OrderedDescending
}
})
}
outlineView.reloadData()
outlineView.expandItem(nil, expandChildren: true)
}
// MARK: NSOutlineView DataSource
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
if (item == nil) {
return items.count
} else {
if (item is Category) {
return (item as! Category).items.count
} else {
return 0
}
}
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
return item is Category && (item as! Category).items.count > 0
}
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
if (item == nil) {
return items.allValues[index]
} else {
if (item is Category) {
return (item as! Category).items[index]
} else {
return 0 // wont be here
}
}
}
func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? {
if (item == nil) {
return ""
} else {
if (item is Category) {
return (item as! Category).type
} else {
return (item as! VaultItem).title
}
}
}
func outlineViewSelectionDidChange(notification: NSNotification) {
let row = outlineView.selectedRow
guard (row >= 0) else {
return
}
let item = outlineView.itemAtRow(row)
if item != nil && !(item is Category) {
vaultViewController.didSelectVaultItem(item as! VaultItem)
}
}
}
| mit | 96bcb4b8c70620369e5d72d420fbf451 | 30.09009 | 144 | 0.558099 | 5.037956 | false | false | false | false |
git-hushuai/MOMO | MMHSMeterialProject/AppDelegate.swift | 1 | 8129 | //
// AppDelegate.swift
// MMHSMeterialProject
//
// Created by hushuaike on 16/3/24.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,MQManagerDelegate{
var window: UIWindow?
var tabBarController : HSTabBarController = HSTabBarController();
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSThread.sleepForTimeInterval(2);
// 105011 // 105003
GNUserService.sharedUserService().userId = "105003";
GNNotificationCenter.addObserver(self, selector: "userServiceLoginOkNotification", name: GNUserServiceLoginNotification, object: nil);
GNNotificationCenter.addObserver(self, selector: "userNeedLoginNotification", name: GNUserNeedLoginNotification, object: nil);
GNNotificationCenter.addObserver(self, selector: "getUserAccountNitification", name: TKDidGetUserAccountInfoNotification, object: nil)
GNNotificationCenter.addObserver(self, selector: "showHeadLineMainController", name: TKUserDidCommitKeyHotWordNotification, object: nil);
// Override point for customization after application launch.
self.window = UIWindow.init(frame: UIScreen.mainScreen().bounds);
self.window?.backgroundColor = UIColor.blackColor();
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default;
UIApplication.sharedApplication().statusBarHidden = false;
self.init3rdPart();
// TKAppInitService.sharedInstance().initApp();
let loginVC = HSLoginController();
let loginNaviVC = HSNavigationController.init(rootViewController: loginVC);
if ((GNUserService.sharedUserService().userId) == nil){
// self.window?.rootViewController = loginNaviVC;
self.showLaunchLeadController();
self.loadLaunchConfigInfo()
}else{
// self.showMainUI();
self.showHeadLineMainController()
}
self.window?.makeKeyAndVisible();
return true
}
//MARK: 提交热词之后进入到主界面
func showHeadLineMainController(){
// dispatch_async(dispatch_get_main_queue()) { () -> Void in
UIApplication.sharedApplication().statusBarHidden = false;
// }
let mainVC = BYMainController();
mainVC.fd_prefersNavigationBarHidden = false;
let mainNavi = HSNavigationController.init(rootViewController: mainVC)
self.window?.rootViewController = mainNavi;
}
// MARK : app启动引导页
func loadLaunchConfigInfo(){
GNNetworkCenter.userLoadResumeItemBaseInfoWithReqObject(nil, andFunName: "c_config") { (response:YWResponse!) -> Void in
print("launch config info :\(response)--data:\(response.data)");
let jobNameArr = response.data.valueForKey("job") as! NSArray;
let workTimeArr = response.data.valueForKey("work_time") as! NSArray
let mutableWorkTimeArr = NSMutableArray();
let mutableNameArr = NSMutableArray();
for dict in jobNameArr{
let jobName = dict.valueForKey("job_name") as! String;
mutableNameArr.addObject(jobName);
}
for dict in workTimeArr{
let workTime = dict.valueForKey("w_name") as! String;
mutableWorkTimeArr.addObject(workTime);
}
print("launch name array :\(mutableNameArr)");
NSUserDefaults.standardUserDefaults().setValue(mutableNameArr, forKey: KLaunchJobNamekey)
NSUserDefaults.standardUserDefaults().synchronize();
let userInfo = [KLaunchJobNamekey : mutableNameArr,
KLaunchWorkTimeKey : mutableWorkTimeArr];
NSNotificationCenter.defaultCenter().postNotificationName(KLaunchPullJobNameSuccessNotification, object: self, userInfo: userInfo);
}
}
func showLaunchLeadController(){
let launchvc = TKLaunchLeadingController();
let launchNavi = HSNavigationController.init(rootViewController: launchvc);
self.window?.rootViewController = launchNavi
}
func init3rdPart(){
MQManager.initWithAppkey("d892607a6de6cdfdbc88e872d1ffc7cb") { (clientID:String!, error :NSError!) -> Void in
if (error == nil){
print("初始化美洽SDK成功");
}else{
print("初始化美洽SDK失败");
}
}
MQManager.setClientOnlineWithCustomizedId("13800000001", success: { (onLineResult:MQClientOnlineResult, agent:MQAgent!, messageArr: [MQMessage]!) -> Void in
print("onlineres:\(onLineResult)---agent:\(agent)--message:\(messageArr)");
}, failure: { (error:NSError!) -> Void in
}, receiveMessageDelegate:self);
}
func userServiceLoginOkNotification(){
self.showMainUI();
}
func userNeedLoginNotification(){
let loginVC = HSLoginController();
let versionInfo = Float(UIDevice.currentDevice().systemVersion);
if(versionInfo >= 8.0){
self.window?.rootViewController?.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext;
}
dispatch_after(UInt64(0.15), dispatch_get_main_queue()) { () -> Void in
self.window?.rootViewController?.presentViewController(loginVC, animated: true, completion: nil);
}
}
func getUserAccountNitification(){
print("getUserAccountNitification");
}
func showMainUI(){
let firstVC = FirstViewController();
firstVC.title = "免费推荐";
let firstNavi = HSNavigationController.init(rootViewController: firstVC)
let secondVC = SecondViewController();
secondVC.title = "订单委托";
let secondNavi = HSNavigationController.init(rootViewController: secondVC);
let threeVC = ThreeViewController();
threeVC.title = "我的订单"
let threeNavi = HSNavigationController.init(rootViewController: threeVC)
let fourVC = FourViewController();
fourVC.title = "简历库";
let fourNavi = HSNavigationController.init(rootViewController: fourVC);
let fiveVC = FiveViewController();
fiveVC.title = "我的";
let fiveNavi = HSNavigationController.init(rootViewController: fiveVC);
let tabBarVC = HSTabBarController();
tabBarVC.viewControllers = [firstNavi,secondNavi,threeNavi,fourNavi,fiveNavi];
tabBarVC.tabBarBtnTitleArray = ["人才推荐","岗位委托","订单","简历库","我的"];
tabBarVC.setTabImages([UIImage.init(named: "推荐常态@2x")!,UIImage.init(named: "到家常态@2x")!,UIImage.init(named: "订单常态@2x")!,UIImage.init(named: "简历库常态@2x")!,UIImage.init(named: "我的常态@2x")!], highlightedImages: [UIImage.init(named: "推荐选中@2x")!,UIImage.init(named: "到家选中@2x")!,UIImage.init(named: "订单选中@2x")!,UIImage.init(named: "简历库选中@2x")!,UIImage.init(named: "我的选中@2x")!]);
self.window?.rootViewController = tabBarVC;
self.tabBarController = tabBarVC;
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
MQManager.closeMeiqiaService();
}
func applicationWillEnterForeground(application: UIApplication) {
MQManager.openMeiqiaService();
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
/**
* 收到了消息
* @param message 消息
*/
func didReceiveMQMessages(message: [MQMessage]!) {
print("message : \(message)");
}
}
| mit | c2c12ef1d6e9cfd079411ecd9d33c170 | 38.118812 | 377 | 0.64819 | 4.731737 | false | false | false | false |
hughbe/swift | test/SILGen/objc_bridging_any.swift | 1 | 43241 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -sil-print-debuginfo -emit-silgen -sil-serialize-witness-tables %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import objc_generics
protocol P {}
protocol CP: class {}
struct KnownUnbridged {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any11passingToId{{.*}}F
func passingToId<T: CP, U>(receiver: NSIdLover,
string: String,
nsString: NSString,
object: AnyObject,
classGeneric: T,
classExistential: CP,
generic: U,
existential: P,
error: Error,
any: Any,
knownUnbridged: KnownUnbridged,
optionalA: String?,
optionalB: NSString?,
optionalC: Any?) {
// CHECK: bb0([[SELF:%.*]] : $NSIdLover,
// CHECK: debug_value [[STRING:%.*]] : $String
// CHECK: debug_value [[NSSTRING:%.*]] : $NSString
// CHECK: debug_value [[OBJECT:%.*]] : $AnyObject
// CHECK: debug_value [[CLASS_GENERIC:%.*]] : $T
// CHECK: debug_value [[CLASS_EXISTENTIAL:%.*]] : $CP
// CHECK: debug_value_addr [[GENERIC:%.*]] : $*U
// CHECK: debug_value_addr [[EXISTENTIAL:%.*]] : $*P
// CHECK: debug_value [[ERROR:%.*]] : $Error
// CHECK: debug_value_addr [[ANY:%.*]] : $*Any
// CHECK: debug_value [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged
// CHECK: debug_value [[OPT_STRING:%.*]] : $Optional<String>
// CHECK: debug_value [[OPT_NSSTRING:%.*]] : $Optional<NSString>
// CHECK: debug_value_addr [[OPT_ANY:%.*]] : $*Optional<Any>
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]]
// CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]]
// CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]]
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: end_borrow [[BORROWED_STRING]] from [[STRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(string)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]]
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject
// CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(nsString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]]
// CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject
// CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(classGeneric)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]]
// CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]]
// CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]]
// CHECK: apply [[METHOD]]([[OBJECT_COPY]], [[BORROWED_SELF]])
// CHECK: destroy_value [[OBJECT_COPY]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(object)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]]
// CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]]
// CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]]
// CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(classExistential)
// These cases perform a universal bridging conversion.
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[COPY:%.*]] = alloc_stack $U
// CHECK: copy_addr [[GENERIC]] to [initialization] [[COPY]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]])
// CHECK: dealloc_stack [[COPY]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(generic)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[COPY:%.*]] = alloc_stack $P
// CHECK: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]]
// CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(existential)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
// CHECK: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error
// CHECK: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
// CHECK: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
// CHECK: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
// CHECK: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: destroy_value [[ERROR_COPY]] : $Error
// CHECK: end_borrow [[BORROWED_ERROR]] from [[ERROR]]
// CHECK: apply [[METHOD]]([[BRIDGED_ERROR]], [[BORROWED_SELF]])
// CHECK: destroy_value [[BRIDGED_ERROR]] : $AnyObject
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(error)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[COPY:%.*]] = alloc_stack $Any
// CHECK: copy_addr [[ANY]] to [initialization] [[COPY]]
// CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK: // function_ref _bridgeAnythingToObjectiveC
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(any)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged
// CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]])
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(knownUnbridged)
// These cases bridge using Optional's _ObjectiveCBridgeable conformance.
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]]
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<String>
// CHECK: store [[OPT_STRING_COPY]] to [init] [[TMP]]
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]])
// CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(optionalA)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OPT_NSSTRING:%.*]] = begin_borrow [[OPT_NSSTRING]]
// CHECK: [[OPT_NSSTRING_COPY:%.*]] = copy_value [[BORROWED_OPT_NSSTRING]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString>
// CHECK: store [[OPT_NSSTRING_COPY]] to [init] [[TMP]]
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]])
// CHECK: end_borrow [[BORROWED_OPT_NSSTRING]] from [[OPT_NSSTRING]]
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(optionalB)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any>
// CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]]
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]])
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesId(optionalC)
// TODO: Property and subscript setters
}
// Workaround for rdar://problem/28318984. Skip the peephole for types with
// nontrivial SIL lowerings because we don't correctly form the substitutions
// for a generic _bridgeAnythingToObjectiveC call.
func zim() {}
struct Zang {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any27typesWithNontrivialLoweringySo9NSIdLoverC8receiver_tF
func typesWithNontrivialLowering(receiver: NSIdLover) {
// CHECK: init_existential_addr {{%.*}} : $*Any, $() -> ()
receiver.takesId(zim)
// CHECK: init_existential_addr {{%.*}} : $*Any, $Zang.Type
receiver.takesId(Zang.self)
// CHECK: init_existential_addr {{%.*}} : $*Any, $(() -> (), Zang.Type)
receiver.takesId((zim, Zang.self))
// CHECK: apply {{%.*}}<(Int, String)>
receiver.takesId((0, "one"))
}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any19passingToNullableId{{.*}}F
func passingToNullableId<T: CP, U>(receiver: NSIdLover,
string: String,
nsString: NSString,
object: AnyObject,
classGeneric: T,
classExistential: CP,
generic: U,
existential: P,
error: Error,
any: Any,
knownUnbridged: KnownUnbridged,
optString: String?,
optNSString: NSString?,
optObject: AnyObject?,
optClassGeneric: T?,
optClassExistential: CP?,
optGeneric: U?,
optExistential: P?,
optAny: Any?,
optKnownUnbridged: KnownUnbridged?,
optOptA: String??,
optOptB: NSString??,
optOptC: Any??)
{
// CHECK: bb0([[SELF:%.*]] : $NSIdLover,
// CHECK: [[STRING:%.*]] : $String,
// CHECK: [[NSSTRING:%.*]] : $NSString
// CHECK: [[OBJECT:%.*]] : $AnyObject
// CHECK: [[CLASS_GENERIC:%.*]] : $T
// CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP
// CHECK: [[GENERIC:%.*]] : $*U
// CHECK: [[EXISTENTIAL:%.*]] : $*P
// CHECK: [[ERROR:%.*]] : $Error
// CHECK: [[ANY:%.*]] : $*Any,
// CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged,
// CHECK: [[OPT_STRING:%.*]] : $Optional<String>,
// CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString>
// CHECK: [[OPT_OBJECT:%.*]] : $Optional<AnyObject>
// CHECK: [[OPT_CLASS_GENERIC:%.*]] : $Optional<T>
// CHECK: [[OPT_CLASS_EXISTENTIAL:%.*]] : $Optional<CP>
// CHECK: [[OPT_GENERIC:%.*]] : $*Optional<U>
// CHECK: [[OPT_EXISTENTIAL:%.*]] : $*Optional<P>
// CHECK: [[OPT_ANY:%.*]] : $*Optional<Any>
// CHECK: [[OPT_KNOWN_UNBRIDGED:%.*]] : $Optional<KnownUnbridged>
// CHECK: [[OPT_OPT_A:%.*]] : $Optional<Optional<String>>
// CHECK: [[OPT_OPT_B:%.*]] : $Optional<Optional<NSString>>
// CHECK: [[OPT_OPT_C:%.*]] : $*Optional<Optional<Any>>
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]]
// CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]]
// CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]]
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: destroy_value [[OPT_ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(string)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]]
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(nsString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]]
// CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]]
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[OBJECT_COPY]]
// CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(object)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]]
// CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(classGeneric)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]]
// CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]]
// CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]]
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(classExistential)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U
// CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(generic)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P
// CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]]
// CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[COPY]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(existential)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
// CHECK-NEXT: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error
// CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
// CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
// CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
// CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
// CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject
// CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
// CHECK-NEXT: destroy_value [[ERROR_COPY]] : $Error
// CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]]
// CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR_OPT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[BRIDGED_ERROR_OPT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(error)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]]
// CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[COPY]]
// CHECK-NEXT: dealloc_stack [[COPY]]
// CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]]
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(any)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover,
// CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged
// CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]])
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(knownUnbridged)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]]
// CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]]
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]]
// CHECK: switch_enum [[OPT_STRING_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[STRING_DATA:%.*]] : $String):
// CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_DATA:%.*]] = begin_borrow [[STRING_DATA]]
// CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_DATA]])
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject
// CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]]
// CHECK: end_borrow [[BORROWED_STRING_DATA]] from [[STRING_DATA]]
// CHECK: destroy_value [[STRING_DATA]]
// CHECK: br [[JOIN:bb.*]]([[OPT_ANYOBJECT]]
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_NONE:%.*]] = enum $Optional<AnyObject>, #Optional.none!enumelt
// CHECK: br [[JOIN]]([[OPT_NONE]]
//
// CHECK: [[JOIN]]([[PHI:%.*]] : $Optional<AnyObject>):
// CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]]
// CHECK: apply [[METHOD]]([[PHI]], [[BORROWED_SELF]])
// CHECK: destroy_value [[PHI]]
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
receiver.takesNullableId(optString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]]
receiver.takesNullableId(optNSString)
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]]
// CHECK: [[BORROWED_OPT_OBJECT:%.*]] = begin_borrow [[OPT_OBJECT]]
// CHECK: [[OPT_OBJECT_COPY:%.*]] = copy_value [[BORROWED_OPT_OBJECT]]
// CHECK: apply [[METHOD]]([[OPT_OBJECT_COPY]], [[BORROWED_SELF]])
receiver.takesNullableId(optObject)
receiver.takesNullableId(optClassGeneric)
receiver.takesNullableId(optClassExistential)
receiver.takesNullableId(optGeneric)
receiver.takesNullableId(optExistential)
receiver.takesNullableId(optAny)
receiver.takesNullableId(optKnownUnbridged)
receiver.takesNullableId(optOptA)
receiver.takesNullableId(optOptB)
receiver.takesNullableId(optOptC)
}
protocol Anyable {
init(any: Any)
init(anyMaybe: Any?)
var anyProperty: Any { get }
var maybeAnyProperty: Any? { get }
}
// Make sure we generate correct bridging thunks
class SwiftIdLover : NSObject, Anyable {
func methodReturningAny() -> Any {}
// SEMANTIC ARC TODO: This is another case of pattern matching the body of one
// function in a different function... Just pattern match the unreachable case
// to preserve behavior. We should check if it is correct.
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF : $@convention(method) (@guaranteed SwiftIdLover) -> @out Any
// CHECK: unreachable
// CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF'
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased AnyObject {
// CHECK: bb0([[SELF:%[0-9]+]] : $SwiftIdLover):
// CHECK: [[NATIVE_RESULT:%.*]] = alloc_stack $Any
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $SwiftIdLover
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE_IMP:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF
// CHECK: apply [[NATIVE_IMP]]([[NATIVE_RESULT]], [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[OPEN_RESULT:%.*]] = open_existential_addr immutable_access [[NATIVE_RESULT]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[OPEN_RESULT]] to [initialization] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
// CHECK: [[OBJC_RESULT:%.*]] = apply [[BRIDGE_ANYTHING]]<{{.*}}>([[TMP]])
// CHECK: return [[OBJC_RESULT]]
// CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo'
func methodReturningOptionalAny() -> Any? {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyF
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyFTo
// CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
@objc func methodTakingAny(a: Any) {}
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> ()
// CHECK: bb0([[ARG:%.*]] : $AnyObject, [[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[OPTIONAL_ARG_COPY:%.*]] = unchecked_ref_cast [[ARG_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] :
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL_ARG_COPY]])
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tF
// CHECK-NEXT: apply [[METHOD]]([[RESULT]], [[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return
func methodTakingOptionalAny(a: Any?) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tF
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tFTo
// CHECK: function_ref [[BRIDGE_TO_ANY_FUNC]]
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF : $@convention(method) (@owned @callee_owned (@in Any) -> (), @guaranteed SwiftIdLover) -> ()
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcFTo : $@convention(objc_method) (@convention(block) (AnyObject) -> (), SwiftIdLover) -> ()
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (AnyObject) -> (), [[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0yXlIyBy_ypIxi_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], [[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0yXlIyBy_ypIxi_TR
// CHECK: bb0([[ANY:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) (AnyObject) -> ()):
// CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_addr immutable_access [[ANY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[OPENED_ANY]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: apply [[BLOCK]]([[BRIDGED]])
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK-NEXT: destroy_value [[BLOCK]]
// CHECK-NEXT: destroy_value [[BRIDGED]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[ANY]]
// CHECK-NEXT: return [[VOID]]
@objc func methodTakingBlockTakingAny(_: (Any) -> ()) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned (@in Any) -> ()
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) (AnyObject) -> ()
// CHECK: bb0([[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD:%.*]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned (@in Any) -> ()
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: store [[RESULT:%.*]] to [init] [[BLOCK_STORAGE_ADDR]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0ypIxi_yXlIyBy_TR
// CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned (@in Any) -> (), invoke [[THUNK_FN]]
// CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]]
// CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]]
// CHECK-NEXT: destroy_value [[RESULT]]
// CHECK-NEXT: return [[BLOCK]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIxi_yXlIyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> (), AnyObject) -> ()
// CHECK: bb0([[BLOCK_STORAGE:%.*]] : $*@block_storage @callee_owned (@in Any) -> (), [[ANY:%.*]] : $AnyObject):
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]]
// CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[ANY_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] :
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]])
// CHECK-NEXT: apply [[FUNCTION]]([[RESULT]])
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: return [[VOID]] : $()
@objc func methodTakingBlockTakingOptionalAny(_: (Any?) -> ()) {}
@objc func methodReturningBlockTakingAny() -> ((Any) -> ()) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF : $@convention(method) (@owned @callee_owned () -> @out Any, @guaranteed SwiftIdLover) -> () {
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycFTo : $@convention(objc_method) (@convention(block) () -> @autoreleased AnyObject, SwiftIdLover) -> ()
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) () -> @autoreleased AnyObject, [[ANY:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0yXlIyBa_ypIxr_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]])
// CHECK-NEXT: [[BORROWED_ANY_COPY:%.*]] = begin_borrow [[ANY_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], [[BORROWED_ANY_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_ANY_COPY]] from [[ANY_COPY]]
// CHECK-NEXT: destroy_value [[ANY_COPY]]
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0yXlIyBa_ypIxr_TR : $@convention(thin) (@owned @convention(block) () -> @autoreleased AnyObject) -> @out Any
// CHECK: bb0([[ANY_ADDR:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) () -> @autoreleased AnyObject):
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BLOCK]]()
// CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[BRIDGED]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] :
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]])
// TODO: Should elide the copy
// CHECK-NEXT: copy_addr [take] [[RESULT]] to [initialization] [[ANY_ADDR]]
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: destroy_value [[BLOCK]]
// CHECK-NEXT: return [[EMPTY]]
@objc func methodReturningBlockTakingOptionalAny() -> ((Any?) -> ()) {}
@objc func methodTakingBlockReturningAny(_: () -> Any) {}
// CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned () -> @out Any
// CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) () -> @autoreleased AnyObject
// CHECK: bb0([[SELF:%.*]] : $SwiftIdLover):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF
// CHECK-NEXT: [[FUNCTION:%.*]] = apply [[METHOD]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned () -> @out Any
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]]
// CHECK-NEXT: store [[FUNCTION]] to [init] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0ypIxr_yXlIyBa_TR
// CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned () -> @out Any, invoke [[THUNK_FN]]
// CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]]
// CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]]
// CHECK-NEXT: destroy_value [[FUNCTION]]
// CHECK-NEXT: return [[BLOCK]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIxr_yXlIyBa_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> @out Any) -> @autoreleased AnyObject
// CHECK: bb0(%0 : $*@block_storage @callee_owned () -> @out Any):
// CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0
// CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]]
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any
// CHECK-NEXT: apply [[FUNCTION]]([[RESULT]])
// CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr immutable_access [[RESULT]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]],
// CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]]
// CHECK: copy_addr [[OPENED]] to [initialization] [[TMP]]
// CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC
// CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref
// CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]])
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: destroy_addr [[RESULT]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: return [[BRIDGED]]
@objc func methodTakingBlockReturningOptionalAny(_: () -> Any?) {}
@objc func methodReturningBlockReturningAny() -> (() -> Any) {}
@objc func methodReturningBlockReturningOptionalAny() -> (() -> Any?) {}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypSgIxr_yXlSgIyBa_TR
// CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
override init() { super.init() }
@objc dynamic required convenience init(any: Any) { self.init() }
@objc dynamic required convenience init(anyMaybe: Any?) { self.init() }
@objc dynamic var anyProperty: Any
@objc dynamic var maybeAnyProperty: Any?
subscript(_: IndexForAnySubscript) -> Any { get {} set {} }
@objc func methodReturningAnyOrError() throws -> Any {}
}
class IndexForAnySubscript {}
func dynamicLookup(x: AnyObject) {
_ = x.anyProperty
_ = x[IndexForAnySubscript()]
}
extension GenericClass {
// CHECK-LABEL: sil hidden @_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF :
func pseudogenericAnyErasure(x: T) -> Any {
// CHECK: bb0([[ANY_OUT:%.*]] : $*Any, [[ARG:%.*]] : $T, [[SELF:%.*]] : $GenericClass<T>
// CHECK: [[ANY_BUF:%.*]] = init_existential_addr [[ANY_OUT]] : $*Any, $AnyObject
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[ARG_COPY]] : $T : $T, $AnyObject
// CHECK: store [[ANYOBJECT]] to [init] [[ANY_BUF]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
return x
}
// CHECK: } // end sil function '_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF'
}
// Make sure AnyHashable erasure marks Hashable conformance as used
class AnyHashableClass : NSObject {
// CHECK-LABEL: sil hidden @_T017objc_bridging_any16AnyHashableClassC07returnsdE0s0dE0VyF
// CHECK: [[FN:%.*]] = function_ref @_swift_convertToAnyHashable
// CHECK: apply [[FN]]<GenericOption>({{.*}})
func returnsAnyHashable() -> AnyHashable {
return GenericOption.multithreaded
}
}
// CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
// CHECK-NEXT: base_protocol Equatable: GenericOption: Equatable module objc_generics
// CHECK-NEXT: method #Hashable.hashValue!getter.1: {{.*}} : @_T0SC13GenericOptionVs8Hashable13objc_genericssACP9hashValueSifgTW
// CHECK-NEXT: }
| apache-2.0 | c6230bc498763c2054fa2c39fd75151e | 56.886212 | 220 | 0.611364 | 3.597421 | false | false | false | false |
lkzhao/Hero | Sources/HeroModifier+Advanced.swift | 1 | 5215 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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.
//
#if canImport(UIKit)
// advance modifiers
extension HeroModifier {
/**
Apply modifiers directly to the view at the start of the transition.
The modifiers supplied here won't be animated.
For source views, modifiers are set directly at the beginning of the animation.
For destination views, they replace the target state (final appearance).
*/
public static func beginWith(_ modifiers: [HeroModifier]) -> HeroModifier {
return HeroModifier { targetState in
if targetState.beginState == nil {
targetState.beginState = []
}
targetState.beginState!.append(contentsOf: modifiers)
}
}
public static func beginWith(modifiers: [HeroModifier]) -> HeroModifier {
return .beginWith(modifiers)
}
public static func beginWith(_ modifiers: HeroModifier...) -> HeroModifier {
return .beginWith(modifiers)
}
/**
Use global coordinate space.
When using global coordinate space. The view become a independent view that is not a subview of any view.
It won't move when its parent view moves, and won't be affected by parent view's attributes.
When a view is matched, this is automatically enabled.
The `source` modifier will also enable this.
Global coordinate space is default for all views prior to version 0.1.3
*/
public static var useGlobalCoordinateSpace: HeroModifier = HeroModifier { targetState in
targetState.coordinateSpace = .global
}
/**
ignore all heroModifiers attributes for a view's direct subviews.
*/
public static var ignoreSubviewModifiers: HeroModifier = .ignoreSubviewModifiers()
/**
ignore all heroModifiers attributes for a view's subviews.
- Parameters:
- recursive: if false, will only ignore direct subviews' modifiers. default false.
*/
public static func ignoreSubviewModifiers(recursive: Bool = false) -> HeroModifier {
return HeroModifier { targetState in
targetState.ignoreSubviewModifiers = recursive
}
}
/**
Will create snapshot optimized for different view type.
For custom views or views with masking, useOptimizedSnapshot might create snapshots
that appear differently than the actual view.
In that case, use .useNormalSnapshot or .useSlowRenderSnapshot to disable the optimization.
This modifier actually does nothing by itself since .useOptimizedSnapshot is the default.
*/
public static var useOptimizedSnapshot: HeroModifier = HeroModifier { targetState in
targetState.snapshotType = .optimized
}
/**
Create snapshot using snapshotView(afterScreenUpdates:).
*/
public static var useNormalSnapshot: HeroModifier = HeroModifier { targetState in
targetState.snapshotType = .normal
}
/**
Create snapshot using layer.render(in: currentContext).
This is slower than .useNormalSnapshot but gives more accurate snapshot for some views (eg. UIStackView).
*/
public static var useLayerRenderSnapshot: HeroModifier = HeroModifier { targetState in
targetState.snapshotType = .layerRender
}
/**
Force Hero to not create any snapshot when animating this view.
This will mess up the view hierarchy, therefore, view controllers have to rebuild
its view structure after the transition finishes.
*/
public static var useNoSnapshot: HeroModifier = HeroModifier { targetState in
targetState.snapshotType = .noSnapshot
}
/**
Force the view to animate.
By default, Hero will not animate if the view is outside the screen bounds or if there is no animatable hero modifier, unless this modifier is used.
*/
public static var forceAnimate = HeroModifier { targetState in
targetState.forceAnimate = true
}
/**
Force Hero use scale based size animation. This will convert all .size modifier into .scale modifier.
This is to help Hero animate layers that doesn't support bounds animation. Also gives better performance.
*/
public static var useScaleBasedSizeChange: HeroModifier = HeroModifier { targetState in
targetState.useScaleBasedSizeChange = true
}
}
#endif
| mit | ebac6e354d75f14a1bcebc4f41d7e481 | 37.345588 | 151 | 0.743049 | 4.819778 | false | false | false | false |
IvanVorobei/TwitterLaunchAnimation | TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/views/views/SPUIViewExtenshion.swift | 1 | 8464 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([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 UIKit
// MARK: - layout
public extension UIView {
func rounded() {
self.layer.cornerRadius = self.getMinSideSize() / 2
}
func getBootomYPosition() -> CGFloat {
return self.frame.origin.y + self.frame.height
}
func getMinSideSize() -> CGFloat {
return min(self.frame.width, self.frame.height)
}
func widthLessThanLength() -> Bool {
return self.bounds.width < self.bounds.height
}
func setEqualsFrameFromBounds(_ view: UIView) {
self.frame = view.bounds
}
func resize(to width: CGFloat) {
let relativeFactor = self.frame.width / self.frame.height
self.frame = CGRect.init(
x: self.frame.origin.x,
y: self.frame.origin.y,
width: width,
height: self.frame.height * relativeFactor
)
}
}
public extension UIImage {
func resize(to size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
self.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: size.width, height: size.height)))
let resizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return resizeImage
}
}
public extension UIView {
func setParalax(amountFactor: CGFloat) {
let amount = self.getMinSideSize() * amountFactor
self.setParalax(amount: amount)
}
func setParalax(amount: CGFloat) {
self.motionEffects.removeAll()
let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
horizontal.minimumRelativeValue = -amount
horizontal.maximumRelativeValue = amount
let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
vertical.minimumRelativeValue = -amount
vertical.maximumRelativeValue = amount
let group = UIMotionEffectGroup()
group.motionEffects = [horizontal, vertical]
self.addMotionEffect(group)
}
}
// MARK: - convertToImage
public extension UIView {
func convertToImage() -> UIImage {
return UIImage.drawFromView(view: self)
}
}
// MARK: - gradeView
public extension UIView {
func addGrade(alpha: CGFloat, color: UIColor = UIColor.black) -> UIView {
let gradeView = UIView.init()
gradeView.alpha = 0
self.addSubview(gradeView)
SPConstraintsAssistent.setEqualSizeConstraint(gradeView, superVuew: self)
gradeView.alpha = alpha
gradeView.backgroundColor = color
return gradeView
}
func setShadow(
xTranslationFactor: CGFloat,
yTranslationFactor: CGFloat,
widthRelativeFactor: CGFloat,
heightRelativeFactor: CGFloat,
blurRadiusFactor: CGFloat,
shadowOpacity: CGFloat,
cornerRadiusFactor: CGFloat = 0
) {
let shadowWidth = self.frame.width * widthRelativeFactor
let shadowHeight = self.frame.height * heightRelativeFactor
let xTranslation = (self.frame.width - shadowWidth) / 2 + (self.frame.width * xTranslationFactor)
let yTranslation = (self.frame.height - shadowHeight) / 2 + (self.frame.height * yTranslationFactor)
let cornerRadius = self.getMinSideSize() * cornerRadiusFactor
let shadowPath = UIBezierPath.init(
roundedRect: CGRect.init(x: xTranslation, y: yTranslation, width: shadowWidth, height: shadowHeight),
cornerRadius: cornerRadius
)
let blurRadius = self.getMinSideSize() * blurRadiusFactor
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowOpacity = Float(shadowOpacity)
self.layer.shadowRadius = blurRadius
self.layer.masksToBounds = false
self.layer.shadowPath = shadowPath.cgPath;
}
/*func setShadow(
xTranslationFactor: CGFloat = 0,
yTranslationFactor: CGFloat = 0.1,
widthRelativeFactor: CGFloat = 0.8,
heightRelativeFactor: CGFloat = 0.9,
blurRadius: CGFloat = 5,
shadowOpacity: Float = 0.35,
animated: Bool = false,
duration: CGFloat = 0)
{
let shadowWidth = self.frame.width * widthRelativeFactor
let shadowHeight = self.frame.height * heightRelativeFactor
let xTranslation = (self.frame.width - shadowWidth) / 2 + (self.frame.width * xTranslationFactor)
let yTranslation = (self.frame.height - shadowHeight) / 2 + (self.frame.height * yTranslationFactor)
let shadowPath = UIBezierPath.init(rect:
CGRect.init(
x: xTranslation,
y: yTranslation,
width: shadowWidth,
height: shadowHeight
)
)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowRadius = blurRadius
self.layer.masksToBounds = false
if animated {
let theAnimation = CABasicAnimation.init(keyPath: "shadowPath")
theAnimation.duration = CFTimeInterval(duration)
theAnimation.fromValue = layer.shadowPath
theAnimation.toValue = shadowPath.cgPath
self.layer.add(theAnimation, forKey: "shadowPath")
}
self.layer.shadowPath = shadowPath.cgPath;
}
func setShadow(
xTranslationFactor: CGFloat = 0,
yTranslationFactor: CGFloat = 0.1,
widthRelativeFactor: CGFloat = 0.8,
heightRelativeFactor: CGFloat = 0.9,
blurRadius: CGFloat = 5,
shadowOpacity: Float = 0.35,
duration: CGFloat,
damping: CGFloat)
{
let shadowWidth = self.frame.width * widthRelativeFactor
let shadowHeight = self.frame.height * heightRelativeFactor
let xTranslation = (self.frame.width - shadowWidth) / 2 + (self.frame.width * xTranslationFactor)
let yTranslation = (self.frame.height - shadowHeight) / 2 + (self.frame.height * yTranslationFactor)
let shadowPath = UIBezierPath.init(rect:
CGRect.init(
x: xTranslation,
y: yTranslation,
width: shadowWidth,
height: shadowHeight
)
)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowRadius = blurRadius
self.layer.masksToBounds = false
if #available(iOS 9.0, *) {
let theAnimation = CASpringAnimation.init(keyPath: "shadowPath")
theAnimation.damping = 0.85
theAnimation.duration = CFTimeInterval(duration)
theAnimation.fromValue = layer.shadowPath
theAnimation.toValue = shadowPath.cgPath
self.layer.add(theAnimation, forKey: "shadowPath")
} else {
// Fallback on earlier versions
}
self.layer.shadowPath = shadowPath.cgPath;
}*/
}
| mit | d927f9a67d2f63e69642bd30cc6ad54c | 35.478448 | 113 | 0.642444 | 4.778656 | false | false | false | false |
belatrix/iOSAllStars | AllStarsV2/AllStarsV2/iPhone/Classes/Events/EventCollectionViewCell.swift | 1 | 1639 | //
// EventCollectionViewCell.swift
// AllStarsV2
//
// Created by Daniel Vasquez Fernandez on 8/24/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
class EventCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var viewImgContainer : UIView!
@IBOutlet weak var imgEvent : UIImageView!
@IBOutlet weak var lblEventName : UILabel!
var objEvent : EventBE!{
didSet{
self.updateData()
}
}
override func prepareForReuse() {
self.imgEvent.image = nil
}
override func draw(_ rect: CGRect) {
self.viewImgContainer.layer.cornerRadius = 8
self.viewImgContainer.layer.shadowRadius = 2
self.viewImgContainer.layer.shadowOffset = CGSize(width: 0, height: 0)
self.viewImgContainer.layer.shadowOpacity = 0.45
self.viewImgContainer.layer.masksToBounds = false
self.imgEvent.layer.cornerRadius = 8
self.imgEvent.layer.masksToBounds = true
self.clipsToBounds = false
}
func updateData(){
self.lblEventName.text = "\(self.objEvent.event_name)"
CDMImageDownloaded.descargarImagen(enURL: objEvent.event_image,
paraImageView: self.imgEvent,
conPlaceHolder: self.imgEvent.image) { (isCorrect, urlImage, image) in
if urlImage == self.objEvent.event_image{
self.imgEvent.image = image
}
}
}
}
| apache-2.0 | bb67f96fe8aa1f30ebe31a99875775b7 | 27.241379 | 113 | 0.579365 | 4.653409 | false | false | false | false |
james-gray/selektor | Selektor/Extensions/SelektorArray.swift | 1 | 1611 | //
// SelektorArray.swift
// Selektor
//
// Created by James Gray on 2016-07-03.
// Copyright © 2016 James Gray. All rights reserved.
//
import Foundation
/**
Array extension to allow the calculation of Euclidean/Manhattan distance
between two arrays of the same dimensionality.
*/
extension _ArrayType where Generator.Element == Double {
/**
Calculate the distance from `self` to `vector` using `formula`.
- parameter otherVector: The vector to calculate distance from.
- parameter withFormula: The formula to use. Defaults to `"euclidean"`.
- returns: The distance as a double.
*/
func calculateDistanceFrom(otherVector vector: [Double], withFormula formula: String = "euclidean") -> Double {
if vector.count != self.count {
print("Vector distance calculation only works on vectors of the same dimensionality")
return Double(FP_INFINITE)
}
switch formula {
case "euclidean":
// Compute the Euclidean distance between self and vector
var runningSum: Double = 0
for i in 0..<self.count {
let p = self[i]
let q = vector[i]
runningSum += pow((q-p), Double(2)) // (q-p)^2
}
return sqrt(runningSum)
case "manhattan":
// Compute the Manhattan distance between self and vector
var runningSum: Double = 0
for i in 0..<self.count {
let p = self[i]
let q = vector[i]
runningSum += abs(p-q) // |p-q|
}
return runningSum
default:
fatalError("Invalid formula specified")
}
}
} | gpl-3.0 | 86d50156db3fbce6dc7bce3dbcd86b26 | 27.767857 | 113 | 0.62236 | 4.055416 | false | false | false | false |
FredrikSjoberg/ParkMillerRandom | ParkMillerRandom/Classes/ParkMillerRandom.swift | 1 | 3658 | /*
* Copyright (c) 2009 Michael Baczynski, http://www.polygonal.de
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Implementation of the Park Miller (1988) "minimal standard" linear
* congruential pseudo-random number generator.
*
* For a full explanation visit: http://www.firstpr.com.au/dsp/rand31/
*
* The generator uses a modulus constant (m) of 2^31 - 1 which is a
* Mersenne Prime number and a full-period-multiplier of 16807.
* Output is a 31 bit unsigned integer. The range of values output is
* 1 to 2,147,483,646 (2^31-1) and the seed must be in this range too.
*
* @author Michael Baczynski, www.polygonal.de
*/
//
// ParkMillerRandom.swift
// ParkMillerRandom
//
// Created by Fredrik Sjöberg on 16/07/15.
// Copyright (c) 2015 Fredrik Sjoberg. All rights reserved.
//
import Foundation
import GameplayKit
private let r0:UInt32 = 2147483647
private let r1:UInt32 = 16807
private let dif:Float = 0.4999
class ParkMillerRandom {
/// Allow seeds between [1, 0X7FFFFFFE]
private var internalSeed: UInt32 = 1
var seed: UInt32 {
set {
if newValue < 1 {
internalSeed = 1
}
else {
internalSeed = newValue
}
}
get {
return internalSeed
}
}
init(seed: UInt32) {
if seed < 1 {
internalSeed = 1
}
else {
internalSeed = seed
}
}
}
/**
* generator:
* new-value = (old-value * 16807) mod (2^31 - 1)
*/
extension ParkMillerRandom {
private func gen() -> UInt32 {
let value = UInt(internalSeed) * UInt(r1) % UInt(r0)
internalSeed = UInt32(value)
return internalSeed
}
}
extension ParkMillerRandom : GKRandom {
/**
Generates a random Int from entire spectrum.
- returns: Int
*/
@objc func nextInt() -> Int {
return Int(gen())
}
/**
Generates a random Int less than upperBound
- parameter upperBound: maximum
- returns: Int
*/
@objc func nextIntWithUpperBound(upperBound: Int) -> Int {
let low = -dif
let high = Float(upperBound) + dif
return Int(low + ((high - low) * nextUniform()))
}
/**
Generates a random Float in [0,1] range
- returns: Float [0,1]
*/
@objc func nextUniform() -> Float {
return Float(gen()) / Float(r0)
}
/**
Generates a random Bool
- returns: true or false
*/
@objc func nextBool() -> Bool {
let x = nextUniform()
if x <= dif { return true }
else { return false }
}
}
| mit | 579deb9945ef8d9726ffcea622f9e710 | 26.704545 | 72 | 0.637955 | 3.949244 | false | false | false | false |
adamahrens/braintweak | BrainTweak/BrainTweak/ViewControllers/MainViewController.swift | 1 | 2716 | //
// MainViewController.swift
// BrainTweak
//
// Created by Adam Ahrens on 2/20/15.
// Copyright (c) 2015 Appsbyahrens. All rights reserved.
//
import UIKit
//MARK: MainViewController
class MainViewController: UITableViewController {
@IBOutlet weak var numberOfQuestionsPicker: UIPickerView!
@IBOutlet weak var easyLabel: UILabel!
@IBOutlet weak var mediumLabel: UILabel!
@IBOutlet weak var difficultLabel: UILabel!
var difficultyLabels : [UILabel] {
get {
return [easyLabel, mediumLabel, difficultLabel]
}
}
var selectedDifficulty: Difficulty = .Easy
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier! == "GameSegue" {
let gameViewController = segue.destinationViewController as! GameViewController
gameViewController.gameBrain = GameBrain(difficulty: selectedDifficulty, numberOfProblems: self.numberOfQuestions[numberOfQuestionsPicker.selectedRowInComponent(0)])
}
}
@IBAction func tappedDifficulty(sender: UITapGestureRecognizer) {
// Only allow one difficulty to be selected
for label in difficultyLabels {
if label == sender.view {
label.textColor = UIColor.whiteColor()
label.backgroundColor = UIColor(red: 229.0/255.0, green: 88.0/255.0, blue: 145.0/255.0, alpha: 1)
if sender.view == easyLabel {
selectedDifficulty = .Easy
} else if sender.view == mediumLabel {
selectedDifficulty = .Medium
} else {
selectedDifficulty = .Hard
}
} else {
label.textColor = UIColor.blackColor()
label.backgroundColor = UIColor.whiteColor()
}
}
}
}
//MARK: UIPickerView Extension
extension MainViewController: UIPickerViewDataSource, UIPickerViewDelegate {
var numberOfQuestions : [Int] {
get {
return [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 100, 200]
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return numberOfQuestions.count
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
return NSAttributedString(string: "\(numberOfQuestions[row])")
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 40.0
}
}
| mit | e4f7724cac8966e13fa7fede7c5c8895 | 33.820513 | 177 | 0.634757 | 5.067164 | false | false | false | false |
ai260697793/weibo | 新浪微博/新浪微博/UIs/Login/MHVisitorView.swift | 1 | 5510 | //
// MHVisitorView.swift
// 新浪微博
//
// Created by 莫煌 on 16/5/5.
// Copyright © 2016年 MH. All rights reserved.
//
import UIKit
import SnapKit
// 定义协议
@objc protocol MHVisitorViewDelegate: NSObjectProtocol {
optional
func didRegister()
func didLogin()
}
class MHVisitorView: UIView {
// 定义一个闭包属性
// var registerClosure: (()->())?
// 定义代理属性
weak var delegate: MHVisitorViewDelegate?
// MARK: - 重写父类的构造方法
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - 添加子控件并设置约束
private func setupUI(){
// 添加子控件
addSubview(turnImageView)
addSubview(maskImageView)
addSubview(bgImageView)
addSubview(noticeLabel)
addSubview(registerButton)
addSubview(loginButton)
// 设置背景颜色
backgroundColor = UIColor(white: 237.0/255, alpha: 1.0)
// 设置遮罩约束
maskImageView.snp_makeConstraints { (make) in
make.center.equalTo(self.snp_center)
}
// 设置约束
bgImageView.snp_makeConstraints { (make) in
make.center.equalTo(self.snp_center)
}
turnImageView.snp_makeConstraints { (make) in
make.center.equalTo(self.snp_center)
}
noticeLabel.snp_makeConstraints { (make) in
make.top.equalTo(turnImageView.snp_bottom).offset(10)
make.centerX.equalTo(self.snp_centerX)
make.width.equalTo(216)
}
registerButton.snp_makeConstraints { (make) in
make.top.equalTo(noticeLabel.snp_bottom).offset(10)
make.left.equalTo(noticeLabel.snp_left)
make.width.equalTo(100)
make.height.equalTo(30)
}
loginButton.snp_makeConstraints { (make) in
make.top.equalTo(noticeLabel.snp_bottom).offset(10)
make.right.equalTo(noticeLabel.snp_right)
make.width.equalTo(100)
make.height.equalTo(30)
}
}
func setupInfo(title: String ,image: String?){
if image == nil {
turnImageView.hidden = false
startAnimation()
}else {
turnImageView.hidden = true
bgImageView.image = UIImage(named: image!)
noticeLabel.text = title
}
}
// MARK: - 动画转动
func startAnimation(){
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.duration = 10
animation.toValue = 2 * M_PI
animation.repeatCount = MAXFLOAT
animation.removedOnCompletion = false
turnImageView.layer.addAnimation(animation, forKey: nil)
}
// MARK: - 按钮点击事件
@objc private func registerButtonClick(){
// 调用
// registerClosure?()
delegate?.didRegister?()
}
@objc private func loginButtonClick(){
delegate?.didLogin()
}
// MARK: - 懒加载视图
/// 遮罩视图
private lazy var maskImageView: UIImageView = {
let imageView = UIImageView(image:UIImage(named: "visitordiscover_feed_mask_smallicon"))
return imageView
}()
/// 共有图片背景
private lazy var bgImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
return imageView
}()
/// 首页转动图片
private lazy var turnImageView: UIImageView = {
let imageView = UIImageView(image:UIImage(named: "visitordiscover_feed_image_smallicon"))
return imageView
}()
/// 提示label
private lazy var noticeLabel: UILabel = {
let label = UILabel()
label.textAlignment = .Center
label.font = UIFont.systemFontOfSize(14)
label.textColor = UIColor.darkGrayColor()
label.text = "关注一些人,回这里看看有什么惊喜"
label.numberOfLines = 0
return label
}()
/// 注册按钮
private lazy var registerButton: UIButton = {
let button = UIButton(type: UIButtonType.Custom)
button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
button.setTitle("注册", forState: UIControlState.Normal)
button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
button.addTarget(self, action: #selector(MHVisitorView.registerButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
/// 登录按钮
private lazy var loginButton: UIButton = {
let button = UIButton(type: UIButtonType.Custom)
button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
button.setTitle("登录", forState: UIControlState.Normal)
button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
button.addTarget(self, action: #selector(MHVisitorView.loginButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
}
| mit | d9e6bcf8e11b1ada6c7bded277a77869 | 27.862637 | 133 | 0.603084 | 4.749548 | false | false | false | false |
SergeMaslyakov/audio-player | app/src/controllers/music/PlayListsViewController.swift | 1 | 2892 | //
// PlayListsViewController.swift
// AudioPlayer
//
// Created by Serge Maslyakov on 07/07/2017.
// Copyright © 2017 Maslyakov. All rights reserved.
//
import UIKit
import MediaPlayer
import Reusable
import DipUI
import TableKit
class PlayListsViewController: UIViewController, StoryboardSceneBased, MusicPickerCoordinatable {
static let sceneStoryboard = UIStoryboard(name: StoryboardScenes.musicLib.rawValue, bundle: nil)
var dataService: AppleMusicPlaylistsDataService?
var data: [MPMediaItemCollection] = []
var tableDirector: TableDirector!
var refreshControl: UIRefreshControl!
@IBOutlet weak var stubDataView: StubDataView! {
didSet {
stubDataView.retryDelegate = self
}
}
@IBOutlet weak var tableView: UITableView! {
didSet {
tableDirector = TableDirector(tableView: tableView)
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
tableView.alpha = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
let titleView = self.navigationItem.titleView as? MusicPickerTitleView
titleView?.delegate = musicCoordinator
installTable()
refresh(manual: false)
}
func installTable() {
let section = TableSection()
section.headerTitle = "COLLECTION".localized(withFile: .music)
section.footerHeight = ThemeHeightHelper.Playlists.sectionFooterHeight
section.headerHeight = ThemeHeightHelper.Playlists.sectionHeaderHeight
tableDirector += section
}
func refresh(manual: Bool) {
if manual {
stubDataView?.dataLoading()
}
dataService?.loadAsync(with: { [weak self] (playlists: [MPMediaItemCollection]) in
guard let strongSelf = self else {
return
}
strongSelf.data = playlists
strongSelf.refreshTable()
strongSelf.refreshControl.endRefreshing()
//if playlists.count > 0 {
// strongSelf.stubDataView?.dataWasLoaded()
//} else {
let error = "NO_PLAYLISTS_IN_THE_LIBRARY".localized(withFile: .music)
strongSelf.stubDataView?.dataNotLoaded(errorMessage: error)
//}
})
}
func refreshTable() {
let section = tableDirector.sections[0]
section.clear()
tableDirector.reload()
}
}
//
// MARK: Retry delegate
//
extension PlayListsViewController: StubDataRetryProtocol {
func userRequestRetry(from stubView: StubDataView) {
refresh(manual: true)
}
}
| apache-2.0 | 02d24aadd4c536163e6382bc81152803 | 25.281818 | 100 | 0.636112 | 5.045375 | false | false | false | false |
CarterPape/Basic-binary-genetic-optimization | Basic binary genetic optimization/Boolean List.swift | 1 | 865 | //
// Boolean List.swift
// Basic binary genetic optimization
//
// Created by Carter Pape on 8/11/15.
// Copyright (c) 2015 Carter Pape. All rights reserved.
//
import Foundation
let BOOL_LIST_SIZE = 5
struct BoolList {
private var _boolList: UInt8
var boolList: [Bool] {
get {
var list: [Bool] = []
for n in 0..<BOOL_LIST_SIZE {
list.append(_boolList & (1 << UInt8(n)) > 0)
}
return list
}
set(newList) {
_boolList = 0
var n: UInt8 = 0
for bitAsBool in newList {
let bitaAsUInt8: UInt8 = bitAsBool ? 1 : 0
_boolList |= bitaAsUInt8 << n
n += 1
}
}
}
init(_ boolList: [Bool]) {
self._boolList = 0
self.boolList = boolList
}
} | mit | ca6f51089984acc3e0a54e6508cf55fb | 21.789474 | 60 | 0.482081 | 3.712446 | false | false | false | false |
nikriek/gesundheit.space | NotYet/OverviewViewModel.swift | 1 | 3919 | //
// OverviewViewModel.swift
// NotYet
//
// Created by Niklas Riekenbrauck on 25.11.16.
// Copyright © 2016 Niklas Riekenbrauck. All rights reserved.
//
import RxSwift
import UIKit
class OverviewViewModel: BaseOverviewViewModel {
var statusText = Variable<NSAttributedString?>(NSAttributedString(string: "You look tired today."))
var tipText = Variable<String?>("Lowering your room temperature could improve your sleep.")
var actionTapped = PublishSubject<Void>()
var skipTapped = PublishSubject<Void>()
var actionTitle = Variable<String?>(nil)
var skipTitle = Variable<String?>("Skip")
var done = PublishSubject<Void>()
var infoTapped = PublishSubject<Void>()
var presentInsight = PublishSubject<Void>()
var recommendations = Array<Recommendation>().makeIterator()
var currentRecommendation = Variable<Recommendation?>(nil)
let disposeBag = DisposeBag()
init() {
infoTapped
.bindTo(presentInsight)
.addDisposableTo(disposeBag)
WebService.shared.fetchRecommendations()
.subscribe(onNext: { [weak self] it in
self?.recommendations = it.makeIterator()
self?.currentRecommendation.value = self?.recommendations.next()
})
.addDisposableTo(disposeBag)
currentRecommendation.asObservable()
.map { recommendation -> NSAttributedString? in
return NSAttributedString(string: recommendation?.title ?? "No more advices :(")
}
.bindTo(statusText)
.addDisposableTo(disposeBag)
currentRecommendation.asObservable()
.map { $0?.advice }
.bindTo(tipText)
.addDisposableTo(disposeBag)
currentRecommendation.asObservable()
.map { rec -> String? in
return rec?.actionTitle ?? " "
}
.bindTo(actionTitle)
.addDisposableTo(disposeBag)
currentRecommendation.asObservable()
.map { $0?.type }
.map { type -> String? in
guard let type = type else { return nil }
switch type {
case .action, .url:
return "Skip"
default:
return nil
}
}
.bindTo(skipTitle)
.addDisposableTo(disposeBag)
skipTapped.asObservable()
.subscribe(onNext: { [weak self] in
self?.currentRecommendation.value = self?.recommendations.next()
}).addDisposableTo(disposeBag)
actionTapped.withLatestFrom(currentRecommendation.asObservable())
.filter {
guard case .action(_)? = $0?.type else { return false }
return true
}
.map { $0?.id }
.flatMap { WebService.shared.doAction(recommendationId: $0 ?? 1) }
.subscribe({ [weak self] (event) in
self?.currentRecommendation.value = self?.recommendations.next()
})
.addDisposableTo(disposeBag)
actionTapped.withLatestFrom(currentRecommendation.asObservable())
.map { rec -> String? in
guard let rec = rec else { return nil }
switch rec.type {
case .url(let link):
return link
default:
return nil
}
}.filter { $0 != nil }
.subscribe(onNext: { [weak self] link in
guard let link = link, let url = URL(string: link) else { return }
self?.currentRecommendation.value = self?.recommendations.next()
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}).addDisposableTo(disposeBag)
}
}
| mit | f621744111117734244dc34d5e55af04 | 36.314286 | 103 | 0.560745 | 5.32337 | false | false | false | false |
PomTTcat/YYModelGuideRead_JEFF | FoundationGuideRead/swift/YJOperation.swift | 2 | 54015 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import Dispatch
import UIKit
import Foundation
import CoreFoundation
internal let _NSOperationIsFinished = "isFinished"
internal let _NSOperationIsFinishedAlternate = "finished"
internal let _NSOperationIsExecuting = "isExecuting"
internal let _NSOperationIsExecutingAlternate = "executing"
internal let _NSOperationIsReady = "isReady"
internal let _NSOperationIsReadyAlternate = "ready"
internal let _NSOperationIsCancelled = "isCancelled"
internal let _NSOperationIsCancelledAlternate = "cancelled"
internal let _NSOperationIsAsynchronous = "isAsynchronous"
internal let _NSOperationQueuePriority = "queuePriority"
internal let _NSOperationThreadPriority = "threadPriority"
internal let _NSOperationCompletionBlock = "completionBlock"
internal let _NSOperationName = "name"
internal let _NSOperationDependencies = "dependencies"
internal let _NSOperationQualityOfService = "qualityOfService"
internal let _NSOperationQueueOperationsKeyPath = "operations"
internal let _NSOperationQueueOperationCountKeyPath = "operationCount"
internal let _NSOperationQueueSuspendedKeyPath = "suspended"
extension QualityOfService {
#if canImport(Darwin)
internal init(_ qos: qos_class_t) {
switch qos {
case QOS_CLASS_DEFAULT: self = .default
case QOS_CLASS_USER_INTERACTIVE: self = .userInteractive
case QOS_CLASS_USER_INITIATED: self = .userInitiated
case QOS_CLASS_UTILITY: self = .utility
case QOS_CLASS_BACKGROUND: self = .background
default: fatalError("Unsupported qos")
}
}
#endif
internal var qosClass: DispatchQoS {
switch self {
case .userInteractive: return .userInteractive
case .userInitiated: return .userInitiated
case .utility: return .utility
case .background: return .background
case .default: return .default
}
}
}
open class YJOperation : NSObject {
struct PointerHashedUnmanagedBox<T: AnyObject>: Hashable {
var contents: Unmanaged<T>
func hash(into hasher: inout Hasher) {
hasher.combine(contents.toOpaque())
}
static func == (_ lhs: PointerHashedUnmanagedBox, _ rhs: PointerHashedUnmanagedBox) -> Bool {
return lhs.contents.toOpaque() == rhs.contents.toOpaque()
}
}
enum __NSOperationState : UInt8 {
case initialized = 0x00
case enqueuing = 0x48
case enqueued = 0x50
case dispatching = 0x88
case starting = 0xD8
case executing = 0xE0
case finishing = 0xF0
case finished = 0xF4
}
internal var __previousOperation: Unmanaged<YJOperation>?
internal var __nextOperation: Unmanaged<YJOperation>?
internal var __nextPriorityOperation: Unmanaged<YJOperation>?
internal var __queue: Unmanaged<YJOperationQueue>?
internal var __dependencies = [YJOperation]() // 自己依赖的Operation
internal var __downDependencies = Set<PointerHashedUnmanagedBox<YJOperation>>() // 依赖自己的Operation
internal var __unfinishedDependencyCount: Int = 0
internal var __completion: (() -> Void)?
internal var __name: String?
internal var __schedule: DispatchWorkItem?
internal var __state: __NSOperationState = .initialized
internal var __priorityValue: YJOperation.QueuePriority.RawValue?
internal var __cachedIsReady: Bool = true
internal var __isCancelled: Bool = false
internal var __propertyQoS: QualityOfService?
var __waitCondition = NSCondition()
var __lock = NSLock()
var __atomicLoad = NSLock()
internal var _state: __NSOperationState {
get {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __state
}
set(newValue) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__state = newValue
}
}
// if == return yes and update。 if != ,return no
internal func _compareAndSwapState(_ old: __NSOperationState, _ new: __NSOperationState) -> Bool {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
if __state != old { return false }
__state = new
return true
}
internal func _lock() {
__lock.lock()
}
internal func _unlock() {
__lock.unlock()
}
internal var _queue: YJOperationQueue? {
_lock()
defer { _unlock() }
return __queue?.takeRetainedValue()
}
internal func _adopt(queue: YJOperationQueue, schedule: DispatchWorkItem) {
_lock()
defer { _unlock() }
__queue = Unmanaged.passRetained(queue)
__schedule = schedule
}
internal var _isCancelled: Bool {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __isCancelled
}
internal var _unfinishedDependencyCount: Int {
get {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __unfinishedDependencyCount
}
}
internal func _incrementUnfinishedDependencyCount(by amount: Int = 1) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__unfinishedDependencyCount += amount
}
internal func _decrementUnfinishedDependencyCount(by amount: Int = 1) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__unfinishedDependencyCount -= amount
}
// 添加一些依赖自己的op。
internal func _addParent(_ parent: YJOperation) {
__downDependencies.insert(PointerHashedUnmanagedBox(contents: .passUnretained(parent)))
}
internal func _removeParent(_ parent: YJOperation) {
__downDependencies.remove(PointerHashedUnmanagedBox(contents: .passUnretained(parent)))
}
internal var _cachedIsReady: Bool {
get {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __cachedIsReady
}
set(newValue) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__cachedIsReady = newValue
}
}
internal func _fetchCachedIsReady(_ retest: inout Bool) -> Bool {
let setting = _cachedIsReady
if !setting {
_lock()
retest = __unfinishedDependencyCount == 0
_unlock()
}
return setting
}
internal func _invalidateQueue() {
_lock()
__schedule = nil
let queue = __queue
__queue = nil
_unlock()
queue?.release()
}
internal func _removeAllDependencies() {
_lock()
let deps = __dependencies
__dependencies.removeAll()
_unlock()
for dep in deps {
dep._lock()
_lock()
let upIsFinished = dep._state == .finished
if !upIsFinished && !_isCancelled {
_decrementUnfinishedDependencyCount()
}
dep._removeParent(self)
_unlock()
dep._unlock()
}
}
internal static func observeValue(forKeyPath keyPath: String, ofObject op: YJOperation) {
enum Transition {
case toFinished
case toExecuting
case toReady
}
let kind: Transition?
if keyPath == _NSOperationIsFinished || keyPath == _NSOperationIsFinishedAlternate {
kind = .toFinished
} else if keyPath == _NSOperationIsExecuting || keyPath == _NSOperationIsReadyAlternate {
kind = .toExecuting
} else if keyPath == _NSOperationIsReady || keyPath == _NSOperationIsReadyAlternate {
kind = .toReady
} else {
kind = nil
}
if let transition = kind {
switch transition {
case .toFinished: // we only care about NO -> YES
if !op.isFinished {
return
}
// 这里就是一些保证 _state 是 finishing。如果是finished,直接退出。
op._lock()
let state = op._state
if op.__queue != nil && state.rawValue < __NSOperationState.starting.rawValue {
print("*** \(type(of: op)) \(Unmanaged.passUnretained(op).toOpaque()) went isFinished=YES without being started by the queue it is in")
}
if state.rawValue < __NSOperationState.finishing.rawValue {
op._state = .finishing
} else if state == .finished {
op._unlock()
return
}
// 对所有依赖自己的op,未完成count - 1.
// 如果本来就是1,说明就等的自己。放到ready_deps里面。
var ready_deps = [YJOperation]()
let down_deps = op.__downDependencies
op.__downDependencies.removeAll()
if 0 < down_deps.count {
for down in down_deps {
let idown = down.contents.takeUnretainedValue()
idown._lock()
if idown._unfinishedDependencyCount == 1 {
ready_deps.append(idown)
} else if idown._unfinishedDependencyCount > 1 {
idown._decrementUnfinishedDependencyCount()
} else {
assert(idown._unfinishedDependencyCount == 0)
assert(idown._isCancelled == true)
}
idown._unlock()
}
}
// op彻底结束,收尾工作。
op._state = .finished
let opreationQue = op.__queue
op.__queue = nil
op._unlock()
// 对 ready_deps 中的op发送信号。可以去执行start了。
if 0 < ready_deps.count {
for down in ready_deps {
down._lock()
if down._unfinishedDependencyCount >= 1 {
down._decrementUnfinishedDependencyCount()
}
down._unlock()
YJOperation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: down)
}
}
// wait until finish 的那些线程,得以解锁。
op.__waitCondition.lock()
op.__waitCondition.broadcast()
op.__waitCondition.unlock()
if let complete = op.__completion {
let held = Unmanaged.passRetained(op)
DispatchQueue.global(qos: .default).async {
complete()
held.release()
}
}
if let queue = opreationQue {
queue.takeUnretainedValue()._operationFinished(op, state)
queue.release()
}
case .toExecuting:
let isExecuting = op.isExecuting
op._lock()
if op._state.rawValue < __NSOperationState.executing.rawValue && isExecuting {
op._state = .executing
}
op._unlock()
case .toReady:
let r = op.isReady
op._cachedIsReady = r
let q = op._queue
if r {
q?._schedule()
}
}
}
}
public override init() {
}
// 简单说,执行了main函数,并且发出一些信号
open func start() {
let state = _state
if __NSOperationState.finished == state { return }
if !_compareAndSwapState(__NSOperationState.initialized, __NSOperationState.starting) && !(__NSOperationState.starting == state && __queue != nil) {
switch state {
case .executing: fallthrough
case .finishing:
fatalError("\(self): receiver is already executing")
default:
fatalError("\(self): something is trying to start the receiver simultaneously from more than one thread")
}
}
if state.rawValue < __NSOperationState.enqueued.rawValue && !isReady {
_state = state
fatalError("\(self): receiver is not yet ready to execute")
}
let isCanc = _isCancelled
if !isCanc {
_state = .executing
YJOperation.observeValue(forKeyPath: _NSOperationIsExecuting, ofObject: self)
// _execute 没有找到。所以默认main()
_queue?._execute(self) ?? main()
}
if __NSOperationState.executing == _state {
_state = .finishing
YJOperation.observeValue(forKeyPath: _NSOperationIsExecuting, ofObject: self)
YJOperation.observeValue(forKeyPath: _NSOperationIsFinished, ofObject: self)
} else {
_state = .finishing
YJOperation.observeValue(forKeyPath: _NSOperationIsFinished, ofObject: self)
}
}
open func main() { }
open var isCancelled: Bool {
return _isCancelled
}
open func cancel() {
if isFinished { return }
__atomicLoad.lock()
__isCancelled = true
__atomicLoad.unlock()
if __NSOperationState.executing.rawValue <= _state.rawValue {
return
}
_lock()
__unfinishedDependencyCount = 0
_unlock()
YJOperation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: self)
}
open var isExecuting: Bool {
return __NSOperationState.executing == _state
}
open var isFinished: Bool {
return __NSOperationState.finishing.rawValue <= _state.rawValue
}
open var isAsynchronous: Bool {
return false
}
open var isReady: Bool {
_lock()
defer { _unlock() }
return __unfinishedDependencyCount == 0
}
internal func _addDependency(_ op: YJOperation) {
withExtendedLifetime(self) {
withExtendedLifetime(op) {
var up: YJOperation?
_lock()
if __dependencies.first(where: { $0 === op }) == nil {
__dependencies.append(op)
up = op
}
_unlock()
if let upwards = up {
upwards._lock()
_lock()
let upIsFinished = upwards._state == __NSOperationState.finished
// 自己没有被取消。 依赖的op没有结束。形成依赖。
if !upIsFinished && !_isCancelled {
assert(_unfinishedDependencyCount >= 0)
_incrementUnfinishedDependencyCount()
// self依赖upwards,upwards的
upwards._addParent(self)
}
_unlock()
upwards._unlock()
}
YJOperation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: self)
}
}
}
open func addDependency(_ op: YJOperation) {
_addDependency(op)
}
open func removeDependency(_ op: YJOperation) {
withExtendedLifetime(self) {
withExtendedLifetime(op) {
var up_canidate: YJOperation?
_lock()
let idxCanidate = __dependencies.firstIndex { $0 === op }
if idxCanidate != nil {
up_canidate = op
}
_unlock()
if let canidate = up_canidate {
canidate._lock()
_lock()
if let idx = __dependencies.firstIndex(where: { $0 === op }) {
if canidate._state == .finished && _isCancelled {
_decrementUnfinishedDependencyCount()
}
canidate._removeParent(self)
__dependencies.remove(at: idx)
}
_unlock()
canidate._unlock()
}
YJOperation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: self)
}
}
}
open var dependencies: [YJOperation] {
get {
_lock()
defer { _unlock() }
return __dependencies.filter { !($0 is _BarrierOperation) }
}
}
internal func changePriority(_ newPri: YJOperation.QueuePriority.RawValue) {
_lock()
guard let oq = __queue?.takeRetainedValue() else {
__priorityValue = newPri
_unlock()
return
}
_unlock()
oq._lock()
var oldPri = __priorityValue
if oldPri == nil {
if let v = (0 == oq.__actualMaxNumOps) ? nil : __propertyQoS {
switch v {
case .default: oldPri = YJOperation.QueuePriority.normal.rawValue
case .userInteractive: oldPri = YJOperation.QueuePriority.veryHigh.rawValue
case .userInitiated: oldPri = YJOperation.QueuePriority.high.rawValue
case .utility: oldPri = YJOperation.QueuePriority.low.rawValue
case .background: oldPri = YJOperation.QueuePriority.veryLow.rawValue
}
} else {
oldPri = YJOperation.QueuePriority.normal.rawValue
}
}
if oldPri == newPri {
oq._unlock()
return
}
__priorityValue = newPri
var op = oq._firstPriorityOperation(oldPri)
var prev: Unmanaged<YJOperation>?
while let YJOperation = op?.takeUnretainedValue() {
let nextOp = YJOperation.__nextPriorityOperation
if YJOperation === self {
// Remove from old list
if let previous = prev?.takeUnretainedValue() {
previous.__nextPriorityOperation = nextOp
} else {
oq._setFirstPriorityOperation(oldPri!, nextOp)
}
if nextOp == nil {
oq._setlastPriorityOperation(oldPri!, prev)
}
__nextPriorityOperation = nil
// Append to new list
if let oldLast = oq._lastPriorityOperation(newPri)?.takeUnretainedValue() {
oldLast.__nextPriorityOperation = Unmanaged.passUnretained(self)
} else {
oq._setFirstPriorityOperation(newPri, Unmanaged.passUnretained(self))
}
oq._setlastPriorityOperation(newPri, Unmanaged.passUnretained(self))
break
}
prev = op
op = nextOp
}
oq._unlock()
}
open var queuePriority: YJOperation.QueuePriority {
get {
guard let prioValue = __priorityValue else {
return YJOperation.QueuePriority.normal
}
if __priorityValue == YJOperation.QueuePriority.barrier {
// return YJOperation.QueuePriority.barrier
}
return YJOperation.QueuePriority(rawValue: prioValue) ?? .veryHigh
}
set(newValue) {
let newPri: YJOperation.QueuePriority.RawValue
if YJOperation.QueuePriority.veryHigh.rawValue <= newValue.rawValue {
newPri = YJOperation.QueuePriority.veryHigh.rawValue
} else if YJOperation.QueuePriority.high.rawValue <= newValue.rawValue {
newPri = YJOperation.QueuePriority.high.rawValue
} else if YJOperation.QueuePriority.normal.rawValue <= newValue.rawValue {
newPri = YJOperation.QueuePriority.normal.rawValue
} else if YJOperation.QueuePriority.low.rawValue < newValue.rawValue {
newPri = YJOperation.QueuePriority.normal.rawValue
} else if YJOperation.QueuePriority.veryLow.rawValue < newValue.rawValue {
newPri = YJOperation.QueuePriority.low.rawValue
} else {
newPri = YJOperation.QueuePriority.veryLow.rawValue
}
if __priorityValue != newPri {
changePriority(newPri)
}
}
}
open var completionBlock: (() -> Void)? {
get {
_lock()
defer { _unlock() }
return __completion
}
set(newValue) {
_lock()
defer { _unlock() }
__completion = newValue
}
}
open func waitUntilFinished() {
__waitCondition.lock()
while !isFinished {
__waitCondition.wait()
}
__waitCondition.unlock()
}
open var qualityOfService: QualityOfService {
get {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __propertyQoS ?? QualityOfService.default
}
set(newValue) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__propertyQoS = newValue
}
}
open var name: String? {
get {
return __name
}
set(newValue) {
__name = newValue
}
}
}
extension YJOperation {
public override func willChangeValue(forKey key: String) {
// do nothing
}
public override func didChangeValue(forKey key: String) {
YJOperation.observeValue(forKeyPath: key, ofObject: self)
}
public func willChangeValue<Value>(for keyPath: KeyPath<Operation, Value>) {
// do nothing
}
public func didChangeValue<Value>(for keyPath: KeyPath<Operation, Value>) {
switch keyPath {
case \Operation.isFinished: didChangeValue(forKey: _NSOperationIsFinished)
case \Operation.isReady: didChangeValue(forKey: _NSOperationIsReady)
case \Operation.isCancelled: didChangeValue(forKey: _NSOperationIsCancelled)
case \Operation.isExecuting: didChangeValue(forKey: _NSOperationIsExecuting)
default: break
}
}
}
extension YJOperation {
public enum QueuePriority : Int {
case veryLow = -8
case low = -4
case normal = 0
case high = 4
case veryHigh = 8
internal static var barrier = 12
internal static let priorities = [
YJOperation.QueuePriority.barrier,
YJOperation.QueuePriority.veryHigh.rawValue,
YJOperation.QueuePriority.high.rawValue,
YJOperation.QueuePriority.normal.rawValue,
YJOperation.QueuePriority.low.rawValue,
YJOperation.QueuePriority.veryLow.rawValue
]
}
}
open class BlockOperation : YJOperation {
var _block: (() -> Void)?
var _executionBlocks: [() -> Void]?
public override init() {
}
public convenience init(block: @escaping () -> Void) {
self.init()
_block = block
}
open func addExecutionBlock(_ block: @escaping () -> Void) {
if isExecuting || isFinished {
fatalError("blocks cannot be added after the YJOperation has started executing or finished")
}
_lock()
defer { _unlock() }
if _block == nil && _executionBlocks == nil {
_block = block
} else {
if _executionBlocks == nil {
if let existing = _block {
_executionBlocks = [existing, block]
} else {
_executionBlocks = [block]
}
} else {
_executionBlocks?.append(block)
}
}
}
open var executionBlocks: [@convention(block) () -> Void] {
get {
_lock()
defer { _unlock() }
var blocks = [() -> Void]()
if let existing = _block {
blocks.append(existing)
}
if let existing = _executionBlocks {
blocks.append(contentsOf: existing)
}
return blocks
}
}
open override func main() {
var blocks = [() -> Void]()
_lock()
if let existing = _block {
blocks.append(existing)
}
if let existing = _executionBlocks {
blocks.append(contentsOf: existing)
}
_unlock()
for block in blocks {
block()
}
}
}
internal final class _BarrierOperation : YJOperation {
var _block: (() -> Void)?
init(_ block: @escaping () -> Void) {
_block = block
}
override func main() {
_lock()
let block = _block
_block = nil
_unlock()
block?()
_removeAllDependencies()
}
}
internal final class _OperationQueueProgress : Progress {
var queue: Unmanaged<YJOperationQueue>?
let lock = NSLock()
init(_ queue: YJOperationQueue) {
self.queue = Unmanaged.passUnretained(queue)
super.init(parent: nil, userInfo: nil)
}
func invalidateQueue() {
lock.lock()
queue = nil
lock.unlock()
}
override var totalUnitCount: Int64 {
get {
return super.totalUnitCount
}
set(newValue) {
super.totalUnitCount = newValue
lock.lock()
queue?.takeUnretainedValue().__progressReporting = true
lock.unlock()
}
}
}
extension YJOperationQueue {
public static let defaultMaxConcurrentOperationCount: Int = -1
}
@available(OSX 10.5, *)
open class YJOperationQueue : NSObject, ProgressReporting {
let __queueLock = NSLock()
let __atomicLoad = NSLock()
var __firstOperation: Unmanaged<YJOperation>?
var __lastOperation: Unmanaged<YJOperation>?
var __firstPriorityOperation: (barrier: Unmanaged<YJOperation>?,
veryHigh: Unmanaged<YJOperation>?,
high: Unmanaged<YJOperation>?,
normal: Unmanaged<YJOperation>?,
low: Unmanaged<YJOperation>?,
veryLow: Unmanaged<YJOperation>?)
var __lastPriorityOperation: (barrier: Unmanaged<YJOperation>?,
veryHigh: Unmanaged<YJOperation>?,
high: Unmanaged<YJOperation>?,
normal: Unmanaged<YJOperation>?,
low: Unmanaged<YJOperation>?,
veryLow: Unmanaged<YJOperation>?)
var _barriers = [_BarrierOperation]()
var _progress: _OperationQueueProgress?
var __operationCount: Int = 0
var __maxNumOps: Int = YJOperationQueue.defaultMaxConcurrentOperationCount
var __actualMaxNumOps: Int32 = .max
var __numExecOps: Int32 = 0
var __dispatch_queue: DispatchQueue?
var __backingQueue: DispatchQueue?
var __name: String?
var __suspended: Bool = false
var __overcommit: Bool = false
var __propertyQoS: QualityOfService?
var __mainQ: Bool = false
var __progressReporting: Bool = false
internal func _lock() {
__queueLock.lock()
}
internal func _unlock() {
__queueLock.unlock()
}
internal var _suspended: Bool {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __suspended
}
internal func _incrementExecutingOperations() {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__numExecOps += 1
}
internal func _decrementExecutingOperations() {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
if __numExecOps > 0 {
__numExecOps -= 1
}
}
internal func _incrementOperationCount(by amount: Int = 1) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__operationCount += amount
}
internal func _decrementOperationCount(by amount: Int = 1) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__operationCount -= amount
}
internal func _firstPriorityOperation(_ prio: YJOperation.QueuePriority.RawValue?) -> Unmanaged<YJOperation>? {
guard let priority = prio else { return nil }
switch priority {
case YJOperation.QueuePriority.barrier: return __firstPriorityOperation.barrier
case YJOperation.QueuePriority.veryHigh.rawValue: return __firstPriorityOperation.veryHigh
case YJOperation.QueuePriority.high.rawValue: return __firstPriorityOperation.high
case YJOperation.QueuePriority.normal.rawValue: return __firstPriorityOperation.normal
case YJOperation.QueuePriority.low.rawValue: return __firstPriorityOperation.low
case YJOperation.QueuePriority.veryLow.rawValue: return __firstPriorityOperation.veryLow
default: fatalError("unsupported priority")
}
}
internal func _setFirstPriorityOperation(_ prio: YJOperation.QueuePriority.RawValue, _ Operation: Unmanaged<YJOperation>?) {
switch prio {
case YJOperation.QueuePriority.barrier: __firstPriorityOperation.barrier = Operation
case YJOperation.QueuePriority.veryHigh.rawValue: __firstPriorityOperation.veryHigh = Operation
case YJOperation.QueuePriority.high.rawValue: __firstPriorityOperation.high = Operation
case YJOperation.QueuePriority.normal.rawValue: __firstPriorityOperation.normal = Operation
case YJOperation.QueuePriority.low.rawValue: __firstPriorityOperation.low = Operation
case YJOperation.QueuePriority.veryLow.rawValue: __firstPriorityOperation.veryLow = Operation
default: fatalError("unsupported priority")
}
}
internal func _lastPriorityOperation(_ prio: YJOperation.QueuePriority.RawValue?) -> Unmanaged<YJOperation>? {
guard let priority = prio else { return nil }
switch priority {
case YJOperation.QueuePriority.barrier: return __lastPriorityOperation.barrier
case YJOperation.QueuePriority.veryHigh.rawValue: return __lastPriorityOperation.veryHigh
case YJOperation.QueuePriority.high.rawValue: return __lastPriorityOperation.high
case YJOperation.QueuePriority.normal.rawValue: return __lastPriorityOperation.normal
case YJOperation.QueuePriority.low.rawValue: return __lastPriorityOperation.low
case YJOperation.QueuePriority.veryLow.rawValue: return __lastPriorityOperation.veryLow
default: fatalError("unsupported priority")
}
}
internal func _setlastPriorityOperation(_ prio: YJOperation.QueuePriority.RawValue, _ op: Unmanaged<YJOperation>?) {
// if let yjop = op?.takeUnretainedValue() {
// if prio == 12 {
// // ? = 8
// print("qp = \(yjop.queuePriority.rawValue)")
// }
// assert(yjop.queuePriority.rawValue == prio)
// }
switch prio {
case YJOperation.QueuePriority.barrier: __lastPriorityOperation.barrier = op
case YJOperation.QueuePriority.veryHigh.rawValue: __lastPriorityOperation.veryHigh = op
case YJOperation.QueuePriority.high.rawValue: __lastPriorityOperation.high = op
case YJOperation.QueuePriority.normal.rawValue: __lastPriorityOperation.normal = op
case YJOperation.QueuePriority.low.rawValue: __lastPriorityOperation.low = op
case YJOperation.QueuePriority.veryLow.rawValue: __lastPriorityOperation.veryLow = op
default: fatalError("unsupported priority")
}
}
internal func _operationFinished(_ op: YJOperation, _ previousState: YJOperation.__NSOperationState) {
// There are only three cases where an YJOperation might have a nil queue
// A) The YJOperation was never added to a queue and we got here by a normal KVO change
// B) The YJOperation was somehow already finished
// C) the YJOperation was attempted to be added to a queue but an exception occured and was ignored...
// Option C is NOT supported!
let isBarrier = op is _BarrierOperation
_lock()
let nextOp = op.__nextOperation
if YJOperation.__NSOperationState.finished == op._state {
// 把op从整个__firstOperation到__lastOperation的链表中移除,纯粹链表操作。
let prevOp = op.__previousOperation
if let prev = prevOp {
prev.takeUnretainedValue().__nextOperation = nextOp
} else {
__firstOperation = nextOp
}
if let next = nextOp {
next.takeUnretainedValue().__previousOperation = prevOp
} else {
__lastOperation = prevOp
}
// only decrement execution count on YJOperations that were executing! (the execution was initially set to __NSOperationStateDispatching so we must compare from that or later)
// else the number of executing YJOperations might underflow
if previousState.rawValue >= YJOperation.__NSOperationState.dispatching.rawValue {
_decrementExecutingOperations()
}
op.__previousOperation = nil
op.__nextOperation = nil
op._invalidateQueue()
}
if !isBarrier {
_decrementOperationCount()
}
_unlock()
_schedule()
if previousState.rawValue >= YJOperation.__NSOperationState.enqueuing.rawValue {
Unmanaged.passUnretained(op).release()
}
}
internal var _propertyQoS: QualityOfService? {
get {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __propertyQoS
}
set(newValue) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__propertyQoS = newValue
}
}
internal func _synthesizeBackingQueue() -> DispatchQueue {
guard let queue = __backingQueue else {
let queue: DispatchQueue
if let qos = _propertyQoS {
if let name = __name {
queue = DispatchQueue(label: name, qos: qos.qosClass)
} else {
queue = DispatchQueue(label: "NSOperationQueue \(Unmanaged.passUnretained(self).toOpaque())", qos: qos.qosClass)
}
} else {
if let name = __name {
queue = DispatchQueue(label: name)
} else {
queue = DispatchQueue(label: "NSOperationQueue \(Unmanaged.passUnretained(self).toOpaque())")
}
}
__backingQueue = queue
return queue
}
return queue
}
static internal var _currentQueue = NSThreadSpecific<YJOperationQueue>()
// op start
internal func _schedule(_ op: YJOperation) {
op._state = .starting
// set current tsd
YJOperationQueue._currentQueue.set(self)
op.start()
YJOperationQueue._currentQueue.clear()
// unset current tsd
// 结束 && ???
// __NSOperationState.finishing.rawValue <= _state.rawValue < __NSOperationState.finishing.rawValue
if op.isFinished && op._state.rawValue < YJOperation.__NSOperationState.finishing.rawValue {
YJOperation.observeValue(forKeyPath: _NSOperationIsFinished, ofObject: op)
}
}
internal func _schedule() {
var retestOps = [YJOperation]()
_lock()
var slotsAvail = __actualMaxNumOps - __numExecOps
// 优先级由高到低进行遍历。最高为barrier。。。所以,优先级高,确实会先执行。
for prio in YJOperation.QueuePriority.priorities {
if 0 >= slotsAvail || _suspended {
break
}
var op = _firstPriorityOperation(prio)
var prev: Unmanaged<YJOperation>?
while let inOp = op?.takeUnretainedValue() {
if 0 >= slotsAvail || _suspended {
break
}
let next = inOp.__nextPriorityOperation
var retest = false
// if the cached state is possibly not valid then the isReady value needs to be re-updated
if YJOperation.__NSOperationState.enqueued == inOp._state && inOp._fetchCachedIsReady(&retest) {
if let previous = prev?.takeUnretainedValue() {
previous.__nextOperation = next
} else {
_setFirstPriorityOperation(prio, next) // 因为第一个op要被执行了,所以把第二个op设置成第一个。
}
if next == nil {
_setlastPriorityOperation(prio, prev)
}
// 链表操作,计数操作
inOp.__nextPriorityOperation = nil
inOp._state = .dispatching
_incrementExecutingOperations()
slotsAvail -= 1
// 保证op是异步执行
let queue: DispatchQueue
if __mainQ {
queue = DispatchQueue.main
} else {
queue = __dispatch_queue ?? _synthesizeBackingQueue() // 返回自己
}
if let schedule = inOp.__schedule {
if inOp is _BarrierOperation {
queue.async(flags: .barrier, execute: {
schedule.perform()
})
} else {
queue.async(execute: schedule)
}
}
op = next
} else {
if retest {
retestOps.append(inOp)
}
prev = op
op = next
}
}
}
_unlock()
for op in retestOps {
if op.isReady {
op._cachedIsReady = true
}
}
}
internal var _isReportingProgress: Bool {
return __progressReporting
}
internal func _execute(_ op: YJOperation) {
var YJOperationProgress: Progress? = nil
if !(op is _BarrierOperation) && _isReportingProgress {
let opProgress = Progress(parent: nil, userInfo: nil)
opProgress.totalUnitCount = 1
progress.addChild(opProgress, withPendingUnitCount: 1)
YJOperationProgress = opProgress
}
YJOperationProgress?.becomeCurrent(withPendingUnitCount: 1)
defer { YJOperationProgress?.resignCurrent() }
op.main()
}
internal var _maxNumOps: Int {
get {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __maxNumOps
}
set(newValue) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__maxNumOps = newValue
}
}
internal var _isSuspended: Bool {
get {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
return __suspended
}
set(newValue) {
__atomicLoad.lock()
defer { __atomicLoad.unlock() }
__suspended = newValue
}
}
internal var _operationCount: Int {
_lock()
defer { _unlock() }
var op = __firstOperation
var cnt = 0
if let YJOperation = op?.takeUnretainedValue() {
if !(YJOperation is _BarrierOperation) {
cnt += 1
}
op = YJOperation.__nextOperation
}
return cnt
}
internal func _operations(includingBarriers: Bool = false) -> [YJOperation] {
_lock()
defer { _unlock() }
var YJOperations = [YJOperation]()
var op = __firstOperation
if let YJOperation = op?.takeUnretainedValue() {
if includingBarriers || !(YJOperation is _BarrierOperation) {
YJOperations.append(YJOperation)
}
op = YJOperation.__nextOperation
}
return YJOperations
}
public override init() {
super.init()
__name = "NSOperationQueue \(Unmanaged<YJOperationQueue>.passUnretained(self).toOpaque())"
__name = "QiBi"
}
internal init(asMainQueue: ()) {
super.init()
__mainQ = true
__maxNumOps = 1
__actualMaxNumOps = 1
__name = "NSOperationQueue Main Queue"
#if canImport(Darwin)
__propertyQoS = QualityOfService(qos_class_main())
#else
__propertyQoS = QualityOfService.userInteractive
#endif
}
deinit {
print("dead now")
}
open var progress: Progress {
get {
_lock()
defer { _unlock() }
guard let progress = _progress else {
let progress = _OperationQueueProgress(self)
_progress = progress
return progress
}
return progress
}
}
internal func _addOperations(_ ops: [YJOperation], barrier: Bool = false) {
if ops.isEmpty { return }
var failures = 0
var successes = 0
var firstNewOp: Unmanaged<YJOperation>?
var lastNewOp: Unmanaged<YJOperation>?
// ops 成为一个双向链表
for op in ops {
// initialized -> enqueuing
if op._compareAndSwapState(.initialized, .enqueuing) {
successes += 1
if 0 == failures {
let retained = Unmanaged.passRetained(op)
op._cachedIsReady = op.isReady
// 依据qos对对op进行分级
let schedule: DispatchWorkItem
if let qos = op.__propertyQoS?.qosClass {
schedule = DispatchWorkItem.init(qos: qos, flags: .enforceQoS, block: {
self._schedule(op)
})
} else {
schedule = DispatchWorkItem(flags: .assignCurrentContext, block: {
self._schedule(op)
})
}
op._adopt(queue: self, schedule: schedule)
op.__previousOperation = lastNewOp
op.__nextOperation = nil
if let lastNewOperation = lastNewOp?.takeUnretainedValue() {
lastNewOperation.__nextOperation = retained
} else {
firstNewOp = retained
}
lastNewOp = retained
} else {
_ = op._compareAndSwapState(.enqueuing, .initialized)
}
} else {
failures += 1
}
}
// 可能发生了一些错误。所以的op都清空。
if 0 < failures {
while let firstNewOperation = firstNewOp?.takeUnretainedValue() {
let nextNewOp = firstNewOperation.__nextOperation
firstNewOperation._invalidateQueue()
firstNewOperation.__previousOperation = nil
firstNewOperation.__nextOperation = nil
_ = firstNewOperation._compareAndSwapState(.enqueuing, .initialized)
firstNewOp?.release()
firstNewOp = nextNewOp
}
fatalError("operations finished, executing or already in a queue cannot be enqueued")
}
// Attach any YJOperations pending attachment to main list
if !barrier {
_lock()
_incrementOperationCount()
}
// 原来的A,B,C. 现在 D,E,F. make queue to A,B,C,D,E,F.
var pending = firstNewOp
if let pendingOperation = pending?.takeUnretainedValue() {
let old_last = __lastOperation
pendingOperation.__previousOperation = old_last
if let old = old_last?.takeUnretainedValue() {
old.__nextOperation = pending
} else {
__firstOperation = pending
}
__lastOperation = lastNewOp
}
// D,E,F.pendingOperation = D
while let pendingOperation = pending?.takeUnretainedValue() {
if !barrier {
// 没有barrier,就用上一次的barrier。
var barrierOp = _firstPriorityOperation(YJOperation.QueuePriority.barrier)
while let barrierOperation = barrierOp?.takeUnretainedValue() {
pendingOperation._addDependency(barrierOperation)
barrierOp = barrierOperation.__nextPriorityOperation
}
} else {
print(ops)
}
_ = pendingOperation._compareAndSwapState(.enqueuing, .enqueued)
var pri = pendingOperation.__priorityValue
// 确保有一个pri值。最后默认为normal。
if pri == nil {
// 看看queue能不能并发。(Mainqueue就不能并发,max == 1)
// 获取优先级
let v = __actualMaxNumOps == 1 ? nil : pendingOperation.__propertyQoS
if let qos = v {
switch qos {
case .default: pri = YJOperation.QueuePriority.normal.rawValue
case .userInteractive: pri = YJOperation.QueuePriority.veryHigh.rawValue
case .userInitiated: pri = YJOperation.QueuePriority.high.rawValue
case .utility: pri = YJOperation.QueuePriority.low.rawValue
case .background: pri = YJOperation.QueuePriority.veryLow.rawValue
}
} else {
pri = YJOperation.QueuePriority.normal.rawValue
}
}
// 依据优先级,获取同一优先级的op链条。不同优先级,有不同的op链条。
// 更新进优先级op链表
pendingOperation.__nextPriorityOperation = nil
if let old_last = _lastPriorityOperation(pri)?.takeUnretainedValue() {
old_last.__nextPriorityOperation = pending
} else {
_setFirstPriorityOperation(pri!, pending)
}
// 更新该优先级lastOp
_setlastPriorityOperation(pri!, pending)
// 操作完D,操作E。
pending = pendingOperation.__nextOperation
}
if !barrier {
_unlock()
}
if !barrier {
_schedule()
}
}
open func addOperation(_ op: YJOperation) {
_addOperations([op], barrier: false)
}
open func addOperations(_ ops: [YJOperation], waitUntilFinished wait: Bool) {
_addOperations(ops, barrier: false)
if wait {
for op in ops {
op.waitUntilFinished()
}
}
}
open func addOperation(_ block: @escaping () -> Void) {
let op = BlockOperation(block: block)
if let qos = __propertyQoS {
op.qualityOfService = qos
}
addOperation(op)
}
open func addBarrierBlock(_ barrier: @escaping () -> Void) {
var queue: DispatchQueue?
_lock()
if let op = __firstOperation {
let barrierOperation = _BarrierOperation(barrier)
barrierOperation.__priorityValue = YJOperation.QueuePriority.barrier
var iterOp: Unmanaged<YJOperation>? = op
while let yjop = iterOp?.takeUnretainedValue() {
barrierOperation.addDependency(yjop)
iterOp = yjop.__nextOperation
}
_addOperations([barrierOperation], barrier: true)
} else {
queue = _synthesizeBackingQueue()
}
_unlock()
if let q = queue {
q.async(flags: .barrier, execute: barrier)
} else {
_schedule()
}
}
open var maxConcurrentOperationCount: Int {
get {
return _maxNumOps
}
set(newValue) {
if newValue < 0 && newValue != YJOperationQueue.defaultMaxConcurrentOperationCount {
fatalError("count (\(newValue)) cannot be negative")
}
if !__mainQ {
_lock()
_maxNumOps = newValue
let acnt = YJOperationQueue.defaultMaxConcurrentOperationCount == newValue || Int32.max < newValue ? Int32.max : Int32(newValue)
__actualMaxNumOps = acnt
_unlock()
_schedule()
}
}
}
open var isSuspended: Bool {
get {
return _isSuspended
}
set(newValue) {
if !__mainQ {
_isSuspended = newValue
if !newValue {
_schedule()
}
}
}
}
open var name: String? {
get {
_lock()
defer { _unlock() }
return __name ?? "NSOperationQueue \(Unmanaged.passUnretained(self).toOpaque())"
}
set(newValue) {
if !__mainQ {
_lock()
__name = newValue ?? ""
_unlock()
}
}
}
open var qualityOfService: QualityOfService {
get {
return _propertyQoS ?? .default
}
set(newValue) {
if !__mainQ {
_lock()
_propertyQoS = newValue
_unlock()
}
}
}
unowned(unsafe) open var underlyingQueue: DispatchQueue? {
get {
if __mainQ {
return DispatchQueue.main
} else {
_lock()
defer { _unlock() }
return __dispatch_queue
}
}
set(newValue) {
if !__mainQ {
if 0 < _operationCount {
fatalError("operation queue must be empty in order to change underlying dispatch queue")
}
__dispatch_queue = newValue
}
}
}
open func cancelAllOperations() {
if !__mainQ {
for op in _operations(includingBarriers: true) {
op.cancel()
}
}
}
open func waitUntilAllOperationsAreFinished() {
var ops = _operations(includingBarriers: true)
while 0 < ops.count {
for op in ops {
op.waitUntilFinished()
}
ops = _operations(includingBarriers: true)
}
}
open class var current: YJOperationQueue? {
get {
if Thread.isMainThread {
return main
}
return YJOperationQueue._currentQueue.current
}
}
open class var main: YJOperationQueue {
get {
struct Once {
static let mainQ = YJOperationQueue(asMainQueue: ())
}
return Once.mainQ
}
}
}
extension YJOperationQueue {
// These two functions are inherently a race condition and should be avoided if possible
@available(OSX, introduced: 10.5, deprecated: 100000, message: "access to YJOperations is inherently a race condition, it should not be used. For barrier style behaviors please use addBarrierBlock: instead")
open var YJOperations: [YJOperation] {
get {
return _operations(includingBarriers: false)
}
}
@available(OSX, introduced: 10.6, deprecated: 100000)
open var YJOperationCount: Int {
get {
return _operationCount
}
}
}
internal class NSThreadSpecific<T: NSObject> {
private var key = "queue"
internal var current: T? {
let threadDict = Thread.current.threadDictionary
return threadDict[key] as? T
}
internal func set(_ value: T) {
let threadDict = Thread.current.threadDictionary
threadDict[key] = value
}
internal func clear() {
let threadDict = Thread.current.threadDictionary
threadDict[key] = nil
}
}
| mit | 0dcf49c46babab5fc2578d5f2844bd31 | 33.520752 | 211 | 0.535027 | 5.157543 | false | false | false | false |
ricardorauber/iOS-Swift | iOS-Swift.playground/Pages/File Manager.xcplaygroundpage/Contents.swift | 1 | 7479 | //: ## File Manager
//: ----
//: [Previous](@previous)
import Foundation
//: Bundle Directory [Read-Only] App and Resources
let bundlePath = NSBundle.mainBundle().bundlePath
//: Documents Directory [Read-Write-Delete] User Content
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first!
//: Documents/Inbox Directory [Read-Delete] Files from outside entities
let inboxPath = documentsPath + "/Inbox"
//: Library Documents [Read-Write-Delete] Content not exposed to User
let libraryPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first!
//: Temporary Dicrectory [Read-Write-Delete] Files that do not need to persist between launches of your app
let tmpPath = NSTemporaryDirectory()
//: File Manager
let fileManager = NSFileManager.defaultManager()
//: Contents of a directory
let fileList = try? fileManager.contentsOfDirectoryAtPath(bundlePath) as NSArray
//: Filter by file extension
let plistFiles = fileList!.filteredArrayUsingPredicate(NSPredicate(format:"pathExtension == 'plist'"))
//: Check if directory or file exists
let dummyFile = documentsPath + "/dummy.txt"
var isDirectory: ObjCBool = false
if fileManager.fileExistsAtPath(dummyFile, isDirectory: &isDirectory) {
if isDirectory {
print("Directory exists!")
} else {
print("File exists!")
}
} else {
print("Directory or File does not exist!")
}
//: Creating a directory
let imagesPath = documentsPath + "/images"
if !fileManager.fileExistsAtPath(imagesPath) {
try? fileManager.createDirectoryAtPath(imagesPath, withIntermediateDirectories: false, attributes: nil)
let tempImagesPath = imagesPath + "/tmp"
try? fileManager.createDirectoryAtPath(tempImagesPath, withIntermediateDirectories: false, attributes: nil)
}
//: Writing and Reading String Files
let textFile = documentsPath + "/text.txt"
let text = "This is a simple text file"
try? text.writeToFile(textFile, atomically: false, encoding: NSUTF8StringEncoding)
let reading = try? NSString(contentsOfFile: textFile, encoding: NSUTF8StringEncoding)
//: Deleting a File
do {
try fileManager.removeItemAtPath(textFile)
print("File deleted")
} catch let error as NSError {
print("Error: \(error)")
}
//: Directory or File Attributes
let directoryAttributes = try? fileManager.attributesOfItemAtPath(documentsPath)
if directoryAttributes != nil {
print(directoryAttributes![NSFileAppendOnly])
print(directoryAttributes![NSFileBusy])
print(directoryAttributes![NSFileCreationDate])
print(directoryAttributes![NSFileOwnerAccountName])
print(directoryAttributes![NSFileGroupOwnerAccountName])
print(directoryAttributes![NSFileDeviceIdentifier])
print(directoryAttributes![NSFileExtensionHidden])
print(directoryAttributes![NSFileGroupOwnerAccountID])
print(directoryAttributes![NSFileHFSCreatorCode])
print(directoryAttributes![NSFileHFSTypeCode])
print(directoryAttributes![NSFileImmutable])
print(directoryAttributes![NSFileModificationDate])
print(directoryAttributes![NSFileOwnerAccountID])
print(directoryAttributes![NSFilePosixPermissions])
print(directoryAttributes![NSFileReferenceCount])
print(directoryAttributes![NSFileSize])
print(directoryAttributes![NSFileSystemFileNumber])
print(directoryAttributes![NSFileType])
}
try? text.writeToFile(textFile, atomically: false, encoding: NSUTF8StringEncoding)
let fileAttributes = try? fileManager.attributesOfItemAtPath(textFile)
if fileAttributes != nil {
print(fileAttributes![NSFileAppendOnly])
print(fileAttributes![NSFileBusy])
print(fileAttributes![NSFileCreationDate])
print(fileAttributes![NSFileOwnerAccountName])
print(fileAttributes![NSFileGroupOwnerAccountName])
print(fileAttributes![NSFileDeviceIdentifier])
print(fileAttributes![NSFileExtensionHidden])
print(fileAttributes![NSFileGroupOwnerAccountID])
print(fileAttributes![NSFileHFSCreatorCode])
print(fileAttributes![NSFileHFSTypeCode])
print(fileAttributes![NSFileImmutable])
print(fileAttributes![NSFileModificationDate])
print(fileAttributes![NSFileOwnerAccountID])
print(fileAttributes![NSFilePosixPermissions])
print(fileAttributes![NSFileReferenceCount])
print(fileAttributes![NSFileSize])
print(fileAttributes![NSFileSystemFileNumber])
print(fileAttributes![NSFileType])
}
//: File Manager Delegate - Use a custom File Manager
// Will try methods with URL first, if it's not implemented then will try PATH
class HandleFiles: NSObject, NSFileManagerDelegate {
func fileManager(fileManager: NSFileManager, shouldCopyItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldCopyItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldLinkItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldLinkItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldMoveItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldMoveItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, copyingItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, linkingItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, linkingItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, movingItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, movingItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, removingItemAtPath path: String) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, removingItemAtURL URL: NSURL) -> Bool {
return true
}
func fileManager(fileManager: NSFileManager, shouldRemoveItemAtPath path: String) -> Bool {
print("will remove file: \(path)")
return true
}
func fileManager(fileManager: NSFileManager, shouldRemoveItemAtURL URL: NSURL) -> Bool {
print("will remove file: \(URL)")
return true
}
}
let handleFiles = HandleFiles()
let customFileManager = NSFileManager()
customFileManager.delegate = handleFiles
try customFileManager.removeItemAtPath(textFile)
//: [Next](@next)
| mit | 3144ab199c203a37edd0f2ed707862d1 | 38.994652 | 157 | 0.758256 | 5.108607 | false | false | false | false |
motylevm/skstylekit | StyleKitTests/SKTextViewTests.swift | 1 | 2262 | //
// Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import XCTest
@testable import SKStyleKit
class SKTextViewTests: XCTestCase {
override func setUp() {
super.setUp()
basicSetup()
}
func testSetStyleByName() {
// given
let textView = SKTextView()
let styleName = "textFieldStyle"
textView.text = defString
// when
textView.styleName = styleName
// then
XCTAssertNotNil(textView)
XCTAssertEqual(textView.styleName, styleName)
checkViewStyle(textView)
checkStringStyle(textView.attributedText)
}
func testSetStyle() {
// given
let style = StyleKit.style(withName: "textFieldStyle")
let textView = SKTextView()
textView.text = defString
// when
textView.style = style
// then
XCTAssertNotNil(textView)
XCTAssertEqual(textView.styleName, "textFieldStyle")
checkViewStyle(textView)
checkStringStyle(textView.attributedText)
}
}
| mit | 8526b7643f745bf486917d22937c3c2e | 33.8 | 86 | 0.662246 | 4.896104 | false | true | false | false |
johnno1962d/swift | test/decl/protocol/objc.swift | 1 | 5129 | // RUN: %target-parse-verify-swift
// Test requirements and conformance for Objective-C protocols.
@objc class ObjCClass { }
@objc protocol P1 {
func method1() // expected-note {{requirement 'method1()' declared here}}
var property1: ObjCClass { get } // expected-note{{requirement 'property1' declared here}}
var property2: ObjCClass { get set } // expected-note{{requirement 'property2' declared here}}
}
@objc class C1 : P1 {
@objc(method1renamed)
func method1() { // expected-error{{Objective-C method 'method1renamed' provided by method 'method1()' does not match the requirement's selector ('method1')}}{{9-23=method1}}
}
var property1: ObjCClass {
@objc(getProperty1) get { // expected-error{{Objective-C method 'getProperty1' provided by getter for 'property1' does not match the requirement's selector ('property1')}}{{11-23=property1}}
return ObjCClass()
}
}
var property2: ObjCClass {
get { return ObjCClass() }
@objc(setProperty2Please:) set { } // expected-error{{Objective-C method 'setProperty2Please:' provided by setter for 'property2' does not match the requirement's selector ('setProperty2:')}}{{11-30=setProperty2:}}
}
}
class C1b : P1 {
func method1() { } // expected-error{{non-'@objc' method 'method1()' does not satisfy requirement of '@objc' protocol 'P1'}}{{3-3=@objc }}
var property1: ObjCClass = ObjCClass() // expected-error{{non-'@objc' property 'property1' does not satisfy requirement of '@objc' protocol 'P1'}}{{3-3=@objc }}
var property2: ObjCClass = ObjCClass() // expected-error{{non-'@objc' property 'property2' does not satisfy requirement of '@objc' protocol 'P1'}}{{3-3=@objc }}
}
@objc protocol P2 {
@objc(methodWithInt:withClass:)
func method(_: Int, class: ObjCClass) // expected-note{{'method(_:class:)' declared here}}
var empty: Bool { @objc(checkIfEmpty) get } // expected-note{{requirement 'empty' declared here}}
}
class C2a : P2 {
func method(_: Int, class: ObjCClass) { } // expected-error{{non-'@objc' method 'method(_:class:)' does not satisfy requirement of '@objc' protocol 'P2'}}{{3-3=@objc(methodWithInt:withClass:) }}
var empty: Bool { // expected-error{{non-'@objc' property 'empty' does not satisfy requirement of '@objc' protocol 'P2'}}{{3-3=@objc }}
get { }
}
}
class C2b : P2 {
@objc func method(_: Int, class: ObjCClass) { } // expected-error{{Objective-C method 'method:class:' provided by method 'method(_:class:)' does not match the requirement's selector ('methodWithInt:withClass:')}}{{8-8=(methodWithInt:withClass:)}}
@objc var empty: Bool {
@objc get { } // expected-error{{Objective-C method 'empty' provided by getter for 'empty' does not match the requirement's selector ('checkIfEmpty')}}{{10-10=(checkIfEmpty)}}
}
}
@objc protocol P3 {
optional func doSomething(x: Int)
optional func doSomething(y: Int)
}
class C3a : P3 {
@objc func doSomething(x: Int) { }
}
// Complain about optional requirements that aren't satisfied
// according to Swift, but would conflict in Objective-C.
@objc protocol OptP1 {
optional func method() // expected-note 2{{requirement 'method()' declared here}}
optional var property1: ObjCClass { get } // expected-note 2{{requirement 'property1' declared here}}
optional var property2: ObjCClass { get set } // expected-note{{requirement 'property2' declared here}}
}
@objc class OptC1a : OptP1 { // expected-note 3{{class 'OptC1a' declares conformance to protocol 'OptP1' here}}
@objc(method) func otherMethod() { } // expected-error{{Objective-C method 'method' provided by method 'otherMethod()' conflicts with optional requirement method 'method()' in protocol 'OptP1'}}
// expected-note@-1{{rename method to match requirement 'method()'}}{{22-33=method}}
var otherProp1: ObjCClass {
@objc(property1) get { return ObjCClass() } // expected-error{{Objective-C method 'property1' provided by getter for 'otherProp1' conflicts with optional requirement getter for 'property1' in protocol 'OptP1'}}
}
var otherProp2: ObjCClass {
get { return ObjCClass() }
@objc(setProperty2:) set { } // expected-error{{Objective-C method 'setProperty2:' provided by setter for 'otherProp2' conflicts with optional requirement setter for 'property2' in protocol 'OptP1'}}
}
}
@objc class OptC1b : OptP1 { // expected-note 2{{class 'OptC1b' declares conformance to protocol 'OptP1' here}}
@objc(property1) func someMethod() { } // expected-error{{Objective-C method 'property1' provided by method 'someMethod()' conflicts with optional requirement getter for 'property1' in protocol 'OptP1'}}
var someProp: ObjCClass {
@objc(method) get { return ObjCClass() } // expected-error{{Objective-C method 'method' provided by getter for 'someProp' conflicts with optional requirement method 'method()' in protocol 'OptP1'}}
}
}
// rdar://problem/19879598
@objc protocol Foo {
init() // expected-note{{requirement 'init()' declared here}}
}
class Bar: Foo {
required init() {} // expected-error{{non-'@objc' initializer 'init()' does not satisfy requirement of '@objc' protocol 'Foo'}}{{3-3=@objc }}
}
| apache-2.0 | 29f0153ecd7eedb90a048e477e3d4c85 | 46.934579 | 248 | 0.702281 | 3.824758 | false | false | false | false |
konduruvijaykumar/ios-sample-apps | TODOAppWithCoreData/TODOAppWithCoreData/ViewController.swift | 1 | 3388 | //
// ViewController.swift
// TODOAppWithCoreData
//
// Created by Vijay Konduru on 04/02/17.
// Copyright © 2017 PJay. All rights reserved.
//
// https://www.youtube.com/watch?v=qt8BNhpEAok
// https://www.youtube.com/watch?v=peSXZi_nxek
// https://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var todoListTableView: UITableView!;
var todos: [Todo] = [];
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
todoListTableView.dataSource = self;
todoListTableView.delegate = self;
}
override func viewWillAppear(_ animated: Bool) {
// Get data from core data
getTodoData();
// Update table view
todoListTableView.reloadData();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todos.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell();
let todo = todos[indexPath.row];
//print("Entity object unique objectID is \(todo.objectID)");
if(todo.isImportant){
cell.textLabel?.text = "❗️ \(todo.itemData!)";
}else{
cell.textLabel?.text = todo.itemData!;
}
return cell;
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let _appDelegate = UIApplication.shared.delegate as! AppDelegate;
let _appContext = _appDelegate.persistentContainer.viewContext;
if(editingStyle == .delete){
let todo = todos[indexPath.row];
_appContext.delete(todo);
_appDelegate.saveContext();
do{
todos = try _appContext.fetch(Todo.fetchRequest());
}catch{
print("Something Is Wrong");
}
}
todoListTableView.reloadData();
}
func getTodoData(){
let _appDelegate = UIApplication.shared.delegate as! AppDelegate;
let _appContext = _appDelegate.persistentContainer.viewContext;
do{
todos = try _appContext.fetch(Todo.fetchRequest());
}catch{
print("Something Is Wrong");
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "updateSegue", sender: todos[indexPath.row]);
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// http://stackoverflow.com/questions/34004252/how-to-segue-to-a-specific-view-controller-depending-on-the-segue-identity-from
if(segue.identifier == "updateSegue"){
// Need this logic only for update segue and else will have no logic. So others will not go through this logic
let referenceGuest = segue.destination as! UpdateTaskViewController;
referenceGuest.todo = sender as? Todo;
}
}
}
| apache-2.0 | 1f48236c1c9f16c194ebe01440ed1541 | 33.520408 | 134 | 0.63287 | 4.791785 | false | false | false | false |
envoyproxy/envoy | mobile/examples/swift/swiftpm/Packages/Sources/NetworkClient/NetworkClient.swift | 2 | 2132 | import Envoy
import Foundation
// MARK: - Network Client
public enum NetworkClient {
public static func getCatFact() async throws -> String {
try await withCheckedThrowingContinuation { continuation in
DispatchQueue.networking.async {
let stream = EngineBuilder.demoEngine
.streamClient()
.newStreamPrototype()
.setOnResponseData(closure: { body, _, _ in
do {
let fact = try JSONDecoder().decode(FactResponse.self, from: body)
continuation.resume(returning: fact.fact)
} catch {
continuation.resume(throwing: FactError.parse)
}
})
.setOnError(closure: { error, _ in
continuation.resume(throwing: FactError.network(error))
})
.start(queue: .networking)
let headers = RequestHeadersBuilder(
method: .get, scheme: "https", authority: "catfact.ninja", path: "/fact"
).build()
stream.sendHeaders(headers, endStream: true)
}
}
}
}
// MARK: - Envoy Engine
private extension EngineBuilder {
static let demoEngine = EngineBuilder()
.build()
}
// MARK: - Networking Concurrent Queue
private extension DispatchQueue {
static let networking = DispatchQueue(label: "io.envoyproxy.envoymobile.networking",
qos: .userInitiated, attributes: .concurrent)
}
// MARK: - Models
private struct FactResponse: Codable {
let fact: String
}
private enum FactError: LocalizedError {
case parse
case network(Error)
var localizedDescription: String {
switch self {
case .parse:
return "Could not parse fact response"
case .network(let error):
return """
Could not fetch fact
\(error.localizedDescription)
"""
}
}
}
| apache-2.0 | 0d228f29adb4c68ada815172d157e106 | 29.457143 | 94 | 0.531895 | 5.343358 | false | false | false | false |
tjnet/NewsAppWithSwift | NewsApp/NewsApp/ViewController.swift | 1 | 3768 | //
// ViewController.swift
// NewsApp
//
// Created by TanakaJun on 2015/11/13.
// Copyright © 2015年 edu.self. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
var pageMenu : CAPSPageMenu?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// MARK: - UI Setup
self.title = "Dev News"
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.grayColor()]
// Do any additional setup after loading the view, typically from a nib.
// Array to keep track of controllers in page menu
var controllerArray : [UIViewController] = []
var feeds: [Dictionary<String, String>] =
[
[
"link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/top/rss",
"title": "top"
],
[
"link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/ruby/rss",
"title": "ruby"
],
[
"link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/ios/rss",
"title": "ios"
],
[
"link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/infrastructure/rss",
"title": "infrastructure"
],
]
// Create variables for all view controllers you want to put in the
// page menu, initialize them, and add each to the controller array.
// (Can be any UIViewController subclass)
// Make sure the title property of all view controllers is set
// Example:
for feed in feeds
{
let feedController = TableViewController(nibName: "TableViewController", bundle: nil)
feedController.fetchFrom = feed["link"]!
feedController.title = feed["title"]
controllerArray.append(feedController)
}
// Customize page menu to your liking (optional) or use default settings by sending nil for 'options' in the init
// Example:
var parameters: [CAPSPageMenuOption] = [
.ScrollMenuBackgroundColor(UIColor.whiteColor()),
.SelectionIndicatorColor(UIColor.clearColor()),
.ViewBackgroundColor(UIColor.whiteColor()),
.MenuItemFont(UIFont(name: "HelveticaNeue-Bold", size: 16.0)!),
.MenuHeight(30.0),
.MenuMargin(0),
.MenuItemWidth(120),
.CenterMenuItems(true)
]
// Initialize page menu with controller array, frame, and optional parameters
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 0.0, self.view.frame.width, self.view.frame.height), pageMenuOptions: parameters)
self.addChildViewController(pageMenu!)
self.view.addSubview(pageMenu!.view)
pageMenu!.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 62c387be06d1b937fa13691d37d189d9 | 37.814433 | 170 | 0.609562 | 4.820743 | false | false | false | false |
robertodias180/RCDExtensions | Connection/RCDConnection.swift | 1 | 540 | //
// TestConnection.swift
//
import Foundation
import Reachability
public class RCDConnection {
public static var isOn: Bool {
return Reachability.forInternetConnection().currentReachabilityStatus() != .NotReachable
}
public static var isWiFi: Bool {
return Reachability.forInternetConnection().currentReachabilityStatus() == .ReachableViaWiFi
}
public static var isWWan: Bool {
return Reachability.forInternetConnection().currentReachabilityStatus() == .ReachableViaWWAN
}
}
| mit | 8e3333c6c7600ec7c2e18d035183251f | 23.545455 | 100 | 0.714815 | 5.454545 | false | false | false | false |
tranhieutt/Swiftz | Swiftz/NonEmptyList.swift | 3 | 5625 | //
// NonEmptyList.swift
// Swiftz
//
// Created by Maxwell Swadling on 10/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
/// A list that may not ever be empty.
///
/// Traditionally partial operations on regular lists are total with non-empty lists.
public struct NonEmptyList<Element> {
public let head : Element
public let tail : List<Element>
public init(_ a : A, _ t : List<Element>) {
head = a
tail = t
}
public init(_ a : A, _ t : NonEmptyList<Element>) {
head = a
tail = t.toList()
}
public init?(_ list : List<Element>) {
switch list.match {
case .Nil:
return nil
case let .Cons(h, t):
self.init(h, t)
}
}
public func toList() -> List<Element> {
return List(head, tail)
}
public func reverse() -> NonEmptyList<Element> {
return NonEmptyList(self.toList().reverse())!
}
/// Indexes into a non-empty list.
public subscript(n : UInt) -> Element {
if n == 0 {
return self.head
}
return self.tail[n.predecessor()]
}
/// Returns the length of the list.
///
/// For infinite lists this function will throw an exception.
public var count : UInt {
return self.tail.count.successor()
}
}
public func == <Element : Equatable>(lhs : NonEmptyList<Element>, rhs : NonEmptyList<Element>) -> Bool {
return lhs.toList() == rhs.toList()
}
public func != <Element : Equatable>(lhs : NonEmptyList<Element>, rhs : NonEmptyList<Element>) -> Bool {
return lhs.toList() != rhs.toList()
}
extension NonEmptyList : ArrayLiteralConvertible {
public init(arrayLiteral xs : Element...) {
var l = NonEmptyList<Element>(xs.first!, List())
for x in xs[1..<xs.endIndex].reverse() {
l = NonEmptyList(x, l)
}
self = l
}
}
extension NonEmptyList : SequenceType {
public typealias Generator = ListGenerator<Element>
public func generate() -> ListGenerator<Element> {
return ListGenerator(self.toList())
}
}
extension NonEmptyList : CollectionType {
public typealias Index = UInt
public var startIndex : UInt { return 0 }
public var endIndex : UInt {
return self.count
}
}
extension NonEmptyList : CustomStringConvertible {
public var description : String {
let x = self.fmap({ String($0) }).joinWithSeparator(", ")
return "[\(x)]"
}
}
extension NonEmptyList : Functor {
public typealias A = Element
public typealias B = Any
public typealias FB = NonEmptyList<B>
public func fmap<B>(f : (A -> B)) -> NonEmptyList<B> {
return NonEmptyList<B>(f(self.head), self.tail.fmap(f))
}
}
public func <^> <A, B>(f : A -> B, l : NonEmptyList<A>) -> NonEmptyList<B> {
return l.fmap(f)
}
extension NonEmptyList : Pointed {
public static func pure(x : A) -> NonEmptyList<Element> {
return NonEmptyList(x, List())
}
}
extension NonEmptyList : Applicative {
public typealias FA = NonEmptyList<Element>
public typealias FAB = NonEmptyList<A -> B>
public func ap<B>(f : NonEmptyList<A -> B>) -> NonEmptyList<B> {
return f.bind({ f in self.bind({ x in NonEmptyList<B>.pure(f(x)) }) })
}
}
public func <*> <A, B>(f : NonEmptyList<(A -> B)>, l : NonEmptyList<A>) -> NonEmptyList<B> {
return l.ap(f)
}
extension NonEmptyList : ApplicativeOps {
public typealias C = Any
public typealias FC = NonEmptyList<C>
public typealias D = Any
public typealias FD = NonEmptyList<D>
public static func liftA<B>(f : A -> B) -> NonEmptyList<A> -> NonEmptyList<B> {
return { a in NonEmptyList<A -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(f : A -> B -> C) -> NonEmptyList<A> -> NonEmptyList<B> -> NonEmptyList<C> {
return { a in { b in f <^> a <*> b } }
}
public static func liftA3<B, C, D>(f : A -> B -> C -> D) -> NonEmptyList<A> -> NonEmptyList<B> -> NonEmptyList<C> -> NonEmptyList<D> {
return { a in { b in { c in f <^> a <*> b <*> c } } }
}
}
extension NonEmptyList : Monad {
public func bind<B>(f : A -> NonEmptyList<B>) -> NonEmptyList<B> {
let nh = f(self.head)
return NonEmptyList<B>(nh.head, nh.tail + self.tail.bind { t in f(t).toList() })
}
}
extension NonEmptyList : MonadOps {
public static func liftM<B>(f : A -> B) -> NonEmptyList<A> -> NonEmptyList<B> {
return { m1 in m1 >>- { x1 in NonEmptyList<B>.pure(f(x1)) } }
}
public static func liftM2<B, C>(f : A -> B -> C) -> NonEmptyList<A> -> NonEmptyList<B> -> NonEmptyList<C> {
return { m1 in { m2 in m1 >>- { x1 in m2 >>- { x2 in NonEmptyList<C>.pure(f(x1)(x2)) } } } }
}
public static func liftM3<B, C, D>(f : A -> B -> C -> D) -> NonEmptyList<A> -> NonEmptyList<B> -> NonEmptyList<C> -> NonEmptyList<D> {
return { m1 in { m2 in { m3 in m1 >>- { x1 in m2 >>- { x2 in m3 >>- { x3 in NonEmptyList<D>.pure(f(x1)(x2)(x3)) } } } } } }
}
}
public func >>->> <A, B, C>(f : A -> NonEmptyList<B>, g : B -> NonEmptyList<C>) -> (A -> NonEmptyList<C>) {
return { x in f(x) >>- g }
}
public func <<-<< <A, B, C>(g : B -> NonEmptyList<C>, f : A -> NonEmptyList<B>) -> (A -> NonEmptyList<C>) {
return f >>->> g
}
public func >>- <A, B>(l : NonEmptyList<A>, f : A -> NonEmptyList<B>) -> NonEmptyList<B> {
return l.bind(f)
}
extension NonEmptyList : Copointed {
public func extract() -> Element {
return self.head
}
}
extension NonEmptyList : Comonad {
public typealias FFA = NonEmptyList<NonEmptyList<Element>>
public func duplicate() -> NonEmptyList<NonEmptyList<Element>> {
switch NonEmptyList(self.tail) {
case .None:
return NonEmptyList<NonEmptyList<Element>>(self, List())
case let .Some(x):
return NonEmptyList<NonEmptyList<Element>>(self, x.duplicate().toList())
}
}
public func extend<B>(fab : NonEmptyList<Element> -> B) -> NonEmptyList<B> {
return self.duplicate().fmap(fab)
}
}
| bsd-3-clause | 85f9f33536ce09baf312428229c2f58e | 26.043269 | 135 | 0.638578 | 3.1372 | false | false | false | false |
Appsaurus/Infinity | Infinity/controls/arrow/ArrowRefreshAnimator.swift | 1 | 4772 | //
// ArrowRefreshAnimator.swift
// InfinitySample
//
// Created by Danis on 15/12/24.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
extension UIColor {
static var ArrowBlue: UIColor {
return UIColor(red: 76/255.0, green: 143/255.0, blue: 1.0, alpha: 1.0)
}
static var ArrowLightGray: UIColor {
return UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0)
}
}
open class ArrowRefreshAnimator: UIView, CustomPullToRefreshAnimator {
fileprivate(set) var animating = false
open var color: UIColor = UIColor.ArrowBlue {
didSet {
arrowLayer.strokeColor = color.cgColor
circleFrontLayer.strokeColor = color.cgColor
activityIndicatorView.color = color
}
}
fileprivate var arrowLayer:CAShapeLayer = CAShapeLayer()
fileprivate var circleFrontLayer: CAShapeLayer = CAShapeLayer()
fileprivate var circleBackLayer: CAShapeLayer = CAShapeLayer()
fileprivate var activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
public override init(frame: CGRect) {
super.init(frame: frame)
circleBackLayer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: frame.width, height: frame.height)).cgPath
circleBackLayer.fillColor = nil
circleBackLayer.strokeColor = UIColor.ArrowLightGray.cgColor
circleBackLayer.lineWidth = 3
circleFrontLayer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: frame.width, height: frame.height)).cgPath
circleFrontLayer.fillColor = nil
circleFrontLayer.strokeColor = color.cgColor
circleFrontLayer.lineWidth = 3
circleFrontLayer.lineCap = kCALineCapRound
circleFrontLayer.strokeStart = 0
circleFrontLayer.strokeEnd = 0
circleFrontLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: CGFloat(-M_PI_2)))
let arrowWidth = min(frame.width, frame.height) / 2
let arrowHeight = arrowWidth * 0.5
let arrowPath = UIBezierPath()
arrowPath.move(to: CGPoint(x: 0, y: arrowHeight))
arrowPath.addLine(to: CGPoint(x: arrowWidth / 2, y: 0))
arrowPath.addLine(to: CGPoint(x: arrowWidth, y: arrowHeight))
arrowLayer.path = arrowPath.cgPath
arrowLayer.fillColor = nil
arrowLayer.strokeColor = color.cgColor
arrowLayer.lineWidth = 3
arrowLayer.lineJoin = kCALineJoinRound
arrowLayer.lineCap = kCALineCapButt
circleBackLayer.frame = self.bounds
circleFrontLayer.frame = self.bounds
arrowLayer.frame = CGRect(x: (frame.width - arrowWidth)/2, y: (frame.height - arrowHeight)/2, width: arrowWidth, height: arrowHeight)
activityIndicatorView.frame = self.bounds
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.color = UIColor.ArrowBlue
self.layer.addSublayer(circleBackLayer)
self.layer.addSublayer(circleFrontLayer)
self.layer.addSublayer(arrowLayer)
self.addSubview(activityIndicatorView)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func animateState(_ state: PullToRefreshState) {
switch state {
case .none:
stopAnimating()
case .releasing(let progress):
updateForProgress(progress)
case .loading:
startAnimating()
}
}
func updateForProgress(_ progress: CGFloat) {
CATransaction.begin()
CATransaction.setDisableActions(true)
circleFrontLayer.strokeEnd = progress * progress
arrowLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: CGFloat(M_PI * 2) * progress * progress))
CATransaction.commit()
}
func startAnimating() {
animating = true
circleFrontLayer.strokeEnd = 0
arrowLayer.transform = CATransform3DIdentity
circleBackLayer.isHidden = true
circleFrontLayer.isHidden = true
arrowLayer.isHidden = true
activityIndicatorView.startAnimating()
}
func stopAnimating() {
animating = false
circleBackLayer.isHidden = false
circleFrontLayer.isHidden = false
arrowLayer.isHidden = false
activityIndicatorView.stopAnimating()
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | 985cd6fa936b70efa756e04c9903efc0 | 35.128788 | 141 | 0.660935 | 4.901336 | false | false | false | false |
liting-8124/Exercise-FilmTicketsBookingApp | FilmTicketsBooking/FilmTicketsBooking/FilmDetailTableViewController.swift | 1 | 7169 | //
// FilmDetailTableViewController.swift
// FilmTicketsBooking
//
// Created by Ting Li on 16/3/26.
// Copyright © 2016年 Ting Li. All rights reserved.
//
import UIKit
class FilmDetailTableViewController: UITableViewController {
var film: Film?
var cinema: Cinema?
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.navigationItem.title = self.film?.name
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func viewTime(sender: UIButton) {
performSegueWithIdentifier("detailToTime", sender: self)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 3
case 1:
return 3
default:
return 3
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return 200
case 1:
return tableView.sectionHeaderHeight
default:
return tableView.sectionHeaderHeight
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(section)"
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
let imageView = UIImageView(image: UIImage(named: (self.film?.imageName)!))
imageView.clipsToBounds = true
//imageView.frame = CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 200)
imageView.frame = CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: tableView.sectionHeaderHeight)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
return imageView
case 1:
return tableView.headerViewForSection(section)
default:
return tableView.headerViewForSection(section)
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
return 70
case 1:
return 150
default:
return 130
}
default:
return 150
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("cellWithButton", forIndexPath: indexPath) as! ButtonTableViewCell
cell.cellButton.setTitle("Find Times & Booking", forState: UIControlState.Normal)
cell.cellButton.addTarget(self, action: #selector(self.viewTime(_:)), forControlEvents: UIControlEvents.TouchUpInside)
return cell
case 1:
let nib = UINib(nibName: "FilmInfoCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: "FilmInfoCell")
let cell = tableView.dequeueReusableCellWithIdentifier("FilmInfoCell", forIndexPath: indexPath) as! FilmInfoTableViewCell
cell.yearLabel.text = "\(self.film!.year)"
cell.directorLabel.text = self.film?.director
cell.genreLabel.text = self.film?.genre
cell.lengthLabel.text = "\(self.film!.length)"
cell.ratingLabel.text = self.film?.ratingSystem
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = self.film?.polt
cell.textLabel?.numberOfLines = 0
cell.textLabel?.font = UIFont.systemFontOfSize(15)
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
return cell
}
default:
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "detailToTime" {
let targetController = segue.destinationViewController as! TimeTableViewController
targetController.film = self.film
targetController.cinema = self.cinema
}
}
}
| mit | d7288e20b4b9754d1cbb2c090b62e882 | 35.938144 | 157 | 0.621546 | 5.646966 | false | false | false | false |
manavgabhawala/swift | stdlib/public/SDK/Foundation/FileManager.swift | 2 | 2859 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
extension FileManager {
/*
renamed syntax should be:
public func replaceItem(at originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options : FileManager.ItemReplacementOptions = []) throws -> URL?
*/
@available(*, deprecated, renamed:"replaceItemAt(_:withItemAt:backupItemName:options:)")
public func replaceItemAtURL(originalItemURL: NSURL, withItemAtURL newItemURL: NSURL, backupItemName: String? = nil, options: FileManager.ItemReplacementOptions = []) throws -> NSURL? {
var error: NSError? = nil
guard let result = __NSFileManagerReplaceItemAtURL(self, originalItemURL as URL, newItemURL as URL, backupItemName, options, &error) else { throw error! }
return result as NSURL
}
@available(swift, obsoleted: 4)
@available(OSX 10.6, iOS 4.0, *)
public func replaceItemAt(_ originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options: FileManager.ItemReplacementOptions = []) throws -> NSURL? {
var error: NSError?
guard let result = __NSFileManagerReplaceItemAtURL(self, originalItemURL, newItemURL , backupItemName, options, &error) else { throw error! }
return result as NSURL
}
@available(swift, introduced: 4)
@available(OSX 10.6, iOS 4.0, *)
public func replaceItemAt(_ originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options: FileManager.ItemReplacementOptions = []) throws -> URL? {
var error: NSError?
guard let result = __NSFileManagerReplaceItemAtURL(self, originalItemURL, newItemURL , backupItemName, options, &error) else { throw error! }
return result
}
@available(OSX 10.6, iOS 4.0, *)
public func enumerator(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = [], errorHandler handler: ((URL, Error) -> Bool)? = nil) -> FileManager.DirectoryEnumerator? {
return __NSFileManagerEnumeratorAtURL(self, url, keys, mask, { (url, error) in
var errorResult = true
if let h = handler {
errorResult = h(url as URL, error)
}
return errorResult
})
}
}
| apache-2.0 | fa294a00c0ab5caeaff1ab48279374b9 | 50.981818 | 242 | 0.655124 | 4.741294 | false | false | false | false |
AlphaJian/LarsonApp | LarsonApp/LarsonApp/View/MaterialTextField/CustomTextField.swift | 2 | 4758 | //
// CustomTextField.swift
// BusinessOS
//
// Created by Jian Zhang on 10/27/15.
// Copyright © 2015 PwC. All rights reserved.
//
import UIKit
class CustomTextField: UIView, UITextFieldDelegate {
var title : String = ""
var strValue : String = ""
var bolEdited : Bool = false
var bolTextfield : Bool = true
var isOptional : Bool = false
let editedColor = UIColor(red: 30/255, green: 144/255, blue: 255/255, alpha: 1)
let uneditedColor = UIColor.lightGray
let fieldColor = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1)
let editedInterval : CGFloat = 20
let uneditedInterval : CGFloat = 10
let editedFont : CGFloat = 11
let uneditedFont : CGFloat = 14
var tapHandler : ButtonTouchUpBlock?
var finishEditHandler : TextFieldFinishBlock?
var itemSelectHandler : ReturnBlock?
var startHandler : TextFieldStartBlock?
var leaveHandler : TextFieldLeaveBlock?
var returnhandler : TextFieldReturnBlock?
@IBOutlet weak var bottomLineInterval: NSLayoutConstraint!
@IBOutlet weak var bottomLineView: UIView!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var fieldTF: UITextField!
@IBOutlet weak var errorLbl: UILabel!
func createCustomField(_title : String, _bolTextfield : Bool)
{
fieldTF.delegate = self
fieldTF.textColor = fieldColor
fieldTF.autocorrectionType = UITextAutocorrectionType.no
title = _title
bolTextfield = _bolTextfield
self.titleLbl.text = _title
errorLbl.isHidden = true
}
func setText(str : String)
{
strValue = str
fieldTF.text = str
animationTitleLbl(bol: true)
}
func showErrorMsg(str : String)-> Void
{
errorLbl.isHidden = false
errorLbl.text = str
}
func setValueField(str : String)
{
self.strValue = str
self.fieldTF.text = str
self.animationTitleLbl(bol: true)
}
func animationTitleLbl(bol : Bool){
bolEdited = bol
if bolEdited
{
bottomLineView.backgroundColor = editedColor
titleLbl.textColor = editedColor
self.titleLbl.font = UIFont.systemFont(ofSize: self.editedFont)
// titleLbl.text = title.stringByReplacingOccurrencesOfString("(optional)", withString: "")
if self.bottomLineInterval.constant != self.editedInterval
{
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.bottomLineInterval.constant = self.editedInterval
self.layoutIfNeeded()
})
}
}
else
{
if fieldTF.text?.characters.count != 0
{
titleLbl.text = title
}
else
{
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.bottomLineInterval.constant = self.uneditedInterval
self.layoutIfNeeded()
}, completion: { (bol) -> Void in
})
}
titleLbl.textColor = uneditedColor
bottomLineView.backgroundColor = uneditedColor
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
bolEdited = true
errorLbl.isHidden = true
animationTitleLbl(bol: bolEdited)
if self.tapHandler != nil
{
self.tapHandler?()
}
if startHandler != nil
{
startHandler?()
}
return bolTextfield
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let prospectiveText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
strValue = prospectiveText
if finishEditHandler != nil
{
finishEditHandler!(prospectiveText)
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
bolEdited = false
if finishEditHandler != nil
{
finishEditHandler!(strValue)
}
if leaveHandler != nil
{
leaveHandler?(textField.text!)
}
animationTitleLbl(bol: bolEdited)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
UIApplication.shared.keyWindow?.endEditing(true)
if returnhandler != nil
{
returnhandler!()
}
return true
}
func hidePassword(hide: Bool){
fieldTF.isSecureTextEntry = hide
}
}
| apache-2.0 | 3069a41a7189db54616f9e68b9e4644b | 28.364198 | 129 | 0.586504 | 4.939772 | false | false | false | false |
tlax/looper | looper/Model/Camera/More/MCameraMoreItemInfoFrames.swift | 1 | 1514 | import UIKit
class MCameraMoreItemInfoFrames:MCameraMoreItemInfo
{
private let kTitleSize:CGFloat = 16
private let kSubtitleSize:CGFloat = 14
init(record:MCameraRecord)
{
let attributedString:NSMutableAttributedString = NSMutableAttributedString()
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:kTitleSize),
NSForegroundColorAttributeName:UIColor.genericLight]
let attributesSubtitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.medium(size:kSubtitleSize),
NSForegroundColorAttributeName:UIColor.black]
let title:String = NSLocalizedString("MCameraMoreItemInfoFrames_title", comment:"")
let countFrames:Int = record.items.count
var countActive:Int = 0
for item:MCameraRecordItem in record.items
{
if item.active
{
countActive += 1
}
}
let countString:String = "\(countActive)/\(countFrames)"
let stringTitleFrames:NSAttributedString = NSAttributedString(
string:title,
attributes:attributesTitle)
let stringFrames:NSAttributedString = NSAttributedString(
string:countString,
attributes:attributesSubtitle)
attributedString.append(stringTitleFrames)
attributedString.append(stringFrames)
super.init(attributedString:attributedString)
}
}
| mit | c0d45592e8212414120769b3923d54a8 | 34.209302 | 91 | 0.652576 | 5.628253 | false | false | false | false |
tonyarnold/Differ | Sources/Differ/Diff+UIKit.swift | 1 | 22104 | #if canImport(UIKit) && !os(watchOS)
import UIKit
#if swift(>=4.2)
public typealias DiffRowAnimation = UITableView.RowAnimation
#else
public typealias DiffRowAnimation = UITableViewRowAnimation
#endif
public extension UITableView {
/// Animates rows which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UITableView`
/// - newData: Data which reflects the current state of `UITableView`
/// - deletionAnimation: Animation type for deletions
/// - insertionAnimation: Animation type for insertions
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
func animateRowChanges<T: Collection>(
oldData: T,
newData: T,
deletionAnimation: DiffRowAnimation = .automatic,
insertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 }
) where T.Element: Equatable {
self.apply(
oldData.extendedDiff(newData),
deletionAnimation: deletionAnimation,
insertionAnimation: insertionAnimation,
indexPathTransform: indexPathTransform
)
}
/// Animates rows which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UITableView`
/// - newData: Data which reflects the current state of `UITableView`
/// - isEqual: A function comparing two elements of `T`
/// - deletionAnimation: Animation type for deletions
/// - insertionAnimation: Animation type for insertions
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
func animateRowChanges<T: Collection>(
oldData: T,
newData: T,
isEqual: EqualityChecker<T>,
deletionAnimation: DiffRowAnimation = .automatic,
insertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 }
) {
self.apply(
oldData.extendedDiff(newData, isEqual: isEqual),
deletionAnimation: deletionAnimation,
insertionAnimation: insertionAnimation,
indexPathTransform: indexPathTransform
)
}
func apply(
_ diff: ExtendedDiff,
deletionAnimation: DiffRowAnimation = .automatic,
insertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 }
) {
let update = BatchUpdate(diff: diff, indexPathTransform: indexPathTransform)
beginUpdates()
deleteRows(at: update.deletions, with: deletionAnimation)
insertRows(at: update.insertions, with: insertionAnimation)
update.moves.forEach { moveRow(at: $0.from, to: $0.to) }
endUpdates()
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UITableView`
/// - newData: Data which reflects the current state of `UITableView`
/// - rowDeletionAnimation: Animation type for row deletions
/// - rowInsertionAnimation: Animation type for row insertions
/// - sectionDeletionAnimation: Animation type for section deletions
/// - sectionInsertionAnimation: Animation type for section insertions
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
rowDeletionAnimation: DiffRowAnimation = .automatic,
rowInsertionAnimation: DiffRowAnimation = .automatic,
sectionDeletionAnimation: DiffRowAnimation = .automatic,
sectionInsertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Element: Collection,
T.Element: Equatable,
T.Element.Element: Equatable {
self.apply(
oldData.nestedExtendedDiff(to: newData),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UITableView`
/// - newData: Data which reflects the current state of `UITableView`
/// - isEqualElement: A function comparing two items (elements of `T.Element`)
/// - rowDeletionAnimation: Animation type for row deletions
/// - rowInsertionAnimation: Animation type for row insertions
/// - sectionDeletionAnimation: Animation type for section deletions
/// - sectionInsertionAnimation: Animation type for section insertions
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualElement: NestedElementEqualityChecker<T>,
rowDeletionAnimation: DiffRowAnimation = .automatic,
rowInsertionAnimation: DiffRowAnimation = .automatic,
sectionDeletionAnimation: DiffRowAnimation = .automatic,
sectionInsertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Element: Collection,
T.Element: Equatable {
self.apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualElement: isEqualElement
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UITableView`
/// - newData: Data which reflects the current state of `UITableView`
/// - isEqualSection: A function comparing two sections (elements of `T`)
/// - rowDeletionAnimation: Animation type for row deletions
/// - rowInsertionAnimation: Animation type for row insertions
/// - sectionDeletionAnimation: Animation type for section deletions
/// - sectionInsertionAnimation: Animation type for section insertions
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
rowDeletionAnimation: DiffRowAnimation = .automatic,
rowInsertionAnimation: DiffRowAnimation = .automatic,
sectionDeletionAnimation: DiffRowAnimation = .automatic,
sectionInsertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Element: Collection,
T.Element.Element: Equatable {
self.apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UITableView`
/// - newData: Data which reflects the current state of `UITableView`
/// - isEqualSection: A function comparing two sections (elements of `T`)
/// - isEqualElement: A function comparing two items (elements of `T.Element`)
/// - rowDeletionAnimation: Animation type for row deletions
/// - rowInsertionAnimation: Animation type for row insertions
/// - sectionDeletionAnimation: Animation type for section deletions
/// - sectionInsertionAnimation: Animation type for section insertions
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
isEqualElement: NestedElementEqualityChecker<T>,
rowDeletionAnimation: DiffRowAnimation = .automatic,
rowInsertionAnimation: DiffRowAnimation = .automatic,
sectionDeletionAnimation: DiffRowAnimation = .automatic,
sectionInsertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Element: Collection {
self.apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection,
isEqualElement: isEqualElement
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
func apply(
_ diff: NestedExtendedDiff,
rowDeletionAnimation: DiffRowAnimation = .automatic,
rowInsertionAnimation: DiffRowAnimation = .automatic,
sectionDeletionAnimation: DiffRowAnimation = .automatic,
sectionInsertionAnimation: DiffRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath,
sectionTransform: (Int) -> Int
) {
let update = NestedBatchUpdate(diff: diff, indexPathTransform: indexPathTransform, sectionTransform: sectionTransform)
beginUpdates()
deleteRows(at: update.itemDeletions, with: rowDeletionAnimation)
insertRows(at: update.itemInsertions, with: rowInsertionAnimation)
update.itemMoves.forEach { moveRow(at: $0.from, to: $0.to) }
deleteSections(update.sectionDeletions, with: sectionDeletionAnimation)
insertSections(update.sectionInsertions, with: sectionInsertionAnimation)
update.sectionMoves.forEach { moveSection($0.from, toSection: $0.to) }
endUpdates()
}
}
public extension UICollectionView {
/// Animates items which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UICollectionView`
/// - newData: Data which reflects the current state of `UICollectionView`
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - updateData: Closure to be called immediately before performing updates, giving you a chance to correctly update data source
/// - completion: Closure to be executed when the animation completes
func animateItemChanges<T: Collection>(
oldData: T,
newData: T,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
updateData: () -> Void,
completion: ((Bool) -> Void)? = nil
) where T.Element: Equatable {
let diff = oldData.extendedDiff(newData)
apply(diff, updateData: updateData, completion: completion, indexPathTransform: indexPathTransform)
}
/// Animates items which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UICollectionView`
/// - newData: Data which reflects the current state of `UICollectionView`
/// - isEqual: A function comparing two elements of `T`
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - updateData: Closure to be called immediately before performing updates, giving you a chance to correctly update data source
/// - completion: Closure to be executed when the animation completes
func animateItemChanges<T: Collection>(
oldData: T,
newData: T,
isEqual: EqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
updateData: () -> Void,
completion: ((Bool) -> Swift.Void)? = nil
) {
let diff = oldData.extendedDiff(newData, isEqual: isEqual)
apply(diff, updateData: updateData, completion: completion, indexPathTransform: indexPathTransform)
}
func apply(
_ diff: ExtendedDiff,
updateData: () -> Void,
completion: ((Bool) -> Swift.Void)? = nil,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 }
) {
performBatchUpdates({
updateData()
let update = BatchUpdate(diff: diff, indexPathTransform: indexPathTransform)
self.deleteItems(at: update.deletions)
self.insertItems(at: update.insertions)
update.moves.forEach { self.moveItem(at: $0.from, to: $0.to) }
}, completion: completion)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UICollectionView`
/// - newData: Data which reflects the current state of `UICollectionView`
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
/// - updateData: Closure to be called immediately before performing updates, giving you a chance to correctly update data source
/// - completion: Closure to be executed when the animation completes
func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
updateData: () -> Void,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Element: Collection,
T.Element: Equatable,
T.Element.Element: Equatable {
self.apply(
oldData.nestedExtendedDiff(to: newData),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
updateData: updateData,
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UICollectionView`
/// - newData: Data which reflects the current state of `UICollectionView`
/// - isEqualElement: A function comparing two items (elements of `T.Element`)
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
/// - updateData: Closure to be called immediately before performing updates, giving you a chance to correctly update data source
/// - completion: Closure to be executed when the animation completes
func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualElement: NestedElementEqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
updateData: () -> Void,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Element: Collection,
T.Element: Equatable {
self.apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualElement: isEqualElement
),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
updateData: updateData,
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UICollectionView`
/// - newData: Data which reflects the current state of `UICollectionView`
/// - isEqualSection: A function comparing two sections (elements of `T`)
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
/// - updateData: Closure to be called immediately before performing updates, giving you a chance to correctly update data source.
/// - completion: Closure to be executed when the animation completes
func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
updateData: () -> Void,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Element: Collection,
T.Element.Element: Equatable {
self.apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection
),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
updateData: updateData,
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - Parameters:
/// - oldData: Data which reflects the previous state of `UICollectionView`
/// - newData: Data which reflects the current state of `UICollectionView`
/// - isEqualSection: A function comparing two sections (elements of `T`)
/// - isEqualElement: A function comparing two items (elements of `T.Element`)
/// - indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
/// - updateData: Closure to be called immediately before performing updates, giving you a chance to correctly update data source
/// - completion: Closure to be executed when the animation completes
func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
isEqualElement: NestedElementEqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
updateData: () -> Void,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Element: Collection {
self.apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection,
isEqualElement: isEqualElement
),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
updateData: updateData,
completion: completion
)
}
func apply(
_ diff: NestedExtendedDiff,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
updateData: () -> Void,
completion: ((Bool) -> Void)? = nil
) {
performBatchUpdates({
updateData()
let update = NestedBatchUpdate(diff: diff, indexPathTransform: indexPathTransform, sectionTransform: sectionTransform)
self.insertSections(update.sectionInsertions)
self.deleteSections(update.sectionDeletions)
update.sectionMoves.forEach { self.moveSection($0.from, toSection: $0.to) }
self.deleteItems(at: update.itemDeletions)
self.insertItems(at: update.itemInsertions)
update.itemMoves.forEach { self.moveItem(at: $0.from, to: $0.to) }
}, completion: completion)
}
}
#endif
| mit | da89fe3d8879e639866cd640f66e5387 | 47.58022 | 144 | 0.640337 | 5.527382 | false | false | false | false |
dsoisson/SwiftLearningExercises | Exercise12_Extensions.playground/Contents.swift | 1 | 2127 | /*:
* callout(Exercise): Leveraging protocols and the delegation design pattern, your task is to build a simple bank teller system. The teller’s job responsibilities are to open, credit, debit savings and checking accounts. The teller is not sure what really happens when they perform their responsibilities, it just works.
**Constraints:**
- Create an audit delegate that tracks when an account is opened, credited and debited
- Create a protocol for which a savings and checking accounts need to conform
- Create a teller class with customers and accounts
- Perform the teller's responsibilities
*/
import Foundation
var teller: Teller? = Teller(name: "Annie")
teller?.auditDelegate = TransactionAuditPrinterDelegate()
teller?.handle(Customer(name: "Matt"))
do {
try teller?.openCheckingAccount()
let account = teller!.customer!.checking!
try teller?.credit(100.00, account: account)
print(account.description)
try teller?.debit(99.00, account: account)
print(account.description)
// try teller?.debit(2.00, account: account)
// print(account.description)
try teller?.done()
} catch TransactionError.NoCustomer {
print("ERROR: teller is not handling a customer")
} catch TransactionError.InsufficientFunds(let balance, let debiting) {
print("ERROR: transaction error: debiting \(debiting), balance = \(balance)")
}
teller?.handle(Customer(name: "Sam"))
do {
try teller?.openSavingsAccount()
let account = teller!.customer!.savings!
try teller?.debit(100.00, account: account)
print(account.description)
try teller?.credit(600.00, account: account)
print(account.description)
if let savings = account as? SavingsAccount {
savings.applyInterest()
}
print(account.description)
try teller?.done()
} catch TransactionError.NoCustomer {
print("ERROR: teller is not handling a customer")
} catch TransactionError.InsufficientFunds(let balance, let debiting) {
print("ERROR: transaction error: debiting \(debiting), balance = \(balance)")
}
teller = nil
| mit | 8df40efd256b4fa7f7c4cfa1b74da3e7 | 31.692308 | 320 | 0.711529 | 4.086538 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/DeliveryGoods/View/Cell/OutBoundListTableViewCell.swift | 1 | 1433 | //
// OutBoundListTableViewCell.swift
// OMS-WH
//
// Created by ___Gwy on 2017/11/1.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class OutBoundListTableViewCell: UITableViewCell {
@IBOutlet weak var outBoundNum: UILabel!
@IBOutlet weak var whName: UILabel!
@IBOutlet weak var outBoundStatus: UILabel!
@IBOutlet weak var hpName: UILabel!
@IBOutlet weak var ownerName: UILabel!
@IBOutlet weak var dlName: UILabel!
@IBOutlet weak var makeOrderName: UILabel!
var outBoundModel:DGOutBoundListModel?{
didSet{
outBoundNum.text = "出库单号:\(outBoundModel!.wONo)"
whName.text = "仓库:\(outBoundModel!.wHName)"
outBoundStatus.text = outBoundModel?.statusName
hpName.text = "医院医生:\(outBoundModel!.hPCodeName) \(outBoundModel!.dTCodeName)"
ownerName.text = "货控方:\(outBoundModel!.sOOIOrgCodeName)"
dlName.text = "技服商:\(outBoundModel!.sOCreateByOrgCodeName)"
makeOrderName.text = "下单人:\(outBoundModel!.soCreateByName)"
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 7ef8c6d36cec8e24ed3f661b8e23de8f | 29.666667 | 90 | 0.649275 | 3.965517 | false | false | false | false |
lorentey/swift | test/ModuleInterface/option-preservation.swift | 6 | 1339 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -enable-library-evolution -emit-module-interface-path %t.swiftinterface -module-name t %s -emit-module -o /dev/null -Onone -enforce-exclusivity=unchecked -autolink-force-load
// RUN: %FileCheck %s < %t.swiftinterface -check-prefix=CHECK-SWIFTINTERFACE
//
// CHECK-SWIFTINTERFACE: swift-module-flags:
// CHECK-SWIFTINTERFACE-SAME: -enable-library-evolution
// CHECK-SWIFTINTERFACE-SAME: -Onone
// CHECK-SWIFTINTERFACE-SAME: -enforce-exclusivity=unchecked
// CHECK-SWIFTINTERFACE-SAME: -autolink-force-load
// Make sure flags show up when filelists are enabled
// RUN: %target-build-swift %s -driver-filelist-threshold=0 -emit-module-interface -o %t/foo -module-name foo -module-link-name fooCore -force-single-frontend-invocation -Ounchecked -enforce-exclusivity=unchecked -autolink-force-load 2>&1
// RUN: %FileCheck %s < %t/foo.swiftinterface --check-prefix CHECK-FILELIST-INTERFACE
// CHECK-FILELIST-INTERFACE: swift-module-flags:
// CHECK-FILELIST-INTERFACE-SAME: -target
// CHECK-FILELIST-INTERFACE-SAME: -autolink-force-load
// CHECK-FILELIST-INTERFACE-SAME: -module-link-name fooCore
// CHECK-FILELIST-INTERFACE-SAME: -enforce-exclusivity=unchecked
// CHECK-FILELIST-INTERFACE-SAME: -Ounchecked
// CHECK-FILELIST-INTERFACE-SAME: -module-name foo
public func foo() { }
| apache-2.0 | 5043cf2601109cd0162fddd531cbc6b7 | 52.56 | 238 | 0.768484 | 3.415816 | false | false | false | false |
flodolo/firefox-ios | Client/Frontend/Home/TopSites/TopSitesViewModel.swift | 1 | 11208 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
import Shared
import Storage
class TopSitesViewModel {
struct UX {
static let numberOfItemsPerRowForSizeClassIpad = UXSizeClasses(compact: 3, regular: 4, other: 2)
static let cellEstimatedSize: CGSize = CGSize(width: 73, height: 83)
static let cardSpacing: CGFloat = 16
}
weak var delegate: HomepageDataModelDelegate?
var isZeroSearch: Bool
var theme: Theme
var tilePressedHandler: ((Site, Bool) -> Void)?
var tileLongPressedHandler: ((Site, UIView?) -> Void)?
private let profile: Profile
private var sentImpressionTelemetry = [String: Bool]()
private var topSites: [TopSite] = []
private let dimensionManager: TopSitesDimension
private var numberOfItems: Int = 0
private let topSitesDataAdaptor: TopSitesDataAdaptor
private let topSiteHistoryManager: TopSiteHistoryManager
private let googleTopSiteManager: GoogleTopSiteManager
private var wallpaperManager: WallpaperManager
init(profile: Profile,
isZeroSearch: Bool = false,
theme: Theme,
wallpaperManager: WallpaperManager) {
self.profile = profile
self.isZeroSearch = isZeroSearch
self.theme = theme
self.dimensionManager = TopSitesDimensionImplementation()
self.topSiteHistoryManager = TopSiteHistoryManager(profile: profile)
self.googleTopSiteManager = GoogleTopSiteManager(prefs: profile.prefs)
let siteImageHelper = SiteImageHelper(profile: profile)
let adaptor = TopSitesDataAdaptorImplementation(profile: profile,
topSiteHistoryManager: topSiteHistoryManager,
googleTopSiteManager: googleTopSiteManager,
siteImageHelper: siteImageHelper)
topSitesDataAdaptor = adaptor
self.wallpaperManager = wallpaperManager
adaptor.delegate = self
}
func tilePressed(site: TopSite, position: Int) {
topSitePressTracking(homeTopSite: site, position: position)
tilePressedHandler?(site.site, site.isGoogleURL)
}
// MARK: - Telemetry
func sendImpressionTelemetry(_ homeTopSite: TopSite, position: Int) {
guard !hasSentImpressionForTile(homeTopSite) else { return }
homeTopSite.impressionTracking(position: position)
}
private func topSitePressTracking(homeTopSite: TopSite, position: Int) {
// Top site extra
let type = homeTopSite.getTelemetrySiteType()
let topSiteExtra = [TelemetryWrapper.EventExtraKey.topSitePosition.rawValue: "\(position)",
TelemetryWrapper.EventExtraKey.topSiteTileType.rawValue: type]
// Origin extra
let originExtra = TelemetryWrapper.getOriginExtras(isZeroSearch: isZeroSearch)
let extras = originExtra.merge(with: topSiteExtra)
TelemetryWrapper.recordEvent(category: .action,
method: .tap,
object: .topSiteTile,
value: nil,
extras: extras)
// Sponsored tile specific telemetry
if let tile = homeTopSite.site as? SponsoredTile {
SponsoredTileTelemetry.sendClickTelemetry(tile: tile, position: position)
}
}
private func hasSentImpressionForTile(_ homeTopSite: TopSite) -> Bool {
guard sentImpressionTelemetry[homeTopSite.site.url] != nil else {
sentImpressionTelemetry[homeTopSite.site.url] = true
return false
}
return true
}
// MARK: - Context actions
func hideURLFromTopSites(_ site: Site) {
guard let host = site.tileURL.normalizedHost else { return }
topSiteHistoryManager.removeDefaultTopSitesTile(site: site)
profile.history.removeHostFromTopSites(host).uponQueue(.main) { [weak self] result in
guard result.isSuccess, let self = self else { return }
self.refreshIfNeeded(refresh: true)
}
}
func pinTopSite(_ site: Site) {
profile.history.addPinnedTopSite(site).uponQueue(.main) { result in
guard result.isSuccess else { return }
self.refreshIfNeeded(refresh: true)
}
}
func removePinTopSite(_ site: Site) {
googleTopSiteManager.removeGoogleTopSite(site: site)
topSiteHistoryManager.removeTopSite(site: site)
}
func refreshIfNeeded(refresh forced: Bool) {
topSiteHistoryManager.refreshIfNeeded(forceRefresh: forced)
}
}
// MARK: HomeViewModelProtocol
extension TopSitesViewModel: HomepageViewModelProtocol, FeatureFlaggable {
var sectionType: HomepageSectionType {
return .topSites
}
var headerViewModel: LabelButtonHeaderViewModel {
// Only show a header if the firefox browser logo isn't showing
let shouldShow = !featureFlags.isFeatureEnabled(.wallpapers, checking: .buildOnly)
var textColor: UIColor?
if wallpaperManager.featureAvailable {
textColor = wallpaperManager.currentWallpaper.textColor
}
return LabelButtonHeaderViewModel(
title: shouldShow ? HomepageSectionType.topSites.title: nil,
titleA11yIdentifier: AccessibilityIdentifiers.FirefoxHomepage.SectionTitles.topSites,
isButtonHidden: true,
textColor: textColor)
}
var isEnabled: Bool {
return featureFlags.isFeatureEnabled(.topSites, checking: .buildAndUser)
}
func numberOfItemsInSection() -> Int {
return numberOfItems
}
func section(for traitCollection: UITraitCollection) -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .estimated(UX.cellEstimatedSize.height)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .estimated(UX.cellEstimatedSize.height)
)
let interface = TopSitesUIInterface(trait: traitCollection)
let sectionDimension = dimensionManager.getSectionDimension(for: topSites,
numberOfRows: topSitesDataAdaptor.numberOfRows,
interface: interface)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
subitem: item,
count: sectionDimension.numberOfTilesPerRow)
group.interItemSpacing = NSCollectionLayoutSpacing.fixed(UX.cardSpacing)
let section = NSCollectionLayoutSection(group: group)
let leadingInset = HomepageViewModel.UX.leadingInset(traitCollection: traitCollection)
section.contentInsets = NSDirectionalEdgeInsets(top: 0,
leading: leadingInset,
bottom: HomepageViewModel.UX.spacingBetweenSections - TopSiteItemCell.UX.bottomSpace,
trailing: leadingInset)
section.interGroupSpacing = UX.cardSpacing
return section
}
var hasData: Bool {
return !topSites.isEmpty
}
func refreshData(for traitCollection: UITraitCollection,
isPortrait: Bool = UIWindow.isPortrait,
device: UIUserInterfaceIdiom = UIDevice.current.userInterfaceIdiom) {
let interface = TopSitesUIInterface(trait: traitCollection)
let sectionDimension = dimensionManager.getSectionDimension(for: topSites,
numberOfRows: topSitesDataAdaptor.numberOfRows,
interface: interface)
topSitesDataAdaptor.recalculateTopSiteData(for: sectionDimension.numberOfTilesPerRow)
topSites = topSitesDataAdaptor.getTopSitesData()
numberOfItems = sectionDimension.numberOfRows * sectionDimension.numberOfTilesPerRow
}
func screenWasShown() {
sentImpressionTelemetry = [String: Bool]()
}
func setTheme(theme: Theme) {
self.theme = theme
}
}
// MARK: - FxHomeTopSitesManagerDelegate
extension TopSitesViewModel: TopSitesManagerDelegate {
func didLoadNewData() {
ensureMainThread {
self.topSites = self.topSitesDataAdaptor.getTopSitesData()
guard self.isEnabled else { return }
self.delegate?.reloadView()
}
}
}
// MARK: - FxHomeSectionHandler
extension TopSitesViewModel: HomepageSectionHandler {
func configure(_ collectionView: UICollectionView,
at indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(cellType: TopSiteItemCell.self, for: indexPath),
let contentItem = topSites[safe: indexPath.row] {
let favicon = topSitesDataAdaptor.getFaviconImage(forSite: contentItem.site)
var textColor: UIColor?
if wallpaperManager.featureAvailable {
textColor = wallpaperManager.currentWallpaper.textColor
}
cell.configure(contentItem,
favicon: favicon,
position: indexPath.row,
theme: theme,
textColor: textColor)
sendImpressionTelemetry(contentItem, position: indexPath.row)
return cell
} else if let cell = collectionView.dequeueReusableCell(cellType: EmptyTopSiteCell.self, for: indexPath) {
cell.applyTheme(theme: theme)
return cell
}
return UICollectionViewCell()
}
func configure(_ cell: UICollectionViewCell,
at indexPath: IndexPath) -> UICollectionViewCell {
// Setup is done through configure(collectionView:indexPath:), shouldn't be called
return UICollectionViewCell()
}
func didSelectItem(at indexPath: IndexPath,
homePanelDelegate: HomePanelDelegate?,
libraryPanelDelegate: LibraryPanelDelegate?) {
guard let site = topSites[safe: indexPath.row] else { return }
tilePressed(site: site, position: indexPath.row)
}
func handleLongPress(with collectionView: UICollectionView, indexPath: IndexPath) {
guard let tileLongPressedHandler = tileLongPressedHandler,
let site = topSites[safe: indexPath.row]?.site
else { return }
let sourceView = collectionView.cellForItem(at: indexPath)
tileLongPressedHandler(site, sourceView)
}
}
| mpl-2.0 | e8b77f084f976fb799347a1660139c01 | 39.462094 | 141 | 0.63642 | 5.540287 | false | false | false | false |
MuYangZhe/Swift30Projects | Project 15 - SnpachatMenu/SnpachatMenu/ViewController.swift | 1 | 2282 | //
// ViewController.swift
// SnpachatMenu
//
// Created by 牧易 on 17/7/27.
// Copyright © 2017年 MuYi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
enum vcName:String {
case chat = "ChatViewController"
case discover = "DiscoverViewController"
case stories = "StoriesViewController"
}
override func viewDidLoad() {
super.viewDidLoad()
// Create view controllers and add them to current view controller.
let chatVC = UIViewController.init(nibName: vcName.chat.rawValue, bundle: nil)
let discoverVC = UIViewController.init(nibName: vcName.chat.rawValue, bundle: nil)
let storiesVC = UIViewController.init(nibName: vcName.stories.rawValue, bundle: nil)
add(childViewController: chatVC, toParentViewController: self)
add(childViewController: discoverVC, toParentViewController: self)
add(childViewController: storiesVC, toParentViewController: self)
//Set up current snap view.
let snapView = UIImageView.init(image: UIImage(named:"Snap"))
changeX(ofView: snapView, xPostion: view.frame.width)
scrollView.addSubview(snapView)
changeX(ofView: discoverVC.view, xPostion: view.frame.width * 2)
changeX(ofView: storiesVC.view, xPostion: view.frame.width * 3)
//Set up contentSize and contentOffset.
scrollView.contentSize = CGSize(width: view.frame.width * 4, height: view.frame.height)
scrollView.contentOffset.x = view.frame.width
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func changeX(ofView view:UIView,xPostion:CGFloat){
var frame = view.frame
frame.origin.x = xPostion
view.frame = frame
}
fileprivate func add (childViewController:UIViewController,toParentViewController:UIViewController){
addChildViewController(childViewController)
scrollView.addSubview(childViewController.view)
childViewController.didMove(toParentViewController: toParentViewController)
}
}
| mit | 597a351878c1b4ba566edcf8cb771d10 | 34.546875 | 104 | 0.686593 | 4.830149 | false | false | false | false |
cristov26/moviesApp | MoviesApp/MoviesApp/Presenter/MovieDetailPresenter.swift | 1 | 1005 | //
// MovieDetailPresenter.swift
// MoviesApp
//
// Created by Cristian Tovar on 11/16/17.
// Copyright © 2017 Cristian Tovar. All rights reserved.
//
import Foundation
final class MovieDetailPresenter{
fileprivate let locator: MoviesUseCaseLocatorProtocol
let movie: MovieData
var videos: [Video] = [Video]()
var title: String
init(movie: MovieData, locator: MoviesUseCaseLocatorProtocol) {
self.movie = movie
self.locator = locator
self.title = movie.title
}
func loadVideos(completion: @escaping videosClosure){
guard let useCase = self.locator.getUseCase(ofType: ListVideos.self) else {
return
}
useCase.execute (movieId: "\(self.movie.movieId)", completion: { [unowned self] (data) in
if let vids = data, vids.count > 0 {
self.videos.append(contentsOf: vids)
}
completion(data)
})
}
}
| mit | 6cee8755662b3a010a5f750d0d5c3c51 | 24.1 | 97 | 0.595618 | 4.422907 | false | false | false | false |
imex94/KCLTech-iOS-Sessions-2014-2015 | HackLondon/HackLondon/CoreMotion.swift | 1 | 1892 | //
// CoreMotion.swift
// HackLondon
//
// Created by Alex Telek on 27/02/2015.
// Copyright (c) 2015 KCLTech. All rights reserved.
//
import UIKit
import CoreMotion
class CoreMotion: UIViewController {
var stepManager: CMPedometer?
var motionManager: CMMotionManager?
@IBOutlet weak var lblSteps: UILabel!
@IBOutlet weak var lblAcc: UILabel!
@IBOutlet weak var lblGyro: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
stepManager = CMPedometer()
if CMPedometer.isStepCountingAvailable() {
stepManager?.startPedometerUpdatesFromDate(NSDate(), withHandler: { (data: CMPedometerData!, error) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.lblSteps.text = "\(data.numberOfSteps)"
})
}
})
}
motionManager = CMMotionManager()
motionManager?.accelerometerUpdateInterval = 0.2;
motionManager?.gyroUpdateInterval = 0.2;
motionManager?.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: { (data, error) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.lblAcc.text = "X: \(data.acceleration.x)\n Y: \(data.acceleration.y)\n Z: \(data.acceleration.z)"
})
}
})
motionManager?.startGyroUpdatesToQueue(NSOperationQueue(), withHandler: { (data, error) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.lblGyro.text = "X: \(data.rotationRate.x)\n Y: \(data.rotationRate.y)\n Z: \(data.rotationRate.z)"
})
}
})
}
}
| mit | c4ef5240e0617e9cd4386f309238d391 | 32.785714 | 123 | 0.562896 | 4.592233 | false | false | false | false |
qingpengchen2011/Cosmos | Cosmos/CosmosView.swift | 1 | 9344 | import UIKit
/**
A star rating view that can be used to show customer rating for the products. On can select stars by tapping on them when updateOnTouch settings is true. An optional text can be supplied that is shown on the right side.
Example:
cosmosView.rating = 4
cosmosView.text = "(123)"
Shows: ★★★★☆ (132)
*/
@IBDesignable public class CosmosView: UIView {
/**
The currently shown number of stars, usually between 1 and 5. If the value is decimal the stars will be shown according to the Fill Mode setting.
*/
@IBInspectable public var rating: Double = CosmosDefaultSettings.rating {
didSet {
if oldValue != rating {
update()
}
}
}
/// Currently shown text. Set it to nil to display just the stars without text.
@IBInspectable public var text: String? {
didSet {
if oldValue != text {
update()
}
}
}
/// Star rating settings.
public var settings = CosmosSettings() {
didSet {
update()
}
}
/// Stores calculated size of the view. It is used as intrinsic content size.
private var viewSize = CGSize()
/// Draws the stars when the view comes out of storyboard with default settings
public override func awakeFromNib() {
super.awakeFromNib()
update()
}
/**
Initializes and returns a newly allocated cosmos view object.
*/
convenience public init() {
self.init(frame: CGRect())
}
/**
Initializes and returns a newly allocated cosmos view object with the specified frame rectangle.
- parameter frame: The frame rectangle for the view.
*/
override public init(frame: CGRect) {
super.init(frame: frame)
update()
self.frame.size = intrinsicContentSize()
improvePerformance()
}
/// Initializes and returns a newly allocated cosmos view object.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
improvePerformance()
}
/// Change view settings for faster drawing
private func improvePerformance() {
/// Cache the view into a bitmap instead of redrawing the stars each time
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.mainScreen().scale
opaque = true
}
/**
Updates the stars and optional text based on current values of `rating` and `text` properties.
*/
public func update() {
// Create star layers
// ------------
var layers = CosmosLayers.createStarLayers(rating, settings: settings)
layer.sublayers = layers
// Create text layer
// ------------
if let text = text {
let textLayer = createTextLayer(text, layers: layers)
layers.append(textLayer)
}
// Update size
// ------------
updateSize(layers)
// Update accesibility
// ------------
updateAccessibility()
}
/**
Creates the text layer for the given text string.
- parameter text: Text string for the text layer.
- parameter layers: Arrays of layers containing the stars.
- returns: The newly created text layer.
*/
private func createTextLayer(text: String, layers: [CALayer]) -> CALayer {
let textLayer = CosmosLayerHelper.createTextLayer(text,
font: settings.textFont, color: settings.textColor)
let starsSize = CosmosSize.calculateSizeToFitLayers(layers)
CosmosText.position(textLayer, starsSize: starsSize, textMargin: settings.textMargin)
layer.addSublayer(textLayer)
return textLayer
}
/**
Updates the size to fit all the layers containing stars and text.
- parameter layers: Array of layers containing stars and the text.
*/
private func updateSize(layers: [CALayer]) {
viewSize = CosmosSize.calculateSizeToFitLayers(layers)
invalidateIntrinsicContentSize()
}
/// Returns the content size to fit all the star and text layers.
override public func intrinsicContentSize() -> CGSize {
return viewSize
}
// MARK: - Accessibility
private func updateAccessibility() {
CosmosAccessibility.update(self, rating: rating, text: text, settings: settings)
}
/// Called by the system in accessibility voice-over mode when the value is incremented by the user.
public override func accessibilityIncrement() {
super.accessibilityIncrement()
rating += CosmosAccessibility.accessibilityIncrement(rating, settings: settings)
}
/// Called by the system in accessibility voice-over mode when the value is decremented by the user.
public override func accessibilityDecrement() {
super.accessibilityDecrement()
rating -= CosmosAccessibility.accessibilityDecrement(rating, settings: settings)
}
// MARK: - Touch recognition
/// Closure will be called when user touches the cosmos view. The touch rating argument is passed to the closure.
public var didTouchCosmos: ((Double)->())?
/// Overriding the function to detect the first touch gesture.
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if let touch = touches.first {
let location = touch.locationInView(self).x
onDidTouch(location, starsWidth: widthOfStars)
}
}
/// Overriding the function to detect touch move.
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
if let touch = touches.first {
let location = touch.locationInView(self).x
onDidTouch(location, starsWidth: widthOfStars)
}
}
/**
Called when the view is touched.
- parameter locationX: The horizontal location of the touch relative to the width of the stars.
- parameter starsWidth: The width of the stars excluding the text.
*/
func onDidTouch(locationX: CGFloat, starsWidth: CGFloat) {
let calculatedTouchRating = CosmosTouch.touchRating(locationX, starsWidth: starsWidth,
settings: settings)
if settings.updateOnTouch {
rating = calculatedTouchRating
}
if calculatedTouchRating == previousRatingForDidTouchCallback {
// Do not call didTouchCosmos if rating has not changed
return
}
didTouchCosmos?(calculatedTouchRating)
previousRatingForDidTouchCallback = calculatedTouchRating
}
private var previousRatingForDidTouchCallback: Double = -123.192
/// Width of the stars (excluding the text). Used for calculating touch location.
var widthOfStars: CGFloat {
if let sublayers = self.layer.sublayers where settings.totalStars <= sublayers.count {
let starLayers = Array(sublayers[0..<settings.totalStars])
return CosmosSize.calculateSizeToFitLayers(starLayers).width
}
return 0
}
/// Increase the hitsize of the view if it's less than 44px for easier touching.
override public func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
let oprimizedBounds = CosmosTouchTarget.optimize(bounds)
return oprimizedBounds.contains(point)
}
// MARK: - Properties inspectable from the storyboard
@IBInspectable var totalStars: Int = CosmosDefaultSettings.totalStars {
didSet {
settings.totalStars = totalStars
}
}
@IBInspectable var starSize: Double = CosmosDefaultSettings.starSize {
didSet {
settings.starSize = starSize
}
}
@IBInspectable var colorFilled: UIColor = CosmosDefaultSettings.colorFilled {
didSet {
settings.colorFilled = colorFilled
}
}
@IBInspectable var colorEmpty: UIColor = CosmosDefaultSettings.colorEmpty {
didSet {
settings.colorEmpty = colorEmpty
}
}
@IBInspectable var borderColorEmpty: UIColor = CosmosDefaultSettings.borderColorEmpty {
didSet {
settings.borderColorEmpty = borderColorEmpty
}
}
@IBInspectable var borderWidthEmpty: Double = CosmosDefaultSettings.borderWidthEmpty {
didSet {
settings.borderWidthEmpty = borderWidthEmpty
}
}
@IBInspectable var starMargin: Double = CosmosDefaultSettings.starMargin {
didSet {
settings.starMargin = starMargin
}
}
@IBInspectable var fillMode: Int = CosmosDefaultSettings.fillMode.rawValue {
didSet {
settings.fillMode = StarFillMode(rawValue: fillMode) ?? CosmosDefaultSettings.fillMode
}
}
@IBInspectable var textSize: Double = CosmosDefaultSettings.textSize {
didSet {
settings.textFont = settings.textFont.fontWithSize(CGFloat(textSize))
}
}
@IBInspectable var textMargin: Double = CosmosDefaultSettings.textMargin {
didSet {
settings.textMargin = textMargin
}
}
@IBInspectable var textColor: UIColor = CosmosDefaultSettings.textColor {
didSet {
settings.textColor = textColor
}
}
@IBInspectable var updateOnTouch: Bool = CosmosDefaultSettings.updateOnTouch {
didSet {
settings.updateOnTouch = updateOnTouch
}
}
@IBInspectable var minTouchRating: Double = CosmosDefaultSettings.minTouchRating {
didSet {
settings.minTouchRating = minTouchRating
}
}
/// Draw the stars in interface buidler
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
update()
}
}
| mit | 888d9eea111bc0856c46dd65e621c161 | 25.976879 | 219 | 0.689201 | 4.946476 | false | false | false | false |
rheinfabrik/Heimdall.swift | Heimdallr/OAuthAccessTokenKeychainStore.swift | 3 | 4579 | import Foundation
import Security
internal struct Keychain {
internal let service: String
fileprivate var defaultClassAndAttributes: [String: AnyObject] {
return [
String(kSecClass): String(kSecClassGenericPassword) as AnyObject,
String(kSecAttrAccessible): String(kSecAttrAccessibleAfterFirstUnlock) as AnyObject,
String(kSecAttrService): service as AnyObject,
]
}
internal func dataForKey(_ key: String) -> Data? {
var attributes = defaultClassAndAttributes
attributes[String(kSecAttrAccount)] = key as AnyObject?
attributes[String(kSecMatchLimit)] = kSecMatchLimitOne
attributes[String(kSecReturnData)] = true as AnyObject?
var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result) { pointer in
return SecItemCopyMatching(attributes as CFDictionary, UnsafeMutablePointer(pointer))
}
guard status == errSecSuccess else {
return nil
}
return result as? Data
}
internal func valueForKey(_ key: String) -> String? {
return dataForKey(key).flatMap { data in
String(data: data, encoding: String.Encoding.utf8)
}
}
internal func setData(_ data: Data, forKey key: String) {
var attributes = defaultClassAndAttributes
attributes[String(kSecAttrAccount)] = key as AnyObject?
attributes[String(kSecValueData)] = data as AnyObject?
SecItemAdd(attributes as CFDictionary, nil)
}
internal func setValue(_ value: String, forKey key: String) {
if let data = value.data(using: String.Encoding.utf8, allowLossyConversion: false) {
setData(data, forKey: key)
}
}
internal func updateData(_ data: Data, forKey key: String) {
var query = defaultClassAndAttributes
query[String(kSecAttrAccount)] = key as AnyObject?
var attributesToUpdate = query
attributesToUpdate[String(kSecClass)] = nil
attributesToUpdate[String(kSecValueData)] = data as AnyObject?
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
if status == errSecItemNotFound || status == errSecNotAvailable {
setData(data, forKey: key)
}
}
internal func updateValue(_ value: String, forKey key: String) {
if let data = value.data(using: String.Encoding.utf8, allowLossyConversion: false) {
updateData(data, forKey: key)
}
}
internal func removeValueForKey(_ key: String) {
var attributes = defaultClassAndAttributes
attributes[String(kSecAttrAccount)] = key as AnyObject?
SecItemDelete(attributes as CFDictionary)
}
internal subscript(key: String) -> String? {
get {
return valueForKey(key)
}
set {
if let value = newValue {
updateValue(value, forKey: key)
} else {
removeValueForKey(key)
}
}
}
}
/// A persistent keychain-based access token store.
@objc public class OAuthAccessTokenKeychainStore: NSObject, OAuthAccessTokenStore {
private var keychain: Keychain
/// Creates an instance initialized to the given keychain service.
///
/// - parameter service: The keychain service.
/// Default: `de.rheinfabrik.heimdallr.oauth`.
public init(service: String = "de.rheinfabrik.heimdallr.oauth") {
keychain = Keychain(service: service)
}
public func storeAccessToken(_ accessToken: OAuthAccessToken?) {
keychain["access_token"] = accessToken?.accessToken
keychain["token_type"] = accessToken?.tokenType
keychain["expires_at"] = accessToken?.expiresAt?.timeIntervalSince1970.description
keychain["refresh_token"] = accessToken?.refreshToken
}
public func retrieveAccessToken() -> OAuthAccessToken? {
let accessToken = keychain["access_token"]
let tokenType = keychain["token_type"]
let refreshToken = keychain["refresh_token"]
let expiresAt = keychain["expires_at"].flatMap { description in
return Double(description).flatMap { expiresAtInSeconds in
Date(timeIntervalSince1970: expiresAtInSeconds)
}
}
if let accessToken = accessToken, let tokenType = tokenType {
return OAuthAccessToken(accessToken: accessToken, tokenType: tokenType, expiresAt: expiresAt, refreshToken: refreshToken)
}
return nil
}
}
| apache-2.0 | 718d431b0be9c25c59bcb710268832cb | 34.773438 | 133 | 0.652326 | 5.245132 | false | false | false | false |
ioscreator/ioscreator | IOSBackgroundFetchTutorial/IOSBackgroundFetchTutorial/ViewController.swift | 1 | 650 | //
// ViewController.swift
// IOSBackgroundFetchTutorial
//
// Created by Arthur Knopper on 11/05/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timeLabel: UILabel!
var currentTime: Date?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func updateTime() {
currentTime = Date()
let formatter = DateFormatter()
formatter.timeStyle = .short
if let currentTime = currentTime {
timeLabel.text = formatter.string(from: currentTime)
}
}
}
| mit | 3e3391ba58daaecd1efdfb188e3f923f | 19.28125 | 58 | 0.677966 | 4.475862 | false | false | false | false |
xingerdayu/dayu | dayu/Extension.swift | 1 | 2116 | //
// Extension.swift
// Community
//
// Created by Xinger on 15/3/18.
// Copyright (c) 2015年 Xinger. All rights reserved.
//
extension NSString {
func textSizeWithFont(font: UIFont, constrainedToSize size:CGSize) -> CGSize {
var textSize:CGSize!
if CGSizeEqualToSize(size, CGSizeZero) {
let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
textSize = self.sizeWithAttributes(attributes as? [String : AnyObject])
} else {
let option = NSStringDrawingOptions.UsesLineFragmentOrigin
let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
let stringRect = self.boundingRectWithSize(size, options: option, attributes: (attributes as! [String : AnyObject]), context: nil)
textSize = stringRect.size
}
return textSize
}
}
extension String {
var md5 : String{
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen);
CC_MD5(str!, strLen, result);
let hash = NSMutableString();
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i]);
}
result.destroy();
return String(format: hash as String).lowercaseString
}}
extension UIImage {
func scaleToSize(newSize:CGSize) -> UIImage {
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this new context, with the desired
// new size
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
// Get the new image from the context
let newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
return newImage
}
} | bsd-3-clause | 18761d6c7db6897d0ec178c7c516b9b3 | 34.847458 | 142 | 0.619205 | 5.298246 | false | false | false | false |
Diuit/DUMessagingUIKit-iOS | DUMessagingUIKit/DUUserCell.swift | 1 | 678 | //
// DUUserCell.swift
// DUMessagingUIKit
//
// Created by Pofat Diuit on 2016/6/3.
// Copyright © 2016年 duolC. All rights reserved.
//
import UIKit
import DTModelStorage
/// Display user information
class DUUserCell: UITableViewCell, ModelTransfer {
@IBOutlet weak var userAvatarImage: DUAvatarImageView!
@IBOutlet weak var userNameLabel: UILabel!
func update(with model: DUUserData) {
if model.userDisplayName != "Add People" {
self.selectionStyle = .none
}
userNameLabel.text = model.userDisplayName
if model.imagePath != nil {
userAvatarImage.imagePath = model.imagePath
}
}
}
| mit | be875c2049c3cfc77d7251120acccb70 | 23.107143 | 58 | 0.663704 | 4.272152 | false | false | false | false |
jisudong/study | MyPlayground.playground/Pages/属性.xcplaygroundpage/Contents.swift | 1 | 4072 | //: [Previous](@previous)
import Foundation
// 属性
//存储属性,就是存储在对象(实例)中的一个变量或者常量,类似于其他面向对象语言中的成员变量
class Dog {
var name: String = "wangcai"
}
class Person {
var age: Int = 10
var height: Double = 1.5
let life = 1
var weight = 100
lazy var dog: Dog = Dog() // 延迟属性,只能用在变量,不能用在常量
func printAgeValue() {
print(age)
}
}
var person5 = Person()
person5.age = 20
person5.height
person5.life
person5.age
MemoryLayout<Dog>.size
MemoryLayout<Person>.size
MemoryLayout.size(ofValue: person5)
//计算属性,不是直接存储值,而是提供get和set
class Square {
// 边长
var width: Double = 0
// 周长
var girth: Double {
get {
return width * 4
}
set(newGirth) {
width = newGirth / 4
}
}
}
var s = Square()
var g = s.girth
s.girth = 40
s.width
s.width = 20
s.girth
// 只读计算属性
class Square1 {
// 边长
var width: Double = 0
// 周长
var girth: Double {
// get {
// return width * 4
// }
return width * 4 //简写
}
}
//类型属性,用class修饰的属性就是类型属性,只能是计算属性不能是存储属性, 直接用类名访问
class Circle {
class var PI: Double {
return 3.14
}
// static 修饰的属性,子类不能重写
static var a: Int {
return 2
}
}
print("圆周率=%f", Circle.PI)
Circle.a
class SubCircle: Circle {
override class var PI: Double {
return 3
}
// 不能重写父类用static修饰的属性
// override static var a: Int {
// return 5
// }
}
//// 属性监视器
// 计算属性可以直接在set方法里监听,
// 存储属性没有set, 用willSet和didSet监听,在属性初始化的时候不会调用
class Square2 {
// 边长
var width: Double = 0.0 {
willSet { // 在赋值之前调用,会将新的属性值作为参数传入,默认是newValue
print("willSet---new=\(newValue), current=\(width)")
}
didSet { // 在属性赋值之后调用,会将旧的属性值作为参数传入,默认是oldValue
print("didSet---old=\(oldValue), current=\(width)")
}
}
// 周长
var girth: Double {
get {
return width * 4
}
set(newGirth) {
width = newGirth / 4
}
}
}
var s2 = Square2()
s2.width = 30
class Square3 {
// 边长
var width: Double = 0.0 {
willSet {
}
didSet {
width = 80 //如果在didSet监视器里为属性赋值,这个值会替换之前设置的值。(不会引发死循环)
}
}
}
var s3 = Square3()
s3.width = 40
print(s3.width)
//// 重写计算属性
class Car {
var speed: Int {
get {
return 20
}
set {
print("Car ---- set")
}
}
}
class Truck : Car {
override var speed: Int {
get {
return 30
}
set {
print("Truck ---- set")
}
}
}
var t = Truck()
t.speed = 30
print("speed = \(t.speed)")
// 重写存储属性
class Car1 {
var speed: Int = 10
}
class Truck1: Car1 {
override var speed: Int {
get {
return super.speed
}
set {
if newValue > 100 {
super.speed = 100
} else {
super.speed = newValue
}
}
}
}
var t1 = Truck1()
t1.speed = 80
print("speed = \(t1.speed)")
class Car2 {
var speed: Int = 10 {
willSet {
print("Car2 - willSet")
}
didSet {
print("Car2 - didSet")
}
}
}
class Truck2: Car2 {
override var speed: Int {
willSet {
print("Truck2 - willSet")
}
didSet {
print("Truck2 - didSet")
}
}
}
var t2 = Truck2()
t2.speed = 20
| mit | ee1e0ed0531138bb1839b6d137089256 | 15.350711 | 66 | 0.502609 | 3.248588 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/OngoingCallContext.swift | 1 | 34506 | //
// OngoingCallContext.swift
// Telegram
//
// Created by Mikhail Filimonov on 23/06/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import Foundation
import SwiftSignalKit
import TelegramCore
import InAppSettings
import Postbox
import TgVoipWebrtc
import TGUIKit
import TelegramVoip
private let debugUseLegacyVersionForReflectors: Bool = {
return false
}()
private func callConnectionDescription(_ connection: CallSessionConnection) -> OngoingCallConnectionDescription? {
switch connection {
case let .reflector(reflector):
return OngoingCallConnectionDescription(connectionId: reflector.id, ip: reflector.ip, ipv6: reflector.ipv6, port: reflector.port, peerTag: reflector.peerTag)
case .webRtcReflector:
return nil
}
}
private func callConnectionDescriptionsWebrtc(_ connection: CallSessionConnection, idMapping: [Int64: UInt8]) -> [OngoingCallConnectionDescriptionWebrtc] {
switch connection {
case let .reflector(reflector):
guard let id = idMapping[reflector.id] else {
return []
}
var result: [OngoingCallConnectionDescriptionWebrtc] = []
if !reflector.ip.isEmpty {
result.append(OngoingCallConnectionDescriptionWebrtc(reflectorId: id, hasStun: false, hasTurn: true, hasTcp: false, ip: reflector.ip, port: reflector.port, username: "reflector", password: hexString(reflector.peerTag)))
}
if !reflector.ipv6.isEmpty {
result.append(OngoingCallConnectionDescriptionWebrtc(reflectorId: id, hasStun: false, hasTurn: true, hasTcp: false, ip: reflector.ipv6, port: reflector.port, username: "reflector", password: hexString(reflector.peerTag)))
}
return result
case let .webRtcReflector(reflector):
var result: [OngoingCallConnectionDescriptionWebrtc] = []
if !reflector.ip.isEmpty {
result.append(OngoingCallConnectionDescriptionWebrtc(reflectorId: 0, hasStun: reflector.hasStun, hasTurn: reflector.hasTurn, hasTcp: false, ip: reflector.ip, port: reflector.port, username: reflector.username, password: reflector.password))
}
if !reflector.ipv6.isEmpty {
result.append(OngoingCallConnectionDescriptionWebrtc(reflectorId: 0, hasStun: reflector.hasStun, hasTurn: reflector.hasTurn, hasTcp: false, ip: reflector.ipv6, port: reflector.port, username: reflector.username, password: reflector.password))
}
return result
}
}
/*private func callConnectionDescriptionWebrtcCustom(_ connection: CallSessionConnection) -> OngoingCallConnectionDescriptionWebrtcCustom {
return OngoingCallConnectionDescriptionWebrtcCustom(connectionId: connection.id, ip: connection.ip, ipv6: connection.ipv6, port: connection.port, peerTag: connection.peerTag)
}*/
private let callLogsLimit = 20
func callLogNameForId(id: Int64, account: Account) -> String? {
let path = callLogsPath(account: account)
let namePrefix = "\(id)_"
if let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: path), includingPropertiesForKeys: [], options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants], errorHandler: nil) {
for url in enumerator {
if let url = url as? URL {
if url.lastPathComponent.hasPrefix(namePrefix) {
return url.lastPathComponent
}
}
}
}
return nil
}
func callLogsPath(account: Account) -> String {
return account.basePath + "/calls"
}
private func cleanupCallLogs(account: Account) {
let path = callLogsPath(account: account)
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path, isDirectory: nil) {
try? fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
var oldest: (URL, Date)? = nil
var count = 0
if let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: path), includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants], errorHandler: nil) {
for url in enumerator {
if let url = url as? URL {
if let date = (try? url.resourceValues(forKeys: Set([.contentModificationDateKey])))?.contentModificationDate {
if let currentOldest = oldest {
if date < currentOldest.1 {
oldest = (url, date)
}
} else {
oldest = (url, date)
}
count += 1
}
}
}
}
if count > callLogsLimit, let oldest = oldest {
try? fileManager.removeItem(atPath: oldest.0.path)
}
}
private let setupLogs: Bool = {
OngoingCallThreadLocalContext.setupLoggingFunction({ value in
if let value = value {
Logger.shared.log("TGVOIP", value)
}
})
OngoingCallThreadLocalContextWebrtc.setupLoggingFunction({ value in
if let value = value {
Logger.shared.log("TGVOIP", value)
}
})
/*OngoingCallThreadLocalContextWebrtcCustom.setupLoggingFunction({ value in
if let value = value {
Logger.shared.log("TGVOIP", value)
}
})*/
return true
}()
public struct OngoingCallContextState: Equatable {
public enum State {
case initializing
case connected
case reconnecting
case failed
}
public enum VideoState: Equatable {
case notAvailable
case inactive
case active
case paused
}
public enum RemoteVideoState: Equatable {
case inactive
case active
case paused
}
public enum RemoteAudioState: Equatable {
case active
case muted
}
public enum RemoteBatteryLevel: Equatable {
case normal
case low
}
public let state: State
public let videoState: VideoState
public let remoteVideoState: RemoteVideoState
public let remoteAudioState: RemoteAudioState
public let remoteBatteryLevel: RemoteBatteryLevel
public let remoteAspectRatio: Float
}
private final class OngoingCallThreadLocalContextQueueImpl: NSObject, OngoingCallThreadLocalContextQueue, OngoingCallThreadLocalContextQueueWebrtc /*, OngoingCallThreadLocalContextQueueWebrtcCustom*/ {
private let queue: Queue
init(queue: Queue) {
self.queue = queue
super.init()
}
func dispatch(_ f: @escaping () -> Void) {
self.queue.async {
f()
}
}
func dispatch(after seconds: Double, block f: @escaping () -> Void) {
self.queue.after(seconds, f)
}
func isCurrent() -> Bool {
return self.queue.isCurrent()
}
}
private func ongoingNetworkTypeForType(_ type: NetworkType) -> OngoingCallNetworkType {
switch type {
case .none:
return .wifi
case .wifi:
return .wifi
}
}
private func ongoingNetworkTypeForTypeWebrtc(_ type: NetworkType) -> OngoingCallNetworkTypeWebrtc {
switch type {
case .none:
return .wifi
case .wifi:
return .wifi
}
}
/*private func ongoingNetworkTypeForTypeWebrtcCustom(_ type: NetworkType) -> OngoingCallNetworkTypeWebrtcCustom {
switch type {
case .none:
return .wifi
case .wifi:
return .wifi
case let .cellular(cellular):
switch cellular {
case .edge:
return .cellularEdge
case .gprs:
return .cellularGprs
case .thirdG, .unknown:
return .cellular3g
case .lte:
return .cellularLte
}
}
}*/
private func ongoingDataSavingForType(_ type: VoiceCallDataSaving) -> OngoingCallDataSaving {
switch type {
case .never:
return .never
case .cellular:
return .cellular
case .always:
return .always
}
}
private func ongoingDataSavingForTypeWebrtc(_ type: VoiceCallDataSaving) -> OngoingCallDataSavingWebrtc {
switch type {
case .never:
return .never
case .cellular:
return .cellular
case .always:
return .always
}
}
private protocol OngoingCallThreadLocalContextProtocol: AnyObject {
func nativeSetNetworkType(_ type: NetworkType)
func nativeSetIsMuted(_ value: Bool)
func nativeSetIsLowBatteryLevel(_ value: Bool)
func nativeRequestVideo(_ capturer: OngoingCallVideoCapturer)
func nativeSetRequestedVideoAspect(_ aspect: Float)
func nativeDisableVideo()
func nativeStop(_ completion: @escaping (String?, Int64, Int64, Int64, Int64) -> Void)
func nativeBeginTermination()
func nativeDebugInfo() -> String
func nativeVersion() -> String
func nativeGetDerivedState() -> Data
func nativeSwitchAudioOutput(_ deviceId: String)
func nativeSwitchAudioInput(_ deviceId: String)
}
private final class OngoingCallThreadLocalContextHolder {
let context: OngoingCallThreadLocalContextProtocol
init(_ context: OngoingCallThreadLocalContextProtocol) {
self.context = context
}
}
extension OngoingCallThreadLocalContext: OngoingCallThreadLocalContextProtocol {
func nativeSetNetworkType(_ type: NetworkType) {
self.setNetworkType(ongoingNetworkTypeForType(type))
}
func nativeStop(_ completion: @escaping (String?, Int64, Int64, Int64, Int64) -> Void) {
self.stop(completion)
}
func nativeBeginTermination() {
}
func nativeSetIsMuted(_ value: Bool) {
self.setIsMuted(value)
}
func nativeRequestVideo(_ capturer: OngoingCallVideoCapturer) {
}
func nativeSwitchAudioOutput(_ deviceId: String) {
self.switchAudioOutput(deviceId)
}
func nativeSwitchAudioInput(_ deviceId: String) {
self.switchAudioInput(deviceId)
}
func nativeAcceptVideo(_ capturer: OngoingCallVideoCapturer) {
}
func nativeSetRequestedVideoAspect(_ aspect: Float) {
}
func nativeSetIsLowBatteryLevel(_ value: Bool) {
}
func nativeDisableVideo() {
}
func nativeSwitchVideoCamera() {
}
func nativeswitchAudioOutput() {
}
func nativeDebugInfo() -> String {
return self.debugInfo() ?? ""
}
func nativeVersion() -> String {
return self.version() ?? ""
}
func nativeGetDerivedState() -> Data {
return self.getDerivedState()
}
}
extension OngoingCallThreadLocalContextWebrtc: OngoingCallThreadLocalContextProtocol {
func nativeSetNetworkType(_ type: NetworkType) {
self.setNetworkType(ongoingNetworkTypeForTypeWebrtc(type))
}
func nativeStop(_ completion: @escaping (String?, Int64, Int64, Int64, Int64) -> Void) {
self.stop(completion)
}
func nativeBeginTermination() {
self.beginTermination()
}
func nativeSetIsMuted(_ value: Bool) {
self.setIsMuted(value)
}
func nativeSetIsLowBatteryLevel(_ value: Bool) {
self.setIsLowBatteryLevel(value)
}
func nativeSwitchAudioOutput(_ deviceId: String) {
self.switchAudioOutput(deviceId)
}
func nativeSwitchAudioInput(_ deviceId: String) {
self.switchAudioInput(deviceId)
}
func nativeRequestVideo(_ capturer: OngoingCallVideoCapturer) {
self.requestVideo(capturer.impl)
}
func nativeSetRequestedVideoAspect(_ aspect: Float) {
self.setRequestedVideoAspect(aspect)
}
func nativeDisableVideo() {
self.disableVideo()
}
func nativeDebugInfo() -> String {
return self.debugInfo() ?? ""
}
func nativeVersion() -> String {
return self.version() ?? ""
}
func nativeGetDerivedState() -> Data {
return self.getDerivedState()
}
}
private extension OngoingCallContextState.State {
init(_ state: OngoingCallState) {
switch state {
case .initializing:
self = .initializing
case .connected:
self = .connected
case .failed:
self = .failed
case .reconnecting:
self = .reconnecting
default:
self = .failed
}
}
}
private extension OngoingCallContextState.State {
init(_ state: OngoingCallStateWebrtc) {
switch state {
case .initializing:
self = .initializing
case .connected:
self = .connected
case .failed:
self = .failed
case .reconnecting:
self = .reconnecting
default:
self = .failed
}
}
}
/*private extension OngoingCallContextState {
init(_ state: OngoingCallStateWebrtcCustom) {
switch state {
case .initializing:
self = .initializing
case .connected:
self = .connected
case .failed:
self = .failed
case .reconnecting:
self = .reconnecting
default:
self = .failed
}
}
}*/
final class OngoingCallContext {
struct AuxiliaryServer {
enum Connection {
case stun
case turn(username: String, password: String)
}
let host: String
let port: Int
let connection: Connection
init(
host: String,
port: Int,
connection: Connection
) {
self.host = host
self.port = port
self.connection = connection
}
}
let internalId: CallSessionInternalId
private let queue = Queue()
private let account: Account
private let callSessionManager: CallSessionManager
private let logPath: String
private var contextRef: Unmanaged<OngoingCallThreadLocalContextHolder>?
private let contextState = Promise<OngoingCallContextState?>(nil)
var state: Signal<OngoingCallContextState?, NoError> {
return self.contextState.get()
}
private var didReportCallAsVideo: Bool = false
private var signalingDataDisposable: Disposable?
private let receptionPromise = Promise<Int32?>(nil)
var reception: Signal<Int32?, NoError> {
return self.receptionPromise.get()
}
private let audioLevelPromise = Promise<Float>(0.0)
public var audioLevel: Signal<Float, NoError> {
return self.audioLevelPromise.get()
}
private let audioSessionDisposable = MetaDisposable()
private var networkTypeDisposable: Disposable?
private let tempLogFile: TempBoxFile
private let tempStatsLogFile: TempBoxFile
public static var maxLayer: Int32 {
return OngoingCallThreadLocalContext.maxLayer()
}
static func versions(includeExperimental: Bool, includeReference: Bool) -> [(version: String, supportsVideo: Bool)] {
if debugUseLegacyVersionForReflectors {
return [(OngoingCallThreadLocalContext.version(), true)]
} else {
var result: [(version: String, supportsVideo: Bool)] = [(OngoingCallThreadLocalContext.version(), false)]
result.append(contentsOf: OngoingCallThreadLocalContextWebrtc.versions(withIncludeReference: includeReference).map { version -> (version: String, supportsVideo: Bool) in
return (version, true)
})
return result
}
}
init(account: Account, callSessionManager: CallSessionManager, internalId: CallSessionInternalId, proxyServer: ProxyServerSettings?, initialNetworkType: NetworkType, updatedNetworkType: Signal<NetworkType, NoError>, serializedData: String?, dataSaving: VoiceCallDataSaving, derivedState: VoipDerivedState, key: Data, isOutgoing: Bool, video: OngoingCallVideoCapturer?, connections: CallSessionConnectionSet, maxLayer: Int32, version: String, allowP2P: Bool, enableTCP: Bool, enableStunMarking: Bool, logName: String, preferredVideoCodec: String?, inputDeviceId: String?, outputDeviceId: String?) {
let _ = setupLogs
OngoingCallThreadLocalContext.applyServerConfig(serializedData)
OngoingCallThreadLocalContextWebrtc.applyServerConfig(serializedData)
self.internalId = internalId
self.account = account
self.callSessionManager = callSessionManager
self.logPath = logName.isEmpty ? "" : callLogsPath(account: self.account) + "/" + logName + ".log"
let logPath = self.logPath
self.tempLogFile = TempBox.shared.tempFile(fileName: "CallLog.txt")
let tempLogPath = self.tempLogFile.path
self.tempStatsLogFile = TempBox.shared.tempFile(fileName: "CallStats.json")
let tempStatsLogPath = self.tempStatsLogFile.path
let queue = self.queue
cleanupCallLogs(account: account)
queue.sync {
var useModernImplementation = true
var version = version
var allowP2P = allowP2P
if debugUseLegacyVersionForReflectors {
useModernImplementation = true
version = "4.1.2"
allowP2P = false
} else {
useModernImplementation = version != OngoingCallThreadLocalContext.version()
}
if useModernImplementation {
var voipProxyServer: VoipProxyServerWebrtc?
if let proxyServer = proxyServer {
switch proxyServer.connection {
case let .socks5(username, password):
voipProxyServer = VoipProxyServerWebrtc(host: proxyServer.host, port: proxyServer.port, username: username, password: password)
case .mtp:
break
}
}
let unfilteredConnections = [connections.primary] + connections.alternatives
var reflectorIdList: [Int64] = []
for connection in unfilteredConnections {
switch connection {
case let .reflector(reflector):
reflectorIdList.append(reflector.id)
case .webRtcReflector:
break
}
}
reflectorIdList.sort()
var reflectorIdMapping: [Int64: UInt8] = [:]
for i in 0 ..< reflectorIdList.count {
reflectorIdMapping[reflectorIdList[i]] = UInt8(i + 1)
}
var processedConnections: [CallSessionConnection] = []
var filteredConnections: [OngoingCallConnectionDescriptionWebrtc] = []
for connection in unfilteredConnections {
if processedConnections.contains(connection) {
continue
}
processedConnections.append(connection)
filteredConnections.append(contentsOf: callConnectionDescriptionsWebrtc(connection, idMapping: reflectorIdMapping))
}
for connection in filteredConnections {
if connection.username == "reflector" {
let peerTag = dataWithHexString(connection.password)
break
}
}
let context = OngoingCallThreadLocalContextWebrtc(version: version, queue: OngoingCallThreadLocalContextQueueImpl(queue: queue), proxy: voipProxyServer, networkType: ongoingNetworkTypeForTypeWebrtc(initialNetworkType), dataSaving: ongoingDataSavingForTypeWebrtc(dataSaving), derivedState: derivedState.data, key: key, isOutgoing: isOutgoing, connections: filteredConnections, maxLayer: maxLayer, allowP2P: allowP2P, allowTCP: enableTCP, enableStunMarking: enableStunMarking, logPath: tempLogPath, statsLogPath: tempStatsLogPath, sendSignalingData: { [weak callSessionManager] data in
callSessionManager?.sendSignalingData(internalId: internalId, data: data)
}, videoCapturer: video?.impl, preferredVideoCodec: preferredVideoCodec, inputDeviceId: inputDeviceId ?? "", outputDeviceId: outputDeviceId ?? "")
self.contextRef = Unmanaged.passRetained(OngoingCallThreadLocalContextHolder(context))
context.stateChanged = { [weak self, weak callSessionManager] state, videoState, remoteVideoState, remoteAudioState, remoteBatteryLevel, remotePreferredAspectRatio in
queue.async {
guard let strongSelf = self else {
return
}
let mappedState = OngoingCallContextState.State(state)
let mappedVideoState: OngoingCallContextState.VideoState
switch videoState {
case .inactive:
mappedVideoState = .inactive
case .active:
mappedVideoState = .active
case .paused:
mappedVideoState = .paused
@unknown default:
mappedVideoState = .notAvailable
}
let mappedRemoteVideoState: OngoingCallContextState.RemoteVideoState
switch remoteVideoState {
case .inactive:
mappedRemoteVideoState = .inactive
case .active:
mappedRemoteVideoState = .active
case .paused:
mappedRemoteVideoState = .paused
@unknown default:
mappedRemoteVideoState = .inactive
}
let mappedRemoteAudioState: OngoingCallContextState.RemoteAudioState
switch remoteAudioState {
case .active:
mappedRemoteAudioState = .active
case .muted:
mappedRemoteAudioState = .muted
@unknown default:
mappedRemoteAudioState = .active
}
let mappedRemoteBatteryLevel: OngoingCallContextState.RemoteBatteryLevel
switch remoteBatteryLevel {
case .normal:
mappedRemoteBatteryLevel = .normal
case .low:
mappedRemoteBatteryLevel = .low
@unknown default:
mappedRemoteBatteryLevel = .normal
}
if case .active = mappedVideoState, !strongSelf.didReportCallAsVideo {
strongSelf.didReportCallAsVideo = true
callSessionManager?.updateCallType(internalId: internalId, type: .video)
}
strongSelf.contextState.set(.single(OngoingCallContextState(state: mappedState, videoState: mappedVideoState, remoteVideoState: mappedRemoteVideoState, remoteAudioState: mappedRemoteAudioState, remoteBatteryLevel: mappedRemoteBatteryLevel, remoteAspectRatio: remotePreferredAspectRatio)))
}
}
self.receptionPromise.set(.single(4))
context.signalBarsChanged = { [weak self] signalBars in
self?.receptionPromise.set(.single(signalBars))
}
context.audioLevelUpdated = { [weak self] level in
self?.audioLevelPromise.set(.single(level))
}
self.networkTypeDisposable = (updatedNetworkType
|> deliverOn(queue)).start(next: { [weak self] networkType in
self?.withContext { context in
context.nativeSetNetworkType(networkType)
}
})
} else {
var voipProxyServer: VoipProxyServer?
if let proxyServer = proxyServer {
switch proxyServer.connection {
case let .socks5(username, password):
voipProxyServer = VoipProxyServer(host: proxyServer.host, port: proxyServer.port, username: username, password: password)
case .mtp:
break
}
}
let context = OngoingCallThreadLocalContext(queue: OngoingCallThreadLocalContextQueueImpl(queue: queue), proxy: voipProxyServer, networkType: ongoingNetworkTypeForType(initialNetworkType), dataSaving: ongoingDataSavingForType(dataSaving), derivedState: derivedState.data, key: key, isOutgoing: isOutgoing, primaryConnection: callConnectionDescription(connections.primary)!, alternativeConnections: connections.alternatives.compactMap(callConnectionDescription), maxLayer: maxLayer, allowP2P: allowP2P, logPath: logPath)
self.contextRef = Unmanaged.passRetained(OngoingCallThreadLocalContextHolder(context))
context.stateChanged = { [weak self] state in
self?.contextState.set(.single(OngoingCallContextState(state: OngoingCallContextState.State(state), videoState: .notAvailable, remoteVideoState: .inactive, remoteAudioState: .active, remoteBatteryLevel: .normal, remoteAspectRatio: 0)))
}
context.signalBarsChanged = { [weak self] signalBars in
self?.receptionPromise.set(.single(signalBars))
}
self.networkTypeDisposable = (updatedNetworkType
|> deliverOn(queue)).start(next: { [weak self] networkType in
self?.withContext { context in
context.nativeSetNetworkType(networkType)
}
})
}
}
self.signalingDataDisposable = callSessionManager.beginReceivingCallSignalingData(internalId: internalId, { [weak self] dataList in
print("data received")
queue.async {
self?.withContext { context in
if let context = context as? OngoingCallThreadLocalContextWebrtc {
for data in dataList {
context.addSignaling(data)
}
}
}
}
})
}
deinit {
let contextRef = self.contextRef
self.queue.async {
contextRef?.release()
}
self.audioSessionDisposable.dispose()
self.networkTypeDisposable?.dispose()
}
private func withContext(_ f: @escaping (OngoingCallThreadLocalContextProtocol) -> Void) {
self.queue.async {
if let contextRef = self.contextRef {
let context = contextRef.takeUnretainedValue()
f(context.context)
}
}
}
private func withContextThenDeallocate(_ f: @escaping (OngoingCallThreadLocalContextProtocol) -> Void) {
self.queue.async {
if let contextRef = self.contextRef {
let context = contextRef.takeUnretainedValue()
f(context.context)
self.contextRef?.release()
self.contextRef = nil
}
}
}
func stop(callId: CallId? = nil, sendDebugLogs: Bool = false, debugLogValue: Promise<String?>) {
let account = self.account
let logPath = self.logPath
var statsLogPath = ""
if !logPath.isEmpty {
statsLogPath = logPath + ".json"
}
let tempLogPath = self.tempLogFile.path
let tempStatsLogPath = self.tempStatsLogFile.path
self.withContextThenDeallocate { context in
context.nativeStop { debugLog, bytesSentWifi, bytesReceivedWifi, bytesSentMobile, bytesReceivedMobile in
let delta = NetworkUsageStatsConnectionsEntry(
cellular: NetworkUsageStatsDirectionsEntry(
incoming: bytesReceivedMobile,
outgoing: bytesSentMobile),
wifi: NetworkUsageStatsDirectionsEntry(
incoming: bytesReceivedWifi,
outgoing: bytesSentWifi))
updateAccountNetworkUsageStats(account: self.account, category: .call, delta: delta)
if !logPath.isEmpty {
let logsPath = callLogsPath(account: account)
let _ = try? FileManager.default.createDirectory(atPath: logsPath, withIntermediateDirectories: true, attributes: nil)
let _ = try? FileManager.default.moveItem(atPath: tempLogPath, toPath: logPath)
}
if !statsLogPath.isEmpty {
let logsPath = callLogsPath(account: account)
let _ = try? FileManager.default.createDirectory(atPath: logsPath, withIntermediateDirectories: true, attributes: nil)
let _ = try? FileManager.default.moveItem(atPath: tempStatsLogPath, toPath: statsLogPath)
}
if let callId = callId, !statsLogPath.isEmpty, let data = try? Data(contentsOf: URL(fileURLWithPath: statsLogPath)), let dataString = String(data: data, encoding: .utf8) {
debugLogValue.set(.single(dataString))
if sendDebugLogs {
// let _ = saveCallDebugLog(network: self.account.network, callId: callId, log: dataString).start()
}
}
}
let derivedState = context.nativeGetDerivedState()
let _ = updateVoipDerivedStateInteractively(postbox: self.account.postbox, { _ in
return VoipDerivedState(data: derivedState)
}).start()
}
}
func setIsMuted(_ value: Bool) {
self.withContext { context in
context.nativeSetIsMuted(value)
}
}
public func setIsLowBatteryLevel(_ value: Bool) {
self.withContext { context in
context.nativeSetIsLowBatteryLevel(value)
}
}
public func requestVideo(_ capturer: OngoingCallVideoCapturer) {
self.withContext { context in
context.nativeRequestVideo(capturer)
}
}
public func setRequestedVideoAspect(_ aspect: Float) {
self.withContext { context in
context.nativeSetRequestedVideoAspect(aspect)
}
}
public func disableVideo() {
self.withContext { context in
context.nativeDisableVideo()
}
}
public func switchAudioOutput(_ deviceId: String) {
self.withContext { context in
context.nativeSwitchAudioOutput(deviceId)
}
}
public func switchAudioInput(_ deviceId: String) {
self.withContext { context in
context.nativeSwitchAudioInput(deviceId)
}
}
func debugInfo() -> Signal<(String, String), NoError> {
let poll = Signal<(String, String), NoError> { subscriber in
self.withContext { context in
let version = context.nativeVersion()
let debugInfo = context.nativeDebugInfo()
subscriber.putNext((version, debugInfo))
subscriber.putCompletion()
}
return EmptyDisposable
}
return (poll |> then(.complete() |> delay(0.5, queue: Queue.concurrentDefaultQueue()))) |> restart
}
func makeIncomingVideoView(completion: @escaping (OngoingCallContextPresentationCallVideoView?) -> Void) {
self.withContext { context in
if let context = context as? OngoingCallThreadLocalContextWebrtc {
context.makeIncomingVideoView { view in
if let view = view {
completion(OngoingCallContextPresentationCallVideoView(
view: view,
setOnFirstFrameReceived: { [weak view] f in
view?.setOnFirstFrameReceived(f)
},
getOrientation: { [weak view] in
if let view = view {
return OngoingCallVideoOrientation(view.orientation)
} else {
return .rotation0
}
},
getAspect: { [weak view] in
if let view = view {
return view.aspect
} else {
return 0.0
}
},
setOnOrientationUpdated: { [weak view] f in
view?.setOnOrientationUpdated { value, aspect in
f?(OngoingCallVideoOrientation(value), aspect)
}
}, setVideoContentMode: { [weak view] mode in
view?.setVideoContentMode(mode)
}, setOnIsMirroredUpdated: { [weak view] f in
view?.setOnIsMirroredUpdated { value in
f?(value)
}
},
setIsPaused: { [weak view] paused in
view?.setIsPaused(paused)
}, renderToSize: { [weak view] size, animated in
view?.render(to: size, animated: animated)
}
))
} else {
completion(nil)
}
}
} else {
completion(nil)
}
}
}
}
| gpl-2.0 | b24ada74d6dd655cde1d5887f408f663 | 36.587146 | 601 | 0.589074 | 5.094493 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift | Example/TLTranstionLib-swift/BaseTabController.swift | 1 | 1112 | //
// BaseTabController.swift
// TLTranstionLib-swift
//
// Created by Andrew on 16/7/22.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
class BaseTabController: UIViewController,UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let attr1 = getAttibutes()
let attr2 = getActiveAttibutes()
self.tabBarItem.setTitleTextAttributes(attr1, forState: .Normal)
self.tabBarItem.setTitleTextAttributes(attr2, forState: .Selected)
// Do any additional setup after loading the view.
}
func getAttibutes() -> [String:AnyObject] {
let font = UIFont.systemFontOfSize(18)
let attrs = [NSFontAttributeName:font,
NSForegroundColorAttributeName:UIColor.grayColor()]
return attrs
}
func getActiveAttibutes() -> [String:AnyObject] {
let font = UIFont.systemFontOfSize(18)
let attrs = [NSFontAttributeName:font,
NSForegroundColorAttributeName:UIColor.redColor()]
return attrs
}
}
| mit | 41d6e83356b274f2123080452adfdd54 | 27.435897 | 74 | 0.651939 | 4.842795 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.